openlearn-next 0.4.0 → 0.4.2

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.
Files changed (33) hide show
  1. package/dist/assets/{BatchPickerModal-BobcoTtn.js → BatchPickerModal-BpWu0Lil.js} +1 -1
  2. package/dist/assets/ClassesView-KbHEqJto.js +22 -0
  3. package/dist/assets/{ClassroomCountdownWidget-AWnCu4JJ.js → ClassroomCountdownWidget-96WFRO9A.js} +1 -1
  4. package/dist/assets/{CloudDriveModal-Dr4kDySU.js → CloudDriveModal-DEQ1nkNk.js} +1 -1
  5. package/dist/assets/{CourseManagement-DtInD0J-.js → CourseManagement-D3ZpxY0l.js} +1 -1
  6. package/dist/assets/{CourseWizardModal-B16QBckO.js → CourseWizardModal-Ck_-M8pk.js} +1 -1
  7. package/dist/assets/{Dashboard-D1gZ_4NI.js → Dashboard-CYbpbofV.js} +1 -1
  8. package/dist/assets/{ExportWeightModal-UPsVax6L.js → ExportWeightModal-DW2bu9Zz.js} +1 -1
  9. package/dist/assets/{HelpView-BryOHwLE.js → HelpView-CtzdqhBq.js} +1 -1
  10. package/dist/assets/{ImportLessonsModal-Dnx_QR0Z.js → ImportLessonsModal-jBuIK453.js} +1 -1
  11. package/dist/assets/InteractiveCoursewareViewer-Bj7ahXMs.js +1 -0
  12. package/dist/assets/{InteractiveWhiteboard-550JMFBu.js → InteractiveWhiteboard-B7JcJvDu.js} +1 -1
  13. package/dist/assets/{LazyCourseware-CLHWQJ8g.js → LazyCourseware-CuiPxhDg.js} +2 -2
  14. package/dist/assets/{LazyWhiteboard-DJWh6sdV.js → LazyWhiteboard-BJwCEZAU.js} +2 -2
  15. package/dist/assets/LessonEditorView-DFrOp2qp.js +1 -0
  16. package/dist/assets/{LiveClassroomView-DgN2Zqe6.js → LiveClassroomView-BZ5nGee3.js} +2 -2
  17. package/dist/assets/{NotificationDetailModal-CMKHpWX1.js → NotificationDetailModal-Baqnc5pU.js} +1 -1
  18. package/dist/assets/{PluginView-BQVWPofY.js → PluginView-CCbIuZ24.js} +1 -1
  19. package/dist/assets/{QuizGeneratorModal-BeaBRn1w.js → QuizGeneratorModal-BBEDssp7.js} +1 -1
  20. package/dist/assets/StudentAssignmentView-DgIjUsXz.js +1 -0
  21. package/dist/assets/{StudentLessonView-CMPqL1ia.js → StudentLessonView-CBJbI5x6.js} +1 -1
  22. package/dist/assets/{StudentPreviewModal-0QSLnD9u.js → StudentPreviewModal-Bh8OZs0t.js} +1 -1
  23. package/dist/assets/{StudentView-9pjzjJgG.js → StudentView--uGxc5TJ.js} +2 -2
  24. package/dist/assets/{SystemResourceLibraryModal-COrhUd53.js → SystemResourceLibraryModal-BVCclcqA.js} +1 -1
  25. package/dist/assets/{TeacherView-mP2YucVr.js → TeacherView-D4Zsc0eZ.js} +2 -2
  26. package/dist/assets/{index-C70OJPV_.js → index-BKBCBKvy.js} +29 -29
  27. package/dist/index.html +1 -1
  28. package/dist/server.cjs +87 -16
  29. package/package.json +1 -1
  30. package/dist/assets/ClassesView-DtO0PJXQ.js +0 -22
  31. package/dist/assets/InteractiveCoursewareViewer-BYMKvIHi.js +0 -1
  32. package/dist/assets/LessonEditorView-DRwi0sjA.js +0 -1
  33. package/dist/assets/StudentAssignmentView-Dn4Bgqr2.js +0 -1
@@ -1,29 +1,29 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/StudentView-9pjzjJgG.js","assets/vendor-pdf-D7rGevI1.js","assets/vendor-react-B0t7H3hh.js","assets/vendor-utils-m0Urvtws.js","assets/vendor-icons-BRmhY6fg.js","assets/vendor-motion-BFAPOs-b.js","assets/vendor-charts-qLbgF1eL.js","assets/vendor-pptx-C5-U7ieS.js","assets/TeacherView-mP2YucVr.js","assets/ImportModal-D7L-KNhZ.js","assets/CourseWizardModal-B16QBckO.js","assets/ImportLessonsModal-Dnx_QR0Z.js","assets/QuizGeneratorModal-BeaBRn1w.js","assets/StudentPreviewModal-0QSLnD9u.js","assets/LazyWhiteboard-DJWh6sdV.js","assets/LazyCourseware-CLHWQJ8g.js","assets/ProcessLogsModal-DmFXg9mG.js","assets/CloudDriveModal-Dr4kDySU.js","assets/SystemResourceLibraryModal-COrhUd53.js","assets/BatchPickerModal-BobcoTtn.js","assets/ExportWeightModal-UPsVax6L.js","assets/NotificationDetailModal-CMKHpWX1.js","assets/HelpTour-CMJbbGne.js","assets/CoursewareHubPanel-CaEizhxl.js"])))=>i.map(i=>d[i]);
2
- import{R as Ze,r as p,j as o,u as Uf,g as Bl,b as Hf,d as wi,h as Si,J as sa,i as ra,k as qf}from"./vendor-react-B0t7H3hh.js";import{G as Ns,S as Wf,U as Vl,C as vi,a as On,L as ki,A as ia,b as dn,c as Qi,P as Ci,d as oa,D as aa,X as Je,e as tt,f as Ut,g as Gf,h as Qf,T as Ul,E as Ms,B as Fs,R as Hl,i as Jf,j as an,k as Zf,M as Yf,l as Kf,m as Xf,n as ep,H as ql,o as tp,p as Wl,q as Gl,r as _t,s as Ei,t as np,K as sp,u as rp,v as fs,w as ip,x as Ji,y as op,z as Zi,F as Ql,V as ap,I as lp,J as cp,N as Ts,O as up,Z as dp,Q as hp,W as fp,Y as pp,_ as Jl,$ as mp,a0 as gp,a1 as xp,a2 as yp,a3 as bp,a4 as Ps,a5 as Vr,a6 as wp,a7 as Sp,a8 as vp,a9 as kp,aa as Cp,ab as Zl,ac as Ep,ad as la,ae as jp,af as ca}from"./vendor-icons-BRmhY6fg.js";import{_ as Ee,E as Np}from"./vendor-pdf-D7rGevI1.js";import{e as Yi,f as Mn,h as $s}from"./vendor-utils-m0Urvtws.js";import{i as Ur,g as Tp,s as Yl,a as Ki,b as Kl,c as ua,d as Pp,e as Ip,f as Ap,h as zp,r as _p,j as Lp,k as Xl,l as Rp,m as Op,n as Dp,o as Mp,S as Fp,H as $p,F as Lt,p as Bp,q as Vp,t as ec,u as Is,v as da,w as nt,x as tc,y as Up,z as ha,A as Hp,B as As,C as ji,D as fa,E as qp,G as Wp,I as Pt,J as Gp,K as Qp,L as Jp,M as pa,N as Zp,O as Yp,P as ma,Q as Kp,R as Xp,T as ps,U as em,V as tm,W as nc,X as nm,Y as sm}from"./vendor-motion-BFAPOs-b.js";import{v as sc}from"./vendor-pptx-C5-U7ieS.js";import{R as ga}from"./vendor-charts-qLbgF1eL.js";const rm=e=>{const t=e.split(/\r?\n/);if(t.length<2)return[];const n=t[0],s=[",",";"," "];let r=",",i=0;s.forEach(g=>{const y=n.split(g).length;y>i&&(i=y,r=g)});const a=g=>{const y=[];let C=!1,w="";for(let P=0;P<g.length;P++){const S=g[P];S==='"'?C=!C:S===r&&!C?(y.push(w.trim()),w=""):w+=S}return y.push(w.trim()),y},l=a(n).map(g=>g.toLowerCase().replace(/["'\r]/g,"").trim()),c=l.findIndex(g=>g.includes("student_number")||g.includes("studentnumber")||g.includes("student_id")||g.includes("studentid")||g.includes("学号")||g.includes("编号")||g.includes("id")&&!g.includes("class")&&!g.includes("lesson")),u=l.findIndex(g=>g.includes("name")||g.includes("姓名")||g.includes("student")&&!g.includes("num")&&!g.includes("id")||g.includes("学生")&&!g.includes("号")),d=l.findIndex(g=>g.includes("email")||g.includes("mail")||g.includes("邮箱")),h=u>=0?u:0,m=d>=0?d:1,f=[];for(let g=1;g<t.length;g++){if(!t[g].trim())continue;const y=a(t[g]),C=y[h]?y[h].replace(/["'\r]/g,"").trim():"",w=y[m]?y[m].replace(/["'\r]/g,"").trim():"",P=c>=0&&y[c]?y[c].replace(/["'\r]/g,"").trim():void 0;C&&f.push({name:C,email:w,...P?{student_number:P}:{}})}return f},xa={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"}},im=Ze.memo(function({onLoginSuccess:t,lang:n}){const[s,r]=p.useState("teacher"),[i,a]=p.useState(null),[l,c]=p.useState(""),[u,d]=p.useState(""),[h,m]=p.useState(""),[f,g]=p.useState(!1),[y,C]=p.useState([]),[w,P]=p.useState(""),[S,j]=p.useState(""),[A,E]=p.useState(""),[R,F]=p.useState(""),[M,O]=p.useState(!1);p.useEffect(()=>{(async()=>{try{const I=await fetch("/api/students");if(I.ok){const N=await I.json();C(N),N.length>0&&P(N[0].id)}}catch(I){console.warn("Failed to fetch student roster for login selection:",I)}})()},[]),p.useEffect(()=>{(async()=>{try{const I=await fetch("/api/site-settings");if(I.ok){const N=await I.json();a(N)}}catch(I){console.warn("Failed to fetch site settings for login branding:",I)}})()},[]);const v=async L=>{if(L.preventDefault(),!l.trim()||!u){m(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{m(""),g(!0);const I=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:l.trim(),password:u})});if(I.ok){const N=await I.json();t(N.session)}else{const N=await I.json();m(N.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{m(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{g(!1)}},_=async L=>{L.preventDefault();const I=w||S.trim();if(!I){F(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!A.trim()){F(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{F(""),O(!0);const N=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:I,password:A.trim()})});if(N.ok){const z=await N.json();t(z.session)}else{const z=await N.json();F(z.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{F(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{O(!1)}};return o.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:[o.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),o.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),o.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:[o.jsxs("div",{className:"text-center mb-8",children:[i?.logoUrl?o.jsx("img",{src:i.logoUrl,alt:i.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):o.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:o.jsx(Ns,{size:32})}),o.jsxs("h1",{className:"text-2xl sm:text-3xl font-black text-white tracking-tight flex items-center justify-center gap-2",children:[i?.siteName||"OpenLearn Next"," ",o.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"})]}),o.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:i?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),o.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[o.jsxs("button",{onClick:()=>r("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 ${s==="teacher"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[o.jsx(Wf,{size:14}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),o.jsxs("button",{onClick:()=>r("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 ${s==="student"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[o.jsx(Vl,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?o.jsxs("form",{onSubmit:v,className:"space-y-4",children:[h&&o.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:[o.jsx(vi,{size:15,className:"shrink-0"}),o.jsx("span",{children:h})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(On,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),o.jsx("input",{type:"text",value:l,onChange:L=>c(L.target.value),placeholder:n==="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})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(ki,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),o.jsx("input",{type:"password",value:u,onChange:L=>d(L.target.value),placeholder:n==="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})]}),o.jsxs("button",{type:"submit",disabled:f,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:[o.jsx("span",{children:f?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),o.jsx(ia,{size:15})]})]}):o.jsxs("form",{onSubmit:_,className:"space-y-4",children:[R&&o.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:[o.jsx(vi,{size:15,className:"shrink-0"}),o.jsx("span",{children:R})]}),y.length>0?o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(Ns,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),o.jsx("select",{value:w,onChange:L=>{P(L.target.value),j("")},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:y.map(L=>o.jsxs("option",{value:L.id,children:[L.name," (",L.student_number||L.id,")"]},L.id))}),o.jsx("p",{className:"text-xs text-slate-500 font-medium",children:n==="zh"?"✨ 在沙盒调试中,你可以直接下拉选择已有的学生账户一键登录为该生。":"✨ Sandbox help: Quick select existing students on file to simulate as student."})]}):null,o.jsxs("div",{className:"relative flex py-2 items-center",children:[o.jsx("div",{className:"flex-grow border-t border-slate-850"}),o.jsx("span",{className:"flex-shrink mx-3 text-xs font-bold text-slate-500 uppercase tracking-wider",children:n==="zh"?"或手动输入学号":"Or input key manually"}),o.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(On,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),o.jsx("input",{type:"text",value:S,onChange:L=>{j(L.target.value),P("")},placeholder:n==="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"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(ki,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),o.jsx("input",{type:"password",required:!0,value:A,onChange:L=>E(L.target.value),placeholder:n==="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"})]}),o.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:[o.jsx("span",{children:M?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),o.jsx(ia,{size:15})]})]})]})]})});function om({session:e,lang:t,onLogout:n,onProfile:s}){const[r,i]=p.useState(!1),a=p.useRef(null);p.useEffect(()=>{if(!r)return;const c=u=>{a.current&&!a.current.contains(u.target)&&i(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[r]);const l=(c,u)=>t==="zh"?c:u;return o.jsxs("div",{className:"relative",ref:a,children:[o.jsxs("button",{type:"button",onClick:()=>i(c=>!c),"aria-haspopup":"menu","aria-expanded":r,title:e.name,className:"flex items-center gap-1 rounded-full p-1 hover:bg-gray-100 transition-colors cursor-pointer",children:[o.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:e.avatar?o.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):o.jsx(On,{size:20})}),o.jsx(dn,{size:14,className:`text-gray-400 transition-transform duration-200 ${r?"rotate-180":""}`})]}),r&&o.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:[o.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[o.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:e.name,children:e.name}),o.jsx("p",{className:"text-xs text-gray-400 truncate",children:e.username})]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),s()},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:[o.jsx(On,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),n()},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:[o.jsx(Qi,{size:16}),l("注销登录","Sign Out")]})]})]})}const am=[{id:"light",label:"浅色日间",description:"明亮通透,适合自然采光良好的日间课堂",previewBg:"#f8fafc",previewPrimary:"#4f46e5",category:"builtin"},{id:"dark",label:"暗夜极客",description:"深邃内敛,适合计算机房与夜间专注备课",previewBg:"#0b0f19",previewPrimary:"#6366f1",category:"builtin"},{id:"eyecare",label:"教学护眼",description:"柔和舒缓,防教室大屏眩光,减轻视觉疲劳",previewBg:"#f2f7f4",previewPrimary:"#2d6a4f",category:"builtin"},{id:"chalkboard",label:"经典黑板",description:"经典墨绿板书质感,沉浸式板书演练",previewBg:"#0e1713",previewPrimary:"#4caf50",category:"builtin"}],ms={light:{"--bg-app":"#f8fafc","--bg-surface":"#ffffff","--bg-surface-secondary":"#f1f5f9","--bg-surface-elevated":"#ffffff","--border-theme":"#e2e8f0","--border-theme-subtle":"#f1f5f9","--text-main":"#0f172a","--text-muted":"#64748b","--color-primary":"#4f46e5","--color-primary-hover":"#4338ca"},dark:{"--bg-app":"#0b0f19","--bg-surface":"#111827","--bg-surface-secondary":"#1f2937","--bg-surface-elevated":"#1f2937","--border-theme":"#374151","--border-theme-subtle":"#1f2937","--text-main":"#f9fafb","--text-muted":"#9ca3af","--color-primary":"#6366f1","--color-primary-hover":"#4f46e5"},eyecare:{"--bg-app":"#f2f7f4","--bg-surface":"#ffffff","--bg-surface-secondary":"#e4eee8","--bg-surface-elevated":"#ffffff","--border-theme":"#cbe0d5","--border-theme-subtle":"#dbeef2","--text-main":"#143526","--text-muted":"#3d6350","--color-primary":"#2d6a4f","--color-primary-hover":"#1b4332"},chalkboard:{"--bg-app":"#0e1713","--bg-surface":"#15241e","--bg-surface-secondary":"#1b2f27","--bg-surface-elevated":"#1f382e","--border-theme":"#28473a","--border-theme-subtle":"#1b2f27","--text-main":"#e8f5e9","--text-muted":"#81c784","--color-primary":"#4caf50","--color-primary-hover":"#388e3c"}},Hr="openlearn_theme",Cn="openlearn_custom_themes",zs={};function Xi(e){return zs[e]?zs[e]:e in ms?ms[e]:ms.light}function qr(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function lm(e,t){if(typeof document>"u")return;zs[e]=t;const n=`openlearn-custom-theme-${e}`;let s=document.getElementById(n);s||(s=document.createElement("style"),s.id=n,document.head.appendChild(s));const r=Object.entries(t).map(([i,a])=>` ${i}: ${a};`).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/StudentView--uGxc5TJ.js","assets/vendor-pdf-D7rGevI1.js","assets/vendor-react-B0t7H3hh.js","assets/vendor-utils-m0Urvtws.js","assets/vendor-icons-BRmhY6fg.js","assets/vendor-motion-BFAPOs-b.js","assets/vendor-charts-qLbgF1eL.js","assets/vendor-pptx-C5-U7ieS.js","assets/TeacherView-D4Zsc0eZ.js","assets/ImportModal-D7L-KNhZ.js","assets/CourseWizardModal-Ck_-M8pk.js","assets/ImportLessonsModal-jBuIK453.js","assets/QuizGeneratorModal-BBEDssp7.js","assets/StudentPreviewModal-Bh8OZs0t.js","assets/LazyWhiteboard-BJwCEZAU.js","assets/LazyCourseware-CuiPxhDg.js","assets/ProcessLogsModal-DmFXg9mG.js","assets/CloudDriveModal-DEQ1nkNk.js","assets/SystemResourceLibraryModal-BVCclcqA.js","assets/BatchPickerModal-BpWu0Lil.js","assets/ExportWeightModal-DW2bu9Zz.js","assets/NotificationDetailModal-Baqnc5pU.js","assets/HelpTour-CMJbbGne.js","assets/CoursewareHubPanel-CaEizhxl.js"])))=>i.map(i=>d[i]);
2
+ import{R as De,r as f,j as o,u as Jf,g as Wl,b as Zf,d as ki,h as Ci,J as ia,i as oa,k as Yf}from"./vendor-react-B0t7H3hh.js";import{G as Ns,S as Kf,U as Gl,C as Ei,a as Mn,L as ji,A as aa,b as dn,c as Yi,P as Ni,d as la,D as ca,X as Ze,e as tt,f as Ut,g as Xf,h as ep,T as Ql,E as $s,B as Bs,R as Jl,i as tp,j as an,k as np,M as sp,l as rp,m as ip,n as op,H as Zl,o as ap,p as Yl,q as Kl,r as _t,s as Ti,t as lp,K as cp,u as up,v as fs,w as dp,x as Ts,y as hp,z as Ki,F as Xl,V as fp,I as pp,J as mp,N as Ps,O as gp,Z as xp,Q as yp,W as bp,Y as wp,_ as ec,$ as Sp,a0 as vp,a1 as kp,a2 as Cp,a3 as Ep,a4 as Is,a5 as Hr,a6 as jp,a7 as Np,a8 as Tp,a9 as Pp,aa as Ip,ab as tc,ac as Ap,ad as ua,ae as zp,af as da}from"./vendor-icons-BRmhY6fg.js";import{_ as Ee,E as _p}from"./vendor-pdf-D7rGevI1.js";import{e as Xi,f as hn,h as Vs}from"./vendor-utils-m0Urvtws.js";import{i as qr,g as Lp,s as nc,a as eo,b as sc,c as ha,d as Rp,e as Op,f as Mp,h as Dp,r as Fp,j as $p,k as rc,l as Bp,m as Vp,n as Up,o as Hp,S as qp,H as Wp,F as Lt,p as Gp,q as Qp,t as ic,u as As,v as fa,w as nt,x as oc,y as Jp,z as pa,A as Zp,B as zs,C as Pi,D as ma,E as Yp,G as Kp,I as Pt,J as Xp,K as em,L as tm,M as ga,N as nm,O as sm,P as xa,Q as rm,R as im,T as ps,U as om,V as am,W as ac,X as lm,Y as cm}from"./vendor-motion-BFAPOs-b.js";import{v as lc}from"./vendor-pptx-C5-U7ieS.js";import{R as ya}from"./vendor-charts-qLbgF1eL.js";const um=e=>{const t=e.split(/\r?\n/);if(t.length<2)return[];const n=t[0],s=[",",";"," "];let r=",",i=0;s.forEach(g=>{const y=n.split(g).length;y>i&&(i=y,r=g)});const a=g=>{const y=[];let v=!1,w="";for(let P=0;P<g.length;P++){const S=g[P];S==='"'?v=!v:S===r&&!v?(y.push(w.trim()),w=""):w+=S}return y.push(w.trim()),y},l=a(n).map(g=>g.toLowerCase().replace(/["'\r]/g,"").trim()),c=l.findIndex(g=>g.includes("student_number")||g.includes("studentnumber")||g.includes("student_id")||g.includes("studentid")||g.includes("学号")||g.includes("编号")||g.includes("id")&&!g.includes("class")&&!g.includes("lesson")),u=l.findIndex(g=>g.includes("name")||g.includes("姓名")||g.includes("student")&&!g.includes("num")&&!g.includes("id")||g.includes("学生")&&!g.includes("号")),d=l.findIndex(g=>g.includes("email")||g.includes("mail")||g.includes("邮箱")),p=u>=0?u:0,m=d>=0?d:1,h=[];for(let g=1;g<t.length;g++){if(!t[g].trim())continue;const y=a(t[g]),v=y[p]?y[p].replace(/["'\r]/g,"").trim():"",w=y[m]?y[m].replace(/["'\r]/g,"").trim():"",P=c>=0&&y[c]?y[c].replace(/["'\r]/g,"").trim():void 0;v&&h.push({name:v,email:w,...P?{student_number:P}:{}})}return h},ba={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"}},dm=De.memo(function({onLoginSuccess:t,lang:n}){const[s,r]=f.useState("teacher"),[i,a]=f.useState(null),[l,c]=f.useState(""),[u,d]=f.useState(""),[p,m]=f.useState(""),[h,g]=f.useState(!1),[y,v]=f.useState([]),[w,P]=f.useState(""),[S,j]=f.useState(""),[A,E]=f.useState(""),[R,F]=f.useState(""),[D,O]=f.useState(!1);f.useEffect(()=>{(async()=>{try{const I=await fetch("/api/students");if(I.ok){const N=await I.json();v(N),N.length>0&&P(N[0].id)}}catch(I){console.warn("Failed to fetch student roster for login selection:",I)}})()},[]),f.useEffect(()=>{(async()=>{try{const I=await fetch("/api/site-settings");if(I.ok){const N=await I.json();a(N)}}catch(I){console.warn("Failed to fetch site settings for login branding:",I)}})()},[]);const k=async L=>{if(L.preventDefault(),!l.trim()||!u){m(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{m(""),g(!0);const I=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:l.trim(),password:u})});if(I.ok){const N=await I.json();t(N.session)}else{const N=await I.json();m(N.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{m(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{g(!1)}},_=async L=>{L.preventDefault();const I=w||S.trim();if(!I){F(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!A.trim()){F(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{F(""),O(!0);const N=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:I,password:A.trim()})});if(N.ok){const z=await N.json();t(z.session)}else{const z=await N.json();F(z.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{F(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{O(!1)}};return o.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:[o.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),o.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),o.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:[o.jsxs("div",{className:"text-center mb-8",children:[i?.logoUrl?o.jsx("img",{src:i.logoUrl,alt:i.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):o.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:o.jsx(Ns,{size:32})}),o.jsxs("h1",{className:"text-2xl sm:text-3xl font-black text-white tracking-tight flex items-center justify-center gap-2",children:[i?.siteName||"OpenLearn Next"," ",o.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"})]}),o.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:i?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),o.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[o.jsxs("button",{onClick:()=>r("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 ${s==="teacher"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[o.jsx(Kf,{size:14}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),o.jsxs("button",{onClick:()=>r("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 ${s==="student"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[o.jsx(Gl,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?o.jsxs("form",{onSubmit:k,className:"space-y-4",children:[p&&o.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:[o.jsx(Ei,{size:15,className:"shrink-0"}),o.jsx("span",{children:p})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(Mn,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),o.jsx("input",{type:"text",value:l,onChange:L=>c(L.target.value),placeholder:n==="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})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(ji,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),o.jsx("input",{type:"password",value:u,onChange:L=>d(L.target.value),placeholder:n==="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})]}),o.jsxs("button",{type:"submit",disabled:h,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:[o.jsx("span",{children:h?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),o.jsx(aa,{size:15})]})]}):o.jsxs("form",{onSubmit:_,className:"space-y-4",children:[R&&o.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:[o.jsx(Ei,{size:15,className:"shrink-0"}),o.jsx("span",{children:R})]}),y.length>0?o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(Ns,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),o.jsx("select",{value:w,onChange:L=>{P(L.target.value),j("")},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:y.map(L=>o.jsxs("option",{value:L.id,children:[L.name," (",L.student_number||L.id,")"]},L.id))}),o.jsx("p",{className:"text-xs text-slate-500 font-medium",children:n==="zh"?"✨ 在沙盒调试中,你可以直接下拉选择已有的学生账户一键登录为该生。":"✨ Sandbox help: Quick select existing students on file to simulate as student."})]}):null,o.jsxs("div",{className:"relative flex py-2 items-center",children:[o.jsx("div",{className:"flex-grow border-t border-slate-850"}),o.jsx("span",{className:"flex-shrink mx-3 text-xs font-bold text-slate-500 uppercase tracking-wider",children:n==="zh"?"或手动输入学号":"Or input key manually"}),o.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(Mn,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),o.jsx("input",{type:"text",value:S,onChange:L=>{j(L.target.value),P("")},placeholder:n==="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"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(ji,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),o.jsx("input",{type:"password",required:!0,value:A,onChange:L=>E(L.target.value),placeholder:n==="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"})]}),o.jsxs("button",{type:"submit",disabled:D,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:[o.jsx("span",{children:D?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),o.jsx(aa,{size:15})]})]})]})]})});function hm({session:e,lang:t,onLogout:n,onProfile:s}){const[r,i]=f.useState(!1),a=f.useRef(null);f.useEffect(()=>{if(!r)return;const c=u=>{a.current&&!a.current.contains(u.target)&&i(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[r]);const l=(c,u)=>t==="zh"?c:u;return o.jsxs("div",{className:"relative",ref:a,children:[o.jsxs("button",{type:"button",onClick:()=>i(c=>!c),"aria-haspopup":"menu","aria-expanded":r,title:e.name,className:"flex items-center gap-1 rounded-full p-1 hover:bg-gray-100 transition-colors cursor-pointer",children:[o.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:e.avatar?o.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):o.jsx(Mn,{size:20})}),o.jsx(dn,{size:14,className:`text-gray-400 transition-transform duration-200 ${r?"rotate-180":""}`})]}),r&&o.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:[o.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[o.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:e.name,children:e.name}),o.jsx("p",{className:"text-xs text-gray-400 truncate",children:e.username})]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),s()},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:[o.jsx(Mn,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),n()},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:[o.jsx(Yi,{size:16}),l("注销登录","Sign Out")]})]})]})}const fm=[{id:"light",label:"浅色日间",description:"明亮通透,适合自然采光良好的日间课堂",previewBg:"#f8fafc",previewPrimary:"#4f46e5",category:"builtin"},{id:"dark",label:"暗夜极客",description:"深邃内敛,适合计算机房与夜间专注备课",previewBg:"#0b0f19",previewPrimary:"#6366f1",category:"builtin"},{id:"eyecare",label:"教学护眼",description:"柔和舒缓,防教室大屏眩光,减轻视觉疲劳",previewBg:"#f2f7f4",previewPrimary:"#2d6a4f",category:"builtin"},{id:"chalkboard",label:"经典黑板",description:"经典墨绿板书质感,沉浸式板书演练",previewBg:"#0e1713",previewPrimary:"#4caf50",category:"builtin"}],ms={light:{"--bg-app":"#f8fafc","--bg-surface":"#ffffff","--bg-surface-secondary":"#f1f5f9","--bg-surface-elevated":"#ffffff","--border-theme":"#e2e8f0","--border-theme-subtle":"#f1f5f9","--text-main":"#0f172a","--text-muted":"#64748b","--color-primary":"#4f46e5","--color-primary-hover":"#4338ca"},dark:{"--bg-app":"#0b0f19","--bg-surface":"#111827","--bg-surface-secondary":"#1f2937","--bg-surface-elevated":"#1f2937","--border-theme":"#374151","--border-theme-subtle":"#1f2937","--text-main":"#f9fafb","--text-muted":"#9ca3af","--color-primary":"#6366f1","--color-primary-hover":"#4f46e5"},eyecare:{"--bg-app":"#f2f7f4","--bg-surface":"#ffffff","--bg-surface-secondary":"#e4eee8","--bg-surface-elevated":"#ffffff","--border-theme":"#cbe0d5","--border-theme-subtle":"#dbeef2","--text-main":"#143526","--text-muted":"#3d6350","--color-primary":"#2d6a4f","--color-primary-hover":"#1b4332"},chalkboard:{"--bg-app":"#0e1713","--bg-surface":"#15241e","--bg-surface-secondary":"#1b2f27","--bg-surface-elevated":"#1f382e","--border-theme":"#28473a","--border-theme-subtle":"#1b2f27","--text-main":"#e8f5e9","--text-muted":"#81c784","--color-primary":"#4caf50","--color-primary-hover":"#388e3c"}},Wr="openlearn_theme",En="openlearn_custom_themes",_s={};function to(e){return _s[e]?_s[e]:e in ms?ms[e]:ms.light}function Gr(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function pm(e,t){if(typeof document>"u")return;_s[e]=t;const n=`openlearn-custom-theme-${e}`;let s=document.getElementById(n);s||(s=document.createElement("style"),s.id=n,document.head.appendChild(s));const r=Object.entries(t).map(([i,a])=>` ${i}: ${a};`).join(`
3
3
  `);s.textContent=`[data-theme="${e}"] {
4
4
  ${r}
5
- }`}function cm(e){if(typeof document>"u")return;delete zs[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function Wr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastThemeToIframes:t}=await Ee(async()=>{const{broadcastThemeToIframes:n}=await Promise.resolve().then(()=>cu);return{broadcastThemeToIframes:n}},void 0);t(e,Xi(e))}catch{}},0)}catch{}}const Bs=Yi((e,t)=>({theme:"light",availableThemes:[...am],initTheme:()=>{if(typeof window>"u")return;try{const r=localStorage.getItem(Cn);if(r){const i=JSON.parse(r);Array.isArray(i)&&i.forEach(a=>{a&&a.spec&&a.spec.id&&t().registerTheme(a.spec,a.cssVariables)})}}catch{}const s=localStorage.getItem(Hr)||"light";qr(s),e({theme:s}),Wr(s)},setTheme:n=>{qr(n),typeof window<"u"&&localStorage.setItem(Hr,n),e({theme:n}),Wr(n)},registerTheme:(n,s)=>{s&&lm(n.id,s),e(r=>({availableThemes:[...r.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{cm(n),e(s=>{const r=s.availableThemes.filter(a=>a.id!==n),i=s.theme===n?"light":s.theme;return s.theme===n&&(qr("light"),typeof window<"u"&&localStorage.setItem(Hr,"light"),Wr("light")),{availableThemes:r,theme:i}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const r=localStorage.getItem(Cn);let i=r?JSON.parse(r):[];Array.isArray(i)||(i=[]),i=i.filter(a=>a.spec.id!==n.id),i.push({spec:n,cssVariables:s}),localStorage.setItem(Cn,JSON.stringify(i))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(Cn);if(s){let r=JSON.parse(s);Array.isArray(r)&&(r=r.filter(i=>i.spec.id!==n),localStorage.setItem(Cn,JSON.stringify(r)))}}catch{}t().unregisterTheme(n)}})),um=[{id:"sapphire-classic",label:"高雅墨蓝",description:"深海午夜蓝灰与经典宝石蓝,适合沉浸式研究与高对比度投影",tokens:{"--bg-app":"#0d131f","--bg-surface":"#161f30","--bg-surface-secondary":"#1f2c42","--bg-surface-elevated":"#24334d","--border-theme":"#2e3f5b","--border-theme-subtle":"#1f2c42","--text-main":"#f1f5f9","--text-muted":"#94a3b8","--color-primary":"#3b82f6","--color-primary-hover":"#2563eb"}},{id:"sakura-dusk",label:"暮樱柔粉",description:"柔和日系樱花与温暖象牙白,适合美育、艺术与温馨研讨课堂",tokens:{"--bg-app":"#fff9fa","--bg-surface":"#ffffff","--bg-surface-secondary":"#fceef1","--bg-surface-elevated":"#ffffff","--border-theme":"#f5d5db","--border-theme-subtle":"#fae8eb","--text-main":"#3f2d33","--text-muted":"#8a6d76","--color-primary":"#f43f5e","--color-primary-hover":"#e11d48"}},{id:"autumn-amber",label:"复古秋叶",description:"温暖金秋落叶色调与复古羊皮纸质感,适合文科通识与阅读研讨",tokens:{"--bg-app":"#fdfaf6","--bg-surface":"#ffffff","--bg-surface-secondary":"#f5eee6","--bg-surface-elevated":"#ffffff","--border-theme":"#e6d7c3","--border-theme-subtle":"#ede3d5","--text-main":"#2d241e","--text-muted":"#7c6a59","--color-primary":"#d97706","--color-primary-hover":"#b45309"}},{id:"deep-sea-cyber",label:"深海极客",description:"赛博暗黑青绿冷光,极高现代感与未来科技探索质感",tokens:{"--bg-app":"#091014","--bg-surface":"#0f1a20","--bg-surface-secondary":"#16262e","--bg-surface-elevated":"#1d333e","--border-theme":"#25414e","--border-theme-subtle":"#16262e","--text-main":"#e0f2fe","--text-muted":"#7dd3fc","--color-primary":"#06b6d4","--color-primary-hover":"#0891b2"}}],ya={...ms.light};function dm({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:r,deleteCustomTheme:i}=Bs(),a=p.useId(),[l,c]=p.useState("custom-mytheme"),[u,d]=p.useState("我的专属主题"),[h,m]=p.useState("自定义教学调色板配置"),[f,g]=p.useState({...ya}),[y,C]=p.useState("none"),[w,P]=p.useState(""),[S,j]=p.useState(!1),[A,E]=p.useState(null);if(!e)return null;const R=s.filter(T=>T.category==="custom"),F=T=>{E(T),setTimeout(()=>E(null),3e3)},M=T=>{c(T.id),d(T.label),m(T.description),g({...T.tokens}),F(`已载入预设: ${T.label}`)},O=T=>{c(T.id),d(T.label),m(T.description);const D=Xi(T.id);D&&Object.keys(D).length>0&&g({...D}),F(`已载入自定义主题: ${T.label}`)},v=(T,D)=>{g(x=>({...x,[T]:D}))},_=()=>{const T=l.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!T){alert("请输入有效的主题标识 (ID)");return}const D={id:T,label:u.trim()||"未命名主题",description:h.trim()||"自定义主题",previewBg:f["--bg-app"]||"#ffffff",previewPrimary:f["--color-primary"]||"#4f46e5",category:"custom"};r(D,f),F(`主题「${D.label}」已保存并成功激活!`)},L=()=>{P(JSON.stringify({version:"1.0",id:l,label:u,description:h,tokens:f},null,2)),C("export")},I=()=>{P(""),C("import")},N=()=>{try{const T=JSON.parse(w);if(!T.tokens||typeof T.tokens!="object")throw new Error("缺少合法的 tokens 字段");T.id&&c(T.id),T.label&&d(T.label),T.description&&m(T.description),g(D=>({...D,...T.tokens})),C("none"),F("主题配置导入成功!")}catch(T){alert(`导入失败: ${T.message||"JSON 格式解析错误"}`)}},z=()=>{navigator.clipboard.writeText(w),j(!0),setTimeout(()=>j(!1),2e3)},U=[{key:"--color-primary",labelZh:"核心主色",labelEn:"Primary Brand Color",desc:"按钮高亮、焦点描边与重点图标"},{key:"--color-primary-hover",labelZh:"主色悬浮",labelEn:"Primary Hover",desc:"按钮悬停交互色"},{key:"--bg-app",labelZh:"全局底色",labelEn:"App Background",desc:"页面整体底衬颜色"},{key:"--bg-surface",labelZh:"卡片底色",labelEn:"Surface Background",desc:"白板卡片、浮层与侧边栏底色"},{key:"--bg-surface-secondary",labelZh:"次级底色",labelEn:"Secondary Surface",desc:"表格斑马纹、标签与次级面板"},{key:"--bg-surface-elevated",labelZh:"浮层底色",labelEn:"Elevated Surface",desc:"弹窗与下拉菜单浮动卡片"},{key:"--border-theme",labelZh:"主边框色",labelEn:"Border Color",desc:"卡片外边框、网格分割线"},{key:"--border-theme-subtle",labelZh:"弱化边框",labelEn:"Subtle Border",desc:"细微内部分割线"},{key:"--text-main",labelZh:"主文本色",labelEn:"Main Text",desc:"正文文字、标题"},{key:"--text-muted",labelZh:"弱化文本",labelEn:"Muted Text",desc:"副标题、辅助信息与提示说明"}];return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/60 backdrop-blur-xs animate-in fade-in duration-150",children:o.jsxs("div",{className:"bg-surface text-main border border-theme rounded-2xl shadow-2xl w-full max-w-6xl h-[92vh] max-h-[900px] flex flex-col overflow-hidden relative",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme shrink-0 bg-surface",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-primary-theme/10 rounded-xl text-primary-theme",children:o.jsx(Ci,{size:22})}),o.jsxs("div",{children:[o.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-main",children:[n==="zh"?"主题可视化设计器":"Theme Visual Designer",o.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-primary-theme/10 text-primary-theme font-medium",children:"v0.3.0"})]}),o.jsx("p",{className:"text-xs text-muted mt-0.5",children:n==="zh"?"自定义课堂交互色盘,支持一键载入创意预设、实时拟真沙箱预览与微前端自动同步":"Customize learning palettes with live previews, creative presets, and micro-frontend sync"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{onClick:I,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导入 JSON",children:[o.jsx(oa,{size:14}),n==="zh"?"导入配置":"Import"]}),o.jsxs("button",{onClick:L,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导出 JSON",children:[o.jsx(aa,{size:14}),n==="zh"?"导出配置":"Export"]}),o.jsx("button",{onClick:t,className:"p-2 rounded-lg text-muted hover:text-main hover:bg-surface-secondary transition-colors cursor-pointer ml-1","aria-label":"Close",children:o.jsx(Je,{size:18})})]})]}),A&&o.jsxs("div",{className:"absolute top-18 left-1/2 -translate-x-1/2 z-50 bg-primary-theme text-white px-4 py-2 rounded-xl shadow-lg text-xs font-medium flex items-center gap-2 animate-in fade-in slide-in-from-top-2",children:[o.jsx(tt,{size:14}),A]}),o.jsxs("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden",children:[o.jsxs("div",{className:"w-full md:w-1/2 border-r border-theme overflow-y-auto p-6 space-y-6",children:[o.jsxs("section",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Ut,{size:14,className:"text-amber-500"}),n==="zh"?"创意预设配色":"Creative Presets"]}),o.jsx("span",{className:"text-xs text-muted",children:"一键填入调色板"})]}),o.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:um.map(T=>o.jsxs("button",{onClick:()=>M(T),className:"flex flex-col p-3 rounded-xl border border-theme hover:border-primary-theme/50 hover:bg-surface-secondary text-left transition-all cursor-pointer group relative overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between w-full",children:[o.jsxs("div",{className:"font-semibold text-xs text-main flex items-center gap-2",children:[o.jsx("span",{className:"w-3 h-3 rounded-full border border-black/10 shrink-0",style:{backgroundColor:T.tokens["--color-primary"]}}),T.label]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:T.tokens["--bg-app"]}}),o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:T.tokens["--bg-surface"]}})]})]}),o.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:T.description})]},T.id))})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Gf,{size:14,className:"text-primary-theme"}),n==="zh"?"主题基础信息":"Theme Metadata"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-themeId`,className:"block text-xs font-medium text-muted mb-1",children:"主题标识 (ID)"}),o.jsx("input",{id:`${a}-themeId`,type:"text",value:l,onChange:T=>c(T.target.value),placeholder:"custom-mytheme",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-label`,className:"block text-xs font-medium text-muted mb-1",children:"主题名称"}),o.jsx("input",{id:`${a}-label`,type:"text",value:u,onChange:T=>d(T.target.value),placeholder:"我的专属主题",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-description`,className:"block text-xs font-medium text-muted mb-1",children:"主题描述"}),o.jsx("input",{id:`${a}-description`,type:"text",value:h,onChange:T=>m(T.target.value),placeholder:"针对特定课堂采光与演示场景优化",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Ci,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),o.jsx("div",{className:"space-y-2.5",children:U.map(T=>{const D=f[T.key]||"#000000";return o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme hover:bg-surface-secondary/40 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0 pr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-main",children:T.labelZh}),o.jsx("span",{className:"text-xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:T.key})]}),o.jsx("p",{className:"text-xs text-muted mt-0.5",children:T.desc})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("div",{className:"relative flex items-center",children:o.jsx("input",{type:"color",value:D.startsWith("#")&&D.length===7?D:"#4f46e5",onChange:x=>v(T.key,x.target.value),className:"w-8 h-8 rounded-lg cursor-pointer border border-theme p-0.5 bg-surface",title:"打开系统拾色器"})}),o.jsx("input",{type:"text",value:D,onChange:x=>v(T.key,x.target.value),className:"w-20 px-2 py-1 text-xs font-mono rounded-lg border border-theme bg-surface text-main text-center focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]},T.key)})})]}),R.length>0&&o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Qf,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),o.jsx("div",{className:"space-y-2",children:R.map(T=>o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme bg-surface-secondary/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[o.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 shrink-0",style:{backgroundColor:T.previewPrimary}}),o.jsxs("div",{className:"truncate",children:[o.jsx("div",{className:"text-xs font-semibold text-main truncate",children:T.label}),o.jsx("div",{className:"text-xs text-muted truncate",children:T.description})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[o.jsx("button",{onClick:()=>O(T),className:"px-2 py-1 text-xs rounded-md bg-surface border border-theme hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:"编辑"}),o.jsx("button",{onClick:()=>{confirm(`确定删除自定义主题「${T.label}」吗?`)&&(i(T.id),F(`已删除主题「${T.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:o.jsx(Ul,{size:13})})]})]},T.id))})]})]}),o.jsxs("div",{className:"w-full md:w-1/2 flex flex-col p-6 bg-surface-secondary/30 overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-muted",children:[o.jsx(Ms,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),o.jsxs("span",{className:"text-xs text-muted font-mono",children:["当前预览: ",u," (",l,")"]})]}),o.jsxs("div",{className:"flex-1 rounded-2xl border shadow-inner overflow-hidden flex flex-col transition-colors duration-200",style:{backgroundColor:f["--bg-app"]||"#f8fafc",borderColor:f["--border-theme"]||"#e2e8f0",color:f["--text-main"]||"#0f172a"},children:[o.jsxs("div",{className:"h-12 border-b px-4 flex items-center justify-between shrink-0",style:{backgroundColor:f["--bg-surface"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center font-bold text-white text-xs",style:{backgroundColor:f["--color-primary"]||"#4f46e5"},children:"OL"}),o.jsx("span",{className:"font-bold text-xs",style:{color:f["--text-main"]},children:"OpenLearn V2"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs px-2 py-0.5 rounded-md font-mono",style:{backgroundColor:f["--bg-surface-secondary"]||"#f1f5f9",color:f["--text-muted"]||"#64748b"},children:"10:30:00"}),o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white",style:{backgroundColor:f["--color-primary"]||"#4f46e5"},children:"T"})]})]}),o.jsxs("div",{className:"p-4 space-y-4 flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"p-4 rounded-xl border shadow-xs space-y-3",style:{backgroundColor:f["--bg-surface"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-start justify-between",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-bold text-sm",style:{color:f["--text-main"]},children:"高中物理实验探究:机械能守恒定律"}),o.jsx("p",{className:"text-xs mt-1",style:{color:f["--text-muted"]},children:"DIS 光电门传感器毫秒级数据回传与曲线拟合分析"})]}),o.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:f["--bg-surface-secondary"],color:f["--color-primary"],border:`1px solid ${f["--border-theme"]}`},children:"进行中"})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"光电门测速 (v)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--text-main"]},children:"2.43 m/s"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"动能增量 (ΔEk)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--color-primary"]},children:"0.589 J"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"误差率 (Err)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--text-main"]},children:"0.84 %"})]})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium text-white shadow-xs transition-opacity hover:opacity-90 cursor-pointer",style:{backgroundColor:f["--color-primary"]||"#4f46e5"},children:"开始数据采集"}),o.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer",style:{backgroundColor:f["--bg-surface-elevated"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0",color:f["--text-main"]||"#0f172a"},children:"重置实验"}),o.jsx("button",{className:"px-2 py-1.5 rounded-lg text-xs transition-colors cursor-pointer",style:{color:f["--text-muted"]},children:"查看教案"})]})]}),o.jsxs("div",{className:"p-3 rounded-xl border space-y-2",style:{backgroundColor:f["--bg-surface-elevated"]||"#ffffff",borderColor:f["--border-theme-subtle"]||"#f1f5f9"},children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold",style:{color:f["--text-main"]},children:"互动白板区域 (Whiteboard Canvas)"}),o.jsx("span",{className:"text-xs font-mono",style:{color:f["--text-muted"]},children:"60 FPS"})]}),o.jsxs("div",{className:"h-28 rounded-lg border border-dashed flex items-center justify-center p-3 relative overflow-hidden",style:{backgroundColor:f["--bg-app"],borderColor:f["--border-theme"]},children:[o.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center text-white font-bold shadow-md transform -rotate-6",style:{backgroundColor:f["--color-primary"]},children:o.jsx(Fs,{size:20})}),o.jsx("div",{className:"absolute bottom-2 right-2 text-xs font-mono px-1.5 py-0.5 rounded border",style:{backgroundColor:f["--bg-surface"],borderColor:f["--border-theme"],color:f["--text-muted"]},children:"iframe Bridge Sync Ready"})]})]})]})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-theme shrink-0 bg-surface",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("button",{onClick:()=>{g({...ya}),F("已重置为系统默认调色板")},className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",children:[o.jsx(Hl,{size:14}),n==="zh"?"重置默认":"Reset Defaults"]})}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 rounded-xl border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:n==="zh"?"关闭":"Close"}),o.jsxs("button",{onClick:_,className:"px-5 py-2 rounded-xl bg-primary-theme text-white text-xs font-semibold shadow-sm hover:opacity-95 transition-opacity flex items-center gap-1.5 cursor-pointer",children:[o.jsx(Jf,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),y!=="none"&&o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-xs flex items-center justify-center p-6 z-50 animate-in fade-in duration-100",children:o.jsxs("div",{className:"bg-surface border border-theme rounded-2xl p-5 w-full max-w-lg shadow-2xl space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"font-bold text-sm text-main flex items-center gap-2",children:y==="export"?o.jsxs(o.Fragment,{children:[o.jsx(aa,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):o.jsxs(o.Fragment,{children:[o.jsx(oa,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),o.jsx("button",{onClick:()=>C("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:o.jsx(Je,{size:16})})]}),o.jsx("div",{children:o.jsx("textarea",{value:w,readOnly:y==="export",onChange:T=>P(T.target.value),placeholder:y==="import"?"请在此粘贴主题导出的 JSON 字符串...":"",rows:10,className:"w-full p-3 font-mono text-xs rounded-xl border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme resize-none"})}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:y==="export"?o.jsx(o.Fragment,{children:o.jsxs("button",{onClick:z,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium flex items-center gap-1.5 cursor-pointer",children:[S?o.jsx(tt,{size:14}):o.jsx(an,{size:14}),S?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>C("none"),className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main cursor-pointer",children:n==="zh"?"取消":"Cancel"}),o.jsx("button",{onClick:N,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium cursor-pointer",children:n==="zh"?"解析并导入":"Parse & Import"})]})})]})})]})})}function hm({lang:e="zh"}){const[t,n]=p.useState(!1),[s,r]=p.useState(!1),i=p.useRef(null),{theme:a,availableThemes:l,setTheme:c}=Bs();p.useEffect(()=>{function d(h){i.current&&!i.current.contains(h.target)&&n(!1)}return t&&document.addEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]);const u=d=>{switch(d){case"dark":return o.jsx(Yf,{size:16,className:"text-indigo-400"});case"eyecare":return o.jsx(Ms,{size:16,className:"text-emerald-500"});case"chalkboard":return o.jsx(Ci,{size:16,className:"text-green-400"});case"light":default:return o.jsx(Zf,{size:16,className:"text-amber-500"})}};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"relative",ref:i,children:[o.jsx("button",{onClick:()=>n(!t),title:e==="zh"?"切换教学界面主题":"Switch Theme",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Theme selector",children:u(a)}),t&&o.jsxs("div",{className:"absolute right-0 mt-2 w-64 rounded-xl border border-theme bg-surface shadow-xl z-50 p-2 overflow-hidden animate-in fade-in zoom-in-95 duration-100",children:[o.jsxs("div",{className:"px-3 py-2 border-b border-theme-subtle mb-1",children:[o.jsx("div",{className:"text-xs font-semibold text-main uppercase tracking-wider",children:e==="zh"?"界面主题模式":"Interface Theme"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"针对不同教学采光与场景优化":"Optimized for diverse lighting"})]}),o.jsx("div",{className:"space-y-1",children:l.map(d=>{const h=a===d.id;return o.jsxs("button",{onClick:()=>{c(d.id),n(!1)},className:`w-full flex items-center justify-between px-3 py-2 rounded-lg text-left text-xs transition-all cursor-pointer ${h?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 dark:border-white/20 shrink-0 shadow-inner",style:{backgroundColor:d.previewPrimary}}),o.jsxs("div",{children:[o.jsx("div",{className:"font-medium text-main leading-none",children:d.label}),o.jsx("div",{className:"text-xs text-muted mt-1 leading-tight opacity-80",children:d.description})]})]}),h&&o.jsx(tt,{size:14,className:"text-primary-theme shrink-0"})]},d.id)})}),o.jsx("div",{className:"pt-2 mt-1 border-t border-theme-subtle",children:o.jsxs("button",{onClick:()=>{n(!1),r(!0)},className:"w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-primary-theme hover:bg-primary-theme/10 transition-colors cursor-pointer",children:[o.jsx(Ut,{size:14}),o.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),o.jsx(dm,{isOpen:s,onClose:()=>r(!1),lang:e})]})}const Gr="openlearn_font_scale",nn=85,sn=140,Qr=5,gs=100,ba=[{scale:90,labelZh:"紧凑 (90%)",labelEn:"Compact (90%)"},{scale:100,labelZh:"标准 (100%)",labelEn:"Standard (100%)"},{scale:110,labelZh:"中大 (110%)",labelEn:"Medium (110%)"},{scale:120,labelZh:"大号 (120%)",labelEn:"Large (120%)"},{scale:130,labelZh:"特大 (130%)",labelEn:"Extra Large (130%)"}];function Jr(e){if(typeof document>"u")return;const t=Math.min(sn,Math.max(nn,Math.round(e)));document.documentElement.style.fontSize=`${t}%`,document.documentElement.style.setProperty("--app-font-scale",(t/100).toFixed(2)),document.documentElement.setAttribute("data-font-scale",String(t))}function Zr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastFontScaleToIframes:t}=await Ee(async()=>{const{broadcastFontScaleToIframes:n}=await Promise.resolve().then(()=>cu);return{broadcastFontScaleToIframes:n}},void 0);t(e)}catch{}},0)}catch{}}const on=Yi((e,t)=>({scale:gs,minScale:nn,maxScale:sn,step:Qr,initFontSize:()=>{if(typeof window>"u")return;let n=gs;try{const s=localStorage.getItem(Gr);if(s){const r=Number(s);!isNaN(r)&&r>=nn&&r<=sn&&(n=r)}}catch{}Jr(n),e({scale:n}),Zr(n);try{window.addEventListener("storage",s=>{if(s.key===Gr&&s.newValue){const r=Number(s.newValue);!isNaN(r)&&r>=nn&&r<=sn&&(Jr(r),e({scale:r}),Zr(r))}})}catch{}},setScale:n=>{const s=Math.min(sn,Math.max(nn,Math.round(n)));if(Jr(s),typeof window<"u")try{localStorage.setItem(Gr,String(s))}catch{}e({scale:s}),Zr(s)},increaseScale:()=>{const n=t().scale,s=Math.min(sn,n+Qr);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max(nn,n-Qr);t().setScale(s)},resetScale:()=>{t().setScale(gs)}}));function rc({lang:e="zh"}){const[t,n]=p.useState(!1),s=p.useRef(null),{scale:r,minScale:i,maxScale:a,setScale:l,increaseScale:c,decreaseScale:u,resetScale:d}=on();p.useEffect(()=>{function f(g){s.current&&!s.current.contains(g.target)&&n(!1)}return t&&document.addEventListener("mousedown",f),()=>{document.removeEventListener("mousedown",f)}},[t]);const h=ba.find(f=>f.scale===r),m=r===gs;return o.jsxs("div",{className:"relative",ref:s,children:[o.jsxs("button",{type:"button",onClick:()=>n(!t),title:e==="zh"?`界面字体缩放: ${r}%(点击调节)`:`Interface Font Scaling: ${r}% (Click to adjust)`,className:`p-2 hover:bg-surface-secondary transition-colors rounded-lg border shadow-3xs flex items-center justify-center shrink-0 cursor-pointer relative ${m?"bg-surface border-theme text-main":"bg-primary-theme-light border-primary-theme text-primary-theme font-bold"}`,"aria-label":"Font size selector","aria-expanded":t,children:[o.jsx(Kf,{size:16}),!m&&o.jsxs("span",{className:"absolute -bottom-1 -right-1 text-xs px-1 py-0.2 rounded-full bg-primary-theme text-white font-extrabold leading-none shadow-xs",children:[r,"%"]})]}),t&&o.jsxs("div",{className:"absolute right-0 mt-2 w-72 rounded-xl border border-theme bg-surface shadow-xl z-50 p-3 overflow-hidden animate-in fade-in zoom-in-95 duration-100 select-none",children:[o.jsxs("div",{className:"px-1 pb-2 border-b border-theme-subtle mb-2.5 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs font-semibold text-main",children:e==="zh"?"界面字号大小":"Interface Font Size"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"全局等比缩放排版与文字":"Proportionally scale typography"})]}),!m&&o.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1 text-xs text-muted hover:text-primary-theme transition-colors cursor-pointer px-1.5 py-0.5 rounded hover:bg-surface-secondary",title:e==="zh"?"恢复默认 100%":"Reset to 100%",children:[o.jsx(Hl,{size:11}),o.jsx("span",{children:e==="zh"?"重置":"Reset"})]})]}),o.jsxs("div",{className:"bg-surface-secondary/70 rounded-lg p-2 flex items-center justify-between mb-3 border border-theme-subtle",children:[o.jsx("button",{type:"button",onClick:u,disabled:r<=i,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"减小字体 (A-)":"Decrease (A-)",children:o.jsx(Xf,{size:14})}),o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"text-sm font-black text-main leading-tight",children:[r,"%"]}),o.jsx("div",{className:"text-xs text-muted",children:h?e==="zh"?h.labelZh.split(" ")[0]:h.labelEn.split(" ")[0]:e==="zh"?"自定义比例":"Custom"})]}),o.jsx("button",{type:"button",onClick:c,disabled:r>=a,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"增大字体 (A+)":"Increase (A+)",children:o.jsx(ep,{size:14})})]}),o.jsxs("div",{className:"space-y-1 mb-3",children:[o.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wider px-1",children:e==="zh"?"常用档位":"Presets"}),o.jsx("div",{className:"grid grid-cols-1 gap-1",children:ba.map(f=>{const g=r===f.scale;return o.jsxs("button",{type:"button",onClick:()=>l(f.scale),className:`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs transition-all cursor-pointer ${g?"bg-primary-theme-light text-primary-theme font-bold border border-primary-theme/30":"text-main hover:bg-surface-secondary border border-transparent"}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-60"}),o.jsx("span",{children:e==="zh"?f.labelZh:f.labelEn})]}),g&&o.jsx(tt,{size:13,className:"text-primary-theme shrink-0"})]},f.scale)})})]}),o.jsxs("div",{className:"p-2.5 rounded-lg border border-theme-subtle bg-surface-secondary/40 mb-2",children:[o.jsxs("div",{className:"text-xs text-muted mb-1 flex items-center justify-between",children:[o.jsx("span",{children:e==="zh"?"实时效果预览":"Live Preview"}),o.jsxs("span",{children:[r,"%"]})]}),o.jsx("p",{className:"text-xs text-main font-medium leading-relaxed",children:e==="zh"?"让每一个文字都清晰舒适,智能赋能教学。":"Clear and comfortable typography empowers modern teaching."})]}),o.jsx("div",{className:"text-xs text-muted/80 text-center px-1",children:e==="zh"?"快捷键:Ctrl + Alt + 加号/减号":"Shortcut: Ctrl + Alt + +/-"})]})]})}function fm(e){const{activeRole:t,lang:n,teacherTab:s,studentViewStatus:r,session:i,activeStudentId:a,students:l,studentDashboardData:c,isNotificationsOpen:u,studentNotifications:d,unreadNotifications:h,readNotifications:m,dbConnected:f,dbStatus:g,siteInfo:y,setActiveStudentId:C,setReadNotifications:w,setIsSystemResourceLibraryOpen:P,setProfileOpen:S,setTeacherTab:j,setStudentViewStatus:A,setIsNotificationsOpen:E,setSelectedNotificationForModal:R,handleLogout:F,toggleLanguage:M,setActiveRole:O,isStudentLocked:v=!1,onBlockedNavigate:_}=e,L=t==="student"&&v,I=()=>{if(L){_?.();return}t==="teacher"?j("dashboard"):t==="student"&&A("dashboard")};return o.jsxs("header",{className:"h-16 border-b border-theme bg-surface text-main flex items-center px-6 justify-between shrink-0 shadow-sm relative z-20 transition-colors duration-200",children:[o.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[o.jsxs("button",{onClick:I,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:L?n==="zh"?"全班专注锁定中,无法返回系统总览":"Class focus locked — cannot return to dashboard":n==="zh"?"返回系统总览":"Back to Dashboard",children:[y.logoUrl?o.jsx("img",{src:y.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):o.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"}),o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:y.siteName||"OpenLearn Next"}),o.jsxs("span",{className:"text-xs font-medium text-slate-400 tracking-tight",children:["v","0.4.0"]}),y.slogan&&o.jsx("span",{className:"hidden md:inline text-xs text-slate-400 font-normal truncate max-w-[200px]",children:y.slogan})]})]}),o.jsxs("button",{onClick:I,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer ${t==="teacher"&&s==="dashboard"||t==="student"&&r==="dashboard"?"bg-indigo-50 text-indigo-700":"text-slate-600 hover:text-indigo-600 hover:bg-slate-100"} ${L?"opacity-50":""}`,children:[L?o.jsx(ki,{size:16}):o.jsx(ql,{size:16}),n==="zh"?"系统总览":"Dashboard"]}),t==="student"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),o.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[o.jsx(tp,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),t==="student"&&i?.role==="teacher"&&o.jsxs("div",{className:"flex items-center gap-2 bg-amber-50/90 border border-amber-200/80 px-2.5 py-1 rounded-lg shadow-2xs",children:[o.jsxs("span",{className:"text-xs font-semibold text-amber-800 flex items-center gap-1",children:[o.jsx(Ms,{size:13,className:"text-amber-600"}),n==="zh"?"模拟学生:":"View as:"]}),o.jsxs("select",{className:"border border-amber-300 rounded px-1.5 py-0.5 text-xs bg-white text-gray-800 font-medium focus:ring-1 focus:ring-amber-400 focus:outline-hidden",value:a||"",onChange:N=>C(N.target.value),children:[o.jsxs("option",{value:"",children:["-- ",n==="zh"?"选择学生":"Select Student"," --"]}),l.map(N=>o.jsx("option",{value:N.id,children:N.name},N.id))]}),O&&o.jsxs("button",{type:"button",onClick:()=>O("teacher"),className:"ml-1 px-2.5 py-1 bg-amber-600 hover:bg-amber-700 active:bg-amber-800 text-white text-xs font-bold rounded-md flex items-center gap-1 transition-all cursor-pointer shadow-2xs",title:n==="zh"?"退出模拟学生并返回教师端工作台":"Exit student view and return to teacher workspace",children:[o.jsx(Qi,{size:12}),n==="zh"?"返回教师端":"Exit Student View"]})]})]}),o.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[t==="student"&&a&&c&&o.jsxs("div",{className:"relative",children:[o.jsxs("button",{onClick:()=>E(!u),className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[o.jsx(Wl,{size:20}),h.length>0&&o.jsx("span",{className:"absolute top-1 right-1 bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full flex items-center justify-center min-w-[18px]",children:h.length})]}),u&&o.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:[o.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),h.length>0&&o.jsx("button",{onClick:async()=>{if(!a)return;try{const z=d.filter(U=>!m.has(U.id)).map(U=>fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:U.id})}));await Promise.all(z)}catch(z){console.error(z)}const N=new Set(m);d.forEach(z=>N.add(z.id)),w(N)},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),o.jsx("div",{className:"max-h-96 overflow-y-auto",children:d.length===0?o.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):o.jsx("div",{className:"divide-y divide-gray-100",children:d.map(N=>{const z=!m.has(N.id);return o.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${z?"bg-indigo-50/30":""}`,onClick:()=>{if(z){a&&fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:N.id})}).catch(console.error);const T=new Set(m);T.add(N.id),w(T)}const U=c?.assignments?.find(T=>T.id===N.relatedId);R({...N,assignment:U}),E(!1)},children:o.jsxs("div",{className:"flex gap-3",children:[o.jsx("div",{className:"mt-0.5",children:N.type==="new_assignment"?o.jsx(Gl,{size:16,className:"text-indigo-500"}):N.type==="rollcall_picked"?o.jsx(Ut,{size:16,className:"text-amber-500 animate-pulse"}):o.jsx(_t,{size:16,className:"text-green-500"})}),o.jsxs("div",{className:"flex-1",children:[o.jsx("div",{className:`text-sm ${z?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:N.title}),o.jsx("div",{className:`text-xs mt-0.5 ${z?"text-gray-600":"text-gray-500"}`,children:N.message})]}),z&&o.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},N.id)})})})]})]}),o.jsxs("button",{onClick:()=>P(!0),className:"flex items-center gap-1.5 hover:text-primary-theme transition-colors bg-surface text-main px-3 py-1.5 rounded-md border border-theme shadow-sm font-medium cursor-pointer",children:[o.jsx(Ei,{size:14,className:"text-emerald-500 animate-pulse"}),n==="zh"?"系统资源库":"System Resource Library"]}),o.jsx("button",{onClick:M,title:n==="zh"?"Switch to English":"切换为中文",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer",children:o.jsx(Ei,{size:16})}),o.jsx(rc,{lang:n}),o.jsx(hm,{lang:n}),(()=>{const N=g==="error"||!f?{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:n==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:g==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:n==="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:n==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return o.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 ${N.bg}`,title:N.label,children:[o.jsx(np,{size:15}),o.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[o.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${N.ping}`}),o.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${N.dot}`})]})]})})(),o.jsx(om,{session:i,lang:n,onLogout:F,onProfile:()=>S(!0)})]})]})}let _s=null;function ic(e){_s=e}function pm(){if(!_s)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return _s}function wt(){return _s}class mm{constructor(t){this.socket=t,ic(t)}emit(t,...n){this.socket.emit(t,...n)}on(t,n){this.socket.on(t,n)}off(t,n){this.socket.off(t,n)}disconnect(){this.socket.disconnect()}}const gm="openlearn_live_classroom_sync";class Ni{constructor(t=gm,n,s){this.channel=null,this.isDestroyed=!1,this.messageListeners=[],this.lessonId=null,this.classId=null,this.lessonId=n||null,this.classId=s||null,typeof window<"u"&&typeof window.BroadcastChannel<"u"&&(this.channel=new BroadcastChannel(t),this.channel.onmessage=i=>{this.isDestroyed||!i.data||this.emitToListeners(i.data)});const r=wt();if(r){const i=a=>{this.isDestroyed||!a?.message||this.lessonId&&a.lessonId&&a.lessonId!==this.lessonId||this.emitToListeners(a.message)};r.on("classroom:sync_message",i),this.socketCleanup=()=>{r.off("classroom:sync_message",i)}}}setLessonContext(t,n){this.lessonId=t,n!==void 0&&(this.classId=n)}emitToListeners(t){this.messageListeners.forEach(n=>{try{n(t)}catch(s){console.error("[ClassroomSyncChannel] Listener error:",s)}})}onMessage(t){return this.messageListeners.push(t),()=>{this.messageListeners=this.messageListeners.filter(n=>n!==t)}}postMessage(t){if(this.isDestroyed)return;if(this.channel)try{this.channel.postMessage(t)}catch(s){console.warn("[ClassroomSyncChannel] Failed to post message to BroadcastChannel:",s)}const n=wt();if(n&&this.lessonId)try{n.emit("teacher-sync-message",{lessonId:this.lessonId,message:t})}catch(s){console.warn("[ClassroomSyncChannel] Failed to emit socket sync message:",s)}}broadcastInitState(t){this.postMessage({type:"TEACHER_INIT_STATE",payload:t})}broadcastChangeLesson(t){this.lessonId=t,this.postMessage({type:"TEACHER_CHANGE_LESSON",payload:{lessonId:t,classId:this.classId}});const n=wt();n&&t&&n.emit("teacher-broadcast-lesson",{lessonId:t,classId:this.classId})}broadcastChangeSegment(t){this.postMessage({type:"TEACHER_CHANGE_SEGMENT",payload:{segmentId:t,lessonId:this.lessonId}});const n=wt();n&&this.lessonId&&t&&n.emit("teacher-broadcast-segment",{lessonId:this.lessonId,activeSegmentId:t})}broadcastChangeTab(t){this.postMessage({type:"TEACHER_CHANGE_TAB",payload:{tab:t,lessonId:this.lessonId}});const n=wt();n&&this.lessonId&&n.emit("teacher-broadcast-tab",{lessonId:this.lessonId,tab:t})}broadcastLockClass(t){this.postMessage({type:"TEACHER_LOCK_CLASS",payload:{locked:t,lessonId:this.lessonId,classId:this.classId}});const n=wt();n&&this.lessonId&&n.emit("teacher-broadcast-lock",{lessonId:this.lessonId,locked:t,classId:this.classId})}broadcastPickStudent(t,n){this.postMessage({type:"TEACHER_PICK_STUDENT",payload:{studentId:t,studentName:n}})}broadcastSyncTimer(t,n){this.postMessage({type:"TEACHER_SYNC_TIMER",payload:{timeRemaining:t,isRunning:n,lessonId:this.lessonId}})}broadcastCountdown(t){this.postMessage({type:"TEACHER_BROADCAST_COUNTDOWN",payload:t}),this.broadcastSyncTimer(t.timeRemaining,t.isRunning)}broadcastPingStudent(t,n){this.postMessage({type:"TEACHER_PING_STUDENT",payload:{studentId:t,message:n}});const s=wt();s&&this.lessonId&&s.emit("teacher-ping-student",{studentId:t,lessonId:this.lessonId,message:n})}broadcastFullscreen(t,n){const s=n||this.lessonId||void 0;this.postMessage({type:"TEACHER_BROADCAST_FULLSCREEN",payload:{elementId:t,lessonId:s}});const r=wt();r&&s&&r.emit("teacher-broadcast-fullscreen",{elementId:t,lessonId:s,classId:this.classId})}requestHandshake(){this.postMessage({type:"STUDENT_HANDSHAKE_REQUEST"})}acknowledgePick(t){this.postMessage({type:"STUDENT_ACKNOWLEDGE_PICK",payload:{studentId:t}})}sendHeartbeat(t){this.postMessage({type:"STUDENT_HEARTBEAT",payload:{studentId:t,timestamp:Date.now()}})}destroy(){this.isDestroyed=!0,this.messageListeners=[],this.socketCleanup&&(this.socketCleanup(),this.socketCleanup=void 0),this.channel&&(this.channel.close(),this.channel=null)}}const ln=Mn(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null})})),Hk=e=>$s(ln,e);function xm({open:e,session:t,lang:n,onClose:s,onSaved:r,onAvatar:i}){const[a,l]=p.useState(t.name),[c,u]=p.useState(!1),[d,h]=p.useState(null),m=p.useRef(null),[f,g]=p.useState(!1),[y,C]=p.useState(null),[w,P]=p.useState(!1),[S,j]=p.useState(""),[A,E]=p.useState(""),[R,F]=p.useState(""),[M,O]=p.useState(!1),[v,_]=p.useState(null),[L,I]=p.useState(!1);if(!e)return null;const N=(Q,X)=>n==="zh"?Q:X,z=t.role==="teacher"?t.subRole==="administrator"?N("管理员","Administrator"):N("教师","Teacher"):N("学生","Student"),U=a.trim(),T=U.length>0&&U!==t.name,D=async()=>{if(!(!T||c)){u(!0),h(null);try{const Q=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:U})}),X=await Q.json();if(!Q.ok){h(X.error||(n==="zh"?"保存失败":"Save failed"));return}r(X.name??U)}catch{h(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{u(!1)}}},x=S.length>0&&A.length>=8&&/[a-zA-Z]/.test(A)&&/[0-9]/.test(A)&&A===R,oe=async()=>{if(!(!x||M)){O(!0),_(null);try{const Q=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:S,newPassword:A})}),X=await Q.json();if(!Q.ok){_(X.error||(n==="zh"?"修改失败":"Change failed"));return}I(!0),j(""),E(""),F(""),P(!1)}catch{_(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{O(!1)}}},me=async Q=>{const X=Q.target.files?.[0];if(Q.target.value="",!!X){g(!0),C(null);try{const B=await new Promise((de,xe)=>{const ae=new FileReader;ae.onload=()=>de(ae.result),ae.onerror=()=>xe(ae.error),ae.readAsDataURL(X)}),Z=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:X.name,base64Data:B})}),re=await Z.json();if(!Z.ok){C(re.error||(n==="zh"?"上传失败":"Upload failed"));return}i?.(re.avatar)}catch{C(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}}},b=async()=>{g(!0),C(null);try{const Q=await fetch("/api/auth/avatar",{method:"DELETE"}),X=await Q.json().catch(()=>({}));if(!Q.ok){C(X.error||(n==="zh"?"移除失败":"Remove failed"));return}i?.(null)}catch{C(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}};return o.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:s,children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden",onClick:Q=>Q.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:N("个人资料","Profile")}),o.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:o.jsx(Je,{size:18})})]}),o.jsxs("div",{className:"p-5 space-y-5",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.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:t.avatar?o.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):o.jsx(On,{size:28})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:t.name}),o.jsx("p",{className:"text-xs text-gray-400",children:z}),o.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[o.jsx("button",{type:"button",onClick:()=>m.current?.click(),disabled:f,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:f?N("上传中…","Uploading…"):t.avatar?N("更换头像","Change avatar"):N("上传头像","Upload avatar")}),t.avatar&&o.jsx("button",{type:"button",onClick:b,disabled:f,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:N("移除","Remove")})]}),o.jsx("input",{ref:m,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:me})]})]}),y&&o.jsx("p",{className:"text-xs text-rose-500",children:y}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:N("显示名称","Display Name")}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("input",{value:a,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"}),o.jsx("button",{onClick:D,disabled:!T||c,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:c?N("保存中…","Saving…"):N("保存","Save")})]}),d&&o.jsx("p",{className:"text-xs text-rose-500 mt-1",children:d})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[o.jsx(sp,{size:16,className:"text-gray-400"}),N("修改密码","Change Password")]}),!w&&!L&&o.jsx("button",{onClick:()=>{P(!0),_(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:N("修改","Edit")})]}),L&&o.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[o.jsx(_t,{size:16}),N("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),w&&o.jsxs("div",{className:"mt-3 space-y-3",children:[o.jsx("input",{type:"password",value:S,onChange:Q=>j(Q.target.value),placeholder:N("当前密码","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"}),o.jsx("input",{type:"password",value:A,onChange:Q=>E(Q.target.value),placeholder:N("新密码(≥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"}),o.jsx("input",{type:"password",value:R,onChange:Q=>F(Q.target.value),placeholder:N("确认新密码","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"}),v&&o.jsx("p",{className:"text-xs text-rose-500",children:v}),o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{onClick:()=>{P(!1),j(""),E(""),F(""),_(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:N("取消","Cancel")}),o.jsx("button",{onClick:oe,disabled:!x||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?N("提交中…","Submitting…"):N("提交","Submit")})]})]})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:N("用户名(登录账号)","Username (login)")}),o.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:t.username,children:t.username||"-"})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:N("角色","Role")}),o.jsx("span",{className:"text-sm font-medium text-gray-700",children:z})]})]})]})]})})}class ym{constructor(){this.store=Mn(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId;this.store.setState(r=>{const i=new Map(r.items);return i.set(t.type,{config:{...t,pluginId:s},pluginId:s}),{items:i}})}unregister(t,n){this.store.setState(s=>{const r=s.items.get(t);if(!r||n&&r.pluginId!==n)return s;const i=new Map(s.items);return i.delete(t),{items:i}})}unregisterPlugin(t){this.store.setState(n=>{let s=!1;const r=new Map(n.items);for(const[i,a]of n.items)a.pluginId===t&&(r.delete(i),s=!0);return s?{items:r}:n})}get(t){return this.store.getState().items.get(t)?.config}getAll(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}has(t){return this.store.getState().items.has(t)}getStore(){return this.store}}const An=new ym;function qk(){return $s(An.getStore(),Uf(e=>Array.from(e.items.values()).map(t=>t.config)))}const Wk={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"}},Gk=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],bm=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:rp,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
5
+ }`}function mm(e){if(typeof document>"u")return;delete _s[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function Qr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastThemeToIframes:t}=await Ee(async()=>{const{broadcastThemeToIframes:n}=await Promise.resolve().then(()=>mu);return{broadcastThemeToIframes:n}},void 0);t(e,to(e))}catch{}},0)}catch{}}const Us=Xi((e,t)=>({theme:"light",availableThemes:[...fm],initTheme:()=>{if(typeof window>"u")return;try{const r=localStorage.getItem(En);if(r){const i=JSON.parse(r);Array.isArray(i)&&i.forEach(a=>{a&&a.spec&&a.spec.id&&t().registerTheme(a.spec,a.cssVariables)})}}catch{}const s=localStorage.getItem(Wr)||"light";Gr(s),e({theme:s}),Qr(s)},setTheme:n=>{Gr(n),typeof window<"u"&&localStorage.setItem(Wr,n),e({theme:n}),Qr(n)},registerTheme:(n,s)=>{s&&pm(n.id,s),e(r=>({availableThemes:[...r.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{mm(n),e(s=>{const r=s.availableThemes.filter(a=>a.id!==n),i=s.theme===n?"light":s.theme;return s.theme===n&&(Gr("light"),typeof window<"u"&&localStorage.setItem(Wr,"light"),Qr("light")),{availableThemes:r,theme:i}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const r=localStorage.getItem(En);let i=r?JSON.parse(r):[];Array.isArray(i)||(i=[]),i=i.filter(a=>a.spec.id!==n.id),i.push({spec:n,cssVariables:s}),localStorage.setItem(En,JSON.stringify(i))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(En);if(s){let r=JSON.parse(s);Array.isArray(r)&&(r=r.filter(i=>i.spec.id!==n),localStorage.setItem(En,JSON.stringify(r)))}}catch{}t().unregisterTheme(n)}})),gm=[{id:"sapphire-classic",label:"高雅墨蓝",description:"深海午夜蓝灰与经典宝石蓝,适合沉浸式研究与高对比度投影",tokens:{"--bg-app":"#0d131f","--bg-surface":"#161f30","--bg-surface-secondary":"#1f2c42","--bg-surface-elevated":"#24334d","--border-theme":"#2e3f5b","--border-theme-subtle":"#1f2c42","--text-main":"#f1f5f9","--text-muted":"#94a3b8","--color-primary":"#3b82f6","--color-primary-hover":"#2563eb"}},{id:"sakura-dusk",label:"暮樱柔粉",description:"柔和日系樱花与温暖象牙白,适合美育、艺术与温馨研讨课堂",tokens:{"--bg-app":"#fff9fa","--bg-surface":"#ffffff","--bg-surface-secondary":"#fceef1","--bg-surface-elevated":"#ffffff","--border-theme":"#f5d5db","--border-theme-subtle":"#fae8eb","--text-main":"#3f2d33","--text-muted":"#8a6d76","--color-primary":"#f43f5e","--color-primary-hover":"#e11d48"}},{id:"autumn-amber",label:"复古秋叶",description:"温暖金秋落叶色调与复古羊皮纸质感,适合文科通识与阅读研讨",tokens:{"--bg-app":"#fdfaf6","--bg-surface":"#ffffff","--bg-surface-secondary":"#f5eee6","--bg-surface-elevated":"#ffffff","--border-theme":"#e6d7c3","--border-theme-subtle":"#ede3d5","--text-main":"#2d241e","--text-muted":"#7c6a59","--color-primary":"#d97706","--color-primary-hover":"#b45309"}},{id:"deep-sea-cyber",label:"深海极客",description:"赛博暗黑青绿冷光,极高现代感与未来科技探索质感",tokens:{"--bg-app":"#091014","--bg-surface":"#0f1a20","--bg-surface-secondary":"#16262e","--bg-surface-elevated":"#1d333e","--border-theme":"#25414e","--border-theme-subtle":"#16262e","--text-main":"#e0f2fe","--text-muted":"#7dd3fc","--color-primary":"#06b6d4","--color-primary-hover":"#0891b2"}}],wa={...ms.light};function xm({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:r,deleteCustomTheme:i}=Us(),a=f.useId(),[l,c]=f.useState("custom-mytheme"),[u,d]=f.useState("我的专属主题"),[p,m]=f.useState("自定义教学调色板配置"),[h,g]=f.useState({...wa}),[y,v]=f.useState("none"),[w,P]=f.useState(""),[S,j]=f.useState(!1),[A,E]=f.useState(null);if(!e)return null;const R=s.filter(T=>T.category==="custom"),F=T=>{E(T),setTimeout(()=>E(null),3e3)},D=T=>{c(T.id),d(T.label),m(T.description),g({...T.tokens}),F(`已载入预设: ${T.label}`)},O=T=>{c(T.id),d(T.label),m(T.description);const M=to(T.id);M&&Object.keys(M).length>0&&g({...M}),F(`已载入自定义主题: ${T.label}`)},k=(T,M)=>{g(x=>({...x,[T]:M}))},_=()=>{const T=l.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!T){alert("请输入有效的主题标识 (ID)");return}const M={id:T,label:u.trim()||"未命名主题",description:p.trim()||"自定义主题",previewBg:h["--bg-app"]||"#ffffff",previewPrimary:h["--color-primary"]||"#4f46e5",category:"custom"};r(M,h),F(`主题「${M.label}」已保存并成功激活!`)},L=()=>{P(JSON.stringify({version:"1.0",id:l,label:u,description:p,tokens:h},null,2)),v("export")},I=()=>{P(""),v("import")},N=()=>{try{const T=JSON.parse(w);if(!T.tokens||typeof T.tokens!="object")throw new Error("缺少合法的 tokens 字段");T.id&&c(T.id),T.label&&d(T.label),T.description&&m(T.description),g(M=>({...M,...T.tokens})),v("none"),F("主题配置导入成功!")}catch(T){alert(`导入失败: ${T.message||"JSON 格式解析错误"}`)}},z=()=>{navigator.clipboard.writeText(w),j(!0),setTimeout(()=>j(!1),2e3)},U=[{key:"--color-primary",labelZh:"核心主色",labelEn:"Primary Brand Color",desc:"按钮高亮、焦点描边与重点图标"},{key:"--color-primary-hover",labelZh:"主色悬浮",labelEn:"Primary Hover",desc:"按钮悬停交互色"},{key:"--bg-app",labelZh:"全局底色",labelEn:"App Background",desc:"页面整体底衬颜色"},{key:"--bg-surface",labelZh:"卡片底色",labelEn:"Surface Background",desc:"白板卡片、浮层与侧边栏底色"},{key:"--bg-surface-secondary",labelZh:"次级底色",labelEn:"Secondary Surface",desc:"表格斑马纹、标签与次级面板"},{key:"--bg-surface-elevated",labelZh:"浮层底色",labelEn:"Elevated Surface",desc:"弹窗与下拉菜单浮动卡片"},{key:"--border-theme",labelZh:"主边框色",labelEn:"Border Color",desc:"卡片外边框、网格分割线"},{key:"--border-theme-subtle",labelZh:"弱化边框",labelEn:"Subtle Border",desc:"细微内部分割线"},{key:"--text-main",labelZh:"主文本色",labelEn:"Main Text",desc:"正文文字、标题"},{key:"--text-muted",labelZh:"弱化文本",labelEn:"Muted Text",desc:"副标题、辅助信息与提示说明"}];return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/60 backdrop-blur-xs animate-in fade-in duration-150",children:o.jsxs("div",{className:"bg-surface text-main border border-theme rounded-2xl shadow-2xl w-full max-w-6xl h-[92vh] max-h-[900px] flex flex-col overflow-hidden relative",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme shrink-0 bg-surface",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-primary-theme/10 rounded-xl text-primary-theme",children:o.jsx(Ni,{size:22})}),o.jsxs("div",{children:[o.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-main",children:[n==="zh"?"主题可视化设计器":"Theme Visual Designer",o.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-primary-theme/10 text-primary-theme font-medium",children:"v0.3.0"})]}),o.jsx("p",{className:"text-xs text-muted mt-0.5",children:n==="zh"?"自定义课堂交互色盘,支持一键载入创意预设、实时拟真沙箱预览与微前端自动同步":"Customize learning palettes with live previews, creative presets, and micro-frontend sync"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{onClick:I,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导入 JSON",children:[o.jsx(la,{size:14}),n==="zh"?"导入配置":"Import"]}),o.jsxs("button",{onClick:L,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导出 JSON",children:[o.jsx(ca,{size:14}),n==="zh"?"导出配置":"Export"]}),o.jsx("button",{onClick:t,className:"p-2 rounded-lg text-muted hover:text-main hover:bg-surface-secondary transition-colors cursor-pointer ml-1","aria-label":"Close",children:o.jsx(Ze,{size:18})})]})]}),A&&o.jsxs("div",{className:"absolute top-18 left-1/2 -translate-x-1/2 z-50 bg-primary-theme text-white px-4 py-2 rounded-xl shadow-lg text-xs font-medium flex items-center gap-2 animate-in fade-in slide-in-from-top-2",children:[o.jsx(tt,{size:14}),A]}),o.jsxs("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden",children:[o.jsxs("div",{className:"w-full md:w-1/2 border-r border-theme overflow-y-auto p-6 space-y-6",children:[o.jsxs("section",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Ut,{size:14,className:"text-amber-500"}),n==="zh"?"创意预设配色":"Creative Presets"]}),o.jsx("span",{className:"text-xs text-muted",children:"一键填入调色板"})]}),o.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:gm.map(T=>o.jsxs("button",{onClick:()=>D(T),className:"flex flex-col p-3 rounded-xl border border-theme hover:border-primary-theme/50 hover:bg-surface-secondary text-left transition-all cursor-pointer group relative overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between w-full",children:[o.jsxs("div",{className:"font-semibold text-xs text-main flex items-center gap-2",children:[o.jsx("span",{className:"w-3 h-3 rounded-full border border-black/10 shrink-0",style:{backgroundColor:T.tokens["--color-primary"]}}),T.label]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:T.tokens["--bg-app"]}}),o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:T.tokens["--bg-surface"]}})]})]}),o.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:T.description})]},T.id))})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Xf,{size:14,className:"text-primary-theme"}),n==="zh"?"主题基础信息":"Theme Metadata"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-themeId`,className:"block text-xs font-medium text-muted mb-1",children:"主题标识 (ID)"}),o.jsx("input",{id:`${a}-themeId`,type:"text",value:l,onChange:T=>c(T.target.value),placeholder:"custom-mytheme",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-label`,className:"block text-xs font-medium text-muted mb-1",children:"主题名称"}),o.jsx("input",{id:`${a}-label`,type:"text",value:u,onChange:T=>d(T.target.value),placeholder:"我的专属主题",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-description`,className:"block text-xs font-medium text-muted mb-1",children:"主题描述"}),o.jsx("input",{id:`${a}-description`,type:"text",value:p,onChange:T=>m(T.target.value),placeholder:"针对特定课堂采光与演示场景优化",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Ni,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),o.jsx("div",{className:"space-y-2.5",children:U.map(T=>{const M=h[T.key]||"#000000";return o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme hover:bg-surface-secondary/40 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0 pr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-main",children:T.labelZh}),o.jsx("span",{className:"text-xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:T.key})]}),o.jsx("p",{className:"text-xs text-muted mt-0.5",children:T.desc})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("div",{className:"relative flex items-center",children:o.jsx("input",{type:"color",value:M.startsWith("#")&&M.length===7?M:"#4f46e5",onChange:x=>k(T.key,x.target.value),className:"w-8 h-8 rounded-lg cursor-pointer border border-theme p-0.5 bg-surface",title:"打开系统拾色器"})}),o.jsx("input",{type:"text",value:M,onChange:x=>k(T.key,x.target.value),className:"w-20 px-2 py-1 text-xs font-mono rounded-lg border border-theme bg-surface text-main text-center focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]},T.key)})})]}),R.length>0&&o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(ep,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),o.jsx("div",{className:"space-y-2",children:R.map(T=>o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme bg-surface-secondary/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[o.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 shrink-0",style:{backgroundColor:T.previewPrimary}}),o.jsxs("div",{className:"truncate",children:[o.jsx("div",{className:"text-xs font-semibold text-main truncate",children:T.label}),o.jsx("div",{className:"text-xs text-muted truncate",children:T.description})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[o.jsx("button",{onClick:()=>O(T),className:"px-2 py-1 text-xs rounded-md bg-surface border border-theme hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:"编辑"}),o.jsx("button",{onClick:()=>{confirm(`确定删除自定义主题「${T.label}」吗?`)&&(i(T.id),F(`已删除主题「${T.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:o.jsx(Ql,{size:13})})]})]},T.id))})]})]}),o.jsxs("div",{className:"w-full md:w-1/2 flex flex-col p-6 bg-surface-secondary/30 overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-muted",children:[o.jsx($s,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),o.jsxs("span",{className:"text-xs text-muted font-mono",children:["当前预览: ",u," (",l,")"]})]}),o.jsxs("div",{className:"flex-1 rounded-2xl border shadow-inner overflow-hidden flex flex-col transition-colors duration-200",style:{backgroundColor:h["--bg-app"]||"#f8fafc",borderColor:h["--border-theme"]||"#e2e8f0",color:h["--text-main"]||"#0f172a"},children:[o.jsxs("div",{className:"h-12 border-b px-4 flex items-center justify-between shrink-0",style:{backgroundColor:h["--bg-surface"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center font-bold text-white text-xs",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"OL"}),o.jsx("span",{className:"font-bold text-xs",style:{color:h["--text-main"]},children:"OpenLearn V2"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs px-2 py-0.5 rounded-md font-mono",style:{backgroundColor:h["--bg-surface-secondary"]||"#f1f5f9",color:h["--text-muted"]||"#64748b"},children:"10:30:00"}),o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"T"})]})]}),o.jsxs("div",{className:"p-4 space-y-4 flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"p-4 rounded-xl border shadow-xs space-y-3",style:{backgroundColor:h["--bg-surface"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-start justify-between",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-bold text-sm",style:{color:h["--text-main"]},children:"高中物理实验探究:机械能守恒定律"}),o.jsx("p",{className:"text-xs mt-1",style:{color:h["--text-muted"]},children:"DIS 光电门传感器毫秒级数据回传与曲线拟合分析"})]}),o.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:h["--bg-surface-secondary"],color:h["--color-primary"],border:`1px solid ${h["--border-theme"]}`},children:"进行中"})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"光电门测速 (v)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"2.43 m/s"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"动能增量 (ΔEk)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--color-primary"]},children:"0.589 J"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"误差率 (Err)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"0.84 %"})]})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium text-white shadow-xs transition-opacity hover:opacity-90 cursor-pointer",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"开始数据采集"}),o.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer",style:{backgroundColor:h["--bg-surface-elevated"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0",color:h["--text-main"]||"#0f172a"},children:"重置实验"}),o.jsx("button",{className:"px-2 py-1.5 rounded-lg text-xs transition-colors cursor-pointer",style:{color:h["--text-muted"]},children:"查看教案"})]})]}),o.jsxs("div",{className:"p-3 rounded-xl border space-y-2",style:{backgroundColor:h["--bg-surface-elevated"]||"#ffffff",borderColor:h["--border-theme-subtle"]||"#f1f5f9"},children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold",style:{color:h["--text-main"]},children:"互动白板区域 (Whiteboard Canvas)"}),o.jsx("span",{className:"text-xs font-mono",style:{color:h["--text-muted"]},children:"60 FPS"})]}),o.jsxs("div",{className:"h-28 rounded-lg border border-dashed flex items-center justify-center p-3 relative overflow-hidden",style:{backgroundColor:h["--bg-app"],borderColor:h["--border-theme"]},children:[o.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center text-white font-bold shadow-md transform -rotate-6",style:{backgroundColor:h["--color-primary"]},children:o.jsx(Bs,{size:20})}),o.jsx("div",{className:"absolute bottom-2 right-2 text-xs font-mono px-1.5 py-0.5 rounded border",style:{backgroundColor:h["--bg-surface"],borderColor:h["--border-theme"],color:h["--text-muted"]},children:"iframe Bridge Sync Ready"})]})]})]})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-theme shrink-0 bg-surface",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("button",{onClick:()=>{g({...wa}),F("已重置为系统默认调色板")},className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",children:[o.jsx(Jl,{size:14}),n==="zh"?"重置默认":"Reset Defaults"]})}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 rounded-xl border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:n==="zh"?"关闭":"Close"}),o.jsxs("button",{onClick:_,className:"px-5 py-2 rounded-xl bg-primary-theme text-white text-xs font-semibold shadow-sm hover:opacity-95 transition-opacity flex items-center gap-1.5 cursor-pointer",children:[o.jsx(tp,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),y!=="none"&&o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-xs flex items-center justify-center p-6 z-50 animate-in fade-in duration-100",children:o.jsxs("div",{className:"bg-surface border border-theme rounded-2xl p-5 w-full max-w-lg shadow-2xl space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"font-bold text-sm text-main flex items-center gap-2",children:y==="export"?o.jsxs(o.Fragment,{children:[o.jsx(ca,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):o.jsxs(o.Fragment,{children:[o.jsx(la,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),o.jsx("button",{onClick:()=>v("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:o.jsx(Ze,{size:16})})]}),o.jsx("div",{children:o.jsx("textarea",{value:w,readOnly:y==="export",onChange:T=>P(T.target.value),placeholder:y==="import"?"请在此粘贴主题导出的 JSON 字符串...":"",rows:10,className:"w-full p-3 font-mono text-xs rounded-xl border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme resize-none"})}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:y==="export"?o.jsx(o.Fragment,{children:o.jsxs("button",{onClick:z,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium flex items-center gap-1.5 cursor-pointer",children:[S?o.jsx(tt,{size:14}):o.jsx(an,{size:14}),S?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>v("none"),className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main cursor-pointer",children:n==="zh"?"取消":"Cancel"}),o.jsx("button",{onClick:N,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium cursor-pointer",children:n==="zh"?"解析并导入":"Parse & Import"})]})})]})})]})})}function ym({lang:e="zh"}){const[t,n]=f.useState(!1),[s,r]=f.useState(!1),i=f.useRef(null),{theme:a,availableThemes:l,setTheme:c}=Us();f.useEffect(()=>{function d(p){i.current&&!i.current.contains(p.target)&&n(!1)}return t&&document.addEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]);const u=d=>{switch(d){case"dark":return o.jsx(sp,{size:16,className:"text-indigo-400"});case"eyecare":return o.jsx($s,{size:16,className:"text-emerald-500"});case"chalkboard":return o.jsx(Ni,{size:16,className:"text-green-400"});case"light":default:return o.jsx(np,{size:16,className:"text-amber-500"})}};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"relative",ref:i,children:[o.jsx("button",{onClick:()=>n(!t),title:e==="zh"?"切换教学界面主题":"Switch Theme",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Theme selector",children:u(a)}),t&&o.jsxs("div",{className:"absolute right-0 mt-2 w-64 rounded-xl border border-theme bg-surface shadow-xl z-50 p-2 overflow-hidden animate-in fade-in zoom-in-95 duration-100",children:[o.jsxs("div",{className:"px-3 py-2 border-b border-theme-subtle mb-1",children:[o.jsx("div",{className:"text-xs font-semibold text-main uppercase tracking-wider",children:e==="zh"?"界面主题模式":"Interface Theme"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"针对不同教学采光与场景优化":"Optimized for diverse lighting"})]}),o.jsx("div",{className:"space-y-1",children:l.map(d=>{const p=a===d.id;return o.jsxs("button",{onClick:()=>{c(d.id),n(!1)},className:`w-full flex items-center justify-between px-3 py-2 rounded-lg text-left text-xs transition-all cursor-pointer ${p?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 dark:border-white/20 shrink-0 shadow-inner",style:{backgroundColor:d.previewPrimary}}),o.jsxs("div",{children:[o.jsx("div",{className:"font-medium text-main leading-none",children:d.label}),o.jsx("div",{className:"text-xs text-muted mt-1 leading-tight opacity-80",children:d.description})]})]}),p&&o.jsx(tt,{size:14,className:"text-primary-theme shrink-0"})]},d.id)})}),o.jsx("div",{className:"pt-2 mt-1 border-t border-theme-subtle",children:o.jsxs("button",{onClick:()=>{n(!1),r(!0)},className:"w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-primary-theme hover:bg-primary-theme/10 transition-colors cursor-pointer",children:[o.jsx(Ut,{size:14}),o.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),o.jsx(xm,{isOpen:s,onClose:()=>r(!1),lang:e})]})}const Jr="openlearn_font_scale",nn=85,sn=140,Zr=5,gs=100,Sa=[{scale:90,labelZh:"紧凑 (90%)",labelEn:"Compact (90%)"},{scale:100,labelZh:"标准 (100%)",labelEn:"Standard (100%)"},{scale:110,labelZh:"中大 (110%)",labelEn:"Medium (110%)"},{scale:120,labelZh:"大号 (120%)",labelEn:"Large (120%)"},{scale:130,labelZh:"特大 (130%)",labelEn:"Extra Large (130%)"}];function Yr(e){if(typeof document>"u")return;const t=Math.min(sn,Math.max(nn,Math.round(e)));document.documentElement.style.fontSize=`${t}%`,document.documentElement.style.setProperty("--app-font-scale",(t/100).toFixed(2)),document.documentElement.setAttribute("data-font-scale",String(t))}function Kr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastFontScaleToIframes:t}=await Ee(async()=>{const{broadcastFontScaleToIframes:n}=await Promise.resolve().then(()=>mu);return{broadcastFontScaleToIframes:n}},void 0);t(e)}catch{}},0)}catch{}}const on=Xi((e,t)=>({scale:gs,minScale:nn,maxScale:sn,step:Zr,initFontSize:()=>{if(typeof window>"u")return;let n=gs;try{const s=localStorage.getItem(Jr);if(s){const r=Number(s);!isNaN(r)&&r>=nn&&r<=sn&&(n=r)}}catch{}Yr(n),e({scale:n}),Kr(n);try{window.addEventListener("storage",s=>{if(s.key===Jr&&s.newValue){const r=Number(s.newValue);!isNaN(r)&&r>=nn&&r<=sn&&(Yr(r),e({scale:r}),Kr(r))}})}catch{}},setScale:n=>{const s=Math.min(sn,Math.max(nn,Math.round(n)));if(Yr(s),typeof window<"u")try{localStorage.setItem(Jr,String(s))}catch{}e({scale:s}),Kr(s)},increaseScale:()=>{const n=t().scale,s=Math.min(sn,n+Zr);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max(nn,n-Zr);t().setScale(s)},resetScale:()=>{t().setScale(gs)}}));function cc({lang:e="zh"}){const[t,n]=f.useState(!1),s=f.useRef(null),{scale:r,minScale:i,maxScale:a,setScale:l,increaseScale:c,decreaseScale:u,resetScale:d}=on();f.useEffect(()=>{function h(g){s.current&&!s.current.contains(g.target)&&n(!1)}return t&&document.addEventListener("mousedown",h),()=>{document.removeEventListener("mousedown",h)}},[t]);const p=Sa.find(h=>h.scale===r),m=r===gs;return o.jsxs("div",{className:"relative",ref:s,children:[o.jsxs("button",{type:"button",onClick:()=>n(!t),title:e==="zh"?`界面字体缩放: ${r}%(点击调节)`:`Interface Font Scaling: ${r}% (Click to adjust)`,className:`p-2 hover:bg-surface-secondary transition-colors rounded-lg border shadow-3xs flex items-center justify-center shrink-0 cursor-pointer relative ${m?"bg-surface border-theme text-main":"bg-primary-theme-light border-primary-theme text-primary-theme font-bold"}`,"aria-label":"Font size selector","aria-expanded":t,children:[o.jsx(rp,{size:16}),!m&&o.jsxs("span",{className:"absolute -bottom-1 -right-1 text-xs px-1 py-0.2 rounded-full bg-primary-theme text-white font-extrabold leading-none shadow-xs",children:[r,"%"]})]}),t&&o.jsxs("div",{className:"absolute right-0 mt-2 w-72 rounded-xl border border-theme bg-surface shadow-xl z-50 p-3 overflow-hidden animate-in fade-in zoom-in-95 duration-100 select-none",children:[o.jsxs("div",{className:"px-1 pb-2 border-b border-theme-subtle mb-2.5 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs font-semibold text-main",children:e==="zh"?"界面字号大小":"Interface Font Size"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"全局等比缩放排版与文字":"Proportionally scale typography"})]}),!m&&o.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1 text-xs text-muted hover:text-primary-theme transition-colors cursor-pointer px-1.5 py-0.5 rounded hover:bg-surface-secondary",title:e==="zh"?"恢复默认 100%":"Reset to 100%",children:[o.jsx(Jl,{size:11}),o.jsx("span",{children:e==="zh"?"重置":"Reset"})]})]}),o.jsxs("div",{className:"bg-surface-secondary/70 rounded-lg p-2 flex items-center justify-between mb-3 border border-theme-subtle",children:[o.jsx("button",{type:"button",onClick:u,disabled:r<=i,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"减小字体 (A-)":"Decrease (A-)",children:o.jsx(ip,{size:14})}),o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"text-sm font-black text-main leading-tight",children:[r,"%"]}),o.jsx("div",{className:"text-xs text-muted",children:p?e==="zh"?p.labelZh.split(" ")[0]:p.labelEn.split(" ")[0]:e==="zh"?"自定义比例":"Custom"})]}),o.jsx("button",{type:"button",onClick:c,disabled:r>=a,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"增大字体 (A+)":"Increase (A+)",children:o.jsx(op,{size:14})})]}),o.jsxs("div",{className:"space-y-1 mb-3",children:[o.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wider px-1",children:e==="zh"?"常用档位":"Presets"}),o.jsx("div",{className:"grid grid-cols-1 gap-1",children:Sa.map(h=>{const g=r===h.scale;return o.jsxs("button",{type:"button",onClick:()=>l(h.scale),className:`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs transition-all cursor-pointer ${g?"bg-primary-theme-light text-primary-theme font-bold border border-primary-theme/30":"text-main hover:bg-surface-secondary border border-transparent"}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-60"}),o.jsx("span",{children:e==="zh"?h.labelZh:h.labelEn})]}),g&&o.jsx(tt,{size:13,className:"text-primary-theme shrink-0"})]},h.scale)})})]}),o.jsxs("div",{className:"p-2.5 rounded-lg border border-theme-subtle bg-surface-secondary/40 mb-2",children:[o.jsxs("div",{className:"text-xs text-muted mb-1 flex items-center justify-between",children:[o.jsx("span",{children:e==="zh"?"实时效果预览":"Live Preview"}),o.jsxs("span",{children:[r,"%"]})]}),o.jsx("p",{className:"text-xs text-main font-medium leading-relaxed",children:e==="zh"?"让每一个文字都清晰舒适,智能赋能教学。":"Clear and comfortable typography empowers modern teaching."})]}),o.jsx("div",{className:"text-xs text-muted/80 text-center px-1",children:e==="zh"?"快捷键:Ctrl + Alt + 加号/减号":"Shortcut: Ctrl + Alt + +/-"})]})]})}function bm(e){const{activeRole:t,lang:n,teacherTab:s,studentViewStatus:r,session:i,activeStudentId:a,students:l,studentDashboardData:c,isNotificationsOpen:u,studentNotifications:d,unreadNotifications:p,readNotifications:m,dbConnected:h,dbStatus:g,siteInfo:y,setActiveStudentId:v,setReadNotifications:w,setIsSystemResourceLibraryOpen:P,setProfileOpen:S,setTeacherTab:j,setStudentViewStatus:A,setIsNotificationsOpen:E,setSelectedNotificationForModal:R,handleLogout:F,toggleLanguage:D,setActiveRole:O,isStudentLocked:k=!1,onBlockedNavigate:_}=e,L=t==="student"&&k,I=()=>{if(L){_?.();return}t==="teacher"?j("dashboard"):t==="student"&&A("dashboard")};return o.jsxs("header",{className:"h-16 border-b border-theme bg-surface text-main flex items-center px-6 justify-between shrink-0 shadow-sm relative z-20 transition-colors duration-200",children:[o.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[o.jsxs("button",{onClick:I,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:L?n==="zh"?"全班专注锁定中,无法返回系统总览":"Class focus locked — cannot return to dashboard":n==="zh"?"返回系统总览":"Back to Dashboard",children:[y.logoUrl?o.jsx("img",{src:y.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):o.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"}),o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:y.siteName||"OpenLearn Next"}),o.jsxs("span",{className:"text-xs font-medium text-slate-400 tracking-tight",children:["v","0.4.2"]}),y.slogan&&o.jsx("span",{className:"hidden md:inline text-xs text-slate-400 font-normal truncate max-w-[200px]",children:y.slogan})]})]}),o.jsxs("button",{onClick:I,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer ${t==="teacher"&&s==="dashboard"||t==="student"&&r==="dashboard"?"bg-indigo-50 text-indigo-700":"text-slate-600 hover:text-indigo-600 hover:bg-slate-100"} ${L?"opacity-50":""}`,children:[L?o.jsx(ji,{size:16}):o.jsx(Zl,{size:16}),n==="zh"?"系统总览":"Dashboard"]}),t==="student"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),o.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[o.jsx(ap,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),t==="student"&&i?.role==="teacher"&&o.jsxs("div",{className:"flex items-center gap-2 bg-amber-50/90 border border-amber-200/80 px-2.5 py-1 rounded-lg shadow-2xs",children:[o.jsxs("span",{className:"text-xs font-semibold text-amber-800 flex items-center gap-1",children:[o.jsx($s,{size:13,className:"text-amber-600"}),n==="zh"?"模拟学生:":"View as:"]}),o.jsxs("select",{className:"border border-amber-300 rounded px-1.5 py-0.5 text-xs bg-white text-gray-800 font-medium focus:ring-1 focus:ring-amber-400 focus:outline-hidden",value:a||"",onChange:N=>v(N.target.value),children:[o.jsxs("option",{value:"",children:["-- ",n==="zh"?"选择学生":"Select Student"," --"]}),l.map(N=>o.jsx("option",{value:N.id,children:N.name},N.id))]}),O&&o.jsxs("button",{type:"button",onClick:()=>O("teacher"),className:"ml-1 px-2.5 py-1 bg-amber-600 hover:bg-amber-700 active:bg-amber-800 text-white text-xs font-bold rounded-md flex items-center gap-1 transition-all cursor-pointer shadow-2xs",title:n==="zh"?"退出模拟学生并返回教师端工作台":"Exit student view and return to teacher workspace",children:[o.jsx(Yi,{size:12}),n==="zh"?"返回教师端":"Exit Student View"]})]})]}),o.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[t==="student"&&a&&c&&o.jsxs("div",{className:"relative",children:[o.jsxs("button",{onClick:()=>E(!u),className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[o.jsx(Yl,{size:20}),p.length>0&&o.jsx("span",{className:"absolute top-1 right-1 bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full flex items-center justify-center min-w-[18px]",children:p.length})]}),u&&o.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:[o.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),p.length>0&&o.jsx("button",{onClick:async()=>{if(!a)return;try{const z=d.filter(U=>!m.has(U.id)).map(U=>fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:U.id})}));await Promise.all(z)}catch(z){console.error(z)}const N=new Set(m);d.forEach(z=>N.add(z.id)),w(N)},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),o.jsx("div",{className:"max-h-96 overflow-y-auto",children:d.length===0?o.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):o.jsx("div",{className:"divide-y divide-gray-100",children:d.map(N=>{const z=!m.has(N.id);return o.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${z?"bg-indigo-50/30":""}`,onClick:()=>{if(z){a&&fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:N.id})}).catch(console.error);const T=new Set(m);T.add(N.id),w(T)}const U=c?.assignments?.find(T=>T.id===N.relatedId);R({...N,assignment:U}),E(!1)},children:o.jsxs("div",{className:"flex gap-3",children:[o.jsx("div",{className:"mt-0.5",children:N.type==="new_assignment"?o.jsx(Kl,{size:16,className:"text-indigo-500"}):N.type==="rollcall_picked"?o.jsx(Ut,{size:16,className:"text-amber-500 animate-pulse"}):o.jsx(_t,{size:16,className:"text-green-500"})}),o.jsxs("div",{className:"flex-1",children:[o.jsx("div",{className:`text-sm ${z?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:N.title}),o.jsx("div",{className:`text-xs mt-0.5 ${z?"text-gray-600":"text-gray-500"}`,children:N.message})]}),z&&o.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},N.id)})})})]})]}),o.jsxs("button",{onClick:()=>P(!0),className:"flex items-center gap-1.5 hover:text-primary-theme transition-colors bg-surface text-main px-3 py-1.5 rounded-md border border-theme shadow-sm font-medium cursor-pointer",children:[o.jsx(Ti,{size:14,className:"text-emerald-500 animate-pulse"}),n==="zh"?"系统资源库":"System Resource Library"]}),o.jsx("button",{onClick:D,title:n==="zh"?"Switch to English":"切换为中文",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer",children:o.jsx(Ti,{size:16})}),o.jsx(cc,{lang:n}),o.jsx(ym,{lang:n}),(()=>{const N=g==="error"||!h?{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:n==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:g==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:n==="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:n==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return o.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 ${N.bg}`,title:N.label,children:[o.jsx(lp,{size:15}),o.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[o.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${N.ping}`}),o.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${N.dot}`})]})]})})(),o.jsx(hm,{session:i,lang:n,onLogout:F,onProfile:()=>S(!0)})]})]})}let Ls=null;function uc(e){Ls=e}function wm(){if(!Ls)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return Ls}function wt(){return Ls}class Sm{constructor(t){this.socket=t,uc(t)}emit(t,...n){this.socket.emit(t,...n)}on(t,n){this.socket.on(t,n)}off(t,n){this.socket.off(t,n)}disconnect(){this.socket.disconnect()}}const vm="openlearn_live_classroom_sync";class Ii{constructor(t=vm,n,s){this.channel=null,this.isDestroyed=!1,this.messageListeners=[],this.lessonId=null,this.classId=null,this.lessonId=n||null,this.classId=s||null,typeof window<"u"&&typeof window.BroadcastChannel<"u"&&(this.channel=new BroadcastChannel(t),this.channel.onmessage=i=>{this.isDestroyed||!i.data||this.emitToListeners(i.data)});const r=wt();if(r){const i=a=>{this.isDestroyed||!a?.message||this.lessonId&&a.lessonId&&a.lessonId!==this.lessonId||this.emitToListeners(a.message)};r.on("classroom:sync_message",i),this.socketCleanup=()=>{r.off("classroom:sync_message",i)}}}setLessonContext(t,n){this.lessonId=t,n!==void 0&&(this.classId=n)}emitToListeners(t){this.messageListeners.forEach(n=>{try{n(t)}catch(s){console.error("[ClassroomSyncChannel] Listener error:",s)}})}onMessage(t){return this.messageListeners.push(t),()=>{this.messageListeners=this.messageListeners.filter(n=>n!==t)}}postMessage(t){if(this.isDestroyed)return;if(this.channel)try{this.channel.postMessage(t)}catch(s){console.warn("[ClassroomSyncChannel] Failed to post message to BroadcastChannel:",s)}const n=wt();if(n&&this.lessonId)try{n.emit("teacher-sync-message",{lessonId:this.lessonId,message:t})}catch(s){console.warn("[ClassroomSyncChannel] Failed to emit socket sync message:",s)}}broadcastInitState(t){this.postMessage({type:"TEACHER_INIT_STATE",payload:t})}broadcastChangeLesson(t){this.lessonId=t,this.postMessage({type:"TEACHER_CHANGE_LESSON",payload:{lessonId:t,classId:this.classId}});const n=wt();n&&t&&n.emit("teacher-broadcast-lesson",{lessonId:t,classId:this.classId})}broadcastChangeSegment(t){this.postMessage({type:"TEACHER_CHANGE_SEGMENT",payload:{segmentId:t,lessonId:this.lessonId}});const n=wt();n&&this.lessonId&&t&&n.emit("teacher-broadcast-segment",{lessonId:this.lessonId,activeSegmentId:t})}broadcastChangeTab(t){this.postMessage({type:"TEACHER_CHANGE_TAB",payload:{tab:t,lessonId:this.lessonId}});const n=wt();n&&this.lessonId&&n.emit("teacher-broadcast-tab",{lessonId:this.lessonId,tab:t})}broadcastLockClass(t){this.postMessage({type:"TEACHER_LOCK_CLASS",payload:{locked:t,lessonId:this.lessonId,classId:this.classId}});const n=wt();n&&this.lessonId&&n.emit("teacher-broadcast-lock",{lessonId:this.lessonId,locked:t,classId:this.classId})}broadcastPickStudent(t,n){this.postMessage({type:"TEACHER_PICK_STUDENT",payload:{studentId:t,studentName:n}})}broadcastSyncTimer(t,n){this.postMessage({type:"TEACHER_SYNC_TIMER",payload:{timeRemaining:t,isRunning:n,lessonId:this.lessonId}})}broadcastCountdown(t){this.postMessage({type:"TEACHER_BROADCAST_COUNTDOWN",payload:t}),this.broadcastSyncTimer(t.timeRemaining,t.isRunning)}broadcastPingStudent(t,n){this.postMessage({type:"TEACHER_PING_STUDENT",payload:{studentId:t,message:n}});const s=wt();s&&this.lessonId&&s.emit("teacher-ping-student",{studentId:t,lessonId:this.lessonId,message:n})}broadcastFullscreen(t,n){const s=n||this.lessonId||void 0;this.postMessage({type:"TEACHER_BROADCAST_FULLSCREEN",payload:{elementId:t,lessonId:s}});const r=wt();r&&s&&r.emit("teacher-broadcast-fullscreen",{elementId:t,lessonId:s,classId:this.classId})}requestHandshake(){this.postMessage({type:"STUDENT_HANDSHAKE_REQUEST"})}acknowledgePick(t){this.postMessage({type:"STUDENT_ACKNOWLEDGE_PICK",payload:{studentId:t}})}sendHeartbeat(t){this.postMessage({type:"STUDENT_HEARTBEAT",payload:{studentId:t,timestamp:Date.now()}})}destroy(){this.isDestroyed=!0,this.messageListeners=[],this.socketCleanup&&(this.socketCleanup(),this.socketCleanup=void 0),this.channel&&(this.channel.close(),this.channel=null)}}const ln=hn(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null})})),Kk=e=>Vs(ln,e);function km({open:e,session:t,lang:n,onClose:s,onSaved:r,onAvatar:i}){const[a,l]=f.useState(t.name),[c,u]=f.useState(!1),[d,p]=f.useState(null),m=f.useRef(null),[h,g]=f.useState(!1),[y,v]=f.useState(null),[w,P]=f.useState(!1),[S,j]=f.useState(""),[A,E]=f.useState(""),[R,F]=f.useState(""),[D,O]=f.useState(!1),[k,_]=f.useState(null),[L,I]=f.useState(!1);if(!e)return null;const N=(Q,X)=>n==="zh"?Q:X,z=t.role==="teacher"?t.subRole==="administrator"?N("管理员","Administrator"):N("教师","Teacher"):N("学生","Student"),U=a.trim(),T=U.length>0&&U!==t.name,M=async()=>{if(!(!T||c)){u(!0),p(null);try{const Q=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:U})}),X=await Q.json();if(!Q.ok){p(X.error||(n==="zh"?"保存失败":"Save failed"));return}r(X.name??U)}catch{p(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{u(!1)}}},x=S.length>0&&A.length>=8&&/[a-zA-Z]/.test(A)&&/[0-9]/.test(A)&&A===R,oe=async()=>{if(!(!x||D)){O(!0),_(null);try{const Q=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:S,newPassword:A})}),X=await Q.json();if(!Q.ok){_(X.error||(n==="zh"?"修改失败":"Change failed"));return}I(!0),j(""),E(""),F(""),P(!1)}catch{_(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{O(!1)}}},me=async Q=>{const X=Q.target.files?.[0];if(Q.target.value="",!!X){g(!0),v(null);try{const B=await new Promise((de,xe)=>{const ae=new FileReader;ae.onload=()=>de(ae.result),ae.onerror=()=>xe(ae.error),ae.readAsDataURL(X)}),Z=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:X.name,base64Data:B})}),re=await Z.json();if(!Z.ok){v(re.error||(n==="zh"?"上传失败":"Upload failed"));return}i?.(re.avatar)}catch{v(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}}},b=async()=>{g(!0),v(null);try{const Q=await fetch("/api/auth/avatar",{method:"DELETE"}),X=await Q.json().catch(()=>({}));if(!Q.ok){v(X.error||(n==="zh"?"移除失败":"Remove failed"));return}i?.(null)}catch{v(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}};return o.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:s,children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden",onClick:Q=>Q.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:N("个人资料","Profile")}),o.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:o.jsx(Ze,{size:18})})]}),o.jsxs("div",{className:"p-5 space-y-5",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.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:t.avatar?o.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):o.jsx(Mn,{size:28})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:t.name}),o.jsx("p",{className:"text-xs text-gray-400",children:z}),o.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[o.jsx("button",{type:"button",onClick:()=>m.current?.click(),disabled:h,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:h?N("上传中…","Uploading…"):t.avatar?N("更换头像","Change avatar"):N("上传头像","Upload avatar")}),t.avatar&&o.jsx("button",{type:"button",onClick:b,disabled:h,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:N("移除","Remove")})]}),o.jsx("input",{ref:m,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:me})]})]}),y&&o.jsx("p",{className:"text-xs text-rose-500",children:y}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:N("显示名称","Display Name")}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("input",{value:a,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"}),o.jsx("button",{onClick:M,disabled:!T||c,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:c?N("保存中…","Saving…"):N("保存","Save")})]}),d&&o.jsx("p",{className:"text-xs text-rose-500 mt-1",children:d})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[o.jsx(cp,{size:16,className:"text-gray-400"}),N("修改密码","Change Password")]}),!w&&!L&&o.jsx("button",{onClick:()=>{P(!0),_(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:N("修改","Edit")})]}),L&&o.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[o.jsx(_t,{size:16}),N("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),w&&o.jsxs("div",{className:"mt-3 space-y-3",children:[o.jsx("input",{type:"password",value:S,onChange:Q=>j(Q.target.value),placeholder:N("当前密码","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"}),o.jsx("input",{type:"password",value:A,onChange:Q=>E(Q.target.value),placeholder:N("新密码(≥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"}),o.jsx("input",{type:"password",value:R,onChange:Q=>F(Q.target.value),placeholder:N("确认新密码","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"}),k&&o.jsx("p",{className:"text-xs text-rose-500",children:k}),o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{onClick:()=>{P(!1),j(""),E(""),F(""),_(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:N("取消","Cancel")}),o.jsx("button",{onClick:oe,disabled:!x||D,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:D?N("提交中…","Submitting…"):N("提交","Submit")})]})]})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:N("用户名(登录账号)","Username (login)")}),o.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:t.username,children:t.username||"-"})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:N("角色","Role")}),o.jsx("span",{className:"text-sm font-medium text-gray-700",children:z})]})]})]})]})})}class Cm{constructor(){this.store=hn(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId;this.store.setState(r=>{const i=new Map(r.items);return i.set(t.type,{config:{...t,pluginId:s},pluginId:s}),{items:i}})}unregister(t,n){this.store.setState(s=>{const r=s.items.get(t);if(!r||n&&r.pluginId!==n)return s;const i=new Map(s.items);return i.delete(t),{items:i}})}unregisterPlugin(t){this.store.setState(n=>{let s=!1;const r=new Map(n.items);for(const[i,a]of n.items)a.pluginId===t&&(r.delete(i),s=!0);return s?{items:r}:n})}get(t){return this.store.getState().items.get(t)?.config}getAll(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}has(t){return this.store.getState().items.has(t)}getStore(){return this.store}}const zn=new Cm;function Xk(){return Vs(zn.getStore(),Jf(e=>Array.from(e.items.values()).map(t=>t.config)))}const eC={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"}},tC=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],Em=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:up,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
6
6
  ---
7
7
  ## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
8
8
  ---
9
- ## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:fs,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:ip,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:Ei,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
9
+ ## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:fs,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:dp,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:Ti,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
10
10
  <div style='padding:20px; text-align:center;'>
11
11
  <h2>Interactive Web Courseware</h2>
12
12
  <p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
13
- </div>`},editFields:[{key:"title",labelZh:"标题",labelEn:"Title",kind:"input",placeholderZh:"课件标题",placeholderEn:"Courseware title"},{key:"coursewareUuid",labelZh:"互动课件 (Courseware)",labelEn:"Courseware",kind:"select",loadOptions:async()=>{try{return(await(await fetch("/api/courseware")).json()).map(n=>({value:n.uuid,label:n.name}))}catch{return[]}}},{key:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:Ji,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:Gl,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:op,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:Ut,color:"pink",group:"manage",defaultData:{},editFields:[]}],wm=bm.reduce((e,t)=>(e[t.type]=t,e),{});function Sm(e){return wm[e]||An.get(e)}const ot=Mn(e=>({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:t=>e({lang:t}),setActiveRole:t=>e({activeRole:t}),setTeacherTab:t=>e({teacherTab:t}),setProfileOpen:t=>e({profileOpen:t}),setIsCourseWizardOpen:t=>e({isCourseWizardOpen:t}),setIsImportLessonsOpen:t=>e({isImportLessonsOpen:t}),setIsQuizGeneratorOpen:t=>e({isQuizGeneratorOpen:t}),setIsLessonPreviewVisible:t=>e({isLessonPreviewVisible:t}),setIsSystemResourceLibraryOpen:t=>e({isSystemResourceLibraryOpen:t}),setBatchPicker:t=>e({batchPicker:t}),setIsExportWeightModalOpen:t=>e({isExportWeightModalOpen:t}),addToast:t=>e(n=>({toasts:[...n.toasts,t]})),removeToast:t=>e(n=>({toasts:n.toasts.filter(s=>s.id!==t)})),setSiteInfo:t=>e({siteInfo:t})})),_e=Mn(e=>({lang:ot.getState().lang,session:null,lessons:[],selectedLesson:null,elements:[],classes:[],students:[],liveClassSelectedClassId:null,liveClassIsActive:!1,teacherTab:ot.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:ot.getState().toasts,siteInfo:ot.getState().siteInfo,setLang:t=>{ot.getState().setLang(t)},setSession:t=>e({session:t}),setLessons:t=>e(n=>({lessons:typeof t=="function"?t(n.lessons):t})),setSelectedLesson:t=>e({selectedLesson:t}),setElements:t=>e({elements:t}),setClasses:t=>e({classes:t}),setStudents:t=>e({students:t}),setLiveClassSelectedClassId:t=>e({liveClassSelectedClassId:t}),setLiveClassIsActive:t=>e({liveClassIsActive:t}),setTeacherTab:t=>{ot.getState().setTeacherTab(t)},setAiProviders:t=>e({aiProviders:t}),setPlugins:t=>e({plugins:t}),setRegisteredCommands:t=>e({registeredCommands:t}),setEvents:t=>e({events:t}),setApprovals:t=>e({approvals:t}),setProcesses:t=>e({processes:t}),setVfsNodes:t=>e({vfsNodes:t}),setTodaySchedules:t=>e({todaySchedules:t}),setComputerLabs:t=>e({computerLabs:t}),setDbConnected:t=>e({dbConnected:t}),setSessionLoading:t=>e({sessionLoading:t}),setClassStudents:(t,n)=>e(s=>({classStudentsMap:{...s.classStudentsMap,[t]:n}})),setClassDashboard:(t,n)=>e(s=>({classDashboardMap:{...s.classDashboardMap,[t]:n}})),setStudentProgress:(t,n)=>e(s=>({studentProgressMap:{...s.studentProgressMap,[t]:n}})),setClassSchedules:(t,n)=>e(s=>({classSchedulesMap:{...s.classSchedulesMap,[t]:n}})),setScheduleAttendance:(t,n)=>e(s=>({scheduleAttendanceMap:{...s.scheduleAttendanceMap,[t]:n}})),setAssignmentSubmissions:(t,n)=>e(s=>({assignmentSubmissionsMap:{...s.assignmentSubmissionsMap,[t]:n}})),setClassAssignments:(t,n)=>e(s=>({classAssignmentsMap:{...s.classAssignmentsMap,[t]:n}})),setClassProgress:(t,n)=>e(s=>({classProgressMap:{...s.classProgressMap,[t]:n}})),setClassSeats:t=>e({classSeats:t}),setOnlineStudentIds:t=>e({onlineStudentIds:t}),setActiveStudentLessons:t=>e({activeStudentLessons:t}),setLiveClassFeed:t=>e({liveClassFeed:t}),appendLiveClassFeed:t=>e(n=>({liveClassFeed:[...n.liveClassFeed.slice(-49),t]})),setLiveClassTimeRemaining:t=>e({liveClassTimeRemaining:t}),setLiveClassAcknowledgedMap:t=>e({liveClassAcknowledgedMap:t}),setLiveClassStudentProgress:t=>e({liveClassStudentProgress:t}),setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t}),addToast:t=>{ot.getState().addToast(t)},removeToast:t=>{ot.getState().removeToast(t)},setSiteInfo:t=>{ot.getState().setSiteInfo(t)}}));ot.subscribe(e=>{_e.setState({lang:e.lang,teacherTab:e.teacherTab,toasts:e.toasts,siteInfo:e.siteInfo})});const he=e=>$s(_e,e);function vm(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const km=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Cm=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Em={};function wa(e,t){return(Em.jsx?Cm:km).test(e)}const jm=/[ \t\n\f\r]/g;function Nm(e){return typeof e=="object"?e.type==="text"?Sa(e.value):!1:Sa(e)}function Sa(e){return e.replace(jm,"")===""}class Fn{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}Fn.prototype.normal={};Fn.prototype.property={};Fn.prototype.space=void 0;function oc(e,t){const n={},s={};for(const r of e)Object.assign(n,r.property),Object.assign(s,r.normal);return new Fn(n,s,t)}function Ti(e){return e.toLowerCase()}class Fe{constructor(t,n){this.attribute=n,this.property=t}}Fe.prototype.attribute="";Fe.prototype.booleanish=!1;Fe.prototype.boolean=!1;Fe.prototype.commaOrSpaceSeparated=!1;Fe.prototype.commaSeparated=!1;Fe.prototype.defined=!1;Fe.prototype.mustUseProperty=!1;Fe.prototype.number=!1;Fe.prototype.overloadedBoolean=!1;Fe.prototype.property="";Fe.prototype.spaceSeparated=!1;Fe.prototype.space=void 0;let Tm=0;const se=Ht(),Se=Ht(),Pi=Ht(),H=Ht(),fe=Ht(),Vt=Ht(),Be=Ht();function Ht(){return 2**++Tm}const Ii=Object.freeze(Object.defineProperty({__proto__:null,boolean:se,booleanish:Se,commaOrSpaceSeparated:Be,commaSeparated:Vt,number:H,overloadedBoolean:Pi,spaceSeparated:fe},Symbol.toStringTag,{value:"Module"})),Yr=Object.keys(Ii);class eo extends Fe{constructor(t,n,s,r){let i=-1;if(super(t,n),va(this,"space",r),typeof s=="number")for(;++i<Yr.length;){const a=Yr[i];va(this,Yr[i],(s&Ii[a])===Ii[a])}}}eo.prototype.defined=!0;function va(e,t,n){n&&(e[t]=n)}function hn(e){const t={},n={};for(const[s,r]of Object.entries(e.properties)){const i=new eo(s,e.transform(e.attributes||{},s),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(i.mustUseProperty=!0),t[s]=i,n[Ti(s)]=s,n[Ti(i.attribute)]=s}return new Fn(t,n,e.space)}const ac=hn({properties:{ariaActiveDescendant:null,ariaAtomic:Se,ariaAutoComplete:null,ariaBusy:Se,ariaChecked:Se,ariaColCount:H,ariaColIndex:H,ariaColSpan:H,ariaControls:fe,ariaCurrent:null,ariaDescribedBy:fe,ariaDetails:null,ariaDisabled:Se,ariaDropEffect:fe,ariaErrorMessage:null,ariaExpanded:Se,ariaFlowTo:fe,ariaGrabbed:Se,ariaHasPopup:null,ariaHidden:Se,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:fe,ariaLevel:H,ariaLive:null,ariaModal:Se,ariaMultiLine:Se,ariaMultiSelectable:Se,ariaOrientation:null,ariaOwns:fe,ariaPlaceholder:null,ariaPosInSet:H,ariaPressed:Se,ariaReadOnly:Se,ariaRelevant:null,ariaRequired:Se,ariaRoleDescription:fe,ariaRowCount:H,ariaRowIndex:H,ariaRowSpan:H,ariaSelected:Se,ariaSetSize:H,ariaSort:null,ariaValueMax:H,ariaValueMin:H,ariaValueNow:H,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function lc(e,t){return t in e?e[t]:t}function cc(e,t){return lc(e,t.toLowerCase())}const Pm=hn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Vt,acceptCharset:fe,accessKey:fe,action:null,allow:null,allowFullScreen:se,allowPaymentRequest:se,allowUserMedia:se,alpha:se,alt:null,as:null,async:se,autoCapitalize:null,autoComplete:fe,autoFocus:se,autoPlay:se,blocking:fe,capture:null,charSet:null,checked:se,cite:null,className:fe,closedBy:null,colorSpace:null,cols:H,colSpan:H,command:null,commandFor:null,content:null,contentEditable:Se,controls:se,controlsList:fe,coords:H|Vt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:se,defer:se,dir:null,dirName:null,disabled:se,download:Pi,draggable:Se,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:se,formTarget:null,headers:fe,height:H,hidden:Pi,high:H,href:null,hrefLang:null,htmlFor:fe,httpEquiv:fe,id:null,imageSizes:null,imageSrcSet:null,inert:se,inputMode:null,integrity:null,is:null,isMap:se,itemId:null,itemProp:fe,itemRef:fe,itemScope:se,itemType:fe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:se,low:H,manifest:null,max:null,maxLength:H,media:null,method:null,min:null,minLength:H,multiple:se,muted:se,name:null,nonce:null,noModule:se,noValidate:se,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:se,optimum:H,pattern:null,ping:fe,placeholder:null,playsInline:se,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:se,referrerPolicy:null,rel:fe,required:se,reversed:se,rows:H,rowSpan:H,sandbox:fe,scope:null,scoped:se,seamless:se,selected:se,shadowRootClonable:se,shadowRootCustomElementRegistry:se,shadowRootDelegatesFocus:se,shadowRootMode:null,shadowRootSerializable:se,shape:null,size:H,sizes:null,slot:null,span:H,spellCheck:Se,src:null,srcDoc:null,srcLang:null,srcSet:null,start:H,step:null,style:null,tabIndex:H,target:null,title:null,translate:null,type:null,typeMustMatch:se,useMap:null,value:Se,width:H,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:fe,axis:null,background:null,bgColor:null,border:H,borderColor:null,bottomMargin:H,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:se,declare:se,event:null,face:null,frame:null,frameBorder:null,hSpace:H,leftMargin:H,link:null,longDesc:null,lowSrc:null,marginHeight:H,marginWidth:H,noResize:se,noHref:se,noShade:se,noWrap:se,object:null,profile:null,prompt:null,rev:null,rightMargin:H,rules:null,scheme:null,scrolling:Se,standby:null,summary:null,text:null,topMargin:H,valueType:null,version:null,vAlign:null,vLink:null,vSpace:H,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:se,disablePictureInPicture:se,disableRemotePlayback:se,exportParts:Vt,part:fe,prefix:null,property:null,results:H,security:null,unselectable:null},space:"html",transform:cc}),Im=hn({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",maskType:"mask-type",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Be,accentHeight:H,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:H,amplitude:H,arabicForm:null,ascent:H,attributeName:null,attributeType:null,azimuth:H,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:H,by:null,calcMode:null,capHeight:H,className:fe,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:H,diffuseConstant:H,direction:null,display:null,dur:null,divisor:H,dominantBaseline:null,download:se,dx:null,dy:null,edgeMode:null,editable:null,elevation:H,enableBackground:null,end:null,event:null,exponent:H,externalResourcesRequired:null,fill:null,fillOpacity:H,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Vt,g2:Vt,glyphName:Vt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:H,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:H,horizOriginX:H,horizOriginY:H,id:null,ideographic:H,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:H,k:H,k1:H,k2:H,k3:H,k4:H,kernelMatrix:Be,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:H,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:H,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:H,overlineThickness:H,paintOrder:null,panose1:null,path:null,pathLength:H,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:fe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:H,pointsAtY:H,pointsAtZ:H,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Be,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Be,rev:Be,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Be,requiredFeatures:Be,requiredFonts:Be,requiredFormats:Be,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:H,specularExponent:H,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:H,strikethroughThickness:H,string:null,stroke:null,strokeDashArray:Be,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:H,strokeOpacity:H,strokeWidth:null,style:null,surfaceScale:H,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Be,tabIndex:H,tableValues:null,target:null,targetX:H,targetY:H,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Be,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:H,underlineThickness:H,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:H,values:null,vAlphabetic:H,vMathematical:H,vectorEffect:null,vHanging:H,vIdeographic:H,version:null,vertAdvY:H,vertOriginX:H,vertOriginY:H,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:H,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:lc}),uc=hn({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),dc=hn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:cc}),hc=hn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Am={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},zm=/[A-Z]/g,ka=/-[a-z]/g,_m=/^data[-\w.:]+$/i;function Lm(e,t){const n=Ti(t);let s=t,r=Fe;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&_m.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ka,Om);s="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ka.test(i)){let a=i.replace(zm,Rm);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}r=eo}return new r(s,t)}function Rm(e){return"-"+e.toLowerCase()}function Om(e){return e.charAt(1).toUpperCase()}const Dm=oc([ac,Pm,uc,dc,hc],"html"),to=oc([ac,Im,uc,dc,hc],"svg");function Mm(e){return e.join(" ").trim()}var en={},Kr,Ca;function Fm(){if(Ca)return Kr;Ca=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,l=/^\s+|\s+$/g,c=`
14
- `,u="/",d="*",h="",m="comment",f="declaration";function g(C,w){if(typeof C!="string")throw new TypeError("First argument must be a string");if(!C)return[];w=w||{};var P=1,S=1;function j(I){var N=I.match(t);N&&(P+=N.length);var z=I.lastIndexOf(c);S=~z?I.length-z:S+I.length}function A(){var I={line:P,column:S};return function(N){return N.position=new E(I),M(),N}}function E(I){this.start=I,this.end={line:P,column:S},this.source=w.source}E.prototype.content=C;function R(I){var N=new Error(w.source+":"+P+":"+S+": "+I);if(N.reason=I,N.filename=w.source,N.line=P,N.column=S,N.source=C,!w.silent)throw N}function F(I){var N=I.exec(C);if(N){var z=N[0];return j(z),C=C.slice(z.length),N}}function M(){F(n)}function O(I){var N;for(I=I||[];N=v();)N!==!1&&I.push(N);return I}function v(){var I=A();if(!(u!=C.charAt(0)||d!=C.charAt(1))){for(var N=2;h!=C.charAt(N)&&(d!=C.charAt(N)||u!=C.charAt(N+1));)++N;if(N+=2,h===C.charAt(N-1))return R("End of comment missing");var z=C.slice(2,N-2);return S+=2,j(z),C=C.slice(N),S+=2,I({type:m,comment:z})}}function _(){var I=A(),N=F(s);if(N){if(v(),!F(r))return R("property missing ':'");var z=F(i),U=I({type:f,property:y(N[0].replace(e,h)),value:z?y(z[0].replace(e,h)):h});return F(a),U}}function L(){var I=[];O(I);for(var N;N=_();)N!==!1&&(I.push(N),O(I));return I}return M(),L()}function y(C){return C?C.replace(l,h):h}return Kr=g,Kr}var Ea;function $m(){if(Ea)return en;Ea=1;var e=en&&en.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(en,"__esModule",{value:!0}),en.default=n;const t=e(Fm());function n(s,r){let i=null;if(!s||typeof s!="string")return i;const a=(0,t.default)(s),l=typeof r=="function";return a.forEach(c=>{if(c.type!=="declaration")return;const{property:u,value:d}=c;l?r(u,d,c):d&&(i=i||{},i[u]=d)}),i}return en}var En={},ja;function Bm(){if(ja)return En;ja=1,Object.defineProperty(En,"__esModule",{value:!0}),En.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},a=function(u,d){return d.toUpperCase()},l=function(u,d){return"".concat(d,"-")},c=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(r,l):u=u.replace(s,l),u.replace(t,a))};return En.camelCase=c,En}var jn,Na;function Vm(){if(Na)return jn;Na=1;var e=jn&&jn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e($m()),n=Bm();function s(r,i){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(l,c){l&&c&&(a[(0,n.camelCase)(l,i)]=c)}),a}return s.default=s,jn=s,jn}var Um=Vm();const Hm=Bl(Um),fc=pc("end"),no=pc("start");function pc(e){return t;function t(n){const s=n&&n.position&&n.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function qm(e){const t=no(e),n=fc(e);if(t&&n)return{start:t,end:n}}function zn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Ta(e.position):"start"in e||"end"in e?Ta(e):"line"in e||"column"in e?Ai(e):""}function Ai(e){return Pa(e&&e.line)+":"+Pa(e&&e.column)}function Ta(e){return Ai(e&&e.start)+"-"+Ai(e&&e.end)}function Pa(e){return e&&typeof e=="number"?e:1}class Le extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let r="",i={},a=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?r=t:!i.cause&&t&&(a=!0,r=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof s=="string"){const c=s.indexOf(":");c===-1?i.ruleId=s:(i.source=s.slice(0,c),i.ruleId=s.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const l=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=l?l.line:void 0,this.name=zn(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Le.prototype.file="";Le.prototype.name="";Le.prototype.reason="";Le.prototype.message="";Le.prototype.stack="";Le.prototype.column=void 0;Le.prototype.line=void 0;Le.prototype.ancestors=void 0;Le.prototype.cause=void 0;Le.prototype.fatal=void 0;Le.prototype.place=void 0;Le.prototype.ruleId=void 0;Le.prototype.source=void 0;const so={}.hasOwnProperty,Wm=new Map,Gm=/[A-Z]/g,Qm=new Set(["table","tbody","thead","tfoot","tr"]),Jm=new Set(["td","th"]),mc="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Zm(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=rg(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=sg(n,t.jsx,t.jsxs)}const r={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?to:Dm,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=gc(r,e,void 0);return i&&typeof i!="string"?i:r.create(e,r.Fragment,{children:i||void 0},void 0)}function gc(e,t,n){if(t.type==="element")return Ym(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Km(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return eg(e,t,n);if(t.type==="mdxjsEsm")return Xm(e,t);if(t.type==="root")return tg(e,t,n);if(t.type==="text")return ng(e,t)}function Ym(e,t,n){const s=e.schema;let r=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(r=to,e.schema=r),e.ancestors.push(t);const i=yc(e,t.tagName,!1),a=ig(e,t);let l=io(e,t);return Qm.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!Nm(c):!0})),xc(e,a,i,t),ro(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function Km(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Dn(e,t.position)}function Xm(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Dn(e,t.position)}function eg(e,t,n){const s=e.schema;let r=s;t.name==="svg"&&s.space==="html"&&(r=to,e.schema=r),e.ancestors.push(t);const i=t.name===null?e.Fragment:yc(e,t.name,!0),a=og(e,t),l=io(e,t);return xc(e,a,i,t),ro(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function tg(e,t,n){const s={};return ro(s,io(e,t)),e.create(t,e.Fragment,s,n)}function ng(e,t){return t.value}function xc(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function ro(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function sg(e,t,n){return s;function s(r,i,a,l){const u=Array.isArray(a.children)?n:t;return l?u(i,a,l):u(i,a)}}function rg(e,t){return n;function n(s,r,i,a){const l=Array.isArray(i.children),c=no(s);return t(r,i,a,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function ig(e,t){const n={};let s,r;for(r in t.properties)if(r!=="children"&&so.call(t.properties,r)){const i=ag(e,r,t.properties[r]);if(i){const[a,l]=i;e.tableCellAlignToStyle&&a==="align"&&typeof l=="string"&&Jm.has(t.tagName)?s=l:n[a]=l}}if(s){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function og(e,t){const n={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const i=s.data.estree.body[0];i.type;const a=i.expression;a.type;const l=a.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else Dn(e,t.position);else{const r=s.name;let i;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const l=s.value.data.estree.body[0];l.type,i=e.evaluater.evaluateExpression(l.expression)}else Dn(e,t.position);else i=s.value===null?!0:s.value;n[r]=i}return n}function io(e,t){const n=[];let s=-1;const r=e.passKeys?new Map:Wm;for(;++s<t.children.length;){const i=t.children[s];let a;if(e.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const u=r.get(c)||0;a=c+"-"+u,r.set(c,u+1)}}const l=gc(e,i,a);l!==void 0&&n.push(l)}return n}function ag(e,t,n){const s=Lm(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?vm(n):Mm(n)),s.property==="style"){let r=typeof n=="object"?n:lg(e,String(n));return e.stylePropertyNameCase==="css"&&(r=cg(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&s.space?Am[s.property]||s.property:s.attribute,n]}}function lg(e,t){try{return Hm(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,r=new Le("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=mc+"#cannot-parse-style-attribute",r}}function yc(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let i=-1,a;for(;++i<r.length;){const l=wa(r[i])?{type:"Identifier",name:r[i]}:{type:"Literal",value:r[i]};a=a?{type:"MemberExpression",object:a,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}s=a}else s=wa(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const r=s.value;return so.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(s);Dn(e)}function Dn(e,t){const n=new Le("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=mc+"#cannot-handle-mdx-estrees-without-createevaluater",n}function cg(e){const t={};let n;for(n in e)so.call(e,n)&&(t[ug(n)]=e[n]);return t}function ug(e){let t=e.replace(Gm,dg);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function dg(e){return"-"+e.toLowerCase()}const Xr={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},hg={};function fg(e,t){const n=hg,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return bc(e,s,r)}function bc(e,t,n){if(pg(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Ia(e.children,t,n)}return Array.isArray(e)?Ia(e,t,n):""}function Ia(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=bc(e[r],t,n);return s.join("")}function pg(e){return!!(e&&typeof e=="object")}const Aa=document.createElement("i");function oo(e){const t="&"+e+";";Aa.innerHTML=t;const n=Aa.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ct(e,t,n,s){const r=e.length;let i=0,a;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,s.length<1e4)a=Array.from(s),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);i<s.length;)a=s.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function Ge(e,t){return e.length>0?(ct(e,e.length,0,t),e):t}const za={}.hasOwnProperty;function mg(e){const t={};let n=-1;for(;++n<e.length;)gg(t,e[n]);return t}function gg(e,t){let n;for(n in t){const r=(za.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){za.call(r,a)||(r[a]=[]);const l=i[a];xg(r[a],Array.isArray(l)?l:l?[l]:[])}}}function xg(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);ct(e,0,0,s)}function wc(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function cn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const lt=Rt(/[A-Za-z]/),Ve=Rt(/[\dA-Za-z]/),yg=Rt(/[#-'*+\--9=?A-Z^-~]/);function zi(e){return e!==null&&(e<32||e===127)}const _i=Rt(/\d/),bg=Rt(/[\dA-Fa-f]/),wg=Rt(/[!-/:-@[-`{-~]/);function te(e){return e!==null&&e<-2}function Me(e){return e!==null&&(e<0||e===32)}function ue(e){return e===-2||e===-1||e===32}const Sg=Rt(/\p{P}|\p{S}/u),vg=Rt(/\s/);function Rt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function fn(e){const t=[];let n=-1,s=0,r=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&Ve(e.charCodeAt(n+1))&&Ve(e.charCodeAt(n+2)))r=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const l=e.charCodeAt(n+1);i<56320&&l>56319&&l<57344?(a=String.fromCharCode(i,l),r=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(s,n),encodeURIComponent(a)),s=n+r+1,a=""),r&&(n+=r,r=0)}return t.join("")+e.slice(s)}function pe(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(c){return ue(c)?(e.enter(n),l(c)):t(c)}function l(c){return ue(c)&&i++<r?(e.consume(c),l):(e.exit(n),t(c))}}const kg={tokenize:Cg};function Cg(e){const t=e.attempt(this.parser.constructs.contentInitial,s,r);let n;return t;function s(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),pe(e,t,"linePrefix")}function r(l){return e.enter("paragraph"),i(l)}function i(l){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(l)}function a(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return te(l)?(e.consume(l),e.exit("chunkText"),i):(e.consume(l),a)}}const Eg={tokenize:jg},_a={tokenize:Ng};function jg(e){const t=this,n=[];let s=0,r,i,a;return l;function l(S){if(s<n.length){const j=n[s];return t.containerState=j[1],e.attempt(j[0].continuation,c,u)(S)}return u(S)}function c(S){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&P();const j=t.events.length;let A=j,E;for(;A--;)if(t.events[A][0]==="exit"&&t.events[A][1].type==="chunkFlow"){E=t.events[A][1].end;break}w(s);let R=j;for(;R<t.events.length;)t.events[R][1].end={...E},R++;return ct(t.events,A+1,0,t.events.slice(j)),t.events.length=R,u(S)}return l(S)}function u(S){if(s===n.length){if(!r)return m(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(_a,d,h)(S)}function d(S){return r&&P(),w(s),m(S)}function h(S){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,g(S)}function m(S){return t.containerState={},e.attempt(_a,f,g)(S)}function f(S){return s++,n.push([t.currentConstruct,t.containerState]),m(S)}function g(S){if(S===null){r&&P(),w(0),e.consume(S);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:i}),y(S)}function y(S){if(S===null){C(e.exit("chunkFlow"),!0),w(0),e.consume(S);return}return te(S)?(e.consume(S),C(e.exit("chunkFlow")),s=0,t.interrupt=void 0,l):(e.consume(S),y)}function C(S,j){const A=t.sliceStream(S);if(j&&A.push(null),S.previous=i,i&&(i.next=S),i=S,r.defineSkip(S.start),r.write(A),t.parser.lazy[S.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<a&&(!r.events[E][1].end||r.events[E][1].end.offset>a))return;const R=t.events.length;let F=R,M,O;for(;F--;)if(t.events[F][0]==="exit"&&t.events[F][1].type==="chunkFlow"){if(M){O=t.events[F][1].end;break}M=!0}for(w(s),E=R;E<t.events.length;)t.events[E][1].end={...O},E++;ct(t.events,F+1,0,t.events.slice(R)),t.events.length=E}}function w(S){let j=n.length;for(;j-- >S;){const A=n[j];t.containerState=A[1],A[0].exit.call(t,e)}n.length=S}function P(){r.write([null]),i=void 0,r=void 0,t.containerState._closeFlow=void 0}}function Ng(e,t,n){return pe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function La(e){if(e===null||Me(e)||vg(e))return 1;if(Sg(e))return 2}function ao(e,t,n){const s=[];let r=-1;for(;++r<e.length;){const i=e[r].resolveAll;i&&!s.includes(i)&&(t=i(t,n),s.push(i))}return t}const Li={name:"attention",resolveAll:Tg,tokenize:Pg};function Tg(e,t){let n=-1,s,r,i,a,l,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(s=n;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[s][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const h={...e[s][1].end},m={...e[n][1].start};Ra(h,-c),Ra(m,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...e[s][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},r={type:c>1?"strong":"emphasis",start:{...a.start},end:{...l.end}},e[s][1].end={...a.start},e[n][1].start={...l.end},u=[],e[s][1].end.offset-e[s][1].start.offset&&(u=Ge(u,[["enter",e[s][1],t],["exit",e[s][1],t]])),u=Ge(u,[["enter",r,t],["enter",a,t],["exit",a,t],["enter",i,t]]),u=Ge(u,ao(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),u=Ge(u,[["exit",i,t],["enter",l,t],["exit",l,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=Ge(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,ct(e,s-1,n-s+3,u),n=s+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function Pg(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,r=La(s);let i;return a;function a(c){return i=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===i)return e.consume(c),l;const u=e.exit("attentionSequence"),d=La(c),h=!d||d===2&&r||n.includes(c),m=!r||r===2&&d||n.includes(s);return u._open=!!(i===42?h:h&&(r||!m)),u._close=!!(i===42?m:m&&(d||!h)),t(c)}}function Ra(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Ig={name:"autolink",tokenize:Ag};function Ag(e,t,n){let s=0;return r;function r(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return lt(f)?(e.consume(f),a):f===64?n(f):u(f)}function a(f){return f===43||f===45||f===46||Ve(f)?(s=1,l(f)):u(f)}function l(f){return f===58?(e.consume(f),s=0,c):(f===43||f===45||f===46||Ve(f))&&s++<32?(e.consume(f),l):(s=0,u(f))}function c(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||zi(f)?n(f):(e.consume(f),c)}function u(f){return f===64?(e.consume(f),d):yg(f)?(e.consume(f),u):n(f)}function d(f){return Ve(f)?h(f):n(f)}function h(f){return f===46?(e.consume(f),s=0,d):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):m(f)}function m(f){if((f===45||Ve(f))&&s++<63){const g=f===45?m:h;return e.consume(f),g}return n(f)}}const Vs={partial:!0,tokenize:zg};function zg(e,t,n){return s;function s(i){return ue(i)?pe(e,r,"linePrefix")(i):r(i)}function r(i){return i===null||te(i)?t(i):n(i)}}const Sc={continuation:{tokenize:Lg},exit:Rg,name:"blockQuote",tokenize:_g};function _g(e,t,n){const s=this;return r;function r(a){if(a===62){const l=s.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return n(a)}function i(a){return ue(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function Lg(e,t,n){const s=this;return r;function r(a){return ue(a)?pe(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(Sc,t,n)(a)}}function Rg(e){e.exit("blockQuote")}const vc={name:"characterEscape",tokenize:Og};function Og(e,t,n){return s;function s(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),r}function r(i){return wg(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const kc={name:"characterReference",tokenize:Dg};function Dg(e,t,n){const s=this;let r=0,i,a;return l;function l(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),c}function c(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,a=Ve,d(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=bg,d):(e.enter("characterReferenceValue"),i=7,a=_i,d(h))}function d(h){if(h===59&&r){const m=e.exit("characterReferenceValue");return a===Ve&&!oo(s.sliceSerialize(m))?n(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(h)&&r++<i?(e.consume(h),d):n(h)}}const Oa={partial:!0,tokenize:Fg},Da={concrete:!0,name:"codeFenced",tokenize:Mg};function Mg(e,t,n){const s=this,r={partial:!0,tokenize:A};let i=0,a=0,l;return c;function c(E){return u(E)}function u(E){const R=s.events[s.events.length-1];return i=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,l=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(E)}function d(E){return E===l?(a++,e.consume(E),d):a<3?n(E):(e.exit("codeFencedFenceSequence"),ue(E)?pe(e,h,"whitespace")(E):h(E))}function h(E){return E===null||te(E)?(e.exit("codeFencedFence"),s.interrupt?t(E):e.check(Oa,y,j)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(E))}function m(E){return E===null||te(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(E)):ue(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),pe(e,f,"whitespace")(E)):E===96&&E===l?n(E):(e.consume(E),m)}function f(E){return E===null||te(E)?h(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||te(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(E)):E===96&&E===l?n(E):(e.consume(E),g)}function y(E){return e.attempt(r,j,C)(E)}function C(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),w}function w(E){return i>0&&ue(E)?pe(e,P,"linePrefix",i+1)(E):P(E)}function P(E){return E===null||te(E)?e.check(Oa,y,j)(E):(e.enter("codeFlowValue"),S(E))}function S(E){return E===null||te(E)?(e.exit("codeFlowValue"),P(E)):(e.consume(E),S)}function j(E){return e.exit("codeFenced"),t(E)}function A(E,R,F){let M=0;return O;function O(N){return E.enter("lineEnding"),E.consume(N),E.exit("lineEnding"),v}function v(N){return E.enter("codeFencedFence"),ue(N)?pe(E,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):_(N)}function _(N){return N===l?(E.enter("codeFencedFenceSequence"),L(N)):F(N)}function L(N){return N===l?(M++,E.consume(N),L):M>=a?(E.exit("codeFencedFenceSequence"),ue(N)?pe(E,I,"whitespace")(N):I(N)):F(N)}function I(N){return N===null||te(N)?(E.exit("codeFencedFence"),R(N)):F(N)}}}function Fg(e,t,n){const s=this;return r;function r(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}const ei={name:"codeIndented",tokenize:Bg},$g={partial:!0,tokenize:Vg};function Bg(e,t,n){const s=this;return r;function r(u){return e.enter("codeIndented"),pe(e,i,"linePrefix",5)(u)}function i(u){const d=s.events[s.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?c(u):te(u)?e.attempt($g,a,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||te(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function Vg(e,t,n){const s=this;return r;function r(a){return s.parser.lazy[s.now().line]?n(a):te(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r):pe(e,i,"linePrefix",5)(a)}function i(a){const l=s.events[s.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):te(a)?r(a):n(a)}}const Ug={name:"codeText",previous:qg,resolve:Hg,tokenize:Wg};function Hg(e){let t=e.length-4,n=3,s,r;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=n;++s<t;)if(e[s][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(s=n-1,t++;++s<=t;)r===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(r=s):(s===t||e[s][1].type==="lineEnding")&&(e[r][1].type="codeTextData",s!==r+2&&(e[r][1].end=e[s-1][1].end,e.splice(r+2,s-r-2),t-=s-r-2,s=r+2),r=void 0);return e}function qg(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Wg(e,t,n){let s=0,r,i;return a;function a(h){return e.enter("codeText"),e.enter("codeTextSequence"),l(h)}function l(h){return h===96?(e.consume(h),s++,l):(e.exit("codeTextSequence"),c(h))}function c(h){return h===null?n(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),c):h===96?(i=e.enter("codeTextSequence"),r=0,d(h)):te(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||te(h)?(e.exit("codeTextData"),c(h)):(e.consume(h),u)}function d(h){return h===96?(e.consume(h),r++,d):r===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(h)):(i.type="codeTextData",u(h))}}class Gg{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const s=n??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,n,s){const r=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return s&&Nn(this.left,s),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Nn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Nn(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Nn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Nn(this.left,n.reverse())}}}function Nn(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Cc(e){const t={};let n=-1,s,r,i,a,l,c,u;const d=new Gg(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(s=d.get(n),n&&s[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=s[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,Qg(d,n)),n=t[n],u=!0);else if(s[1]._container){for(i=n,r=void 0;i--;)if(a=d.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(d.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(s[1].end={...d.get(r)[1].start},l=d.slice(r,n),l.unshift(s),d.splice(r,n-r+1,l))}}return ct(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Qg(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];let a=n._tokenizer;a||(a=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const l=a.events,c=[],u={};let d,h,m=-1,f=n,g=0,y=0;const C=[y];for(;f;){for(;e.get(++r)[1]!==f;);i.push(r),f._tokenizer||(d=s.sliceStream(f),f.next||d.push(null),h&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),h=f,f=f.next}for(f=n;++m<l.length;)l[m][0]==="exit"&&l[m-1][0]==="enter"&&l[m][1].type===l[m-1][1].type&&l[m][1].start.line!==l[m][1].end.line&&(y=m+1,C.push(y),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):C.pop(),m=C.length;m--;){const w=l.slice(C[m],C[m+1]),P=i.pop();c.push([P,P+w.length-1]),e.splice(P,2,w)}for(c.reverse(),m=-1;++m<c.length;)u[g+c[m][0]]=g+c[m][1],g+=c[m][1]-c[m][0]-1;return u}const Jg={resolve:Yg,tokenize:Kg},Zg={partial:!0,tokenize:Xg};function Yg(e){return Cc(e),e}function Kg(e,t){let n;return s;function s(l){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(l)}function r(l){return l===null?i(l):te(l)?e.check(Zg,a,i)(l):(e.consume(l),r)}function i(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function a(l){return e.consume(l),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function Xg(e,t,n){const s=this;return r;function r(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),pe(e,i,"linePrefix")}function i(a){if(a===null||te(a))return n(a);const l=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):e.interrupt(s.parser.constructs.flow,n,t)(a)}}function Ec(e,t,n,s,r,i,a,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return h;function h(w){return w===60?(e.enter(s),e.enter(r),e.enter(i),e.consume(w),e.exit(i),m):w===null||w===32||w===41||zi(w)?n(w):(e.enter(s),e.enter(a),e.enter(l),e.enter("chunkString",{contentType:"string"}),y(w))}function m(w){return w===62?(e.enter(i),e.consume(w),e.exit(i),e.exit(r),e.exit(s),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===62?(e.exit("chunkString"),e.exit(l),m(w)):w===null||w===60||te(w)?n(w):(e.consume(w),w===92?g:f)}function g(w){return w===60||w===62||w===92?(e.consume(w),f):f(w)}function y(w){return!d&&(w===null||w===41||Me(w))?(e.exit("chunkString"),e.exit(l),e.exit(a),e.exit(s),t(w)):d<u&&w===40?(e.consume(w),d++,y):w===41?(e.consume(w),d--,y):w===null||w===32||w===40||zi(w)?n(w):(e.consume(w),w===92?C:y)}function C(w){return w===40||w===41||w===92?(e.consume(w),y):y(w)}}function jc(e,t,n,s,r,i){const a=this;let l=0,c;return u;function u(f){return e.enter(s),e.enter(r),e.consume(f),e.exit(r),e.enter(i),d}function d(f){return l>999||f===null||f===91||f===93&&!c||f===94&&!l&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(e.exit(i),e.enter(r),e.consume(f),e.exit(r),e.exit(s),t):te(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||te(f)||l++>999?(e.exit("chunkString"),d(f)):(e.consume(f),c||(c=!ue(f)),f===92?m:h)}function m(f){return f===91||f===92||f===93?(e.consume(f),l++,h):h(f)}}function Nc(e,t,n,s,r,i){let a;return l;function l(m){return m===34||m===39||m===40?(e.enter(s),e.enter(r),e.consume(m),e.exit(r),a=m===40?41:m,c):n(m)}function c(m){return m===a?(e.enter(r),e.consume(m),e.exit(r),e.exit(s),t):(e.enter(i),u(m))}function u(m){return m===a?(e.exit(i),c(a)):m===null?n(m):te(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),pe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===a||m===null||te(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?h:d)}function h(m){return m===a||m===92?(e.consume(m),d):d(m)}}function _n(e,t){let n;return s;function s(r){return te(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):ue(r)?pe(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const ex={name:"definition",tokenize:nx},tx={partial:!0,tokenize:sx};function nx(e,t,n){const s=this;let r;return i;function i(f){return e.enter("definition"),a(f)}function a(f){return jc.call(s,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function l(f){return r=cn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):n(f)}function c(f){return Me(f)?_n(e,u)(f):u(f)}function u(f){return Ec(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(tx,h,h)(f)}function h(f){return ue(f)?pe(e,m,"whitespace")(f):m(f)}function m(f){return f===null||te(f)?(e.exit("definition"),s.parser.defined.push(r),t(f)):n(f)}}function sx(e,t,n){return s;function s(l){return Me(l)?_n(e,r)(l):n(l)}function r(l){return Nc(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return ue(l)?pe(e,a,"whitespace")(l):a(l)}function a(l){return l===null||te(l)?t(l):n(l)}}const rx={name:"hardBreakEscape",tokenize:ix};function ix(e,t,n){return s;function s(i){return e.enter("hardBreakEscape"),e.consume(i),r}function r(i){return te(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const ox={name:"headingAtx",resolve:ax,tokenize:lx};function ax(e,t){let n=e.length-2,s=3,r,i;return e[s][1].type==="whitespace"&&(s+=2),n-2>s&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(s===n-1||n-4>s&&e[n-2][1].type==="whitespace")&&(n-=s+1===n?2:4),n>s&&(r={type:"atxHeadingText",start:e[s][1].start,end:e[n][1].end},i={type:"chunkText",start:e[s][1].start,end:e[n][1].end,contentType:"text"},ct(e,s,n-s+1,[["enter",r,t],["enter",i,t],["exit",i,t],["exit",r,t]])),e}function lx(e,t,n){let s=0;return r;function r(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&s++<6?(e.consume(d),a):d===null||Me(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||te(d)?(e.exit("atxHeading"),t(d)):ue(d)?pe(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||Me(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const cx=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ma=["pre","script","style","textarea"],ux={concrete:!0,name:"htmlFlow",resolveTo:fx,tokenize:px},dx={partial:!0,tokenize:gx},hx={partial:!0,tokenize:mx};function fx(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function px(e,t,n){const s=this;let r,i,a,l,c;return u;function u(b){return d(b)}function d(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),h}function h(b){return b===33?(e.consume(b),m):b===47?(e.consume(b),i=!0,y):b===63?(e.consume(b),r=3,s.interrupt?t:x):lt(b)?(e.consume(b),a=String.fromCharCode(b),C):n(b)}function m(b){return b===45?(e.consume(b),r=2,f):b===91?(e.consume(b),r=5,l=0,g):lt(b)?(e.consume(b),r=4,s.interrupt?t:x):n(b)}function f(b){return b===45?(e.consume(b),s.interrupt?t:x):n(b)}function g(b){const Q="CDATA[";return b===Q.charCodeAt(l++)?(e.consume(b),l===Q.length?s.interrupt?t:_:g):n(b)}function y(b){return lt(b)?(e.consume(b),a=String.fromCharCode(b),C):n(b)}function C(b){if(b===null||b===47||b===62||Me(b)){const Q=b===47,X=a.toLowerCase();return!Q&&!i&&Ma.includes(X)?(r=1,s.interrupt?t(b):_(b)):cx.includes(a.toLowerCase())?(r=6,Q?(e.consume(b),w):s.interrupt?t(b):_(b)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(b):i?P(b):S(b))}return b===45||Ve(b)?(e.consume(b),a+=String.fromCharCode(b),C):n(b)}function w(b){return b===62?(e.consume(b),s.interrupt?t:_):n(b)}function P(b){return ue(b)?(e.consume(b),P):O(b)}function S(b){return b===47?(e.consume(b),O):b===58||b===95||lt(b)?(e.consume(b),j):ue(b)?(e.consume(b),S):O(b)}function j(b){return b===45||b===46||b===58||b===95||Ve(b)?(e.consume(b),j):A(b)}function A(b){return b===61?(e.consume(b),E):ue(b)?(e.consume(b),A):S(b)}function E(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),c=b,R):ue(b)?(e.consume(b),E):F(b)}function R(b){return b===c?(e.consume(b),c=null,M):b===null||te(b)?n(b):(e.consume(b),R)}function F(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||Me(b)?A(b):(e.consume(b),F)}function M(b){return b===47||b===62||ue(b)?S(b):n(b)}function O(b){return b===62?(e.consume(b),v):n(b)}function v(b){return b===null||te(b)?_(b):ue(b)?(e.consume(b),v):n(b)}function _(b){return b===45&&r===2?(e.consume(b),z):b===60&&r===1?(e.consume(b),U):b===62&&r===4?(e.consume(b),oe):b===63&&r===3?(e.consume(b),x):b===93&&r===5?(e.consume(b),D):te(b)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(dx,me,L)(b)):b===null||te(b)?(e.exit("htmlFlowData"),L(b)):(e.consume(b),_)}function L(b){return e.check(hx,I,me)(b)}function I(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),N}function N(b){return b===null||te(b)?L(b):(e.enter("htmlFlowData"),_(b))}function z(b){return b===45?(e.consume(b),x):_(b)}function U(b){return b===47?(e.consume(b),a="",T):_(b)}function T(b){if(b===62){const Q=a.toLowerCase();return Ma.includes(Q)?(e.consume(b),oe):_(b)}return lt(b)&&a.length<8?(e.consume(b),a+=String.fromCharCode(b),T):_(b)}function D(b){return b===93?(e.consume(b),x):_(b)}function x(b){return b===62?(e.consume(b),oe):b===45&&r===2?(e.consume(b),x):_(b)}function oe(b){return b===null||te(b)?(e.exit("htmlFlowData"),me(b)):(e.consume(b),oe)}function me(b){return e.exit("htmlFlow"),t(b)}}function mx(e,t,n){const s=this;return r;function r(a){return te(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):n(a)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}function gx(e,t,n){return s;function s(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Vs,t,n)}}const xx={name:"htmlText",tokenize:yx};function yx(e,t,n){const s=this;let r,i,a;return l;function l(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),c}function c(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),A):x===63?(e.consume(x),S):lt(x)?(e.consume(x),F):n(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):lt(x)?(e.consume(x),P):n(x)}function d(x){return x===45?(e.consume(x),f):n(x)}function h(x){return x===null?n(x):x===45?(e.consume(x),m):te(x)?(a=h,U(x)):(e.consume(x),h)}function m(x){return x===45?(e.consume(x),f):h(x)}function f(x){return x===62?z(x):x===45?m(x):h(x)}function g(x){const oe="CDATA[";return x===oe.charCodeAt(i++)?(e.consume(x),i===oe.length?y:g):n(x)}function y(x){return x===null?n(x):x===93?(e.consume(x),C):te(x)?(a=y,U(x)):(e.consume(x),y)}function C(x){return x===93?(e.consume(x),w):y(x)}function w(x){return x===62?z(x):x===93?(e.consume(x),w):y(x)}function P(x){return x===null||x===62?z(x):te(x)?(a=P,U(x)):(e.consume(x),P)}function S(x){return x===null?n(x):x===63?(e.consume(x),j):te(x)?(a=S,U(x)):(e.consume(x),S)}function j(x){return x===62?z(x):S(x)}function A(x){return lt(x)?(e.consume(x),E):n(x)}function E(x){return x===45||Ve(x)?(e.consume(x),E):R(x)}function R(x){return te(x)?(a=R,U(x)):ue(x)?(e.consume(x),R):z(x)}function F(x){return x===45||Ve(x)?(e.consume(x),F):x===47||x===62||Me(x)?M(x):n(x)}function M(x){return x===47?(e.consume(x),z):x===58||x===95||lt(x)?(e.consume(x),O):te(x)?(a=M,U(x)):ue(x)?(e.consume(x),M):z(x)}function O(x){return x===45||x===46||x===58||x===95||Ve(x)?(e.consume(x),O):v(x)}function v(x){return x===61?(e.consume(x),_):te(x)?(a=v,U(x)):ue(x)?(e.consume(x),v):M(x)}function _(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),r=x,L):te(x)?(a=_,U(x)):ue(x)?(e.consume(x),_):(e.consume(x),I)}function L(x){return x===r?(e.consume(x),r=void 0,N):x===null?n(x):te(x)?(a=L,U(x)):(e.consume(x),L)}function I(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||Me(x)?M(x):(e.consume(x),I)}function N(x){return x===47||x===62||Me(x)?M(x):n(x)}function z(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function U(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),T}function T(x){return ue(x)?pe(e,D,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):D(x)}function D(x){return e.enter("htmlTextData"),a(x)}}const lo={name:"labelEnd",resolveAll:vx,resolveTo:kx,tokenize:Cx},bx={tokenize:Ex},wx={tokenize:jx},Sx={tokenize:Nx};function vx(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const r=s.type==="labelImage"?4:2;s.type="data",t+=r}}return e.length!==n.length&&ct(e,0,e.length,n),e}function kx(e,t){let n=e.length,s=0,r,i,a,l;for(;n--;)if(r=e[n][1],i){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(i=n,r.type!=="labelLink")){s=2;break}}else r.type==="labelEnd"&&(a=n);const c={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[a][1].end}},d={type:"labelText",start:{...e[i+s+2][1].end},end:{...e[a-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=Ge(l,e.slice(i+1,i+s+3)),l=Ge(l,[["enter",d,t]]),l=Ge(l,ao(t.parser.constructs.insideSpan.null,e.slice(i+s+4,a-3),t)),l=Ge(l,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),l=Ge(l,e.slice(a+1)),l=Ge(l,[["exit",c,t]]),ct(e,i,e.length,l),e}function Cx(e,t,n){const s=this;let r=s.events.length,i,a;for(;r--;)if((s.events[r][1].type==="labelImage"||s.events[r][1].type==="labelLink")&&!s.events[r][1]._balanced){i=s.events[r][1];break}return l;function l(m){return i?i._inactive?h(m):(a=s.parser.defined.includes(cn(s.sliceSerialize({start:i.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):n(m)}function c(m){return m===40?e.attempt(bx,d,a?d:h)(m):m===91?e.attempt(wx,d,a?u:h)(m):a?d(m):h(m)}function u(m){return e.attempt(Sx,d,h)(m)}function d(m){return t(m)}function h(m){return i._balanced=!0,n(m)}}function Ex(e,t,n){return s;function s(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Me(h)?_n(e,i)(h):i(h)}function i(h){return h===41?d(h):Ec(e,a,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function a(h){return Me(h)?_n(e,c)(h):d(h)}function l(h){return n(h)}function c(h){return h===34||h===39||h===40?Nc(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):d(h)}function u(h){return Me(h)?_n(e,d)(h):d(h)}function d(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),t):n(h)}}function jx(e,t,n){const s=this;return r;function r(l){return jc.call(s,e,i,a,"reference","referenceMarker","referenceString")(l)}function i(l){return s.parser.defined.includes(cn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function a(l){return n(l)}}function Nx(e,t,n){return s;function s(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),r}function r(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const Tx={name:"labelStartImage",resolveAll:lo.resolveAll,tokenize:Px};function Px(e,t,n){const s=this;return r;function r(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),i}function i(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),a):n(l)}function a(l){return l===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(l):t(l)}}const Ix={name:"labelStartLink",resolveAll:lo.resolveAll,tokenize:Ax};function Ax(e,t,n){const s=this;return r;function r(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(a):t(a)}}const ti={name:"lineEnding",tokenize:zx};function zx(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),pe(e,t,"linePrefix")}}const xs={name:"thematicBreak",tokenize:_x};function _x(e,t,n){let s=0,r;return i;function i(u){return e.enter("thematicBreak"),a(u)}function a(u){return r=u,l(u)}function l(u){return u===r?(e.enter("thematicBreakSequence"),c(u)):s>=3&&(u===null||te(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===r?(e.consume(u),s++,c):(e.exit("thematicBreakSequence"),ue(u)?pe(e,l,"whitespace")(u):l(u))}}const De={continuation:{tokenize:Dx},exit:Fx,name:"list",tokenize:Ox},Lx={partial:!0,tokenize:$x},Rx={partial:!0,tokenize:Mx};function Ox(e,t,n){const s=this,r=s.events[s.events.length-1];let i=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,a=0;return l;function l(f){const g=s.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!s.containerState.marker||f===s.containerState.marker:_i(f)){if(s.containerState.type||(s.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(xs,n,u)(f):u(f);if(!s.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return n(f)}function c(f){return _i(f)&&++a<10?(e.consume(f),c):(!s.interrupt||a<2)&&(s.containerState.marker?f===s.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||f,e.check(Vs,s.interrupt?n:d,e.attempt(Lx,m,h))}function d(f){return s.containerState.initialBlankLine=!0,i++,m(f)}function h(f){return ue(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),m):n(f)}function m(f){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Dx(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Vs,r,i);function r(l){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,pe(e,t,"listItemIndent",s.containerState.size+1)(l)}function i(l){return s.containerState.furtherBlankLines||!ue(l)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,a(l)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Rx,t,a)(l))}function a(l){return s.containerState._closeFlow=!0,s.interrupt=void 0,pe(e,e.attempt(De,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Mx(e,t,n){const s=this;return pe(e,r,"listItemIndent",s.containerState.size+1);function r(i){const a=s.events[s.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===s.containerState.size?t(i):n(i)}}function Fx(e){e.exit(this.containerState.type)}function $x(e,t,n){const s=this;return pe(e,r,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(i){const a=s.events[s.events.length-1];return!ue(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Fa={name:"setextUnderline",resolveTo:Bx,tokenize:Vx};function Bx(e,t){let n=e.length,s,r,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){s=n;break}e[n][1].type==="paragraph"&&(r=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const a={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",i?(e.splice(r,0,["enter",a,t]),e.splice(i+1,0,["exit",e[s][1],t]),e[s][1].end={...e[i][1].end}):e[s][1]=a,e.push(["exit",a,t]),e}function Vx(e,t,n){const s=this;let r;return i;function i(u){let d=s.events.length,h;for(;d--;)if(s.events[d][1].type!=="lineEnding"&&s.events[d][1].type!=="linePrefix"&&s.events[d][1].type!=="content"){h=s.events[d][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||h)?(e.enter("setextHeadingLine"),r=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===r?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),ue(u)?pe(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||te(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Ux={tokenize:Hx};function Hx(e){const t=this,n=e.attempt(Vs,s,e.attempt(this.parser.constructs.flowInitial,r,pe(e,e.attempt(this.parser.constructs.flow,r,e.attempt(Jg,r)),"linePrefix")));return n;function s(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function r(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const qx={resolveAll:Pc()},Wx=Tc("string"),Gx=Tc("text");function Tc(e){return{resolveAll:Pc(e==="text"?Qx:void 0),tokenize:t};function t(n){const s=this,r=this.parser.constructs[e],i=n.attempt(r,a,l);return a;function a(d){return u(d)?i(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const h=r[d];let m=-1;if(h)for(;++m<h.length;){const f=h[m];if(!f.previous||f.previous.call(s,s.previous))return!0}return!1}}}function Pc(e){return t;function t(n,s){let r=-1,i;for(;++r<=n.length;)i===void 0?n[r]&&n[r][1].type==="data"&&(i=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==i+2&&(n[i][1].end=n[r-1][1].end,n.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(n,s):n}}function Qx(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const s=e[n-1][1],r=t.sliceStream(s);let i=r.length,a=-1,l=0,c;for(;i--;){const u=r[i];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)l++,a--;if(a)break;a=-1}else if(u===-2)c=!0,l++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const u={type:n===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:s.start._bufferIndex+a,_index:s.start._index+i,line:s.end.line,column:s.end.column-l,offset:s.end.offset-l},end:{...s.end}};s.end={...u.start},s.start.offset===s.end.offset?Object.assign(s,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Jx={42:De,43:De,45:De,48:De,49:De,50:De,51:De,52:De,53:De,54:De,55:De,56:De,57:De,62:Sc},Zx={91:ex},Yx={[-2]:ei,[-1]:ei,32:ei},Kx={35:ox,42:xs,45:[Fa,xs],60:ux,61:Fa,95:xs,96:Da,126:Da},Xx={38:kc,92:vc},ey={[-5]:ti,[-4]:ti,[-3]:ti,33:Tx,38:kc,42:Li,60:[Ig,xx],91:Ix,92:[rx,vc],93:lo,95:Li,96:Ug},ty={null:[Li,qx]},ny={null:[42,95]},sy={null:[]},ry=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:ny,contentInitial:Zx,disable:sy,document:Jx,flow:Kx,flowInitial:Yx,insideSpan:ty,string:Xx,text:ey},Symbol.toStringTag,{value:"Module"}));function iy(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},i=[];let a=[],l=[];const c={attempt:R(A),check:R(E),consume:P,enter:S,exit:j,interrupt:R(E,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:e,previous:null,sliceSerialize:m,sliceStream:f,write:h};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function h(v){return a=Ge(a,v),C(),a[a.length-1]!==null?[]:(F(t,0),u.events=ao(i,u.events,u),u.events)}function m(v,_){return ay(f(v),_)}function f(v){return oy(a,v)}function g(){const{_bufferIndex:v,_index:_,line:L,column:I,offset:N}=s;return{_bufferIndex:v,_index:_,line:L,column:I,offset:N}}function y(v){r[v.line]=v.column,O()}function C(){let v;for(;s._index<a.length;){const _=a[s._index];if(typeof _=="string")for(v=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===v&&s._bufferIndex<_.length;)w(_.charCodeAt(s._bufferIndex));else w(_)}}function w(v){d=d(v)}function P(v){te(v)?(s.line++,s.column=1,s.offset+=v===-3?2:1,O()):v!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===a[s._index].length&&(s._bufferIndex=-1,s._index++)),u.previous=v}function S(v,_){const L=_||{};return L.type=v,L.start=g(),u.events.push(["enter",L,u]),l.push(L),L}function j(v){const _=l.pop();return _.end=g(),u.events.push(["exit",_,u]),_}function A(v,_){F(v,_.from)}function E(v,_){_.restore()}function R(v,_){return L;function L(I,N,z){let U,T,D,x;return Array.isArray(I)?me(I):"tokenize"in I?me([I]):oe(I);function oe(B){return Z;function Z(re){const de=re!==null&&B[re],xe=re!==null&&B.null,ae=[...Array.isArray(de)?de:de?[de]:[],...Array.isArray(xe)?xe:xe?[xe]:[]];return me(ae)(re)}}function me(B){return U=B,T=0,B.length===0?z:b(B[T])}function b(B){return Z;function Z(re){return x=M(),D=B,B.partial||(u.currentConstruct=B),B.name&&u.parser.constructs.disable.null.includes(B.name)?X():B.tokenize.call(_?Object.assign(Object.create(u),_):u,c,Q,X)(re)}}function Q(B){return v(D,x),N}function X(B){return x.restore(),++T<U.length?b(U[T]):z}}}function F(v,_){v.resolveAll&&!i.includes(v)&&i.push(v),v.resolve&&ct(u.events,_,u.events.length-_,v.resolve(u.events.slice(_),u)),v.resolveTo&&(u.events=v.resolveTo(u.events,u))}function M(){const v=g(),_=u.previous,L=u.currentConstruct,I=u.events.length,N=Array.from(l);return{from:I,restore:z};function z(){s=v,u.previous=_,u.currentConstruct=L,u.events.length=I,l=N,O()}}function O(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}function oy(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let a;if(n===r)a=[e[n].slice(s,i)];else{if(a=e.slice(n,r),s>-1){const l=a[0];typeof l=="string"?a[0]=l.slice(s):a.shift()}i>0&&a.push(e[r].slice(0,i))}return a}function ay(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
13
+ </div>`},editFields:[{key:"title",labelZh:"标题",labelEn:"Title",kind:"input",placeholderZh:"课件标题",placeholderEn:"Courseware title"},{key:"coursewareUuid",labelZh:"互动课件 (Courseware)",labelEn:"Courseware",kind:"select",loadOptions:async()=>{try{return(await(await fetch("/api/courseware")).json()).map(n=>({value:n.uuid,label:n.name}))}catch{return[]}}},{key:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:Ts,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:Kl,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:hp,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:Ut,color:"pink",group:"manage",defaultData:{},editFields:[]}],jm=Em.reduce((e,t)=>(e[t.type]=t,e),{});function Nm(e){return jm[e]||zn.get(e)}const ot=hn(e=>({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:t=>e({lang:t}),setActiveRole:t=>e({activeRole:t}),setTeacherTab:t=>e({teacherTab:t}),setProfileOpen:t=>e({profileOpen:t}),setIsCourseWizardOpen:t=>e({isCourseWizardOpen:t}),setIsImportLessonsOpen:t=>e({isImportLessonsOpen:t}),setIsQuizGeneratorOpen:t=>e({isQuizGeneratorOpen:t}),setIsLessonPreviewVisible:t=>e({isLessonPreviewVisible:t}),setIsSystemResourceLibraryOpen:t=>e({isSystemResourceLibraryOpen:t}),setBatchPicker:t=>e({batchPicker:t}),setIsExportWeightModalOpen:t=>e({isExportWeightModalOpen:t}),addToast:t=>e(n=>({toasts:[...n.toasts,t]})),removeToast:t=>e(n=>({toasts:n.toasts.filter(s=>s.id!==t)})),setSiteInfo:t=>e({siteInfo:t})})),_e=hn(e=>({lang:ot.getState().lang,session:null,lessons:[],selectedLesson:null,elements:[],classes:[],students:[],liveClassSelectedClassId:null,liveClassIsActive:!1,teacherTab:ot.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:ot.getState().toasts,siteInfo:ot.getState().siteInfo,setLang:t=>{ot.getState().setLang(t)},setSession:t=>e({session:t}),setLessons:t=>e(n=>({lessons:typeof t=="function"?t(n.lessons):t})),setSelectedLesson:t=>e({selectedLesson:t}),setElements:t=>e({elements:t}),setClasses:t=>e({classes:t}),setStudents:t=>e({students:t}),setLiveClassSelectedClassId:t=>e({liveClassSelectedClassId:t}),setLiveClassIsActive:t=>e({liveClassIsActive:t}),setTeacherTab:t=>{ot.getState().setTeacherTab(t)},setAiProviders:t=>e({aiProviders:t}),setPlugins:t=>e({plugins:t}),setRegisteredCommands:t=>e({registeredCommands:t}),setEvents:t=>e({events:t}),setApprovals:t=>e({approvals:t}),setProcesses:t=>e({processes:t}),setVfsNodes:t=>e({vfsNodes:t}),setTodaySchedules:t=>e({todaySchedules:t}),setComputerLabs:t=>e({computerLabs:t}),setDbConnected:t=>e({dbConnected:t}),setSessionLoading:t=>e({sessionLoading:t}),setClassStudents:(t,n)=>e(s=>({classStudentsMap:{...s.classStudentsMap,[t]:n}})),setClassDashboard:(t,n)=>e(s=>({classDashboardMap:{...s.classDashboardMap,[t]:n}})),setStudentProgress:(t,n)=>e(s=>({studentProgressMap:{...s.studentProgressMap,[t]:n}})),setClassSchedules:(t,n)=>e(s=>({classSchedulesMap:{...s.classSchedulesMap,[t]:n}})),setScheduleAttendance:(t,n)=>e(s=>({scheduleAttendanceMap:{...s.scheduleAttendanceMap,[t]:n}})),setAssignmentSubmissions:(t,n)=>e(s=>({assignmentSubmissionsMap:{...s.assignmentSubmissionsMap,[t]:n}})),setClassAssignments:(t,n)=>e(s=>({classAssignmentsMap:{...s.classAssignmentsMap,[t]:n}})),setClassProgress:(t,n)=>e(s=>({classProgressMap:{...s.classProgressMap,[t]:n}})),setClassSeats:t=>e({classSeats:t}),setOnlineStudentIds:t=>e({onlineStudentIds:t}),setActiveStudentLessons:t=>e({activeStudentLessons:t}),setLiveClassFeed:t=>e({liveClassFeed:t}),appendLiveClassFeed:t=>e(n=>({liveClassFeed:[...n.liveClassFeed.slice(-49),t]})),setLiveClassTimeRemaining:t=>e({liveClassTimeRemaining:t}),setLiveClassAcknowledgedMap:t=>e({liveClassAcknowledgedMap:t}),setLiveClassStudentProgress:t=>e({liveClassStudentProgress:t}),setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t}),addToast:t=>{ot.getState().addToast(t)},removeToast:t=>{ot.getState().removeToast(t)},setSiteInfo:t=>{ot.getState().setSiteInfo(t)}}));ot.subscribe(e=>{_e.setState({lang:e.lang,teacherTab:e.teacherTab,toasts:e.toasts,siteInfo:e.siteInfo})});const he=e=>Vs(_e,e);function Tm(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Pm=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Im=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Am={};function va(e,t){return(Am.jsx?Im:Pm).test(e)}const zm=/[ \t\n\f\r]/g;function _m(e){return typeof e=="object"?e.type==="text"?ka(e.value):!1:ka(e)}function ka(e){return e.replace(zm,"")===""}class Fn{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}Fn.prototype.normal={};Fn.prototype.property={};Fn.prototype.space=void 0;function dc(e,t){const n={},s={};for(const r of e)Object.assign(n,r.property),Object.assign(s,r.normal);return new Fn(n,s,t)}function Ai(e){return e.toLowerCase()}class $e{constructor(t,n){this.attribute=n,this.property=t}}$e.prototype.attribute="";$e.prototype.booleanish=!1;$e.prototype.boolean=!1;$e.prototype.commaOrSpaceSeparated=!1;$e.prototype.commaSeparated=!1;$e.prototype.defined=!1;$e.prototype.mustUseProperty=!1;$e.prototype.number=!1;$e.prototype.overloadedBoolean=!1;$e.prototype.property="";$e.prototype.spaceSeparated=!1;$e.prototype.space=void 0;let Lm=0;const se=Ht(),Se=Ht(),zi=Ht(),H=Ht(),fe=Ht(),Vt=Ht(),Ve=Ht();function Ht(){return 2**++Lm}const _i=Object.freeze(Object.defineProperty({__proto__:null,boolean:se,booleanish:Se,commaOrSpaceSeparated:Ve,commaSeparated:Vt,number:H,overloadedBoolean:zi,spaceSeparated:fe},Symbol.toStringTag,{value:"Module"})),Xr=Object.keys(_i);class no extends $e{constructor(t,n,s,r){let i=-1;if(super(t,n),Ca(this,"space",r),typeof s=="number")for(;++i<Xr.length;){const a=Xr[i];Ca(this,Xr[i],(s&_i[a])===_i[a])}}}no.prototype.defined=!0;function Ca(e,t,n){n&&(e[t]=n)}function fn(e){const t={},n={};for(const[s,r]of Object.entries(e.properties)){const i=new no(s,e.transform(e.attributes||{},s),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(i.mustUseProperty=!0),t[s]=i,n[Ai(s)]=s,n[Ai(i.attribute)]=s}return new Fn(t,n,e.space)}const hc=fn({properties:{ariaActiveDescendant:null,ariaAtomic:Se,ariaAutoComplete:null,ariaBusy:Se,ariaChecked:Se,ariaColCount:H,ariaColIndex:H,ariaColSpan:H,ariaControls:fe,ariaCurrent:null,ariaDescribedBy:fe,ariaDetails:null,ariaDisabled:Se,ariaDropEffect:fe,ariaErrorMessage:null,ariaExpanded:Se,ariaFlowTo:fe,ariaGrabbed:Se,ariaHasPopup:null,ariaHidden:Se,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:fe,ariaLevel:H,ariaLive:null,ariaModal:Se,ariaMultiLine:Se,ariaMultiSelectable:Se,ariaOrientation:null,ariaOwns:fe,ariaPlaceholder:null,ariaPosInSet:H,ariaPressed:Se,ariaReadOnly:Se,ariaRelevant:null,ariaRequired:Se,ariaRoleDescription:fe,ariaRowCount:H,ariaRowIndex:H,ariaRowSpan:H,ariaSelected:Se,ariaSetSize:H,ariaSort:null,ariaValueMax:H,ariaValueMin:H,ariaValueNow:H,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function fc(e,t){return t in e?e[t]:t}function pc(e,t){return fc(e,t.toLowerCase())}const Rm=fn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Vt,acceptCharset:fe,accessKey:fe,action:null,allow:null,allowFullScreen:se,allowPaymentRequest:se,allowUserMedia:se,alpha:se,alt:null,as:null,async:se,autoCapitalize:null,autoComplete:fe,autoFocus:se,autoPlay:se,blocking:fe,capture:null,charSet:null,checked:se,cite:null,className:fe,closedBy:null,colorSpace:null,cols:H,colSpan:H,command:null,commandFor:null,content:null,contentEditable:Se,controls:se,controlsList:fe,coords:H|Vt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:se,defer:se,dir:null,dirName:null,disabled:se,download:zi,draggable:Se,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:se,formTarget:null,headers:fe,height:H,hidden:zi,high:H,href:null,hrefLang:null,htmlFor:fe,httpEquiv:fe,id:null,imageSizes:null,imageSrcSet:null,inert:se,inputMode:null,integrity:null,is:null,isMap:se,itemId:null,itemProp:fe,itemRef:fe,itemScope:se,itemType:fe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:se,low:H,manifest:null,max:null,maxLength:H,media:null,method:null,min:null,minLength:H,multiple:se,muted:se,name:null,nonce:null,noModule:se,noValidate:se,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:se,optimum:H,pattern:null,ping:fe,placeholder:null,playsInline:se,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:se,referrerPolicy:null,rel:fe,required:se,reversed:se,rows:H,rowSpan:H,sandbox:fe,scope:null,scoped:se,seamless:se,selected:se,shadowRootClonable:se,shadowRootCustomElementRegistry:se,shadowRootDelegatesFocus:se,shadowRootMode:null,shadowRootSerializable:se,shape:null,size:H,sizes:null,slot:null,span:H,spellCheck:Se,src:null,srcDoc:null,srcLang:null,srcSet:null,start:H,step:null,style:null,tabIndex:H,target:null,title:null,translate:null,type:null,typeMustMatch:se,useMap:null,value:Se,width:H,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:fe,axis:null,background:null,bgColor:null,border:H,borderColor:null,bottomMargin:H,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:se,declare:se,event:null,face:null,frame:null,frameBorder:null,hSpace:H,leftMargin:H,link:null,longDesc:null,lowSrc:null,marginHeight:H,marginWidth:H,noResize:se,noHref:se,noShade:se,noWrap:se,object:null,profile:null,prompt:null,rev:null,rightMargin:H,rules:null,scheme:null,scrolling:Se,standby:null,summary:null,text:null,topMargin:H,valueType:null,version:null,vAlign:null,vLink:null,vSpace:H,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:se,disablePictureInPicture:se,disableRemotePlayback:se,exportParts:Vt,part:fe,prefix:null,property:null,results:H,security:null,unselectable:null},space:"html",transform:pc}),Om=fn({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",maskType:"mask-type",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ve,accentHeight:H,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:H,amplitude:H,arabicForm:null,ascent:H,attributeName:null,attributeType:null,azimuth:H,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:H,by:null,calcMode:null,capHeight:H,className:fe,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:H,diffuseConstant:H,direction:null,display:null,dur:null,divisor:H,dominantBaseline:null,download:se,dx:null,dy:null,edgeMode:null,editable:null,elevation:H,enableBackground:null,end:null,event:null,exponent:H,externalResourcesRequired:null,fill:null,fillOpacity:H,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Vt,g2:Vt,glyphName:Vt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:H,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:H,horizOriginX:H,horizOriginY:H,id:null,ideographic:H,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:H,k:H,k1:H,k2:H,k3:H,k4:H,kernelMatrix:Ve,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:H,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:H,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:H,overlineThickness:H,paintOrder:null,panose1:null,path:null,pathLength:H,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:fe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:H,pointsAtY:H,pointsAtZ:H,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ve,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ve,rev:Ve,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ve,requiredFeatures:Ve,requiredFonts:Ve,requiredFormats:Ve,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:H,specularExponent:H,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:H,strikethroughThickness:H,string:null,stroke:null,strokeDashArray:Ve,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:H,strokeOpacity:H,strokeWidth:null,style:null,surfaceScale:H,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ve,tabIndex:H,tableValues:null,target:null,targetX:H,targetY:H,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ve,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:H,underlineThickness:H,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:H,values:null,vAlphabetic:H,vMathematical:H,vectorEffect:null,vHanging:H,vIdeographic:H,version:null,vertAdvY:H,vertOriginX:H,vertOriginY:H,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:H,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:fc}),mc=fn({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),gc=fn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:pc}),xc=fn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Mm={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Dm=/[A-Z]/g,Ea=/-[a-z]/g,Fm=/^data[-\w.:]+$/i;function $m(e,t){const n=Ai(t);let s=t,r=$e;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Fm.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Ea,Vm);s="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Ea.test(i)){let a=i.replace(Dm,Bm);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}r=no}return new r(s,t)}function Bm(e){return"-"+e.toLowerCase()}function Vm(e){return e.charAt(1).toUpperCase()}const Um=dc([hc,Rm,mc,gc,xc],"html"),so=dc([hc,Om,mc,gc,xc],"svg");function Hm(e){return e.join(" ").trim()}var en={},ei,ja;function qm(){if(ja)return ei;ja=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,l=/^\s+|\s+$/g,c=`
14
+ `,u="/",d="*",p="",m="comment",h="declaration";function g(v,w){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];w=w||{};var P=1,S=1;function j(I){var N=I.match(t);N&&(P+=N.length);var z=I.lastIndexOf(c);S=~z?I.length-z:S+I.length}function A(){var I={line:P,column:S};return function(N){return N.position=new E(I),D(),N}}function E(I){this.start=I,this.end={line:P,column:S},this.source=w.source}E.prototype.content=v;function R(I){var N=new Error(w.source+":"+P+":"+S+": "+I);if(N.reason=I,N.filename=w.source,N.line=P,N.column=S,N.source=v,!w.silent)throw N}function F(I){var N=I.exec(v);if(N){var z=N[0];return j(z),v=v.slice(z.length),N}}function D(){F(n)}function O(I){var N;for(I=I||[];N=k();)N!==!1&&I.push(N);return I}function k(){var I=A();if(!(u!=v.charAt(0)||d!=v.charAt(1))){for(var N=2;p!=v.charAt(N)&&(d!=v.charAt(N)||u!=v.charAt(N+1));)++N;if(N+=2,p===v.charAt(N-1))return R("End of comment missing");var z=v.slice(2,N-2);return S+=2,j(z),v=v.slice(N),S+=2,I({type:m,comment:z})}}function _(){var I=A(),N=F(s);if(N){if(k(),!F(r))return R("property missing ':'");var z=F(i),U=I({type:h,property:y(N[0].replace(e,p)),value:z?y(z[0].replace(e,p)):p});return F(a),U}}function L(){var I=[];O(I);for(var N;N=_();)N!==!1&&(I.push(N),O(I));return I}return D(),L()}function y(v){return v?v.replace(l,p):p}return ei=g,ei}var Na;function Wm(){if(Na)return en;Na=1;var e=en&&en.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(en,"__esModule",{value:!0}),en.default=n;const t=e(qm());function n(s,r){let i=null;if(!s||typeof s!="string")return i;const a=(0,t.default)(s),l=typeof r=="function";return a.forEach(c=>{if(c.type!=="declaration")return;const{property:u,value:d}=c;l?r(u,d,c):d&&(i=i||{},i[u]=d)}),i}return en}var jn={},Ta;function Gm(){if(Ta)return jn;Ta=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},a=function(u,d){return d.toUpperCase()},l=function(u,d){return"".concat(d,"-")},c=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(r,l):u=u.replace(s,l),u.replace(t,a))};return jn.camelCase=c,jn}var Nn,Pa;function Qm(){if(Pa)return Nn;Pa=1;var e=Nn&&Nn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(Wm()),n=Gm();function s(r,i){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(l,c){l&&c&&(a[(0,n.camelCase)(l,i)]=c)}),a}return s.default=s,Nn=s,Nn}var Jm=Qm();const Zm=Wl(Jm),yc=bc("end"),ro=bc("start");function bc(e){return t;function t(n){const s=n&&n.position&&n.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function Ym(e){const t=ro(e),n=yc(e);if(t&&n)return{start:t,end:n}}function _n(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Ia(e.position):"start"in e||"end"in e?Ia(e):"line"in e||"column"in e?Li(e):""}function Li(e){return Aa(e&&e.line)+":"+Aa(e&&e.column)}function Ia(e){return Li(e&&e.start)+"-"+Li(e&&e.end)}function Aa(e){return e&&typeof e=="number"?e:1}class Le extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let r="",i={},a=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?r=t:!i.cause&&t&&(a=!0,r=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof s=="string"){const c=s.indexOf(":");c===-1?i.ruleId=s:(i.source=s.slice(0,c),i.ruleId=s.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const l=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=l?l.line:void 0,this.name=_n(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Le.prototype.file="";Le.prototype.name="";Le.prototype.reason="";Le.prototype.message="";Le.prototype.stack="";Le.prototype.column=void 0;Le.prototype.line=void 0;Le.prototype.ancestors=void 0;Le.prototype.cause=void 0;Le.prototype.fatal=void 0;Le.prototype.place=void 0;Le.prototype.ruleId=void 0;Le.prototype.source=void 0;const io={}.hasOwnProperty,Km=new Map,Xm=/[A-Z]/g,eg=new Set(["table","tbody","thead","tfoot","tr"]),tg=new Set(["td","th"]),wc="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ng(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=ug(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=cg(n,t.jsx,t.jsxs)}const r={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?so:Um,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Sc(r,e,void 0);return i&&typeof i!="string"?i:r.create(e,r.Fragment,{children:i||void 0},void 0)}function Sc(e,t,n){if(t.type==="element")return sg(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return rg(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return og(e,t,n);if(t.type==="mdxjsEsm")return ig(e,t);if(t.type==="root")return ag(e,t,n);if(t.type==="text")return lg(e,t)}function sg(e,t,n){const s=e.schema;let r=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(r=so,e.schema=r),e.ancestors.push(t);const i=kc(e,t.tagName,!1),a=dg(e,t);let l=ao(e,t);return eg.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!_m(c):!0})),vc(e,a,i,t),oo(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function rg(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Dn(e,t.position)}function ig(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Dn(e,t.position)}function og(e,t,n){const s=e.schema;let r=s;t.name==="svg"&&s.space==="html"&&(r=so,e.schema=r),e.ancestors.push(t);const i=t.name===null?e.Fragment:kc(e,t.name,!0),a=hg(e,t),l=ao(e,t);return vc(e,a,i,t),oo(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function ag(e,t,n){const s={};return oo(s,ao(e,t)),e.create(t,e.Fragment,s,n)}function lg(e,t){return t.value}function vc(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function oo(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function cg(e,t,n){return s;function s(r,i,a,l){const u=Array.isArray(a.children)?n:t;return l?u(i,a,l):u(i,a)}}function ug(e,t){return n;function n(s,r,i,a){const l=Array.isArray(i.children),c=ro(s);return t(r,i,a,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function dg(e,t){const n={};let s,r;for(r in t.properties)if(r!=="children"&&io.call(t.properties,r)){const i=fg(e,r,t.properties[r]);if(i){const[a,l]=i;e.tableCellAlignToStyle&&a==="align"&&typeof l=="string"&&tg.has(t.tagName)?s=l:n[a]=l}}if(s){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function hg(e,t){const n={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const i=s.data.estree.body[0];i.type;const a=i.expression;a.type;const l=a.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else Dn(e,t.position);else{const r=s.name;let i;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const l=s.value.data.estree.body[0];l.type,i=e.evaluater.evaluateExpression(l.expression)}else Dn(e,t.position);else i=s.value===null?!0:s.value;n[r]=i}return n}function ao(e,t){const n=[];let s=-1;const r=e.passKeys?new Map:Km;for(;++s<t.children.length;){const i=t.children[s];let a;if(e.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const u=r.get(c)||0;a=c+"-"+u,r.set(c,u+1)}}const l=Sc(e,i,a);l!==void 0&&n.push(l)}return n}function fg(e,t,n){const s=$m(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?Tm(n):Hm(n)),s.property==="style"){let r=typeof n=="object"?n:pg(e,String(n));return e.stylePropertyNameCase==="css"&&(r=mg(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&s.space?Mm[s.property]||s.property:s.attribute,n]}}function pg(e,t){try{return Zm(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,r=new Le("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=wc+"#cannot-parse-style-attribute",r}}function kc(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let i=-1,a;for(;++i<r.length;){const l=va(r[i])?{type:"Identifier",name:r[i]}:{type:"Literal",value:r[i]};a=a?{type:"MemberExpression",object:a,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}s=a}else s=va(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const r=s.value;return io.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(s);Dn(e)}function Dn(e,t){const n=new Le("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=wc+"#cannot-handle-mdx-estrees-without-createevaluater",n}function mg(e){const t={};let n;for(n in e)io.call(e,n)&&(t[gg(n)]=e[n]);return t}function gg(e){let t=e.replace(Xm,xg);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function xg(e){return"-"+e.toLowerCase()}const ti={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},yg={};function bg(e,t){const n=yg,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Cc(e,s,r)}function Cc(e,t,n){if(wg(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return za(e.children,t,n)}return Array.isArray(e)?za(e,t,n):""}function za(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=Cc(e[r],t,n);return s.join("")}function wg(e){return!!(e&&typeof e=="object")}const _a=document.createElement("i");function lo(e){const t="&"+e+";";_a.innerHTML=t;const n=_a.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ct(e,t,n,s){const r=e.length;let i=0,a;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,s.length<1e4)a=Array.from(s),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);i<s.length;)a=s.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function Qe(e,t){return e.length>0?(ct(e,e.length,0,t),e):t}const La={}.hasOwnProperty;function Sg(e){const t={};let n=-1;for(;++n<e.length;)vg(t,e[n]);return t}function vg(e,t){let n;for(n in t){const r=(La.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){La.call(r,a)||(r[a]=[]);const l=i[a];kg(r[a],Array.isArray(l)?l:l?[l]:[])}}}function kg(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);ct(e,0,0,s)}function Ec(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function cn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const lt=Rt(/[A-Za-z]/),Ue=Rt(/[\dA-Za-z]/),Cg=Rt(/[#-'*+\--9=?A-Z^-~]/);function Ri(e){return e!==null&&(e<32||e===127)}const Oi=Rt(/\d/),Eg=Rt(/[\dA-Fa-f]/),jg=Rt(/[!-/:-@[-`{-~]/);function te(e){return e!==null&&e<-2}function Fe(e){return e!==null&&(e<0||e===32)}function ue(e){return e===-2||e===-1||e===32}const Ng=Rt(/\p{P}|\p{S}/u),Tg=Rt(/\s/);function Rt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function pn(e){const t=[];let n=-1,s=0,r=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&Ue(e.charCodeAt(n+1))&&Ue(e.charCodeAt(n+2)))r=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const l=e.charCodeAt(n+1);i<56320&&l>56319&&l<57344?(a=String.fromCharCode(i,l),r=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(s,n),encodeURIComponent(a)),s=n+r+1,a=""),r&&(n+=r,r=0)}return t.join("")+e.slice(s)}function pe(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(c){return ue(c)?(e.enter(n),l(c)):t(c)}function l(c){return ue(c)&&i++<r?(e.consume(c),l):(e.exit(n),t(c))}}const Pg={tokenize:Ig};function Ig(e){const t=e.attempt(this.parser.constructs.contentInitial,s,r);let n;return t;function s(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),pe(e,t,"linePrefix")}function r(l){return e.enter("paragraph"),i(l)}function i(l){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(l)}function a(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return te(l)?(e.consume(l),e.exit("chunkText"),i):(e.consume(l),a)}}const Ag={tokenize:zg},Ra={tokenize:_g};function zg(e){const t=this,n=[];let s=0,r,i,a;return l;function l(S){if(s<n.length){const j=n[s];return t.containerState=j[1],e.attempt(j[0].continuation,c,u)(S)}return u(S)}function c(S){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&P();const j=t.events.length;let A=j,E;for(;A--;)if(t.events[A][0]==="exit"&&t.events[A][1].type==="chunkFlow"){E=t.events[A][1].end;break}w(s);let R=j;for(;R<t.events.length;)t.events[R][1].end={...E},R++;return ct(t.events,A+1,0,t.events.slice(j)),t.events.length=R,u(S)}return l(S)}function u(S){if(s===n.length){if(!r)return m(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Ra,d,p)(S)}function d(S){return r&&P(),w(s),m(S)}function p(S){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,g(S)}function m(S){return t.containerState={},e.attempt(Ra,h,g)(S)}function h(S){return s++,n.push([t.currentConstruct,t.containerState]),m(S)}function g(S){if(S===null){r&&P(),w(0),e.consume(S);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:i}),y(S)}function y(S){if(S===null){v(e.exit("chunkFlow"),!0),w(0),e.consume(S);return}return te(S)?(e.consume(S),v(e.exit("chunkFlow")),s=0,t.interrupt=void 0,l):(e.consume(S),y)}function v(S,j){const A=t.sliceStream(S);if(j&&A.push(null),S.previous=i,i&&(i.next=S),i=S,r.defineSkip(S.start),r.write(A),t.parser.lazy[S.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<a&&(!r.events[E][1].end||r.events[E][1].end.offset>a))return;const R=t.events.length;let F=R,D,O;for(;F--;)if(t.events[F][0]==="exit"&&t.events[F][1].type==="chunkFlow"){if(D){O=t.events[F][1].end;break}D=!0}for(w(s),E=R;E<t.events.length;)t.events[E][1].end={...O},E++;ct(t.events,F+1,0,t.events.slice(R)),t.events.length=E}}function w(S){let j=n.length;for(;j-- >S;){const A=n[j];t.containerState=A[1],A[0].exit.call(t,e)}n.length=S}function P(){r.write([null]),i=void 0,r=void 0,t.containerState._closeFlow=void 0}}function _g(e,t,n){return pe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Oa(e){if(e===null||Fe(e)||Tg(e))return 1;if(Ng(e))return 2}function co(e,t,n){const s=[];let r=-1;for(;++r<e.length;){const i=e[r].resolveAll;i&&!s.includes(i)&&(t=i(t,n),s.push(i))}return t}const Mi={name:"attention",resolveAll:Lg,tokenize:Rg};function Lg(e,t){let n=-1,s,r,i,a,l,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(s=n;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[s][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const p={...e[s][1].end},m={...e[n][1].start};Ma(p,-c),Ma(m,c),a={type:c>1?"strongSequence":"emphasisSequence",start:p,end:{...e[s][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},r={type:c>1?"strong":"emphasis",start:{...a.start},end:{...l.end}},e[s][1].end={...a.start},e[n][1].start={...l.end},u=[],e[s][1].end.offset-e[s][1].start.offset&&(u=Qe(u,[["enter",e[s][1],t],["exit",e[s][1],t]])),u=Qe(u,[["enter",r,t],["enter",a,t],["exit",a,t],["enter",i,t]]),u=Qe(u,co(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),u=Qe(u,[["exit",i,t],["enter",l,t],["exit",l,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=Qe(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,ct(e,s-1,n-s+3,u),n=s+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function Rg(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,r=Oa(s);let i;return a;function a(c){return i=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===i)return e.consume(c),l;const u=e.exit("attentionSequence"),d=Oa(c),p=!d||d===2&&r||n.includes(c),m=!r||r===2&&d||n.includes(s);return u._open=!!(i===42?p:p&&(r||!m)),u._close=!!(i===42?m:m&&(d||!p)),t(c)}}function Ma(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Og={name:"autolink",tokenize:Mg};function Mg(e,t,n){let s=0;return r;function r(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(h){return lt(h)?(e.consume(h),a):h===64?n(h):u(h)}function a(h){return h===43||h===45||h===46||Ue(h)?(s=1,l(h)):u(h)}function l(h){return h===58?(e.consume(h),s=0,c):(h===43||h===45||h===46||Ue(h))&&s++<32?(e.consume(h),l):(s=0,u(h))}function c(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||Ri(h)?n(h):(e.consume(h),c)}function u(h){return h===64?(e.consume(h),d):Cg(h)?(e.consume(h),u):n(h)}function d(h){return Ue(h)?p(h):n(h)}function p(h){return h===46?(e.consume(h),s=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):m(h)}function m(h){if((h===45||Ue(h))&&s++<63){const g=h===45?m:p;return e.consume(h),g}return n(h)}}const Hs={partial:!0,tokenize:Dg};function Dg(e,t,n){return s;function s(i){return ue(i)?pe(e,r,"linePrefix")(i):r(i)}function r(i){return i===null||te(i)?t(i):n(i)}}const jc={continuation:{tokenize:$g},exit:Bg,name:"blockQuote",tokenize:Fg};function Fg(e,t,n){const s=this;return r;function r(a){if(a===62){const l=s.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return n(a)}function i(a){return ue(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function $g(e,t,n){const s=this;return r;function r(a){return ue(a)?pe(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(jc,t,n)(a)}}function Bg(e){e.exit("blockQuote")}const Nc={name:"characterEscape",tokenize:Vg};function Vg(e,t,n){return s;function s(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),r}function r(i){return jg(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const Tc={name:"characterReference",tokenize:Ug};function Ug(e,t,n){const s=this;let r=0,i,a;return l;function l(p){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),c}function c(p){return p===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(p),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,a=Ue,d(p))}function u(p){return p===88||p===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(p),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=Eg,d):(e.enter("characterReferenceValue"),i=7,a=Oi,d(p))}function d(p){if(p===59&&r){const m=e.exit("characterReferenceValue");return a===Ue&&!lo(s.sliceSerialize(m))?n(p):(e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(p)&&r++<i?(e.consume(p),d):n(p)}}const Da={partial:!0,tokenize:qg},Fa={concrete:!0,name:"codeFenced",tokenize:Hg};function Hg(e,t,n){const s=this,r={partial:!0,tokenize:A};let i=0,a=0,l;return c;function c(E){return u(E)}function u(E){const R=s.events[s.events.length-1];return i=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,l=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(E)}function d(E){return E===l?(a++,e.consume(E),d):a<3?n(E):(e.exit("codeFencedFenceSequence"),ue(E)?pe(e,p,"whitespace")(E):p(E))}function p(E){return E===null||te(E)?(e.exit("codeFencedFence"),s.interrupt?t(E):e.check(Da,y,j)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(E))}function m(E){return E===null||te(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(E)):ue(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),pe(e,h,"whitespace")(E)):E===96&&E===l?n(E):(e.consume(E),m)}function h(E){return E===null||te(E)?p(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||te(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),p(E)):E===96&&E===l?n(E):(e.consume(E),g)}function y(E){return e.attempt(r,j,v)(E)}function v(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),w}function w(E){return i>0&&ue(E)?pe(e,P,"linePrefix",i+1)(E):P(E)}function P(E){return E===null||te(E)?e.check(Da,y,j)(E):(e.enter("codeFlowValue"),S(E))}function S(E){return E===null||te(E)?(e.exit("codeFlowValue"),P(E)):(e.consume(E),S)}function j(E){return e.exit("codeFenced"),t(E)}function A(E,R,F){let D=0;return O;function O(N){return E.enter("lineEnding"),E.consume(N),E.exit("lineEnding"),k}function k(N){return E.enter("codeFencedFence"),ue(N)?pe(E,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):_(N)}function _(N){return N===l?(E.enter("codeFencedFenceSequence"),L(N)):F(N)}function L(N){return N===l?(D++,E.consume(N),L):D>=a?(E.exit("codeFencedFenceSequence"),ue(N)?pe(E,I,"whitespace")(N):I(N)):F(N)}function I(N){return N===null||te(N)?(E.exit("codeFencedFence"),R(N)):F(N)}}}function qg(e,t,n){const s=this;return r;function r(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}const ni={name:"codeIndented",tokenize:Gg},Wg={partial:!0,tokenize:Qg};function Gg(e,t,n){const s=this;return r;function r(u){return e.enter("codeIndented"),pe(e,i,"linePrefix",5)(u)}function i(u){const d=s.events[s.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?c(u):te(u)?e.attempt(Wg,a,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||te(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function Qg(e,t,n){const s=this;return r;function r(a){return s.parser.lazy[s.now().line]?n(a):te(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r):pe(e,i,"linePrefix",5)(a)}function i(a){const l=s.events[s.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):te(a)?r(a):n(a)}}const Jg={name:"codeText",previous:Yg,resolve:Zg,tokenize:Kg};function Zg(e){let t=e.length-4,n=3,s,r;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=n;++s<t;)if(e[s][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(s=n-1,t++;++s<=t;)r===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(r=s):(s===t||e[s][1].type==="lineEnding")&&(e[r][1].type="codeTextData",s!==r+2&&(e[r][1].end=e[s-1][1].end,e.splice(r+2,s-r-2),t-=s-r-2,s=r+2),r=void 0);return e}function Yg(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Kg(e,t,n){let s=0,r,i;return a;function a(p){return e.enter("codeText"),e.enter("codeTextSequence"),l(p)}function l(p){return p===96?(e.consume(p),s++,l):(e.exit("codeTextSequence"),c(p))}function c(p){return p===null?n(p):p===32?(e.enter("space"),e.consume(p),e.exit("space"),c):p===96?(i=e.enter("codeTextSequence"),r=0,d(p)):te(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(p))}function u(p){return p===null||p===32||p===96||te(p)?(e.exit("codeTextData"),c(p)):(e.consume(p),u)}function d(p){return p===96?(e.consume(p),r++,d):r===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(p)):(i.type="codeTextData",u(p))}}class Xg{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const s=n??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,n,s){const r=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return s&&Tn(this.left,s),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Tn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Tn(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Tn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Tn(this.left,n.reverse())}}}function Tn(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Pc(e){const t={};let n=-1,s,r,i,a,l,c,u;const d=new Xg(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(s=d.get(n),n&&s[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=s[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,ex(d,n)),n=t[n],u=!0);else if(s[1]._container){for(i=n,r=void 0;i--;)if(a=d.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(d.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(s[1].end={...d.get(r)[1].start},l=d.slice(r,n),l.unshift(s),d.splice(r,n-r+1,l))}}return ct(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function ex(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];let a=n._tokenizer;a||(a=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const l=a.events,c=[],u={};let d,p,m=-1,h=n,g=0,y=0;const v=[y];for(;h;){for(;e.get(++r)[1]!==h;);i.push(r),h._tokenizer||(d=s.sliceStream(h),h.next||d.push(null),p&&a.defineSkip(h.start),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),p=h,h=h.next}for(h=n;++m<l.length;)l[m][0]==="exit"&&l[m-1][0]==="enter"&&l[m][1].type===l[m-1][1].type&&l[m][1].start.line!==l[m][1].end.line&&(y=m+1,v.push(y),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(a.events=[],h?(h._tokenizer=void 0,h.previous=void 0):v.pop(),m=v.length;m--;){const w=l.slice(v[m],v[m+1]),P=i.pop();c.push([P,P+w.length-1]),e.splice(P,2,w)}for(c.reverse(),m=-1;++m<c.length;)u[g+c[m][0]]=g+c[m][1],g+=c[m][1]-c[m][0]-1;return u}const tx={resolve:sx,tokenize:rx},nx={partial:!0,tokenize:ix};function sx(e){return Pc(e),e}function rx(e,t){let n;return s;function s(l){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(l)}function r(l){return l===null?i(l):te(l)?e.check(nx,a,i)(l):(e.consume(l),r)}function i(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function a(l){return e.consume(l),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function ix(e,t,n){const s=this;return r;function r(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),pe(e,i,"linePrefix")}function i(a){if(a===null||te(a))return n(a);const l=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):e.interrupt(s.parser.constructs.flow,n,t)(a)}}function Ic(e,t,n,s,r,i,a,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return p;function p(w){return w===60?(e.enter(s),e.enter(r),e.enter(i),e.consume(w),e.exit(i),m):w===null||w===32||w===41||Ri(w)?n(w):(e.enter(s),e.enter(a),e.enter(l),e.enter("chunkString",{contentType:"string"}),y(w))}function m(w){return w===62?(e.enter(i),e.consume(w),e.exit(i),e.exit(r),e.exit(s),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===62?(e.exit("chunkString"),e.exit(l),m(w)):w===null||w===60||te(w)?n(w):(e.consume(w),w===92?g:h)}function g(w){return w===60||w===62||w===92?(e.consume(w),h):h(w)}function y(w){return!d&&(w===null||w===41||Fe(w))?(e.exit("chunkString"),e.exit(l),e.exit(a),e.exit(s),t(w)):d<u&&w===40?(e.consume(w),d++,y):w===41?(e.consume(w),d--,y):w===null||w===32||w===40||Ri(w)?n(w):(e.consume(w),w===92?v:y)}function v(w){return w===40||w===41||w===92?(e.consume(w),y):y(w)}}function Ac(e,t,n,s,r,i){const a=this;let l=0,c;return u;function u(h){return e.enter(s),e.enter(r),e.consume(h),e.exit(r),e.enter(i),d}function d(h){return l>999||h===null||h===91||h===93&&!c||h===94&&!l&&"_hiddenFootnoteSupport"in a.parser.constructs?n(h):h===93?(e.exit(i),e.enter(r),e.consume(h),e.exit(r),e.exit(s),t):te(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),p(h))}function p(h){return h===null||h===91||h===93||te(h)||l++>999?(e.exit("chunkString"),d(h)):(e.consume(h),c||(c=!ue(h)),h===92?m:p)}function m(h){return h===91||h===92||h===93?(e.consume(h),l++,p):p(h)}}function zc(e,t,n,s,r,i){let a;return l;function l(m){return m===34||m===39||m===40?(e.enter(s),e.enter(r),e.consume(m),e.exit(r),a=m===40?41:m,c):n(m)}function c(m){return m===a?(e.enter(r),e.consume(m),e.exit(r),e.exit(s),t):(e.enter(i),u(m))}function u(m){return m===a?(e.exit(i),c(a)):m===null?n(m):te(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),pe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===a||m===null||te(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?p:d)}function p(m){return m===a||m===92?(e.consume(m),d):d(m)}}function Ln(e,t){let n;return s;function s(r){return te(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):ue(r)?pe(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const ox={name:"definition",tokenize:lx},ax={partial:!0,tokenize:cx};function lx(e,t,n){const s=this;let r;return i;function i(h){return e.enter("definition"),a(h)}function a(h){return Ac.call(s,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function l(h){return r=cn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),c):n(h)}function c(h){return Fe(h)?Ln(e,u)(h):u(h)}function u(h){return Ic(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(ax,p,p)(h)}function p(h){return ue(h)?pe(e,m,"whitespace")(h):m(h)}function m(h){return h===null||te(h)?(e.exit("definition"),s.parser.defined.push(r),t(h)):n(h)}}function cx(e,t,n){return s;function s(l){return Fe(l)?Ln(e,r)(l):n(l)}function r(l){return zc(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return ue(l)?pe(e,a,"whitespace")(l):a(l)}function a(l){return l===null||te(l)?t(l):n(l)}}const ux={name:"hardBreakEscape",tokenize:dx};function dx(e,t,n){return s;function s(i){return e.enter("hardBreakEscape"),e.consume(i),r}function r(i){return te(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const hx={name:"headingAtx",resolve:fx,tokenize:px};function fx(e,t){let n=e.length-2,s=3,r,i;return e[s][1].type==="whitespace"&&(s+=2),n-2>s&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(s===n-1||n-4>s&&e[n-2][1].type==="whitespace")&&(n-=s+1===n?2:4),n>s&&(r={type:"atxHeadingText",start:e[s][1].start,end:e[n][1].end},i={type:"chunkText",start:e[s][1].start,end:e[n][1].end,contentType:"text"},ct(e,s,n-s+1,[["enter",r,t],["enter",i,t],["exit",i,t],["exit",r,t]])),e}function px(e,t,n){let s=0;return r;function r(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&s++<6?(e.consume(d),a):d===null||Fe(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||te(d)?(e.exit("atxHeading"),t(d)):ue(d)?pe(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||Fe(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const mx=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],$a=["pre","script","style","textarea"],gx={concrete:!0,name:"htmlFlow",resolveTo:bx,tokenize:wx},xx={partial:!0,tokenize:vx},yx={partial:!0,tokenize:Sx};function bx(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function wx(e,t,n){const s=this;let r,i,a,l,c;return u;function u(b){return d(b)}function d(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),p}function p(b){return b===33?(e.consume(b),m):b===47?(e.consume(b),i=!0,y):b===63?(e.consume(b),r=3,s.interrupt?t:x):lt(b)?(e.consume(b),a=String.fromCharCode(b),v):n(b)}function m(b){return b===45?(e.consume(b),r=2,h):b===91?(e.consume(b),r=5,l=0,g):lt(b)?(e.consume(b),r=4,s.interrupt?t:x):n(b)}function h(b){return b===45?(e.consume(b),s.interrupt?t:x):n(b)}function g(b){const Q="CDATA[";return b===Q.charCodeAt(l++)?(e.consume(b),l===Q.length?s.interrupt?t:_:g):n(b)}function y(b){return lt(b)?(e.consume(b),a=String.fromCharCode(b),v):n(b)}function v(b){if(b===null||b===47||b===62||Fe(b)){const Q=b===47,X=a.toLowerCase();return!Q&&!i&&$a.includes(X)?(r=1,s.interrupt?t(b):_(b)):mx.includes(a.toLowerCase())?(r=6,Q?(e.consume(b),w):s.interrupt?t(b):_(b)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(b):i?P(b):S(b))}return b===45||Ue(b)?(e.consume(b),a+=String.fromCharCode(b),v):n(b)}function w(b){return b===62?(e.consume(b),s.interrupt?t:_):n(b)}function P(b){return ue(b)?(e.consume(b),P):O(b)}function S(b){return b===47?(e.consume(b),O):b===58||b===95||lt(b)?(e.consume(b),j):ue(b)?(e.consume(b),S):O(b)}function j(b){return b===45||b===46||b===58||b===95||Ue(b)?(e.consume(b),j):A(b)}function A(b){return b===61?(e.consume(b),E):ue(b)?(e.consume(b),A):S(b)}function E(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),c=b,R):ue(b)?(e.consume(b),E):F(b)}function R(b){return b===c?(e.consume(b),c=null,D):b===null||te(b)?n(b):(e.consume(b),R)}function F(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||Fe(b)?A(b):(e.consume(b),F)}function D(b){return b===47||b===62||ue(b)?S(b):n(b)}function O(b){return b===62?(e.consume(b),k):n(b)}function k(b){return b===null||te(b)?_(b):ue(b)?(e.consume(b),k):n(b)}function _(b){return b===45&&r===2?(e.consume(b),z):b===60&&r===1?(e.consume(b),U):b===62&&r===4?(e.consume(b),oe):b===63&&r===3?(e.consume(b),x):b===93&&r===5?(e.consume(b),M):te(b)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(xx,me,L)(b)):b===null||te(b)?(e.exit("htmlFlowData"),L(b)):(e.consume(b),_)}function L(b){return e.check(yx,I,me)(b)}function I(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),N}function N(b){return b===null||te(b)?L(b):(e.enter("htmlFlowData"),_(b))}function z(b){return b===45?(e.consume(b),x):_(b)}function U(b){return b===47?(e.consume(b),a="",T):_(b)}function T(b){if(b===62){const Q=a.toLowerCase();return $a.includes(Q)?(e.consume(b),oe):_(b)}return lt(b)&&a.length<8?(e.consume(b),a+=String.fromCharCode(b),T):_(b)}function M(b){return b===93?(e.consume(b),x):_(b)}function x(b){return b===62?(e.consume(b),oe):b===45&&r===2?(e.consume(b),x):_(b)}function oe(b){return b===null||te(b)?(e.exit("htmlFlowData"),me(b)):(e.consume(b),oe)}function me(b){return e.exit("htmlFlow"),t(b)}}function Sx(e,t,n){const s=this;return r;function r(a){return te(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):n(a)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}function vx(e,t,n){return s;function s(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Hs,t,n)}}const kx={name:"htmlText",tokenize:Cx};function Cx(e,t,n){const s=this;let r,i,a;return l;function l(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),c}function c(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),A):x===63?(e.consume(x),S):lt(x)?(e.consume(x),F):n(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):lt(x)?(e.consume(x),P):n(x)}function d(x){return x===45?(e.consume(x),h):n(x)}function p(x){return x===null?n(x):x===45?(e.consume(x),m):te(x)?(a=p,U(x)):(e.consume(x),p)}function m(x){return x===45?(e.consume(x),h):p(x)}function h(x){return x===62?z(x):x===45?m(x):p(x)}function g(x){const oe="CDATA[";return x===oe.charCodeAt(i++)?(e.consume(x),i===oe.length?y:g):n(x)}function y(x){return x===null?n(x):x===93?(e.consume(x),v):te(x)?(a=y,U(x)):(e.consume(x),y)}function v(x){return x===93?(e.consume(x),w):y(x)}function w(x){return x===62?z(x):x===93?(e.consume(x),w):y(x)}function P(x){return x===null||x===62?z(x):te(x)?(a=P,U(x)):(e.consume(x),P)}function S(x){return x===null?n(x):x===63?(e.consume(x),j):te(x)?(a=S,U(x)):(e.consume(x),S)}function j(x){return x===62?z(x):S(x)}function A(x){return lt(x)?(e.consume(x),E):n(x)}function E(x){return x===45||Ue(x)?(e.consume(x),E):R(x)}function R(x){return te(x)?(a=R,U(x)):ue(x)?(e.consume(x),R):z(x)}function F(x){return x===45||Ue(x)?(e.consume(x),F):x===47||x===62||Fe(x)?D(x):n(x)}function D(x){return x===47?(e.consume(x),z):x===58||x===95||lt(x)?(e.consume(x),O):te(x)?(a=D,U(x)):ue(x)?(e.consume(x),D):z(x)}function O(x){return x===45||x===46||x===58||x===95||Ue(x)?(e.consume(x),O):k(x)}function k(x){return x===61?(e.consume(x),_):te(x)?(a=k,U(x)):ue(x)?(e.consume(x),k):D(x)}function _(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),r=x,L):te(x)?(a=_,U(x)):ue(x)?(e.consume(x),_):(e.consume(x),I)}function L(x){return x===r?(e.consume(x),r=void 0,N):x===null?n(x):te(x)?(a=L,U(x)):(e.consume(x),L)}function I(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||Fe(x)?D(x):(e.consume(x),I)}function N(x){return x===47||x===62||Fe(x)?D(x):n(x)}function z(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function U(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),T}function T(x){return ue(x)?pe(e,M,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):M(x)}function M(x){return e.enter("htmlTextData"),a(x)}}const uo={name:"labelEnd",resolveAll:Tx,resolveTo:Px,tokenize:Ix},Ex={tokenize:Ax},jx={tokenize:zx},Nx={tokenize:_x};function Tx(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const r=s.type==="labelImage"?4:2;s.type="data",t+=r}}return e.length!==n.length&&ct(e,0,e.length,n),e}function Px(e,t){let n=e.length,s=0,r,i,a,l;for(;n--;)if(r=e[n][1],i){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(i=n,r.type!=="labelLink")){s=2;break}}else r.type==="labelEnd"&&(a=n);const c={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[a][1].end}},d={type:"labelText",start:{...e[i+s+2][1].end},end:{...e[a-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=Qe(l,e.slice(i+1,i+s+3)),l=Qe(l,[["enter",d,t]]),l=Qe(l,co(t.parser.constructs.insideSpan.null,e.slice(i+s+4,a-3),t)),l=Qe(l,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),l=Qe(l,e.slice(a+1)),l=Qe(l,[["exit",c,t]]),ct(e,i,e.length,l),e}function Ix(e,t,n){const s=this;let r=s.events.length,i,a;for(;r--;)if((s.events[r][1].type==="labelImage"||s.events[r][1].type==="labelLink")&&!s.events[r][1]._balanced){i=s.events[r][1];break}return l;function l(m){return i?i._inactive?p(m):(a=s.parser.defined.includes(cn(s.sliceSerialize({start:i.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):n(m)}function c(m){return m===40?e.attempt(Ex,d,a?d:p)(m):m===91?e.attempt(jx,d,a?u:p)(m):a?d(m):p(m)}function u(m){return e.attempt(Nx,d,p)(m)}function d(m){return t(m)}function p(m){return i._balanced=!0,n(m)}}function Ax(e,t,n){return s;function s(p){return e.enter("resource"),e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),r}function r(p){return Fe(p)?Ln(e,i)(p):i(p)}function i(p){return p===41?d(p):Ic(e,a,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function a(p){return Fe(p)?Ln(e,c)(p):d(p)}function l(p){return n(p)}function c(p){return p===34||p===39||p===40?zc(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):d(p)}function u(p){return Fe(p)?Ln(e,d)(p):d(p)}function d(p){return p===41?(e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),e.exit("resource"),t):n(p)}}function zx(e,t,n){const s=this;return r;function r(l){return Ac.call(s,e,i,a,"reference","referenceMarker","referenceString")(l)}function i(l){return s.parser.defined.includes(cn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function a(l){return n(l)}}function _x(e,t,n){return s;function s(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),r}function r(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const Lx={name:"labelStartImage",resolveAll:uo.resolveAll,tokenize:Rx};function Rx(e,t,n){const s=this;return r;function r(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),i}function i(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),a):n(l)}function a(l){return l===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(l):t(l)}}const Ox={name:"labelStartLink",resolveAll:uo.resolveAll,tokenize:Mx};function Mx(e,t,n){const s=this;return r;function r(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(a):t(a)}}const si={name:"lineEnding",tokenize:Dx};function Dx(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),pe(e,t,"linePrefix")}}const xs={name:"thematicBreak",tokenize:Fx};function Fx(e,t,n){let s=0,r;return i;function i(u){return e.enter("thematicBreak"),a(u)}function a(u){return r=u,l(u)}function l(u){return u===r?(e.enter("thematicBreakSequence"),c(u)):s>=3&&(u===null||te(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===r?(e.consume(u),s++,c):(e.exit("thematicBreakSequence"),ue(u)?pe(e,l,"whitespace")(u):l(u))}}const Me={continuation:{tokenize:Ux},exit:qx,name:"list",tokenize:Vx},$x={partial:!0,tokenize:Wx},Bx={partial:!0,tokenize:Hx};function Vx(e,t,n){const s=this,r=s.events[s.events.length-1];let i=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,a=0;return l;function l(h){const g=s.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!s.containerState.marker||h===s.containerState.marker:Oi(h)){if(s.containerState.type||(s.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(xs,n,u)(h):u(h);if(!s.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(h)}return n(h)}function c(h){return Oi(h)&&++a<10?(e.consume(h),c):(!s.interrupt||a<2)&&(s.containerState.marker?h===s.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||h,e.check(Hs,s.interrupt?n:d,e.attempt($x,m,p))}function d(h){return s.containerState.initialBlankLine=!0,i++,m(h)}function p(h){return ue(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),m):n(h)}function m(h){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function Ux(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Hs,r,i);function r(l){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,pe(e,t,"listItemIndent",s.containerState.size+1)(l)}function i(l){return s.containerState.furtherBlankLines||!ue(l)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,a(l)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Bx,t,a)(l))}function a(l){return s.containerState._closeFlow=!0,s.interrupt=void 0,pe(e,e.attempt(Me,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Hx(e,t,n){const s=this;return pe(e,r,"listItemIndent",s.containerState.size+1);function r(i){const a=s.events[s.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===s.containerState.size?t(i):n(i)}}function qx(e){e.exit(this.containerState.type)}function Wx(e,t,n){const s=this;return pe(e,r,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(i){const a=s.events[s.events.length-1];return!ue(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Ba={name:"setextUnderline",resolveTo:Gx,tokenize:Qx};function Gx(e,t){let n=e.length,s,r,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){s=n;break}e[n][1].type==="paragraph"&&(r=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const a={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",i?(e.splice(r,0,["enter",a,t]),e.splice(i+1,0,["exit",e[s][1],t]),e[s][1].end={...e[i][1].end}):e[s][1]=a,e.push(["exit",a,t]),e}function Qx(e,t,n){const s=this;let r;return i;function i(u){let d=s.events.length,p;for(;d--;)if(s.events[d][1].type!=="lineEnding"&&s.events[d][1].type!=="linePrefix"&&s.events[d][1].type!=="content"){p=s.events[d][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||p)?(e.enter("setextHeadingLine"),r=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===r?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),ue(u)?pe(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||te(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Jx={tokenize:Zx};function Zx(e){const t=this,n=e.attempt(Hs,s,e.attempt(this.parser.constructs.flowInitial,r,pe(e,e.attempt(this.parser.constructs.flow,r,e.attempt(tx,r)),"linePrefix")));return n;function s(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function r(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Yx={resolveAll:Lc()},Kx=_c("string"),Xx=_c("text");function _c(e){return{resolveAll:Lc(e==="text"?ey:void 0),tokenize:t};function t(n){const s=this,r=this.parser.constructs[e],i=n.attempt(r,a,l);return a;function a(d){return u(d)?i(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const p=r[d];let m=-1;if(p)for(;++m<p.length;){const h=p[m];if(!h.previous||h.previous.call(s,s.previous))return!0}return!1}}}function Lc(e){return t;function t(n,s){let r=-1,i;for(;++r<=n.length;)i===void 0?n[r]&&n[r][1].type==="data"&&(i=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==i+2&&(n[i][1].end=n[r-1][1].end,n.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(n,s):n}}function ey(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const s=e[n-1][1],r=t.sliceStream(s);let i=r.length,a=-1,l=0,c;for(;i--;){const u=r[i];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)l++,a--;if(a)break;a=-1}else if(u===-2)c=!0,l++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const u={type:n===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:s.start._bufferIndex+a,_index:s.start._index+i,line:s.end.line,column:s.end.column-l,offset:s.end.offset-l},end:{...s.end}};s.end={...u.start},s.start.offset===s.end.offset?Object.assign(s,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const ty={42:Me,43:Me,45:Me,48:Me,49:Me,50:Me,51:Me,52:Me,53:Me,54:Me,55:Me,56:Me,57:Me,62:jc},ny={91:ox},sy={[-2]:ni,[-1]:ni,32:ni},ry={35:hx,42:xs,45:[Ba,xs],60:gx,61:Ba,95:xs,96:Fa,126:Fa},iy={38:Tc,92:Nc},oy={[-5]:si,[-4]:si,[-3]:si,33:Lx,38:Tc,42:Mi,60:[Og,kx],91:Ox,92:[ux,Nc],93:uo,95:Mi,96:Jg},ay={null:[Mi,Yx]},ly={null:[42,95]},cy={null:[]},uy=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:ly,contentInitial:ny,disable:cy,document:ty,flow:ry,flowInitial:sy,insideSpan:ay,string:iy,text:oy},Symbol.toStringTag,{value:"Module"}));function dy(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},i=[];let a=[],l=[];const c={attempt:R(A),check:R(E),consume:P,enter:S,exit:j,interrupt:R(E,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:e,previous:null,sliceSerialize:m,sliceStream:h,write:p};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function p(k){return a=Qe(a,k),v(),a[a.length-1]!==null?[]:(F(t,0),u.events=co(i,u.events,u),u.events)}function m(k,_){return fy(h(k),_)}function h(k){return hy(a,k)}function g(){const{_bufferIndex:k,_index:_,line:L,column:I,offset:N}=s;return{_bufferIndex:k,_index:_,line:L,column:I,offset:N}}function y(k){r[k.line]=k.column,O()}function v(){let k;for(;s._index<a.length;){const _=a[s._index];if(typeof _=="string")for(k=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===k&&s._bufferIndex<_.length;)w(_.charCodeAt(s._bufferIndex));else w(_)}}function w(k){d=d(k)}function P(k){te(k)?(s.line++,s.column=1,s.offset+=k===-3?2:1,O()):k!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===a[s._index].length&&(s._bufferIndex=-1,s._index++)),u.previous=k}function S(k,_){const L=_||{};return L.type=k,L.start=g(),u.events.push(["enter",L,u]),l.push(L),L}function j(k){const _=l.pop();return _.end=g(),u.events.push(["exit",_,u]),_}function A(k,_){F(k,_.from)}function E(k,_){_.restore()}function R(k,_){return L;function L(I,N,z){let U,T,M,x;return Array.isArray(I)?me(I):"tokenize"in I?me([I]):oe(I);function oe(B){return Z;function Z(re){const de=re!==null&&B[re],xe=re!==null&&B.null,ae=[...Array.isArray(de)?de:de?[de]:[],...Array.isArray(xe)?xe:xe?[xe]:[]];return me(ae)(re)}}function me(B){return U=B,T=0,B.length===0?z:b(B[T])}function b(B){return Z;function Z(re){return x=D(),M=B,B.partial||(u.currentConstruct=B),B.name&&u.parser.constructs.disable.null.includes(B.name)?X():B.tokenize.call(_?Object.assign(Object.create(u),_):u,c,Q,X)(re)}}function Q(B){return k(M,x),N}function X(B){return x.restore(),++T<U.length?b(U[T]):z}}}function F(k,_){k.resolveAll&&!i.includes(k)&&i.push(k),k.resolve&&ct(u.events,_,u.events.length-_,k.resolve(u.events.slice(_),u)),k.resolveTo&&(u.events=k.resolveTo(u.events,u))}function D(){const k=g(),_=u.previous,L=u.currentConstruct,I=u.events.length,N=Array.from(l);return{from:I,restore:z};function z(){s=k,u.previous=_,u.currentConstruct=L,u.events.length=I,l=N,O()}}function O(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}function hy(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let a;if(n===r)a=[e[n].slice(s,i)];else{if(a=e.slice(n,r),s>-1){const l=a[0];typeof l=="string"?a[0]=l.slice(s):a.shift()}i>0&&a.push(e[r].slice(0,i))}return a}function fy(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
15
15
  `;break}case-3:{a=`\r
16
- `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(i)}r=i===-2,s.push(a)}return s.join("")}function ly(e){const s={constructs:mg([ry,...(e||{}).extensions||[]]),content:r(kg),defined:[],document:r(Eg),flow:r(Ux),lazy:{},string:r(Wx),text:r(Gx)};return s;function r(i){return a;function a(l){return iy(s,i,l)}}}function cy(e){for(;!Cc(e););return e}const $a=/[\0\t\n\r]/g;function uy(){let e=1,t="",n=!0,s;return r;function r(i,a,l){const c=[];let u,d,h,m,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),h=0,t="",n&&(i.charCodeAt(0)===65279&&h++,n=void 0);h<i.length;){if($a.lastIndex=h,u=$a.exec(i),m=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(m),!u){t=i.slice(h);break}if(f===10&&h===m&&s)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),h<m&&(c.push(i.slice(h,m)),e+=m-h),f){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:s=!0,e=1}h=m+1}return l&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const dy=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function hy(e){return e.replace(dy,fy)}function fy(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),i=r===120||r===88;return wc(n.slice(i?2:1),i?16:10)}return oo(n)||e}const Ic={}.hasOwnProperty;function py(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),my(n)(cy(ly(n).document().write(uy()(e,t,!0))))}function my(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(ne),autolinkProtocol:M,autolinkEmail:M,atxHeading:i(vt),blockQuote:i(xe),characterEscape:M,characterReference:M,codeFenced:i(ae),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(ae,a),codeText:i(je,a),codeTextData:M,data:M,codeFlowValue:M,definition:i(St),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(qt),hardBreakEscape:i(kt),hardBreakTrailing:i(kt),htmlFlow:i(Ot,a),htmlFlowData:M,htmlText:i(Ot,a),htmlTextData:M,image:i(Y),label:a,link:i(ne),listItem:i(Ne),listItemValue:m,listOrdered:i(le,h),listUnordered:i(le),paragraph:i(Ue),reference:b,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(vt),strong:i(He),thematicBreak:i(Te)},exit:{atxHeading:c(),atxHeadingSequence:A,autolink:c(),autolinkEmail:de,autolinkProtocol:re,blockQuote:c(),characterEscapeValue:O,characterReferenceMarkerHexadecimal:X,characterReferenceMarkerNumeric:X,characterReferenceValue:B,characterReference:Z,codeFenced:c(C),codeFencedFence:y,codeFencedFenceInfo:f,codeFencedFenceMeta:g,codeFlowValue:O,codeIndented:c(w),codeText:c(N),codeTextData:O,data:O,definition:c(),definitionDestinationString:j,definitionLabelString:P,definitionTitleString:S,emphasis:c(),hardBreakEscape:c(_),hardBreakTrailing:c(_),htmlFlow:c(L),htmlFlowData:O,htmlText:c(I),htmlTextData:O,image:c(U),label:D,labelText:T,lineEnding:v,link:c(z),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:Q,resourceDestinationString:x,resourceTitleString:oe,resource:me,setextHeading:c(F),setextHeadingLineSequence:R,setextHeadingText:E,strong:c(),thematicBreak:c()}};Ac(t,(e||{}).mdastExtensions||[]);const n={};return s;function s($){let q={type:"root",children:[]};const K={stack:[q],tokenStack:[],config:t,enter:l,exit:u,buffer:a,resume:d,data:n},J=[];let ee=-1;for(;++ee<$.length;)if($[ee][1].type==="listOrdered"||$[ee][1].type==="listUnordered")if($[ee][0]==="enter")J.push(ee);else{const Pe=J.pop();ee=r($,Pe,ee)}for(ee=-1;++ee<$.length;){const Pe=t[$[ee][0]];Ic.call(Pe,$[ee][1].type)&&Pe[$[ee][1].type].call(Object.assign({sliceSerialize:$[ee][2].sliceSerialize},K),$[ee][1])}if(K.tokenStack.length>0){const Pe=K.tokenStack[K.tokenStack.length-1];(Pe[1]||Ba).call(K,void 0,Pe[0])}for(q.position={start:It($.length>0?$[0][1].start:{line:1,column:1,offset:0}),end:It($.length>0?$[$.length-2][1].end:{line:1,column:1,offset:0})},ee=-1;++ee<t.transforms.length;)q=t.transforms[ee](q)||q;return q}function r($,q,K){let J=q-1,ee=-1,Pe=!1,Ye,$e,st,ht;for(;++J<=K;){const ge=$[J];switch(ge[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ge[0]==="enter"?ee++:ee--,ht=void 0;break}case"lineEndingBlank":{ge[0]==="enter"&&(Ye&&!ht&&!ee&&!st&&(st=J),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!ee&&ge[0]==="enter"&&ge[1].type==="listItemPrefix"||ee===-1&&ge[0]==="exit"&&(ge[1].type==="listUnordered"||ge[1].type==="listOrdered")){if(Ye){let rt=J;for($e=void 0;rt--;){const Re=$[rt];if(Re[1].type==="lineEnding"||Re[1].type==="lineEndingBlank"){if(Re[0]==="exit")continue;$e&&($[$e][1].type="lineEndingBlank",Pe=!0),Re[1].type="lineEnding",$e=rt}else if(!(Re[1].type==="linePrefix"||Re[1].type==="blockQuotePrefix"||Re[1].type==="blockQuotePrefixWhitespace"||Re[1].type==="blockQuoteMarker"||Re[1].type==="listItemIndent"))break}st&&(!$e||st<$e)&&(Ye._spread=!0),Ye.end=Object.assign({},$e?$[$e][1].start:ge[1].end),$.splice($e||J,0,["exit",Ye,ge[2]]),J++,K++}if(ge[1].type==="listItemPrefix"){const rt={type:"listItem",_spread:!1,start:Object.assign({},ge[1].start),end:void 0};Ye=rt,$.splice(J,0,["enter",rt,ge[2]]),J++,K++,st=void 0,ht=!0}}}return $[q][1]._spread=Pe,K}function i($,q){return K;function K(J){l.call(this,$(J),J),q&&q.call(this,J)}}function a(){this.stack.push({type:"fragment",children:[]})}function l($,q,K){this.stack[this.stack.length-1].children.push($),this.stack.push($),this.tokenStack.push([q,K||void 0]),$.position={start:It(q.start),end:void 0}}function c($){return q;function q(K){$&&$.call(this,K),u.call(this,K)}}function u($,q){const K=this.stack.pop(),J=this.tokenStack.pop();if(J)J[0].type!==$.type&&(q?q.call(this,$,J[0]):(J[1]||Ba).call(this,$,J[0]));else throw new Error("Cannot close `"+$.type+"` ("+zn({start:$.start,end:$.end})+"): it’s not open");K.position.end=It($.end)}function d(){return fg(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function m($){if(this.data.expectingFirstListItemValue){const q=this.stack[this.stack.length-2];q.start=Number.parseInt(this.sliceSerialize($),10),this.data.expectingFirstListItemValue=void 0}}function f(){const $=this.resume(),q=this.stack[this.stack.length-1];q.lang=$}function g(){const $=this.resume(),q=this.stack[this.stack.length-1];q.meta=$}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function C(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/(\r?\n|\r)$/g,"")}function P($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=cn(this.sliceSerialize($)).toLowerCase()}function S(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function j(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function A($){const q=this.stack[this.stack.length-1];if(!q.depth){const K=this.sliceSerialize($).length;q.depth=K}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function R($){const q=this.stack[this.stack.length-1];q.depth=this.sliceSerialize($).codePointAt(0)===61?1:2}function F(){this.data.setextHeadingSlurpLineEnding=void 0}function M($){const K=this.stack[this.stack.length-1].children;let J=K[K.length-1];(!J||J.type!=="text")&&(J=dt(),J.position={start:It($.start),end:void 0},K.push(J)),this.stack.push(J)}function O($){const q=this.stack.pop();q.value+=this.sliceSerialize($),q.position.end=It($.end)}function v($){const q=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=q.children[q.children.length-1];K.position.end=It($.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(q.type)&&(M.call(this,$),O.call(this,$))}function _(){this.data.atHardBreak=!0}function L(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function I(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function N(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function z(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function U(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function T($){const q=this.sliceSerialize($),K=this.stack[this.stack.length-2];K.label=hy(q),K.identifier=cn(q).toLowerCase()}function D(){const $=this.stack[this.stack.length-1],q=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const J=$.children;K.children=J}else K.alt=q}function x(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function oe(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function me(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function Q($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=cn(this.sliceSerialize($)).toLowerCase(),this.data.referenceType="full"}function X($){this.data.characterReferenceType=$.type}function B($){const q=this.sliceSerialize($),K=this.data.characterReferenceType;let J;K?(J=wc(q,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):J=oo(q);const ee=this.stack[this.stack.length-1];ee.value+=J}function Z($){const q=this.stack.pop();q.position.end=It($.end)}function re($){O.call(this,$);const q=this.stack[this.stack.length-1];q.url=this.sliceSerialize($)}function de($){O.call(this,$);const q=this.stack[this.stack.length-1];q.url="mailto:"+this.sliceSerialize($)}function xe(){return{type:"blockquote",children:[]}}function ae(){return{type:"code",lang:null,meta:null,value:""}}function je(){return{type:"inlineCode",value:""}}function St(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function qt(){return{type:"emphasis",children:[]}}function vt(){return{type:"heading",depth:0,children:[]}}function kt(){return{type:"break"}}function Ot(){return{type:"html",value:""}}function Y(){return{type:"image",title:null,url:"",alt:null}}function ne(){return{type:"link",title:null,url:"",children:[]}}function le($){return{type:"list",ordered:$.type==="listOrdered",start:null,spread:$._spread,children:[]}}function Ne($){return{type:"listItem",spread:$._spread,checked:null,children:[]}}function Ue(){return{type:"paragraph",children:[]}}function He(){return{type:"strong",children:[]}}function dt(){return{type:"text",value:""}}function Te(){return{type:"thematicBreak"}}}function It(e){return{line:e.line,column:e.column,offset:e.offset}}function Ac(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Ac(e,s):gy(e,s)}}function gy(e,t){let n;for(n in t)if(Ic.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function Ba(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+zn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+zn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+zn({start:t.start,end:t.end})+") is still open")}function xy(e){const t=this;t.parser=n;function n(s){return py(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function yy(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function by(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
17
- `}]}function wy(e,t){const n=t.value?t.value+`
18
- `:"",s={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(s.className=["language-"+r[0]]);let i={type:"element",tagName:"code",properties:s,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function Sy(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function vy(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ky(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),r=fn(s.toLowerCase()),i=e.footnoteOrder.indexOf(s);let a,l=e.footnoteCounts.get(s);l===void 0?(l=0,e.footnoteOrder.push(s),a=e.footnoteOrder.length):a=i+1,l+=1,e.footnoteCounts.set(s,l);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function Cy(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ey(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function zc(e,t){const n=t.referenceType;let s="]";if(n==="collapsed"?s+="[]":n==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const r=e.all(t),i=r[0];i&&i.type==="text"?i.value="["+i.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=s:r.push({type:"text",value:s}),r}function jy(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return zc(e,t);const r={src:fn(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,i),e.applyData(t,i)}function Ny(e,t){const n={src:fn(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,s),e.applyData(t,s)}function Ty(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const s={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,s),e.applyData(t,s)}function Py(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return zc(e,t);const r={href:fn(s.url||"")};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Iy(e,t){const n={href:fn(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function Ay(e,t,n){const s=e.all(t),r=n?zy(n):_c(t),i={},a=[];if(typeof t.checked=="boolean"){const d=s[0];let h;d&&d.type==="element"&&d.tagName==="p"?h=d:(h={type:"element",tagName:"p",properties:{},children:[]},s.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let l=-1;for(;++l<s.length;){const d=s[l];(r||l!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
16
+ `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(i)}r=i===-2,s.push(a)}return s.join("")}function py(e){const s={constructs:Sg([uy,...(e||{}).extensions||[]]),content:r(Pg),defined:[],document:r(Ag),flow:r(Jx),lazy:{},string:r(Kx),text:r(Xx)};return s;function r(i){return a;function a(l){return dy(s,i,l)}}}function my(e){for(;!Pc(e););return e}const Va=/[\0\t\n\r]/g;function gy(){let e=1,t="",n=!0,s;return r;function r(i,a,l){const c=[];let u,d,p,m,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),p=0,t="",n&&(i.charCodeAt(0)===65279&&p++,n=void 0);p<i.length;){if(Va.lastIndex=p,u=Va.exec(i),m=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(m),!u){t=i.slice(p);break}if(h===10&&p===m&&s)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),p<m&&(c.push(i.slice(p,m)),e+=m-p),h){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:s=!0,e=1}p=m+1}return l&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const xy=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function yy(e){return e.replace(xy,by)}function by(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),i=r===120||r===88;return Ec(n.slice(i?2:1),i?16:10)}return lo(n)||e}const Rc={}.hasOwnProperty;function wy(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),Sy(n)(my(py(n).document().write(gy()(e,t,!0))))}function Sy(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(ne),autolinkProtocol:D,autolinkEmail:D,atxHeading:i(vt),blockQuote:i(xe),characterEscape:D,characterReference:D,codeFenced:i(ae),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(ae,a),codeText:i(je,a),codeTextData:D,data:D,codeFlowValue:D,definition:i(St),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(qt),hardBreakEscape:i(kt),hardBreakTrailing:i(kt),htmlFlow:i(Ot,a),htmlFlowData:D,htmlText:i(Ot,a),htmlTextData:D,image:i(Y),label:a,link:i(ne),listItem:i(Ne),listItemValue:m,listOrdered:i(le,p),listUnordered:i(le),paragraph:i(He),reference:b,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(vt),strong:i(qe),thematicBreak:i(Te)},exit:{atxHeading:c(),atxHeadingSequence:A,autolink:c(),autolinkEmail:de,autolinkProtocol:re,blockQuote:c(),characterEscapeValue:O,characterReferenceMarkerHexadecimal:X,characterReferenceMarkerNumeric:X,characterReferenceValue:B,characterReference:Z,codeFenced:c(v),codeFencedFence:y,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:O,codeIndented:c(w),codeText:c(N),codeTextData:O,data:O,definition:c(),definitionDestinationString:j,definitionLabelString:P,definitionTitleString:S,emphasis:c(),hardBreakEscape:c(_),hardBreakTrailing:c(_),htmlFlow:c(L),htmlFlowData:O,htmlText:c(I),htmlTextData:O,image:c(U),label:M,labelText:T,lineEnding:k,link:c(z),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:Q,resourceDestinationString:x,resourceTitleString:oe,resource:me,setextHeading:c(F),setextHeadingLineSequence:R,setextHeadingText:E,strong:c(),thematicBreak:c()}};Oc(t,(e||{}).mdastExtensions||[]);const n={};return s;function s($){let q={type:"root",children:[]};const K={stack:[q],tokenStack:[],config:t,enter:l,exit:u,buffer:a,resume:d,data:n},J=[];let ee=-1;for(;++ee<$.length;)if($[ee][1].type==="listOrdered"||$[ee][1].type==="listUnordered")if($[ee][0]==="enter")J.push(ee);else{const Pe=J.pop();ee=r($,Pe,ee)}for(ee=-1;++ee<$.length;){const Pe=t[$[ee][0]];Rc.call(Pe,$[ee][1].type)&&Pe[$[ee][1].type].call(Object.assign({sliceSerialize:$[ee][2].sliceSerialize},K),$[ee][1])}if(K.tokenStack.length>0){const Pe=K.tokenStack[K.tokenStack.length-1];(Pe[1]||Ua).call(K,void 0,Pe[0])}for(q.position={start:It($.length>0?$[0][1].start:{line:1,column:1,offset:0}),end:It($.length>0?$[$.length-2][1].end:{line:1,column:1,offset:0})},ee=-1;++ee<t.transforms.length;)q=t.transforms[ee](q)||q;return q}function r($,q,K){let J=q-1,ee=-1,Pe=!1,Ye,Be,st,ht;for(;++J<=K;){const ge=$[J];switch(ge[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ge[0]==="enter"?ee++:ee--,ht=void 0;break}case"lineEndingBlank":{ge[0]==="enter"&&(Ye&&!ht&&!ee&&!st&&(st=J),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!ee&&ge[0]==="enter"&&ge[1].type==="listItemPrefix"||ee===-1&&ge[0]==="exit"&&(ge[1].type==="listUnordered"||ge[1].type==="listOrdered")){if(Ye){let rt=J;for(Be=void 0;rt--;){const Re=$[rt];if(Re[1].type==="lineEnding"||Re[1].type==="lineEndingBlank"){if(Re[0]==="exit")continue;Be&&($[Be][1].type="lineEndingBlank",Pe=!0),Re[1].type="lineEnding",Be=rt}else if(!(Re[1].type==="linePrefix"||Re[1].type==="blockQuotePrefix"||Re[1].type==="blockQuotePrefixWhitespace"||Re[1].type==="blockQuoteMarker"||Re[1].type==="listItemIndent"))break}st&&(!Be||st<Be)&&(Ye._spread=!0),Ye.end=Object.assign({},Be?$[Be][1].start:ge[1].end),$.splice(Be||J,0,["exit",Ye,ge[2]]),J++,K++}if(ge[1].type==="listItemPrefix"){const rt={type:"listItem",_spread:!1,start:Object.assign({},ge[1].start),end:void 0};Ye=rt,$.splice(J,0,["enter",rt,ge[2]]),J++,K++,st=void 0,ht=!0}}}return $[q][1]._spread=Pe,K}function i($,q){return K;function K(J){l.call(this,$(J),J),q&&q.call(this,J)}}function a(){this.stack.push({type:"fragment",children:[]})}function l($,q,K){this.stack[this.stack.length-1].children.push($),this.stack.push($),this.tokenStack.push([q,K||void 0]),$.position={start:It(q.start),end:void 0}}function c($){return q;function q(K){$&&$.call(this,K),u.call(this,K)}}function u($,q){const K=this.stack.pop(),J=this.tokenStack.pop();if(J)J[0].type!==$.type&&(q?q.call(this,$,J[0]):(J[1]||Ua).call(this,$,J[0]));else throw new Error("Cannot close `"+$.type+"` ("+_n({start:$.start,end:$.end})+"): it’s not open");K.position.end=It($.end)}function d(){return bg(this.stack.pop())}function p(){this.data.expectingFirstListItemValue=!0}function m($){if(this.data.expectingFirstListItemValue){const q=this.stack[this.stack.length-2];q.start=Number.parseInt(this.sliceSerialize($),10),this.data.expectingFirstListItemValue=void 0}}function h(){const $=this.resume(),q=this.stack[this.stack.length-1];q.lang=$}function g(){const $=this.resume(),q=this.stack[this.stack.length-1];q.meta=$}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/(\r?\n|\r)$/g,"")}function P($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=cn(this.sliceSerialize($)).toLowerCase()}function S(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function j(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function A($){const q=this.stack[this.stack.length-1];if(!q.depth){const K=this.sliceSerialize($).length;q.depth=K}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function R($){const q=this.stack[this.stack.length-1];q.depth=this.sliceSerialize($).codePointAt(0)===61?1:2}function F(){this.data.setextHeadingSlurpLineEnding=void 0}function D($){const K=this.stack[this.stack.length-1].children;let J=K[K.length-1];(!J||J.type!=="text")&&(J=dt(),J.position={start:It($.start),end:void 0},K.push(J)),this.stack.push(J)}function O($){const q=this.stack.pop();q.value+=this.sliceSerialize($),q.position.end=It($.end)}function k($){const q=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=q.children[q.children.length-1];K.position.end=It($.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(q.type)&&(D.call(this,$),O.call(this,$))}function _(){this.data.atHardBreak=!0}function L(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function I(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function N(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function z(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function U(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function T($){const q=this.sliceSerialize($),K=this.stack[this.stack.length-2];K.label=yy(q),K.identifier=cn(q).toLowerCase()}function M(){const $=this.stack[this.stack.length-1],q=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const J=$.children;K.children=J}else K.alt=q}function x(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function oe(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function me(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function Q($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=cn(this.sliceSerialize($)).toLowerCase(),this.data.referenceType="full"}function X($){this.data.characterReferenceType=$.type}function B($){const q=this.sliceSerialize($),K=this.data.characterReferenceType;let J;K?(J=Ec(q,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):J=lo(q);const ee=this.stack[this.stack.length-1];ee.value+=J}function Z($){const q=this.stack.pop();q.position.end=It($.end)}function re($){O.call(this,$);const q=this.stack[this.stack.length-1];q.url=this.sliceSerialize($)}function de($){O.call(this,$);const q=this.stack[this.stack.length-1];q.url="mailto:"+this.sliceSerialize($)}function xe(){return{type:"blockquote",children:[]}}function ae(){return{type:"code",lang:null,meta:null,value:""}}function je(){return{type:"inlineCode",value:""}}function St(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function qt(){return{type:"emphasis",children:[]}}function vt(){return{type:"heading",depth:0,children:[]}}function kt(){return{type:"break"}}function Ot(){return{type:"html",value:""}}function Y(){return{type:"image",title:null,url:"",alt:null}}function ne(){return{type:"link",title:null,url:"",children:[]}}function le($){return{type:"list",ordered:$.type==="listOrdered",start:null,spread:$._spread,children:[]}}function Ne($){return{type:"listItem",spread:$._spread,checked:null,children:[]}}function He(){return{type:"paragraph",children:[]}}function qe(){return{type:"strong",children:[]}}function dt(){return{type:"text",value:""}}function Te(){return{type:"thematicBreak"}}}function It(e){return{line:e.line,column:e.column,offset:e.offset}}function Oc(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Oc(e,s):vy(e,s)}}function vy(e,t){let n;for(n in t)if(Rc.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function Ua(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+_n({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+_n({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+_n({start:t.start,end:t.end})+") is still open")}function ky(e){const t=this;t.parser=n;function n(s){return wy(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function Cy(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function Ey(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
17
+ `}]}function jy(e,t){const n=t.value?t.value+`
18
+ `:"",s={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(s.className=["language-"+r[0]]);let i={type:"element",tagName:"code",properties:s,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function Ny(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ty(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Py(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),r=pn(s.toLowerCase()),i=e.footnoteOrder.indexOf(s);let a,l=e.footnoteCounts.get(s);l===void 0?(l=0,e.footnoteOrder.push(s),a=e.footnoteOrder.length):a=i+1,l+=1,e.footnoteCounts.set(s,l);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function Iy(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ay(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function Mc(e,t){const n=t.referenceType;let s="]";if(n==="collapsed"?s+="[]":n==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const r=e.all(t),i=r[0];i&&i.type==="text"?i.value="["+i.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=s:r.push({type:"text",value:s}),r}function zy(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return Mc(e,t);const r={src:pn(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,i),e.applyData(t,i)}function _y(e,t){const n={src:pn(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,s),e.applyData(t,s)}function Ly(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const s={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,s),e.applyData(t,s)}function Ry(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return Mc(e,t);const r={href:pn(s.url||"")};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Oy(e,t){const n={href:pn(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function My(e,t,n){const s=e.all(t),r=n?Dy(n):Dc(t),i={},a=[];if(typeof t.checked=="boolean"){const d=s[0];let p;d&&d.type==="element"&&d.tagName==="p"?p=d:(p={type:"element",tagName:"p",properties:{},children:[]},s.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let l=-1;for(;++l<s.length;){const d=s[l];(r||l!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
19
19
  `}),d.type==="element"&&d.tagName==="p"&&!r?a.push(...d.children):a.push(d)}const c=s[s.length-1];c&&(r||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
20
- `});const u={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,u),e.applyData(t,u)}function zy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let s=-1;for(;!t&&++s<n.length;)t=_c(n[s])}return t}function _c(e){const t=e.spread;return t??e.children.length>1}function _y(e,t){const n={},s=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<s.length;){const a=s[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function Ly(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ry(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Oy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Dy(e,t){const n=e.all(t),s=n.shift(),r=[];if(s){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([s],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=no(t.children[1]),c=fc(t.children[t.children.length-1]);l&&c&&(a.position={start:l,end:c}),r.push(a)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function My(e,t,n){const s=n?n.children:void 0,i=(s?s.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,l=a?a.length:t.children.length;let c=-1;const u=[];for(;++c<l;){const h=t.children[c],m={},f=a?a[c]:void 0;f&&(m.align=f);let g={type:"element",tagName:i,properties:m,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Fy(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Va=9,Ua=32;function $y(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),r=0;const i=[];for(;s;)i.push(Ha(t.slice(r,s.index),r>0,!0),s[0]),r=s.index+s[0].length,s=n.exec(t);return i.push(Ha(t.slice(r),r>0,!1)),i.join("")}function Ha(e,t,n){let s=0,r=e.length;if(t){let i=e.codePointAt(s);for(;i===Va||i===Ua;)s++,i=e.codePointAt(s)}if(n){let i=e.codePointAt(r-1);for(;i===Va||i===Ua;)r--,i=e.codePointAt(r-1)}return r>s?e.slice(s,r):""}function By(e,t){const n={type:"text",value:$y(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Vy(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Uy={blockquote:yy,break:by,code:wy,delete:Sy,emphasis:vy,footnoteReference:ky,heading:Cy,html:Ey,imageReference:jy,image:Ny,inlineCode:Ty,linkReference:Py,link:Iy,listItem:Ay,list:_y,paragraph:Ly,root:Ry,strong:Oy,table:Dy,tableCell:Fy,tableRow:My,text:By,thematicBreak:Vy,toml:ts,yaml:ts,definition:ts,footnoteDefinition:ts};function ts(){}const Lc=-1,Us=0,Ln=1,Ls=2,co=3,uo=4,ho=5,fo=6,Rc=7,Oc=8,Hy=typeof self=="object"?self:globalThis,qa=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new Hy[e](t)},qy=(e,t)=>{const n=(r,i)=>(e.set(i,r),r),s=r=>{if(e.has(r))return e.get(r);const[i,a]=t[r];switch(i){case Us:case Lc:return n(a,r);case Ln:{const l=n([],r);for(const c of a)l.push(s(c));return l}case Ls:{const l=n({},r);for(const[c,u]of a)l[s(c)]=s(u);return l}case co:return n(new Date(a),r);case uo:{const{source:l,flags:c}=a;return n(new RegExp(l,c),r)}case ho:{const l=n(new Map,r);for(const[c,u]of a)l.set(s(c),s(u));return l}case fo:{const l=n(new Set,r);for(const c of a)l.add(s(c));return l}case Rc:{const{name:l,message:c}=a;return n(qa(l,c),r)}case Oc:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:l}=new Uint8Array(a);return n(new DataView(l),a)}}return n(qa(i,a),r)};return s},Wa=e=>qy(new Map,e)(0),tn="",{toString:Wy}={},{keys:Gy}=Object,Tn=e=>{const t=typeof e;if(t!=="object"||!e)return[Us,t];const n=Wy.call(e).slice(8,-1);switch(n){case"Array":return[Ln,tn];case"Object":return[Ls,tn];case"Date":return[co,tn];case"RegExp":return[uo,tn];case"Map":return[ho,tn];case"Set":return[fo,tn];case"DataView":return[Ln,n]}return n.includes("Array")?[Ln,n]:n.includes("Error")?[Rc,n]:[Ls,n]},ns=([e,t])=>e===Us&&(t==="function"||t==="symbol"),Qy=(e,t,n,s)=>{const r=(a,l)=>{const c=s.push(a)-1;return n.set(l,c),c},i=a=>{if(n.has(a))return n.get(a);let[l,c]=Tn(a);switch(l){case Us:{let d=a;switch(c){case"bigint":l=Oc,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return r([Lc],a)}return r([l,d],a)}case Ln:{if(c){let m=a;return c==="DataView"?m=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(a)),r([c,[...m]],a)}const d=[],h=r([l,d],a);for(const m of a)d.push(i(m));return h}case Ls:{if(c)switch(c){case"BigInt":return r([c,a.toString()],a);case"Boolean":case"Number":case"String":return r([c,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const d=[],h=r([l,d],a);for(const m of Gy(a))(e||!ns(Tn(a[m])))&&d.push([i(m),i(a[m])]);return h}case co:return r([l,a.toISOString()],a);case uo:{const{source:d,flags:h}=a;return r([l,{source:d,flags:h}],a)}case ho:{const d=[],h=r([l,d],a);for(const[m,f]of a)(e||!(ns(Tn(m))||ns(Tn(f))))&&d.push([i(m),i(f)]);return h}case fo:{const d=[],h=r([l,d],a);for(const m of a)(e||!ns(Tn(m)))&&d.push(i(m));return h}}const{message:u}=a;return r([l,{name:c,message:u}],a)};return i},Ga=(e,{json:t,lossy:n}={})=>{const s=[];return Qy(!(t||n),!!t,new Map,s)(e),s},Rs=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Wa(Ga(e,t)):structuredClone(e):(e,t)=>Wa(Ga(e,t));function Jy(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function Zy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Yy(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Jy,s=e.options.footnoteBackLabel||Zy,r=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),h=String(u.identifier).toUpperCase(),m=fn(h.toLowerCase());let f=0;const g=[],y=e.footnoteCounts.get(h);for(;y!==void 0&&++f<=y;){g.length>0&&g.push({type:"text",value:" "});let P=typeof n=="string"?n:n(c,f);typeof P=="string"&&(P={type:"text",value:P}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,f),className:["data-footnote-backref"]},children:Array.isArray(P)?P:[P]})}const C=d[d.length-1];if(C&&C.type==="element"&&C.tagName==="p"){const P=C.children[C.children.length-1];P&&P.type==="text"?P.value+=" ":C.children.push({type:"text",value:" "}),C.children.push(...g)}else d.push(...g);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(u,w),l.push(w)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Rs(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
20
+ `});const u={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,u),e.applyData(t,u)}function Dy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let s=-1;for(;!t&&++s<n.length;)t=Dc(n[s])}return t}function Dc(e){const t=e.spread;return t??e.children.length>1}function Fy(e,t){const n={},s=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<s.length;){const a=s[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function $y(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function By(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Vy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Uy(e,t){const n=e.all(t),s=n.shift(),r=[];if(s){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([s],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=ro(t.children[1]),c=yc(t.children[t.children.length-1]);l&&c&&(a.position={start:l,end:c}),r.push(a)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function Hy(e,t,n){const s=n?n.children:void 0,i=(s?s.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,l=a?a.length:t.children.length;let c=-1;const u=[];for(;++c<l;){const p=t.children[c],m={},h=a?a[c]:void 0;h&&(m.align=h);let g={type:"element",tagName:i,properties:m,children:[]};p&&(g.children=e.all(p),e.patch(p,g),g=e.applyData(p,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function qy(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Ha=9,qa=32;function Wy(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),r=0;const i=[];for(;s;)i.push(Wa(t.slice(r,s.index),r>0,!0),s[0]),r=s.index+s[0].length,s=n.exec(t);return i.push(Wa(t.slice(r),r>0,!1)),i.join("")}function Wa(e,t,n){let s=0,r=e.length;if(t){let i=e.codePointAt(s);for(;i===Ha||i===qa;)s++,i=e.codePointAt(s)}if(n){let i=e.codePointAt(r-1);for(;i===Ha||i===qa;)r--,i=e.codePointAt(r-1)}return r>s?e.slice(s,r):""}function Gy(e,t){const n={type:"text",value:Wy(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Qy(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Jy={blockquote:Cy,break:Ey,code:jy,delete:Ny,emphasis:Ty,footnoteReference:Py,heading:Iy,html:Ay,imageReference:zy,image:_y,inlineCode:Ly,linkReference:Ry,link:Oy,listItem:My,list:Fy,paragraph:$y,root:By,strong:Vy,table:Uy,tableCell:qy,tableRow:Hy,text:Gy,thematicBreak:Qy,toml:ts,yaml:ts,definition:ts,footnoteDefinition:ts};function ts(){}const Fc=-1,qs=0,Rn=1,Rs=2,ho=3,fo=4,po=5,mo=6,$c=7,Bc=8,Zy=typeof self=="object"?self:globalThis,Ga=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new Zy[e](t)},Yy=(e,t)=>{const n=(r,i)=>(e.set(i,r),r),s=r=>{if(e.has(r))return e.get(r);const[i,a]=t[r];switch(i){case qs:case Fc:return n(a,r);case Rn:{const l=n([],r);for(const c of a)l.push(s(c));return l}case Rs:{const l=n({},r);for(const[c,u]of a)l[s(c)]=s(u);return l}case ho:return n(new Date(a),r);case fo:{const{source:l,flags:c}=a;return n(new RegExp(l,c),r)}case po:{const l=n(new Map,r);for(const[c,u]of a)l.set(s(c),s(u));return l}case mo:{const l=n(new Set,r);for(const c of a)l.add(s(c));return l}case $c:{const{name:l,message:c}=a;return n(Ga(l,c),r)}case Bc:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:l}=new Uint8Array(a);return n(new DataView(l),a)}}return n(Ga(i,a),r)};return s},Qa=e=>Yy(new Map,e)(0),tn="",{toString:Ky}={},{keys:Xy}=Object,Pn=e=>{const t=typeof e;if(t!=="object"||!e)return[qs,t];const n=Ky.call(e).slice(8,-1);switch(n){case"Array":return[Rn,tn];case"Object":return[Rs,tn];case"Date":return[ho,tn];case"RegExp":return[fo,tn];case"Map":return[po,tn];case"Set":return[mo,tn];case"DataView":return[Rn,n]}return n.includes("Array")?[Rn,n]:n.includes("Error")?[$c,n]:[Rs,n]},ns=([e,t])=>e===qs&&(t==="function"||t==="symbol"),eb=(e,t,n,s)=>{const r=(a,l)=>{const c=s.push(a)-1;return n.set(l,c),c},i=a=>{if(n.has(a))return n.get(a);let[l,c]=Pn(a);switch(l){case qs:{let d=a;switch(c){case"bigint":l=Bc,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return r([Fc],a)}return r([l,d],a)}case Rn:{if(c){let m=a;return c==="DataView"?m=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(a)),r([c,[...m]],a)}const d=[],p=r([l,d],a);for(const m of a)d.push(i(m));return p}case Rs:{if(c)switch(c){case"BigInt":return r([c,a.toString()],a);case"Boolean":case"Number":case"String":return r([c,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const d=[],p=r([l,d],a);for(const m of Xy(a))(e||!ns(Pn(a[m])))&&d.push([i(m),i(a[m])]);return p}case ho:return r([l,a.toISOString()],a);case fo:{const{source:d,flags:p}=a;return r([l,{source:d,flags:p}],a)}case po:{const d=[],p=r([l,d],a);for(const[m,h]of a)(e||!(ns(Pn(m))||ns(Pn(h))))&&d.push([i(m),i(h)]);return p}case mo:{const d=[],p=r([l,d],a);for(const m of a)(e||!ns(Pn(m)))&&d.push(i(m));return p}}const{message:u}=a;return r([l,{name:c,message:u}],a)};return i},Ja=(e,{json:t,lossy:n}={})=>{const s=[];return eb(!(t||n),!!t,new Map,s)(e),s},Os=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Qa(Ja(e,t)):structuredClone(e):(e,t)=>Qa(Ja(e,t));function tb(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function nb(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function sb(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||tb,s=e.options.footnoteBackLabel||nb,r=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),p=String(u.identifier).toUpperCase(),m=pn(p.toLowerCase());let h=0;const g=[],y=e.footnoteCounts.get(p);for(;y!==void 0&&++h<=y;){g.length>0&&g.push({type:"text",value:" "});let P=typeof n=="string"?n:n(c,h);typeof P=="string"&&(P={type:"text",value:P}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,h),className:["data-footnote-backref"]},children:Array.isArray(P)?P:[P]})}const v=d[d.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const P=v.children[v.children.length-1];P&&P.type==="text"?P.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else d.push(...g);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(u,w),l.push(w)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Os(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
21
21
  `},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:`
22
- `}]}}const Dc=(function(e){if(e==null)return tb;if(typeof e=="function")return Hs(e);if(typeof e=="object")return Array.isArray(e)?Ky(e):Xy(e);if(typeof e=="string")return eb(e);throw new Error("Expected function, string, or object as test")});function Ky(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Dc(e[n]);return Hs(s);function s(...r){let i=-1;for(;++i<t.length;)if(t[i].apply(this,r))return!0;return!1}}function Xy(e){const t=e;return Hs(n);function n(s){const r=s;let i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function eb(e){return Hs(t);function t(n){return n&&n.type===e}}function Hs(e){return t;function t(n,s,r){return!!(nb(n)&&e.call(this,n,typeof s=="number"?s:void 0,r||void 0))}}function tb(){return!0}function nb(e){return e!==null&&typeof e=="object"&&"type"in e}const Mc=[],sb=!0,Qa=!1,rb="skip";function ib(e,t,n,s){let r;typeof t=="function"&&typeof n!="function"?(s=n,n=t):r=t;const i=Dc(r),a=s?-1:1;l(e,void 0,[])();function l(c,u,d){const h=c&&typeof c=="object"?c:{};if(typeof h.type=="string"){const f=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(f?"<"+f+">":""))+")"})}return m;function m(){let f=Mc,g,y,C;if((!t||i(c,u,d[d.length-1]||void 0))&&(f=ob(n(c,d)),f[0]===Qa))return f;if("children"in c&&c.children){const w=c;if(w.children&&f[0]!==rb)for(y=(s?w.children.length:-1)+a,C=d.concat(w);y>-1&&y<w.children.length;){const P=w.children[y];if(g=l(P,y,C)(),g[0]===Qa)return g;y=typeof g[1]=="number"?g[1]:y+a}}return f}}}function ob(e){return Array.isArray(e)?e:typeof e=="number"?[sb,e]:e==null?Mc:[e]}function Fc(e,t,n,s){let r,i,a;typeof t=="function"&&typeof n!="function"?(i=void 0,a=t,r=n):(i=t,a=n,r=s),ib(e,i,l,r);function l(c,u){const d=u[u.length-1],h=d?d.children.indexOf(c):void 0;return a(c,h,d)}}const Ri={}.hasOwnProperty,ab={};function lb(e,t){const n=t||ab,s=new Map,r=new Map,i=new Map,a={...Uy,...n.handlers},l={all:u,applyData:ub,definitionById:s,footnoteById:r,footnoteCounts:i,footnoteOrder:[],handlers:a,one:c,options:n,patch:cb,wrap:hb};return Fc(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const h=d.type==="definition"?s:r,m=String(d.identifier).toUpperCase();h.has(m)||h.set(m,d)}}),l;function c(d,h){const m=d.type,f=l.handlers[m];if(Ri.call(l.handlers,m)&&f)return f(l,d,h);if(l.options.passThrough&&l.options.passThrough.includes(m)){if("children"in d){const{children:y,...C}=d,w=Rs(C);return w.children=l.all(d),w}return Rs(d)}return(l.options.unknownHandler||db)(l,d,h)}function u(d){const h=[];if("children"in d){const m=d.children;let f=-1;for(;++f<m.length;){const g=l.one(m[f],d);if(g){if(f&&m[f-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Ja(g.value)),!Array.isArray(g)&&g.type==="element")){const y=g.children[0];y&&y.type==="text"&&(y.value=Ja(y.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function cb(e,t){e.position&&(t.position=qm(e))}function ub(e,t){let n=t;if(e&&e.data){const s=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;if(typeof s=="string")if(n.type==="element")n.tagName=s;else{const a="children"in n?n.children:[n];n={type:"element",tagName:s,properties:{},children:a}}n.type==="element"&&i&&Object.assign(n.properties,Rs(i)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function db(e,t){const n=t.data||{},s="value"in t&&!(Ri.call(n,"hProperties")||Ri.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function hb(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
22
+ `}]}}const Vc=(function(e){if(e==null)return ab;if(typeof e=="function")return Ws(e);if(typeof e=="object")return Array.isArray(e)?rb(e):ib(e);if(typeof e=="string")return ob(e);throw new Error("Expected function, string, or object as test")});function rb(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Vc(e[n]);return Ws(s);function s(...r){let i=-1;for(;++i<t.length;)if(t[i].apply(this,r))return!0;return!1}}function ib(e){const t=e;return Ws(n);function n(s){const r=s;let i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function ob(e){return Ws(t);function t(n){return n&&n.type===e}}function Ws(e){return t;function t(n,s,r){return!!(lb(n)&&e.call(this,n,typeof s=="number"?s:void 0,r||void 0))}}function ab(){return!0}function lb(e){return e!==null&&typeof e=="object"&&"type"in e}const Uc=[],cb=!0,Za=!1,ub="skip";function db(e,t,n,s){let r;typeof t=="function"&&typeof n!="function"?(s=n,n=t):r=t;const i=Vc(r),a=s?-1:1;l(e,void 0,[])();function l(c,u,d){const p=c&&typeof c=="object"?c:{};if(typeof p.type=="string"){const h=typeof p.tagName=="string"?p.tagName:typeof p.name=="string"?p.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(h?"<"+h+">":""))+")"})}return m;function m(){let h=Uc,g,y,v;if((!t||i(c,u,d[d.length-1]||void 0))&&(h=hb(n(c,d)),h[0]===Za))return h;if("children"in c&&c.children){const w=c;if(w.children&&h[0]!==ub)for(y=(s?w.children.length:-1)+a,v=d.concat(w);y>-1&&y<w.children.length;){const P=w.children[y];if(g=l(P,y,v)(),g[0]===Za)return g;y=typeof g[1]=="number"?g[1]:y+a}}return h}}}function hb(e){return Array.isArray(e)?e:typeof e=="number"?[cb,e]:e==null?Uc:[e]}function Hc(e,t,n,s){let r,i,a;typeof t=="function"&&typeof n!="function"?(i=void 0,a=t,r=n):(i=t,a=n,r=s),db(e,i,l,r);function l(c,u){const d=u[u.length-1],p=d?d.children.indexOf(c):void 0;return a(c,p,d)}}const Di={}.hasOwnProperty,fb={};function pb(e,t){const n=t||fb,s=new Map,r=new Map,i=new Map,a={...Jy,...n.handlers},l={all:u,applyData:gb,definitionById:s,footnoteById:r,footnoteCounts:i,footnoteOrder:[],handlers:a,one:c,options:n,patch:mb,wrap:yb};return Hc(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const p=d.type==="definition"?s:r,m=String(d.identifier).toUpperCase();p.has(m)||p.set(m,d)}}),l;function c(d,p){const m=d.type,h=l.handlers[m];if(Di.call(l.handlers,m)&&h)return h(l,d,p);if(l.options.passThrough&&l.options.passThrough.includes(m)){if("children"in d){const{children:y,...v}=d,w=Os(v);return w.children=l.all(d),w}return Os(d)}return(l.options.unknownHandler||xb)(l,d,p)}function u(d){const p=[];if("children"in d){const m=d.children;let h=-1;for(;++h<m.length;){const g=l.one(m[h],d);if(g){if(h&&m[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Ya(g.value)),!Array.isArray(g)&&g.type==="element")){const y=g.children[0];y&&y.type==="text"&&(y.value=Ya(y.value))}Array.isArray(g)?p.push(...g):p.push(g)}}}return p}}function mb(e,t){e.position&&(t.position=Ym(e))}function gb(e,t){let n=t;if(e&&e.data){const s=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;if(typeof s=="string")if(n.type==="element")n.tagName=s;else{const a="children"in n?n.children:[n];n={type:"element",tagName:s,properties:{},children:a}}n.type==="element"&&i&&Object.assign(n.properties,Os(i)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function xb(e,t){const n=t.data||{},s="value"in t&&!(Di.call(n,"hProperties")||Di.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function yb(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
23
23
  `});++s<e.length;)s&&n.push({type:"text",value:`
24
24
  `}),n.push(e[s]);return t&&e.length>0&&n.push({type:"text",value:`
25
- `}),n}function Ja(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Za(e,t){const n=lb(e,t),s=n.one(e,void 0),r=Yy(n),i=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return r&&i.children.push({type:"text",value:`
26
- `},r),i}function fb(e,t){return e&&"run"in e?async function(n,s){const r=Za(n,{file:s,...t});await e.run(r,s)}:function(n,s){return Za(n,{file:s,...e||t})}}function Ya(e){if(e)throw e}var ni,Ka;function pb(){if(Ka)return ni;Ka=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!h)return!1;var m;for(m in u);return typeof m>"u"||e.call(u,m)},a=function(u,d){n&&d.name==="__proto__"?n(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},l=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(s)return s(u,d).value}else return;return u[d]};return ni=function c(){var u,d,h,m,f,g,y=arguments[0],C=1,w=arguments.length,P=!1;for(typeof y=="boolean"&&(P=y,y=arguments[1]||{},C=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});C<w;++C)if(u=arguments[C],u!=null)for(d in u)h=l(y,d),m=l(u,d),y!==m&&(P&&m&&(i(m)||(f=r(m)))?(f?(f=!1,g=h&&r(h)?h:[]):g=h&&i(h)?h:{},a(y,{name:d,newValue:c(P,g,m)})):typeof m<"u"&&a(y,{name:d,newValue:m}));return y},ni}var mb=pb();const si=Bl(mb);function Oi(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function gb(){const e=[],t={run:n,use:s};return t;function n(...r){let i=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);l(null,...r);function l(c,...u){const d=e[++i];let h=-1;if(c){a(c);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,d?xb(d,l)(...u):a(null,...u)}}function s(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function xb(e,t){let n;return s;function s(...a){const l=e.length>a.length;let c;l&&a.push(r);try{c=e.apply(this,a)}catch(u){const d=u;if(l&&n)throw d;return r(d)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,r):c instanceof Error?r(c):i(c))}function r(a,...l){n||(n=!0,t(a,...l))}function i(a){r(null,a)}}const at={basename:yb,dirname:bb,extname:wb,join:Sb,sep:"/"};function yb(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');$n(e);let n=0,s=-1,r=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else s<0&&(i=!0,s=r+1);return s<0?"":e.slice(n,s)}if(t===e)return"";let a=-1,l=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else a<0&&(i=!0,a=r+1),l>-1&&(e.codePointAt(r)===t.codePointAt(l--)?l<0&&(s=r):(l=-1,s=a));return n===s?s=a:s<0&&(s=e.length),e.slice(n,s)}function bb(e){if($n(e),e.length===0)return".";let t=-1,n=e.length,s;for(;--n;)if(e.codePointAt(n)===47){if(s){t=n;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function wb(e){$n(e);let t=e.length,n=-1,s=0,r=-1,i=0,a;for(;t--;){const l=e.codePointAt(t);if(l===47){if(a){s=t+1;break}continue}n<0&&(a=!0,n=t+1),l===46?r<0?r=t:i!==1&&(i=1):r>-1&&(i=-1)}return r<0||n<0||i===0||i===1&&r===n-1&&r===s+1?"":e.slice(r,n)}function Sb(...e){let t=-1,n;for(;++t<e.length;)$n(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":vb(n)}function vb(e){$n(e);const t=e.codePointAt(0)===47;let n=kb(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function kb(e,t){let n="",s=0,r=-1,i=0,a=-1,l,c;for(;++a<=e.length;){if(a<e.length)l=e.codePointAt(a);else{if(l===47)break;l=47}if(l===47){if(!(r===a-1||i===1))if(r!==a-1&&i===2){if(n.length<2||s!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",s=0):(n=n.slice(0,c),s=n.length-1-n.lastIndexOf("/")),r=a,i=0;continue}}else if(n.length>0){n="",s=0,r=a,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",s=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),s=a-r-1;r=a,i=0}else l===46&&i>-1?i++:i=-1}return n}function $n(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Cb={cwd:Eb};function Eb(){return"/"}function Di(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function jb(e){if(typeof e=="string")e=new URL(e);else if(!Di(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return Nb(e)}function Nb(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const s=t.codePointAt(n+2);if(s===70||s===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(t)}const ri=["history","path","basename","stem","extname","dirname"];class $c{constructor(t){let n;t?Di(t)?n={path:t}:typeof t=="string"||Tb(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Cb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<ri.length;){const i=ri[s];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let r;for(r in n)ri.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){oi(t,"basename"),ii(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){Xa(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(ii(t,"extname"),Xa(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Di(t)&&(t=jb(t)),oi(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){oi(t,"stem"),ii(t,"stem"),this.path=at.join(this.dirname||"",t+(this.extname||""))}fail(t,n,s){const r=this.message(t,n,s);throw r.fatal=!0,r}info(t,n,s){const r=this.message(t,n,s);return r.fatal=void 0,r}message(t,n,s){const r=new Le(t,n,s);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function ii(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function oi(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Xa(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function Tb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Pb=(function(e){const s=this.constructor.prototype,r=s[e],i=function(){return r.apply(i,arguments)};return Object.setPrototypeOf(i,s),i}),Ib={}.hasOwnProperty;class po extends Pb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=gb()}copy(){const t=new po;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(si(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(ci("data",this.frozen),this.namespace[t]=n,this):Ib.call(this.namespace,t)&&this.namespace[t]||void 0:t?(ci("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...s]=this.attachers[this.freezeIndex];if(s[0]===!1)continue;s[0]===!0&&(s[0]=void 0);const r=n.call(t,...s);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=ss(t),s=this.parser||this.Parser;return ai("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),ai("process",this.parser||this.Parser),li("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(i,a){const l=ss(t),c=s.parse(l);s.run(c,l,function(d,h,m){if(d||!h||!m)return u(d);const f=h,g=s.stringify(f,m);_b(g)?m.value=g:m.result=g,u(d,m)});function u(d,h){d||!h?a(d):i?i(h):n(void 0,h)}}}processSync(t){let n=!1,s;return this.freeze(),ai("processSync",this.parser||this.Parser),li("processSync",this.compiler||this.Compiler),this.process(t,r),tl("processSync","process",n),s;function r(i,a){n=!0,Ya(i),s=a}}run(t,n,s){el(t),this.freeze();const r=this.transformers;return!s&&typeof n=="function"&&(s=n,n=void 0),s?i(void 0,s):new Promise(i);function i(a,l){const c=ss(n);r.run(t,c,u);function u(d,h,m){const f=h||t;d?l(d):a?a(f):s(void 0,f,m)}}}runSync(t,n){let s=!1,r;return this.run(t,n,i),tl("runSync","run",s),r;function i(a,l){Ya(a),r=l,s=!0}}stringify(t,n){this.freeze();const s=ss(n),r=this.compiler||this.Compiler;return li("stringify",r),el(t),r(t,s)}use(t,...n){const s=this.attachers,r=this.namespace;if(ci("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...h]=u;c(d,h)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(r.settings=si(!0,r.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const h=u[d];i(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let h=-1,m=-1;for(;++h<s.length;)if(s[h][0]===u){m=h;break}if(m===-1)s.push([u,...d]);else if(d.length>0){let[f,...g]=d;const y=s[m][1];Oi(y)&&Oi(f)&&(f=si(!0,y,f)),s[m]=[u,f,...g]}}}}const Ab=new po().freeze();function ai(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function li(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ci(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function el(e){if(!Oi(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function tl(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ss(e){return zb(e)?e:new $c(e)}function zb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function _b(e){return typeof e=="string"||Lb(e)}function Lb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Rb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",nl=[],sl={allowDangerousHtml:!0},Ob=/^(https?|ircs?|mailto|xmpp)$/i,Db=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Mb(e){const t=Fb(e),n=$b(e);return Bb(t.runSync(t.parse(n),n),e)}function Fb(e){const t=e.rehypePlugins||nl,n=e.remarkPlugins||nl,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...sl}:sl;return Ab().use(xy).use(n).use(fb,s).use(t)}function $b(e){const t=e.children||"",n=new $c;return typeof t=="string"&&(n.value=t),n}function Bb(e,t){const n=t.allowedElements,s=t.allowElement,r=t.components,i=t.disallowedElements,a=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Vb;for(const d of Db)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+Rb+d.id,void 0);return Fc(e,u),Zm(e,{Fragment:o.Fragment,components:r,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(d,h,m){if(d.type==="raw"&&m&&typeof h=="number")return a?m.children.splice(h,1):m.children[h]={type:"text",value:d.value},h;if(d.type==="element"){let f;for(f in Xr)if(Object.hasOwn(Xr,f)&&Object.hasOwn(d.properties,f)){const g=d.properties[f],y=Xr[f];(y===null||y.includes(d.tagName))&&(d.properties[f]=c(String(g||""),f,d))}}if(d.type==="element"){let f=n?!n.includes(d.tagName):i?i.includes(d.tagName):!1;if(!f&&s&&typeof h=="number"&&(f=!s(d,h,m)),f&&m&&typeof h=="number")return l&&d.children?m.children.splice(h,1,...d.children):m.children.splice(h,1),h}}}function Vb(e){const t=e.indexOf(":"),n=e.indexOf("?"),s=e.indexOf("#"),r=e.indexOf("/");return t===-1||r!==-1&&t>r||n!==-1&&t>n||s!==-1&&t>s||Ob.test(e.slice(0,t))?e:""}const mo=p.createContext(null);function Ub({children:e,host:t}){return o.jsx(mo.Provider,{value:t,children:e})}function Hb(){const e=p.useContext(mo);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}function qb(){return p.useContext(mo)}const Bc="openlearn:dashboardVisibility";function Wb(){try{const e=localStorage.getItem(Bc);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function rl(e){try{localStorage.setItem(Bc,JSON.stringify([...e.entries()]))}catch{}}const Ce=Yi()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:Wb(),initialized:!1,initialize:n=>e({services:n,initialized:!0}),addPlugin:n=>e(s=>({activePlugins:[...s.activePlugins,n]})),removePlugin:n=>e(s=>({activePlugins:s.activePlugins.filter(r=>r.id!==n)})),updatePluginState:(n,s)=>e(r=>({activePlugins:r.activePlugins.map(i=>i.id===n?{...i,state:s}:i)})),registerExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n)??[];if(i.find(c=>c.id===s.id)){const c=new Map(r.extensionPoints);return c.set(n,i.map(u=>u.id===s.id?s:u)),{extensionPoints:c}}const l=new Map(r.extensionPoints);return l.set(n,[...i,s]),{extensionPoints:l}}),unregisterExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n);if(!i)return r;const a=i.filter(c=>c.id!==s),l=new Map(r.extensionPoints);return a.length===0?l.delete(n):l.set(n,a),{extensionPoints:l}}),unregisterPluginExtensionPoints:n=>e(s=>{const r=new Map(s.extensionPoints);for(const[i,a]of r){const l=a.filter(c=>c.pluginId!==n);l.length===0?r.delete(i):r.set(i,l)}return{extensionPoints:r}}),getExtensions:n=>[...t().extensionPoints.get(n)??[]].sort((r,i)=>(r.position??100)-(i.position??100)),setDashboardVisibility:(n,s)=>e(r=>{const i=new Map(r.dashboardVisibility);return i.set(n,s),rl(i),{dashboardVisibility:i}}),setDashboardVisibilityBatch:n=>e(s=>{const r=new Map(s.dashboardVisibility);for(const[i,a]of n)r.set(i,a);return rl(r),{dashboardVisibility:r}})}));function Gb(){return o.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(Zi,{size:24,className:"text-gray-400 animate-spin"}),o.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}class Qb extends Ze.Component{constructor(t){super(t),this.state={hasError:!1},this.props=t}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function Jb({ext:e,route:t,slotProps:n,slot:s}){const r=Ze.useRef(null),i=JSON.stringify(n||{});Ze.useEffect(()=>{r.current&&typeof e.render=="function"&&(r.current.innerHTML="",Promise.resolve(e.render(r.current,{route:t,...n})).catch(console.error))},[e,t,i]);const l=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return o.jsx("div",{ref:r,className:`w-full ${l}`})}const ui=new WeakMap;function Zb(e){const t=e.component,n=ui.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=Ze.lazy(t);return ui.set(t,s),s}return ui.set(t,t),t}function Mi({slot:e,fallback:t,lang:n,route:s,slotProps:r,placement:i}){const a=qb();if(!a)return t??null;let l=a.getExtensions(e);const c=Ce(h=>h.dashboardVisibility),u=he(h=>h.selectedLesson),d=he(h=>h.liveClassSelectedClassId);return i&&(l=l.filter(h=>(h.placement??"after")===i)),l.length===0?null:e==="teacher.tab"&&r?.renderType==="button"?o.jsx(o.Fragment,{children:l.map(h=>{const m=`${h.pluginId}/${h.id}`,f=r?.teacherTab===m,g=h.title||h.label||h.id;return o.jsxs("button",{onClick:()=>r?.setTeacherTab?.(m),className:`flex items-center gap-3 p-3 transition-colors text-sm font-medium rounded-xl ${f?"bg-indigo-50 text-indigo-700 font-bold":"text-gray-600 hover:bg-gray-50"} ${r?.mainNavCollapsed?"justify-center px-2":""}`,title:g,children:[o.jsx(Ji,{size:20,className:"shrink-0"}),o.jsx("span",{className:r?.mainNavCollapsed?"hidden":"hidden md:block",children:g})]},`${h.pluginId}/${h.id}`)})}):o.jsx(o.Fragment,{children:l.map(h=>{const m=typeof h.component=="function",f=typeof h.render=="function";return e==="teacher.dashboard.widget"&&c.get(h.pluginId)===!1||!m&&!f?null:o.jsx(Qb,{fallback:o.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:o.jsx("p",{children:n==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:o.jsx(p.Suspense,{fallback:t??o.jsx(Gb,{}),children:m?Ze.createElement(Zb(h),{route:h.route||s,lessonId:u,classId:d,...h.slotProps,...r}):o.jsx(Jb,{ext:h,route:h.route||s,slotProps:{lessonId:u,classId:d,...h.slotProps,...r},slot:e})})},`${h.pluginId}/${h.id}`)})})}const Yb=(e,t)=>{const n=e?e.trim():"New Course";switch(t){case"Mathematics":return`# ${n}
25
+ `}),n}function Ya(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Ka(e,t){const n=pb(e,t),s=n.one(e,void 0),r=sb(n),i=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return r&&i.children.push({type:"text",value:`
26
+ `},r),i}function bb(e,t){return e&&"run"in e?async function(n,s){const r=Ka(n,{file:s,...t});await e.run(r,s)}:function(n,s){return Ka(n,{file:s,...e||t})}}function Xa(e){if(e)throw e}var ri,el;function wb(){if(el)return ri;el=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),p=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!p)return!1;var m;for(m in u);return typeof m>"u"||e.call(u,m)},a=function(u,d){n&&d.name==="__proto__"?n(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},l=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(s)return s(u,d).value}else return;return u[d]};return ri=function c(){var u,d,p,m,h,g,y=arguments[0],v=1,w=arguments.length,P=!1;for(typeof y=="boolean"&&(P=y,y=arguments[1]||{},v=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});v<w;++v)if(u=arguments[v],u!=null)for(d in u)p=l(y,d),m=l(u,d),y!==m&&(P&&m&&(i(m)||(h=r(m)))?(h?(h=!1,g=p&&r(p)?p:[]):g=p&&i(p)?p:{},a(y,{name:d,newValue:c(P,g,m)})):typeof m<"u"&&a(y,{name:d,newValue:m}));return y},ri}var Sb=wb();const ii=Wl(Sb);function Fi(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function vb(){const e=[],t={run:n,use:s};return t;function n(...r){let i=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);l(null,...r);function l(c,...u){const d=e[++i];let p=-1;if(c){a(c);return}for(;++p<r.length;)(u[p]===null||u[p]===void 0)&&(u[p]=r[p]);r=u,d?kb(d,l)(...u):a(null,...u)}}function s(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function kb(e,t){let n;return s;function s(...a){const l=e.length>a.length;let c;l&&a.push(r);try{c=e.apply(this,a)}catch(u){const d=u;if(l&&n)throw d;return r(d)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,r):c instanceof Error?r(c):i(c))}function r(a,...l){n||(n=!0,t(a,...l))}function i(a){r(null,a)}}const at={basename:Cb,dirname:Eb,extname:jb,join:Nb,sep:"/"};function Cb(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');$n(e);let n=0,s=-1,r=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else s<0&&(i=!0,s=r+1);return s<0?"":e.slice(n,s)}if(t===e)return"";let a=-1,l=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else a<0&&(i=!0,a=r+1),l>-1&&(e.codePointAt(r)===t.codePointAt(l--)?l<0&&(s=r):(l=-1,s=a));return n===s?s=a:s<0&&(s=e.length),e.slice(n,s)}function Eb(e){if($n(e),e.length===0)return".";let t=-1,n=e.length,s;for(;--n;)if(e.codePointAt(n)===47){if(s){t=n;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function jb(e){$n(e);let t=e.length,n=-1,s=0,r=-1,i=0,a;for(;t--;){const l=e.codePointAt(t);if(l===47){if(a){s=t+1;break}continue}n<0&&(a=!0,n=t+1),l===46?r<0?r=t:i!==1&&(i=1):r>-1&&(i=-1)}return r<0||n<0||i===0||i===1&&r===n-1&&r===s+1?"":e.slice(r,n)}function Nb(...e){let t=-1,n;for(;++t<e.length;)$n(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Tb(n)}function Tb(e){$n(e);const t=e.codePointAt(0)===47;let n=Pb(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Pb(e,t){let n="",s=0,r=-1,i=0,a=-1,l,c;for(;++a<=e.length;){if(a<e.length)l=e.codePointAt(a);else{if(l===47)break;l=47}if(l===47){if(!(r===a-1||i===1))if(r!==a-1&&i===2){if(n.length<2||s!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",s=0):(n=n.slice(0,c),s=n.length-1-n.lastIndexOf("/")),r=a,i=0;continue}}else if(n.length>0){n="",s=0,r=a,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",s=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),s=a-r-1;r=a,i=0}else l===46&&i>-1?i++:i=-1}return n}function $n(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Ib={cwd:Ab};function Ab(){return"/"}function $i(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function zb(e){if(typeof e=="string")e=new URL(e);else if(!$i(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return _b(e)}function _b(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const s=t.codePointAt(n+2);if(s===70||s===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(t)}const oi=["history","path","basename","stem","extname","dirname"];class qc{constructor(t){let n;t?$i(t)?n={path:t}:typeof t=="string"||Lb(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Ib.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<oi.length;){const i=oi[s];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let r;for(r in n)oi.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){li(t,"basename"),ai(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){tl(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(ai(t,"extname"),tl(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){$i(t)&&(t=zb(t)),li(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){li(t,"stem"),ai(t,"stem"),this.path=at.join(this.dirname||"",t+(this.extname||""))}fail(t,n,s){const r=this.message(t,n,s);throw r.fatal=!0,r}info(t,n,s){const r=this.message(t,n,s);return r.fatal=void 0,r}message(t,n,s){const r=new Le(t,n,s);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function ai(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function li(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function tl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function Lb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Rb=(function(e){const s=this.constructor.prototype,r=s[e],i=function(){return r.apply(i,arguments)};return Object.setPrototypeOf(i,s),i}),Ob={}.hasOwnProperty;class go extends Rb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=vb()}copy(){const t=new go;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(ii(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(di("data",this.frozen),this.namespace[t]=n,this):Ob.call(this.namespace,t)&&this.namespace[t]||void 0:t?(di("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...s]=this.attachers[this.freezeIndex];if(s[0]===!1)continue;s[0]===!0&&(s[0]=void 0);const r=n.call(t,...s);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=ss(t),s=this.parser||this.Parser;return ci("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),ci("process",this.parser||this.Parser),ui("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(i,a){const l=ss(t),c=s.parse(l);s.run(c,l,function(d,p,m){if(d||!p||!m)return u(d);const h=p,g=s.stringify(h,m);Fb(g)?m.value=g:m.result=g,u(d,m)});function u(d,p){d||!p?a(d):i?i(p):n(void 0,p)}}}processSync(t){let n=!1,s;return this.freeze(),ci("processSync",this.parser||this.Parser),ui("processSync",this.compiler||this.Compiler),this.process(t,r),sl("processSync","process",n),s;function r(i,a){n=!0,Xa(i),s=a}}run(t,n,s){nl(t),this.freeze();const r=this.transformers;return!s&&typeof n=="function"&&(s=n,n=void 0),s?i(void 0,s):new Promise(i);function i(a,l){const c=ss(n);r.run(t,c,u);function u(d,p,m){const h=p||t;d?l(d):a?a(h):s(void 0,h,m)}}}runSync(t,n){let s=!1,r;return this.run(t,n,i),sl("runSync","run",s),r;function i(a,l){Xa(a),r=l,s=!0}}stringify(t,n){this.freeze();const s=ss(n),r=this.compiler||this.Compiler;return ui("stringify",r),nl(t),r(t,s)}use(t,...n){const s=this.attachers,r=this.namespace;if(di("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...p]=u;c(d,p)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(r.settings=ii(!0,r.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const p=u[d];i(p)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let p=-1,m=-1;for(;++p<s.length;)if(s[p][0]===u){m=p;break}if(m===-1)s.push([u,...d]);else if(d.length>0){let[h,...g]=d;const y=s[m][1];Fi(y)&&Fi(h)&&(h=ii(!0,y,h)),s[m]=[u,h,...g]}}}}const Mb=new go().freeze();function ci(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ui(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function di(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function nl(e){if(!Fi(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function sl(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ss(e){return Db(e)?e:new qc(e)}function Db(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Fb(e){return typeof e=="string"||$b(e)}function $b(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Bb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",rl=[],il={allowDangerousHtml:!0},Vb=/^(https?|ircs?|mailto|xmpp)$/i,Ub=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Hb(e){const t=qb(e),n=Wb(e);return Gb(t.runSync(t.parse(n),n),e)}function qb(e){const t=e.rehypePlugins||rl,n=e.remarkPlugins||rl,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...il}:il;return Mb().use(ky).use(n).use(bb,s).use(t)}function Wb(e){const t=e.children||"",n=new qc;return typeof t=="string"&&(n.value=t),n}function Gb(e,t){const n=t.allowedElements,s=t.allowElement,r=t.components,i=t.disallowedElements,a=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Qb;for(const d of Ub)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+Bb+d.id,void 0);return Hc(e,u),ng(e,{Fragment:o.Fragment,components:r,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(d,p,m){if(d.type==="raw"&&m&&typeof p=="number")return a?m.children.splice(p,1):m.children[p]={type:"text",value:d.value},p;if(d.type==="element"){let h;for(h in ti)if(Object.hasOwn(ti,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],y=ti[h];(y===null||y.includes(d.tagName))&&(d.properties[h]=c(String(g||""),h,d))}}if(d.type==="element"){let h=n?!n.includes(d.tagName):i?i.includes(d.tagName):!1;if(!h&&s&&typeof p=="number"&&(h=!s(d,p,m)),h&&m&&typeof p=="number")return l&&d.children?m.children.splice(p,1,...d.children):m.children.splice(p,1),p}}}function Qb(e){const t=e.indexOf(":"),n=e.indexOf("?"),s=e.indexOf("#"),r=e.indexOf("/");return t===-1||r!==-1&&t>r||n!==-1&&t>n||s!==-1&&t>s||Vb.test(e.slice(0,t))?e:""}const xo=f.createContext(null);function Jb({children:e,host:t}){return o.jsx(xo.Provider,{value:t,children:e})}function Zb(){const e=f.useContext(xo);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}function Yb(){return f.useContext(xo)}const Wc="openlearn:dashboardVisibility";function Kb(){try{const e=localStorage.getItem(Wc);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function ol(e){try{localStorage.setItem(Wc,JSON.stringify([...e.entries()]))}catch{}}const Ce=Xi()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:Kb(),initialized:!1,initialize:n=>e({services:n,initialized:!0}),addPlugin:n=>e(s=>({activePlugins:[...s.activePlugins,n]})),removePlugin:n=>e(s=>({activePlugins:s.activePlugins.filter(r=>r.id!==n)})),updatePluginState:(n,s)=>e(r=>({activePlugins:r.activePlugins.map(i=>i.id===n?{...i,state:s}:i)})),registerExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n)??[];if(i.find(c=>c.id===s.id)){const c=new Map(r.extensionPoints);return c.set(n,i.map(u=>u.id===s.id?s:u)),{extensionPoints:c}}const l=new Map(r.extensionPoints);return l.set(n,[...i,s]),{extensionPoints:l}}),unregisterExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n);if(!i)return r;const a=i.filter(c=>c.id!==s),l=new Map(r.extensionPoints);return a.length===0?l.delete(n):l.set(n,a),{extensionPoints:l}}),unregisterPluginExtensionPoints:n=>e(s=>{const r=new Map(s.extensionPoints);for(const[i,a]of r){const l=a.filter(c=>c.pluginId!==n);l.length===0?r.delete(i):r.set(i,l)}return{extensionPoints:r}}),getExtensions:n=>[...t().extensionPoints.get(n)??[]].sort((r,i)=>(r.position??100)-(i.position??100)),setDashboardVisibility:(n,s)=>e(r=>{const i=new Map(r.dashboardVisibility);return i.set(n,s),ol(i),{dashboardVisibility:i}}),setDashboardVisibilityBatch:n=>e(s=>{const r=new Map(s.dashboardVisibility);for(const[i,a]of n)r.set(i,a);return ol(r),{dashboardVisibility:r}})}));function al(){return o.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(Ki,{size:24,className:"text-gray-400 animate-spin"}),o.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}const Gc=3,Xb=300*1e3,Ms=new Map;function e0(e){const t=Date.now(),n=Ms.get(e);if(!n||t-n.lastAt>Xb)return Ms.set(e,{count:1,lastAt:t,blown:!1}),{shouldBreak:!1,count:1};n.count+=1,n.lastAt=t;const s=n.count>=Gc;return s&&(n.blown=!0),{shouldBreak:s,count:n.count}}function t0(e){Ms.delete(e)}function n0(e){return Ms.get(e)?.blown??!1}class ll extends De.Component{constructor(t){super(t),this.state={hasError:!1},this.props=t}componentDidCatch(t){const n=this.props.pluginId;if(!n)return;const{shouldBreak:s,count:r}=e0(n);if(console.error(`[ExtensionBreaker] Plugin "${n}" frontend crash #${r}/${Gc}`+(s?" — 达到熔断阈值,自动停用":""),t?.message?.slice(0,120)),s)try{this.props.onBreakerTrip?.(n)}catch(i){console.error("[ExtensionBreaker] breaker trip callback failed:",i)}}static getDerivedStateFromError(){return{hasError:!0}}componentDidMount(){this.props.pluginId&&t0(this.props.pluginId)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function s0({ext:e,route:t,slotProps:n,slot:s}){const r=De.useRef(null),i=JSON.stringify(n||{});De.useEffect(()=>{r.current&&typeof e.render=="function"&&(r.current.innerHTML="",Promise.resolve(e.render(r.current,{route:t,...n})).catch(console.error))},[e,t,i]);const l=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return o.jsx("div",{ref:r,className:`w-full ${l}`})}const hi=new WeakMap;function cl(e){const t=e.component,n=hi.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=De.lazy(t);return hi.set(t,s),s}return hi.set(t,t),t}function Bi({slot:e,fallback:t,lang:n,route:s,slotProps:r,placement:i}){const a=De.useRef(new Set),l=Yb(),c=Ce(m=>m.dashboardVisibility),u=he(m=>m.selectedLesson),d=he(m=>m.liveClassSelectedClassId);if(!l)return t??null;let p=l.getExtensions(e);if(i&&(p=p.filter(m=>(m.placement??"after")===i)),p.length===0)return null;if(e==="class.tab"&&r?.renderType==="button")return o.jsx(o.Fragment,{children:p.map(m=>{const h=`plugin:${m.pluginId}/${m.id}`,g=r?.classActiveTab===h,y=m.title||m.label||m.id;return o.jsxs("button",{onClick:v=>{v.stopPropagation(),r?.setClassActiveTab?.(h)},className:`py-1.5 px-3 rounded-lg text-xs font-semibold flex items-center justify-center gap-1.5 transition-all duration-200 cursor-pointer ${g?"bg-white text-indigo-600 shadow-xs font-bold border border-slate-200/50":"text-slate-500 hover:text-slate-800 hover:bg-white/40"}`,title:y,children:[o.jsx(Ts,{size:12}),o.jsx("span",{children:y})]},`${m.pluginId}/${m.id}`)})});if(e==="class.tab"&&r?.renderType==="panel"){const m=r?.classActiveTab,h=p.find(g=>`plugin:${g.pluginId}/${g.id}`===m);return h?o.jsx(ll,{pluginId:h.pluginId,fallback:o.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:"扩展 Tab 加载失败"}),children:o.jsx(f.Suspense,{fallback:o.jsx(al,{}),children:De.createElement(cl(h),{classId:r?.classId,students:r?.students,lang:r?.lang,...h.slotProps})})},`${h.pluginId}/${h.id}`):null}return e==="teacher.tab"&&r?.renderType==="button"?o.jsx(o.Fragment,{children:p.map(m=>{const h=`${m.pluginId}/${m.id}`,g=r?.teacherTab===h,y=m.title||m.label||m.id;return o.jsxs("button",{onClick:()=>r?.setTeacherTab?.(h),className:`flex items-center gap-3 p-3 transition-colors text-sm font-medium rounded-xl ${g?"bg-indigo-50 text-indigo-700 font-bold":"text-gray-600 hover:bg-gray-50"} ${r?.mainNavCollapsed?"justify-center px-2":""}`,title:y,children:[o.jsx(Ts,{size:20,className:"shrink-0"}),o.jsx("span",{className:r?.mainNavCollapsed?"hidden":"hidden md:block",children:y})]},`${m.pluginId}/${m.id}`)})}):o.jsx(o.Fragment,{children:p.map(m=>{const h=typeof m.component=="function",g=typeof m.render=="function";return e==="teacher.dashboard.widget"&&c.get(m.pluginId)===!1||!h&&!g?null:n0(m.pluginId)?(a.current.has(m.pluginId)||(a.current.add(m.pluginId),console.warn(`[ExtensionBreaker] Plugin "${m.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),null):o.jsx(ll,{pluginId:m.pluginId,onBreakerTrip:y=>{l.deactivatePlugin(y).catch(v=>console.error(`[ExtensionBreaker] auto-deactivate "${y}" failed:`,v))},fallback:o.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:o.jsx("p",{children:n==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:o.jsx(f.Suspense,{fallback:t??o.jsx(al,{}),children:h?De.createElement(cl(m),{route:m.route||s,lessonId:u,classId:d,...m.slotProps,...r}):o.jsx(s0,{ext:m,route:m.route||s,slotProps:{lessonId:u,classId:d,...m.slotProps,...r},slot:e})})},`${m.pluginId}/${m.id}`)})})}const r0=(e,t)=>{const n=e?e.trim():"New Course";switch(t){case"Mathematics":return`# ${n}
27
27
 
28
28
  ## 101 Course Core Foundations
29
29
  Welcome to our mathematics laboratory. This course is designed to break down abstract calculations into visual whiteboard proofs and real-world application models.
@@ -122,33 +122,33 @@ This course integrates cross-subject paradigms, cognitive practices, and critica
122
122
  2. Sketch the systemic flow diagram depicting interaction factors.
123
123
 
124
124
  ### 📥 Assignment Brief
125
- Draft a 300-word integration proposal based on today's whiteboard exercises.`}};function Kb(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return;const t=new e,n=t.currentTime,s=t.createOscillator(),r=t.createGain();s.type="sine",s.frequency.setValueAtTime(587.33,n),s.frequency.exponentialRampToValueAtTime(880,n+.3),r.gain.setValueAtTime(.25,n),r.gain.exponentialRampToValueAtTime(.001,n+.8),s.connect(r),r.connect(t.destination),s.start(n),s.stop(n+.8)}catch{}}function Xb({lessonId:e,lang:t="zh",syncChannel:n}){const[s,r]=p.useState(null),[i,a]=p.useState(!1),[l,c]=p.useState(!0),[u,d]=p.useState(!1),h=p.useRef(s);if(h.current=s,p.useEffect(()=>{if(!e)return;let w=null,P;try{w=n||new Ni,P=w.onMessage(A=>{A.type==="TEACHER_BROADCAST_COUNTDOWN"?r(A.payload):A.type==="TEACHER_SYNC_TIMER"&&r(E=>E?{...E,timeRemaining:A.payload.timeRemaining,isRunning:A.payload.isRunning,endsAt:A.payload.isRunning?Date.now()+A.payload.timeRemaining*1e3:null}:{lessonId:e,totalDuration:Math.max(300,A.payload.timeRemaining),timeRemaining:A.payload.timeRemaining,isRunning:A.payload.isRunning,isPaused:!1,label:t==="zh"?"⏱️ 课堂限时任务":"⏱️ Timed Task",endsAt:A.payload.isRunning?Date.now()+A.payload.timeRemaining*1e3:null,updatedAt:Date.now()})})}catch{}(async()=>{try{const A=await fetch(`/api/classroom/sessions/${e}/countdown`);if(A.ok){const E=await A.json();E.success&&E.countdown&&r(E.countdown)}}catch{}})();const j=A=>{A.detail&&r(A.detail)};return window.addEventListener("openlearn:countdown:updated",j),()=>{P?.(),!n&&typeof w?.destroy=="function"&&w.destroy(),window.removeEventListener("openlearn:countdown:updated",j)}},[e,t]),p.useEffect(()=>{if(!s||!s.isRunning||!s.endsAt)return;const w=setInterval(()=>{const P=h.current;if(!P||!P.isRunning||!P.endsAt)return;const S=Date.now(),j=Math.max(0,Math.round((P.endsAt-S)/1e3));if(j!==P.timeRemaining){const A={...P,timeRemaining:j,updatedAt:S};j<=0&&(A.isRunning=!1,A.isPaused=!1,A.endsAt=null,l&&!u&&(Kb(),d(!0))),r(A);try{window.dispatchEvent(new CustomEvent("openlearn:student:countdown_tick",{detail:{timeRemaining:j,totalDuration:P.totalDuration,label:P.label}}))}catch{}}},500);return()=>clearInterval(w)},[s?.isRunning,s?.endsAt,l,u]),!s||s.timeRemaining===0&&!s.isRunning&&!u)return null;const m=w=>{const P=Math.floor(w/60),S=w%60,j=A=>A.toString().padStart(2,"0");return`${j(P)}:${j(S)}`},f=s.totalDuration>0?Math.min(100,Math.max(0,s.timeRemaining/s.totalDuration*100)):0,g=s.timeRemaining>0&&s.timeRemaining<=60,y=s.timeRemaining>60&&s.timeRemaining<=180,C=s.timeRemaining===0;return o.jsx("aside",{id:"student-classroom-countdown-banner","aria-label":t==="zh"?"课堂倒计时通知":"Classroom Countdown Alert",className:`fixed top-4 right-6 z-50 transition-all duration-300 select-none ${i?"w-auto":"w-72 sm:w-80"}`,children:o.jsxs("div",{className:`bg-surface/95 backdrop-blur-md border rounded-2xl shadow-2xl p-3 flex flex-col gap-2 transition-all ${g?"border-rose-500/80 shadow-rose-500/20":y?"border-amber-500/80 shadow-amber-500/20":C?"border-emerald-500/80 shadow-emerald-500/20":"border-theme shadow-primary-theme/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between gap-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("span",{className:`p-1 rounded-lg text-white shrink-0 ${g?"bg-rose-500 animate-pulse":y?"bg-amber-500":C?"bg-emerald-500":"bg-primary-theme"}`,children:o.jsx(Ql,{size:12,className:s.isRunning?"animate-spin":"",style:{animationDuration:"6s"}})}),o.jsx("span",{className:"text-xs font-bold text-main truncate",children:s.label||(t==="zh"?"课堂任务":"Task")})]}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o.jsx("button",{type:"button",onClick:()=>c(!l),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:l?"提示音已开启":"提示音已静音",children:l?o.jsx(ap,{size:12}):o.jsx(lp,{size:12})}),o.jsx("button",{type:"button",onClick:()=>a(!i),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:i?"展开":"收起",children:i?o.jsx(dn,{size:12}):o.jsx(cp,{size:12})})]})]}),!i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline justify-between px-1",children:[o.jsx("span",{id:"student-countdown-digits",className:`text-2xl font-black font-mono tracking-widest ${g?"text-rose-500 animate-pulse":y?"text-amber-500":C?"text-emerald-500":"text-primary-theme"}`,children:m(s.timeRemaining)}),o.jsx("span",{className:"text-[11px] font-semibold text-muted",children:C?t==="zh"?"🎉 时间已截止!":"Time is up!":s.isPaused?t==="zh"?"⏸️ 老师已暂停计时":"Paused":t==="zh"?"与全班同步中":"Synced"})]}),o.jsx("div",{className:"w-full h-1.5 bg-surface-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:`h-full transition-all duration-500 ${g?"bg-rose-500":y?"bg-amber-500":C?"bg-emerald-500":"bg-primary-theme"}`,style:{width:`${f}%`}})}),o.jsx(Mi,{slot:"student.classroom.countdown",slotProps:{countdown:s,lang:t}})]})]})})}const e0={id:"core-q-1",question:"关于变力沿曲线轨道做功过程,下列说法严格正确的是:",options:[{key:"A",text:"可以直接利用恒力做功公式 W = F·s·cosθ 统一计算"},{key:"B",text:"可将位移划分为无限小微元 Δs,在每个微元内以恒代变累加求和"},{key:"C",text:"只要动能有变化,机械能一定严格守恒"},{key:"D",text:"变力做功的数值与运动路径完全无关"}],correctOption:"B",explanation:"变力方向或大小随位置改变,不能直接套用恒力公式;微元法(微分与积分思想)是求解变力功的根本物理方法。",scaffoldHint:"⚠️ 巩固支架提示:请回顾牛顿第二定律与微积分思想,变力无法一次求和,必须采用 F-s 面积或微元累加!"},t0={id:"challenge-q-1",title:"高阶思维跃迁:变力与非弹性碰撞复合临界",prompt:"若物块在变阻力 f = -kv 作用下滑动并与弹性挡板碰撞,下列守恒与极限关系成立的是:",options:[{key:"A",text:"全程动量守恒且机械能保持守恒"},{key:"B",text:"当速度衰减为 0 前,系统动量损耗率与瞬时阻力成正比"},{key:"C",text:"滑动阻力做功仅取决于物块最终停止位置与重力势能无关"},{key:"D",text:"以上均不正确"}],correctOption:"B",rewardBadge:"🏅 物理探究思维跃迁徽章"},n0=({isOpen:e,onClose:t,lessonId:n,studentName:s="我",lang:r="zh",coreQuestion:i=e0,challengeQuestion:a=t0,onSubmitSuccess:l})=>{const[c,u]=p.useState(null),[d,h]=p.useState(!1),[m,f]=p.useState(null),[g,y]=p.useState(null),[C,w]=p.useState(5),[P,S]=p.useState(""),[j,A]=p.useState(""),[E,R]=p.useState(!1),[F,M]=p.useState(!1),O=()=>{if(!c)return;const _=c===i.correctOption;f(_),h(!0)},v=async()=>{if(E)return;R(!0);const _=m?g?"challenge_done":"passed":"remediation";try{n&&await fetch(`/api/classroom/sessions/${n}/exit-ticket`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rating:C,puzzledConcept:P.trim(),feedback:j.trim(),coreAnswer:c,isCorrect:m,tierLevel:_,challengeAnswer:g})}),M(!0),l?.()}catch{M(!0)}finally{R(!1)}};return e?o.jsx("div",{"data-testid":"adaptive-exit-ticket-modal",className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-fade-in select-none",children:o.jsxs("div",{className:"bg-surface rounded-3xl border border-indigo-500/40 p-6 w-full max-w-lg shadow-2xl flex flex-col gap-4 max-h-[92vh] overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/80 pb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-2 text-indigo-500 font-extrabold text-base",children:[o.jsx(_t,{size:20}),o.jsx("span",{children:r==="zh"?"60 秒自适应结课通票 (Adaptive Exit Ticket)":"60s Adaptive Exit Ticket"})]}),o.jsx("button",{onClick:t,className:"text-muted hover:text-main rounded-lg p-1 cursor-pointer","aria-label":"Close",children:o.jsx(Je,{size:18})})]}),F?o.jsxs("div",{className:"py-8 flex flex-col items-center justify-center text-center gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-full bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 flex items-center justify-center",children:o.jsx(_t,{size:32})}),o.jsx("h3",{className:"text-base font-black text-main",children:r==="zh"?"结课通票提交成功!":"Exit Ticket Submitted!"}),o.jsx("p",{className:"text-xs text-muted max-w-xs",children:r==="zh"?"你的学情反馈与梯级作答已实时同步至教师大屏与个人课后学情卡。":"Feedback synced to classroom dashboard."}),o.jsx("button",{onClick:t,className:"mt-2 px-6 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs transition-colors cursor-pointer",children:r==="zh"?"完成":"Done"})]}):o.jsxs("div",{className:"flex flex-col gap-4 text-xs",children:[o.jsxs("div",{className:"bg-surface-secondary/70 p-4 rounded-2xl border border-border/60 flex flex-col gap-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"font-extrabold text-main flex items-center gap-1.5 text-xs",children:[o.jsx("span",{className:"px-2 py-0.5 rounded bg-indigo-500 text-white font-mono text-[10px]",children:"必做诊断"}),o.jsx("span",{children:"1. 核心概念过关题"})]}),d&&o.jsx("span",{className:`text-2xs font-bold px-2 py-0.5 rounded-full ${m?"bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300":"bg-rose-100 text-rose-700 dark:bg-rose-950 dark:text-rose-300"}`,children:m?"✓ 概念通关":"需巩固"})]}),o.jsx("p",{className:"text-main font-semibold leading-relaxed",children:i.question}),o.jsx("div",{className:"space-y-1.5",children:i.options.map(_=>o.jsxs("button",{type:"button",disabled:d,onClick:()=>u(_.key),className:`w-full p-2.5 rounded-xl border text-left flex items-start gap-2.5 transition-all cursor-pointer ${c===_.key?"border-indigo-500 bg-indigo-50/50 dark:bg-indigo-950/40 font-bold text-indigo-700 dark:text-indigo-300":"border-border/60 hover:bg-surface text-main"} ${d?"cursor-default opacity-90":""}`,children:[o.jsx("span",{className:"w-5 h-5 rounded-full bg-surface-secondary border border-border flex items-center justify-center text-[10px] font-mono shrink-0",children:_.key}),o.jsx("span",{className:"text-2xs leading-relaxed",children:_.text})]},_.key))}),!d&&o.jsxs("button",{type:"button",disabled:!c,onClick:O,className:`mt-1 py-1.5 px-3 rounded-xl font-bold text-2xs transition-colors flex items-center justify-center gap-1 ${c?"bg-indigo-600 hover:bg-indigo-700 text-white cursor-pointer shadow-xs":"bg-surface-secondary text-muted cursor-not-allowed"}`,children:[o.jsx("span",{children:"确认本题答案"}),o.jsx(Ts,{size:12})]}),d&&m&&o.jsxs("div",{"data-testid":"challenge-branch",className:"mt-2 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-800 dark:text-emerald-200 space-y-2 animate-fade-in",children:[o.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs",children:[o.jsx(Ut,{size:14,className:"text-emerald-600 dark:text-emerald-400"}),o.jsx("span",{children:"太棒了!已解锁【Lv.2 进阶探究挑战题】(冲刺思维勋章)"})]}),o.jsx("p",{className:"text-2xs font-semibold text-main",children:a.prompt}),o.jsx("div",{className:"grid grid-cols-1 gap-1",children:a.options.map(_=>o.jsxs("button",{type:"button",onClick:()=>y(_.key),className:`p-2 rounded-lg border text-left text-2xs transition-colors ${g===_.key?"border-emerald-500 bg-emerald-100/60 dark:bg-emerald-950 font-bold text-emerald-800 dark:text-emerald-200":"border-emerald-500/20 bg-surface text-main hover:bg-surface-secondary"}`,children:[o.jsxs("span",{className:"font-mono font-bold mr-1.5",children:[_.key,"."]}),o.jsx("span",{children:_.text})]},_.key))})]}),d&&!m&&o.jsxs("div",{"data-testid":"scaffold-branch",className:"mt-2 p-3 rounded-xl bg-amber-500/10 border border-amber-500/30 text-amber-800 dark:text-amber-200 space-y-1.5 animate-fade-in",children:[o.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs text-amber-600 dark:text-amber-400",children:[o.jsx(Fs,{size:14}),o.jsx("span",{children:"核心概念支架提示卡"})]}),o.jsx("p",{className:"text-2xs leading-relaxed",children:i.scaffoldHint}),o.jsxs("p",{className:"text-3xs text-muted",children:["解析:",i.explanation]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"2. 今日课堂综合掌握感评估":"Rate Today Lesson"}),o.jsxs("div",{className:"flex items-center gap-2",children:[[1,2,3,4,5].map(_=>o.jsx("button",{type:"button",onClick:()=>w(_),className:"p-0.5 text-xl transition-transform hover:scale-125 cursor-pointer",children:o.jsx(up,{size:20,className:_<=C?"text-amber-400 fill-amber-400":"text-slate-300"})},_)),o.jsxs("span",{className:"text-2xs font-bold text-amber-500 font-mono ml-1",children:[C,".0 星"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"3. 今天最困惑或没完全搞懂的知识点/卡点是什么?":"Most Confused Concept"}),o.jsx("input",{type:"text",value:P,onChange:_=>S(_.target.value),placeholder:r==="zh"?"例如:变力做功 F-s 面积法、临界滑动摩擦...":"e.g. friction boundary...",className:"w-full px-3 py-2 bg-surface-secondary border border-border rounded-xl text-xs text-main focus:outline-hidden focus:ring-2 focus:ring-indigo-500"})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"4. 给老师的一句小建议 (选填)":"Feedback (Optional)"}),o.jsx("input",{type:"text",value:j,onChange:_=>A(_.target.value),placeholder:r==="zh"?"例如:希望能补充一道微元积分经典例题...":"Feedback...",className:"w-full px-3 py-1.5 bg-surface-secondary border border-border rounded-xl text-xs text-main focus:outline-hidden focus:ring-2 focus:ring-indigo-500"})]}),o.jsx("button",{type:"button",disabled:E,onClick:v,className:"w-full py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-extrabold rounded-xl transition-colors cursor-pointer shadow-md text-xs flex items-center justify-center gap-1.5",children:o.jsx("span",{children:E?r==="zh"?"正在提交...":"Submitting...":r==="zh"?"提交自适应结课通票":"Submit Exit Ticket"})})]})]})}):null};function s0({lessonId:e,studentId:t="student_demo",studentName:n="我",lang:s="zh"}){const[r,i]=p.useState(null),[a,l]=p.useState(null),[c,u]=p.useState("IN_CLASS_TEACHING"),[d,h]=p.useState(null),[m,f]=p.useState(!1),[g,y]=p.useState("IDLE"),[C,w]=p.useState(null),[P,S]=p.useState(!1),[j,A]=p.useState(!1),[E,R]=p.useState(5),[F,M]=p.useState(""),[O,v]=p.useState(""),_=p.useRef(Date.now());if(p.useEffect(()=>{if(!e)return;let z=!0;const U=async()=>{try{const D=await fetch(`/api/classroom/sessions/${e}`);if(D.ok&&z){const x=await D.json();x.hasActiveSession&&(u(x.stage),x.stage==="WRAP_UP_EXIT_TICKET"&&!j&&S(!0),x.activePoll&&(!r||r.id!==x.activePoll.id)?(i(x.activePoll),h(null),f(!1)):x.activePoll||i(null),x.activeBuzzer&&(!a||a.id!==x.activeBuzzer.id)?(l(x.activeBuzzer),y("IDLE"),_.current=Date.now()):x.activeBuzzer&&a?(x.activeBuzzer.status==="LOCKED"&&(x.activeBuzzer.winner_student_id===t?y("WINNER"):y("MISSED")),l(x.activeBuzzer)):x.activeBuzzer||(l(null),y("IDLE")))}}catch{}};U();const T=setInterval(U,2500);return()=>{z=!1,clearInterval(T)}},[e,j,r,a,t]),!e)return null;const L=async z=>{try{await fetch(`/api/classroom/sessions/${e}/pacing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signal:z})}),w(z==="TOO_FAST"?"🐇 太快":z==="SLOW"?"🐢 太慢":z==="CONFUSED"?"❓ 困惑":"💡 听懂了"),setTimeout(()=>w(null),2e3)}catch{}},I=async z=>{if(!(!r||m))try{h(z),f(!0),await fetch(`/api/classroom/sessions/${e}/quick-poll/${r.id}/vote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({option:z})})}catch{}},N=async()=>{if(!a||a.status!=="READY"||g!=="IDLE")return;const z=Date.now()-_.current;y("BUZZED");try{const U=await fetch(`/api/classroom/sessions/${e}/buzzer/${a.id}/buzz`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentName:n,responseTimeMs:z})});U.ok&&((await U.json()).winner?y("WINNER"):y("MISSED"))}catch{y("MISSED")}};return o.jsxs(o.Fragment,{children:[o.jsx(Xb,{lessonId:e,lang:s}),o.jsx(Mi,{slot:"student.classroom.overlay",slotProps:{studentId:t,lessonId:e}}),o.jsx(Mi,{slot:"student.fullscreen",slotProps:{studentId:t,lessonId:e}}),o.jsxs("aside",{"aria-label":s==="zh"?"课堂互动工具栏":"Classroom interaction toolbar",className:"fixed bottom-6 right-6 z-40 flex items-center gap-2 bg-surface/95 backdrop-blur-md border border-border/80 p-2 rounded-2xl shadow-xl transition-all",children:[C&&o.jsxs("span",{className:"text-xs font-bold text-primary-theme px-2 py-1 animate-fade-in",children:[C," 已传达给老师"]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("button",{onClick:()=>L("CLEAR"),className:"px-2.5 py-1.5 rounded-xl hover:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"听懂了,节奏适宜",children:[o.jsx("span",{children:"💡"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"听懂了":"Clear"})]}),o.jsxs("button",{onClick:()=>L("CONFUSED"),className:"px-2.5 py-1.5 rounded-xl hover:bg-amber-500/10 text-amber-600 dark:text-amber-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"有点困惑,希望老师点拨",children:[o.jsx("span",{children:"❓"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"有疑问":"Confused"})]}),o.jsxs("button",{onClick:()=>L("TOO_FAST"),className:"px-2.5 py-1.5 rounded-xl hover:bg-rose-500/10 text-rose-600 dark:text-rose-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"讲得太快了,希望能慢一点",children:[o.jsx("span",{children:"🐇"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太快":"Too Fast"})]}),o.jsxs("button",{onClick:()=>L("SLOW"),className:"px-2.5 py-1.5 rounded-xl hover:bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"讲太慢了,希望快一点",children:[o.jsx("span",{children:"🐢"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太慢":"Too Slow"})]})]})]}),r&&r.status==="ACTIVE"&&o.jsxs("div",{className:"fixed bottom-20 right-6 z-50 bg-surface rounded-2xl border border-amber-500/40 p-5 shadow-2xl w-80 flex flex-col gap-3 animate-slide-up",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[o.jsxs("span",{className:"text-xs font-extrabold text-amber-500 flex items-center gap-1.5",children:[o.jsx(Ut,{size:14}),s==="zh"?"极速答题进行中":"Quick Poll Active"]}),m&&o.jsxs("span",{className:"text-[11px] text-emerald-500 font-bold flex items-center gap-1",children:[o.jsx(_t,{size:12}),s==="zh"?"已提交":"Submitted"]})]}),o.jsx("p",{className:"font-bold text-sm text-foreground",children:r.title}),o.jsx("div",{className:"grid grid-cols-2 gap-2 mt-1",children:(r.options||["A","B","C","D"]).map(z=>{const U=d===z;return o.jsx("button",{disabled:m,onClick:()=>I(z),className:`p-3 rounded-xl font-bold text-center text-sm transition-all cursor-pointer ${U?"bg-primary-theme text-white ring-2 ring-primary-theme shadow-md scale-95":m?"bg-surface-secondary text-muted opacity-60 cursor-not-allowed":"bg-surface-secondary hover:bg-primary-theme/10 hover:border-primary-theme border border-border text-foreground"}`,children:z},z)})})]}),a&&o.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4",children:o.jsxs("div",{className:"bg-surface rounded-3xl border border-rose-500/50 p-8 w-full max-w-sm shadow-2xl flex flex-col items-center text-center gap-4 animate-scale-up",children:[o.jsxs("h3",{className:"text-xl font-black text-foreground flex items-center gap-2",children:[o.jsx(Wl,{size:22,className:"text-rose-500 animate-bounce"}),o.jsx("span",{children:a.title||"全班极速抢答"})]}),g==="IDLE"&&a.status==="READY"&&o.jsxs("div",{className:"my-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{onClick:N,className:"w-36 h-36 rounded-full bg-gradient-to-tr from-rose-600 to-rose-400 text-white font-black text-2xl shadow-xl hover:scale-105 active:scale-95 transition-all flex flex-col items-center justify-center border-4 border-white dark:border-slate-800 cursor-pointer animate-pulse",children:[o.jsx(dp,{size:32,className:"mb-1"}),o.jsx("span",{children:"抢!"})]}),o.jsx("span",{className:"text-xs text-muted",children:"点击红色大按钮抢得首答权"})]}),g==="WINNER"&&o.jsxs("div",{className:"my-4 p-6 bg-emerald-500/10 border border-emerald-500/30 rounded-2xl flex flex-col items-center text-center",children:[o.jsx("span",{className:"text-4xl mb-2",children:"🎉"}),o.jsx("span",{className:"text-lg font-black text-emerald-500",children:"恭喜你率先抢答!"}),o.jsx("span",{className:"text-xs text-muted mt-1",children:"请起立或开麦回答老师的问题"})]}),g==="MISSED"&&o.jsxs("div",{className:"my-4 p-6 bg-slate-800/20 border border-border rounded-2xl flex flex-col items-center text-center",children:[o.jsx("span",{className:"text-4xl mb-2",children:"⚡"}),o.jsxs("span",{className:"text-base font-bold text-foreground",children:["已被 ",a.winner_student_name||"其他同学"," 抢先一步!"]}),o.jsx("span",{className:"text-xs text-muted mt-1",children:"下次手速要更快哦"})]})]})}),o.jsx(n0,{isOpen:P&&!j,onClose:()=>S(!1),lessonId:e,studentName:n,lang:s,onSubmitSuccess:()=>{A(!0)}})]})}async function r0(e="all"){const t=await fetch(`/api/activities?role=${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load activities (${t.status})`);return(await t.json()).activities??[]}async function il(){const e=await fetch("/api/activities/running",{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load running activities (${e.status})`);return(await e.json()).activities??[]}async function i0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/finish`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to finish activity (${t.status})`)}}async function o0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/pause`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to pause activity (${t.status})`)}}async function a0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/resume`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to resume activity (${t.status})`)}}async function l0(e,t,n){const s=await fetch(`/api/activities/${encodeURIComponent(e)}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t??{},actorId:n})}),r=await s.json();if(!s.ok||r.ok===!1)throw new Error(r.error||`Failed to start activity (${s.status})`);return r}const rs={padding:"12px",color:"#e2e8f0",fontSize:"13px"},c0={HelpCircle:yp,Vote:xp,BarChart3:gp,MessagesSquare:mp,Users:Vl,FileText:Jl,Trophy:pp,CheckCircle2:_t,BookOpen:Fs};function u0({name:e,className:t}){const n=e&&c0[e]||Ji;return o.jsx(n,{size:18,className:t})}function d0(e,t){if(!e)return t==="zh"?"进行中":"In progress";const n=Math.max(0,Math.floor((Date.now()-e)/1e3)),s=Math.floor(n/60),r=n%60;return t==="zh"?`${s} 分 ${r} 秒`:`${s}m ${r}s`}const Vc=({role:e,actorId:t,lang:n="en",classroomId:s,mode:r="launcher"})=>{const[i,a]=p.useState([]),[l,c]=p.useState(!0),[u,d]=p.useState(null),[h,m]=p.useState({}),[f,g]=p.useState([]),[y,C]=p.useState(!0),[w,P]=p.useState(null),[S,j]=p.useState(null),[A,E]=p.useState(!1),[R,F]=p.useState(null),M=he(T=>T.setTeacherTab),O=p.useMemo(()=>{const T=new Map;for(const D of i){const x=D.category;T.has(x)||T.set(x,[]),T.get(x).push(D)}return Array.from(T.entries())},[i]);p.useEffect(()=>{if(r!=="launcher")return;let T=!1;return c(!0),r0(e).then(D=>{T||a(D)}).catch(D=>{T||d(D instanceof Error?D.message:String(D))}).finally(()=>{T||c(!1)}),()=>{T=!0}},[e,r]),p.useEffect(()=>{if(r!=="status")return;let T=!1;const D=async()=>{try{const oe=await il();T||g(oe)}catch(oe){T||P(oe instanceof Error?oe.message:String(oe))}finally{T||C(!1)}};D();const x=setInterval(D,5e3);return()=>{T=!0,clearInterval(x)}},[r]);const v=async T=>{if(S){E(!0),F(null);try{await T(S),g(await il())}catch(D){F(D instanceof Error?D.message:String(D))}finally{E(!1)}}},_=()=>v(i0),L=()=>v(o0),I=()=>v(a0),N=()=>{j(null),M("live_class")};if(r==="status"){if(y)return o.jsx("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm h-24 animate-pulse"});if(w||f.length===0)return null;const T=f.find(D=>D.id===S)||null;return o.jsxs("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-slate-800 font-extrabold",children:[o.jsx("span",{children:"🧩"}),o.jsx("span",{children:n==="zh"?"进行中的活动":"Activities in Progress"})]}),o.jsx("span",{className:"text-xs font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full",children:f.length})]}),o.jsx("div",{className:"flex flex-col gap-2",children:f.map(D=>{const x=D.state==="running";return o.jsxs("button",{onClick:()=>j(D.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:[o.jsx(u0,{name:D.icon,className:"text-indigo-600 shrink-0"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"font-bold text-slate-800 truncate",children:D.name}),D.category&&o.jsx("div",{className:"text-xs text-slate-500 truncate",children:D.category})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[o.jsx("span",{className:`text-xs font-bold px-2 py-0.5 rounded-full ${x?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"}`,children:x?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"}),o.jsxs("span",{className:"text-xs text-slate-400 flex items-center gap-1",children:[o.jsx(Ql,{size:10})," ",d0(D.startedAt,n)]})]})]},D.id)})}),T&&o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4",onClick:()=>j(null),children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-sm p-5",onClick:D=>D.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"font-bold text-slate-800",children:T.name}),o.jsx("button",{onClick:()=>j(null),className:"text-slate-400 hover:text-slate-600","aria-label":"close",children:o.jsx(Je,{size:18})})]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-1",children:[n==="zh"?"状态":"Status",":"," ",T.state==="running"?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-4",children:[n==="zh"?"开始时间":"Started",":"," ",T.startedAt?new Date(T.startedAt).toLocaleString():"-"]}),R&&o.jsx("div",{className:"text-xs text-rose-600 mb-2",children:R}),o.jsxs("div",{className:"flex gap-2",children:[T.state==="running"?o.jsxs("button",{disabled:A,onClick:L,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:[o.jsx(hp,{size:14})," ",n==="zh"?"暂停":"Pause"]}):o.jsxs("button",{disabled:A,onClick:I,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:[o.jsx(fp,{size:14})," ",n==="zh"?"恢复":"Resume"]}),o.jsx("button",{disabled:A,onClick:_,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:A?n==="zh"?"处理中…":"Working…":n==="zh"?"结束":"End"})]}),o.jsx("button",{onClick:N,className:"w-full mt-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg py-2 text-sm font-bold",children:n==="zh"?"进入课堂":"Enter Classroom"})]})})]})}const z=async T=>{m(D=>({...D,[T.id]:n==="zh"?"启动中…":"Starting…"}));try{const D=await l0(T.id,{classroomId:s,role:e},t);m(x=>({...x,[T.id]:D.dispatched?n==="zh"?"已启动 ✓":"Started ✓":n==="zh"?"已通知 ✓":"Notified ✓"}))}catch(D){m(x=>({...x,[T.id]:D instanceof Error?D.message:String(D)}))}};if(l)return o.jsx("div",{style:rs,children:n==="zh"?"加载活动中…":"Loading activities…"});if(u)return o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",n==="zh"?"活动中心":"Activity Center"]}),o.jsx("div",{style:{opacity:.7},children:u})]});const U=e==="teacher"?n==="zh"?"活动中心(教师)":"Activity Center":n==="zh"?"活动(学生)":"Activities";return i.length===0?o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",U]}),o.jsx("div",{style:{opacity:.7},children:n==="zh"?"暂无可用活动。":"No activities available."})]}):o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:8},children:["🧩 ",U]}),O.map(([T,D])=>o.jsxs("div",{style:{marginBottom:10},children:[o.jsx("div",{style:{opacity:.6,fontSize:12,textTransform:"uppercase",marginBottom:4},children:T}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:D.map(x=>o.jsxs("div",{style:{border:"1px solid #334155",borderRadius:8,padding:"8px 10px",minWidth:150,background:"#0f172a"},children:[o.jsxs("div",{style:{fontWeight:600},children:[x.icon?`${x.icon} `:"▫️ ",x.name]}),x.description&&o.jsx("div",{style:{opacity:.7,fontSize:12,margin:"2px 0 6px"},children:x.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("button",{onClick:()=>z(x),style:{cursor:"pointer",background:e==="teacher"?"#2563eb":"#0ea5e9",color:"#fff",border:"none",borderRadius:6,padding:"4px 10px",fontSize:12},children:e==="teacher"?n==="zh"?"启动":"Start":n==="zh"?"参与":"Open"}),h[x.id]&&o.jsx("span",{style:{fontSize:12,opacity:.85},children:h[x.id]})]}),o.jsx("div",{style:{opacity:.5,fontSize:12,marginTop:4},children:x.provider==="official"?"official":x.provider})]},x.id))})]},T))]})},h0=Object.freeze(Object.defineProperty({__proto__:null,ActivityWorkspaceWidget:Vc},Symbol.toStringTag,{value:"Module"}));let ol=!1;function f0(){if(ol)return;ol=!0;const e=()=>Ee(()=>Promise.resolve().then(()=>h0),void 0).then(t=>({default:()=>o.jsx(Vc,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,Ce.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}const al="@openlearn/frontend:IFrontendAPI",ll="@openlearn/frontend:ISocketService",cl="@openlearn/frontend:IUIService",ul="@openlearn/frontend:IStorageService",p0="@openlearn/frontend:ISemesterGradeService";var we=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(we||{});const m0=p.lazy(()=>Ee(()=>import("./StudentView-9pjzjJgG.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.StudentView}))),g0=p.lazy(()=>Ee(()=>import("./TeacherView-mP2YucVr.js"),__vite__mapDeps([8,1,2,3,4,5,7,6])).then(e=>({default:e.TeacherView})));function x0(e){const{activeRole:t}=e;return o.jsx(p.Suspense,{fallback:o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-slate-400 gap-3",children:[o.jsx(Zi,{className:"w-8 h-8 animate-spin text-indigo-500"}),o.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?o.jsx(m0,{...e}):o.jsx(g0,{...e})})}const go=p.createContext({});function xo(e){const t=p.useRef(null);return t.current===null&&(t.current=e()),t.current}const y0=typeof window<"u",Uc=y0?p.useLayoutEffect:p.useEffect,qs=p.createContext(null),yo=p.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function dl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function b0(...e){return t=>{let n=!1;const s=e.map(r=>{const i=dl(r,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<s.length;r++){const i=s[r];typeof i=="function"?i():dl(e[r],null)}}}}function w0(...e){return p.useCallback(b0(...e),e)}class S0 extends p.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Ur(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,r=Ur(s)&&s.offsetWidth||0,i=Ur(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=r-l.width-l.left,l.bottom=i-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function v0({children:e,isPresent:t,anchorX:n,anchorY:s,root:r,pop:i}){const a=p.useId(),l=p.useRef(null),c=p.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:u}=p.useContext(yo),d=e.props?.ref??e?.ref,h=w0(l,d);return p.useInsertionEffect(()=>{const{width:m,height:f,top:g,left:y,right:C,bottom:w,direction:P}=c.current;if(t||i===!1||!l.current||!m||!f)return;const S=P==="rtl",j=n==="left"?S?`right: ${C}`:`left: ${y}`:S?`left: ${y}`:`right: ${C}`,A=s==="bottom"?`bottom: ${w}`:`top: ${g}`;l.current.dataset.motionPopId=a;const E=document.createElement("style");u&&(E.nonce=u);const R=r??document.head;return R.appendChild(E),E.sheet&&E.sheet.insertRule(`
125
+ Draft a 300-word integration proposal based on today's whiteboard exercises.`}};function i0(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return;const t=new e,n=t.currentTime,s=t.createOscillator(),r=t.createGain();s.type="sine",s.frequency.setValueAtTime(587.33,n),s.frequency.exponentialRampToValueAtTime(880,n+.3),r.gain.setValueAtTime(.25,n),r.gain.exponentialRampToValueAtTime(.001,n+.8),s.connect(r),r.connect(t.destination),s.start(n),s.stop(n+.8)}catch{}}function o0({lessonId:e,lang:t="zh",syncChannel:n}){const[s,r]=f.useState(null),[i,a]=f.useState(!1),[l,c]=f.useState(!0),[u,d]=f.useState(!1),p=f.useRef(s);if(p.current=s,f.useEffect(()=>{if(!e)return;let w=null,P;try{w=n||new Ii,P=w.onMessage(A=>{A.type==="TEACHER_BROADCAST_COUNTDOWN"?r(A.payload):A.type==="TEACHER_SYNC_TIMER"&&r(E=>E?{...E,timeRemaining:A.payload.timeRemaining,isRunning:A.payload.isRunning,endsAt:A.payload.isRunning?Date.now()+A.payload.timeRemaining*1e3:null}:{lessonId:e,totalDuration:Math.max(300,A.payload.timeRemaining),timeRemaining:A.payload.timeRemaining,isRunning:A.payload.isRunning,isPaused:!1,label:t==="zh"?"⏱️ 课堂限时任务":"⏱️ Timed Task",endsAt:A.payload.isRunning?Date.now()+A.payload.timeRemaining*1e3:null,updatedAt:Date.now()})})}catch{}(async()=>{try{const A=await fetch(`/api/classroom/sessions/${e}/countdown`);if(A.ok){const E=await A.json();E.success&&E.countdown&&r(E.countdown)}}catch{}})();const j=A=>{A.detail&&r(A.detail)};return window.addEventListener("openlearn:countdown:updated",j),()=>{P?.(),!n&&typeof w?.destroy=="function"&&w.destroy(),window.removeEventListener("openlearn:countdown:updated",j)}},[e,t]),f.useEffect(()=>{if(!s||!s.isRunning||!s.endsAt)return;const w=setInterval(()=>{const P=p.current;if(!P||!P.isRunning||!P.endsAt)return;const S=Date.now(),j=Math.max(0,Math.round((P.endsAt-S)/1e3));if(j!==P.timeRemaining){const A={...P,timeRemaining:j,updatedAt:S};j<=0&&(A.isRunning=!1,A.isPaused=!1,A.endsAt=null,l&&!u&&(i0(),d(!0))),r(A);try{window.dispatchEvent(new CustomEvent("openlearn:student:countdown_tick",{detail:{timeRemaining:j,totalDuration:P.totalDuration,label:P.label}}))}catch{}}},500);return()=>clearInterval(w)},[s?.isRunning,s?.endsAt,l,u]),!s||s.timeRemaining===0&&!s.isRunning&&!u)return null;const m=w=>{const P=Math.floor(w/60),S=w%60,j=A=>A.toString().padStart(2,"0");return`${j(P)}:${j(S)}`},h=s.totalDuration>0?Math.min(100,Math.max(0,s.timeRemaining/s.totalDuration*100)):0,g=s.timeRemaining>0&&s.timeRemaining<=60,y=s.timeRemaining>60&&s.timeRemaining<=180,v=s.timeRemaining===0;return o.jsx("aside",{id:"student-classroom-countdown-banner","aria-label":t==="zh"?"课堂倒计时通知":"Classroom Countdown Alert",className:`fixed top-4 right-6 z-50 transition-all duration-300 select-none ${i?"w-auto":"w-72 sm:w-80"}`,children:o.jsxs("div",{className:`bg-surface/95 backdrop-blur-md border rounded-2xl shadow-2xl p-3 flex flex-col gap-2 transition-all ${g?"border-rose-500/80 shadow-rose-500/20":y?"border-amber-500/80 shadow-amber-500/20":v?"border-emerald-500/80 shadow-emerald-500/20":"border-theme shadow-primary-theme/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between gap-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("span",{className:`p-1 rounded-lg text-white shrink-0 ${g?"bg-rose-500 animate-pulse":y?"bg-amber-500":v?"bg-emerald-500":"bg-primary-theme"}`,children:o.jsx(Xl,{size:12,className:s.isRunning?"animate-spin":"",style:{animationDuration:"6s"}})}),o.jsx("span",{className:"text-xs font-bold text-main truncate",children:s.label||(t==="zh"?"课堂任务":"Task")})]}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o.jsx("button",{type:"button",onClick:()=>c(!l),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:l?"提示音已开启":"提示音已静音",children:l?o.jsx(fp,{size:12}):o.jsx(pp,{size:12})}),o.jsx("button",{type:"button",onClick:()=>a(!i),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:i?"展开":"收起",children:i?o.jsx(dn,{size:12}):o.jsx(mp,{size:12})})]})]}),!i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline justify-between px-1",children:[o.jsx("span",{id:"student-countdown-digits",className:`text-2xl font-black font-mono tracking-widest ${g?"text-rose-500 animate-pulse":y?"text-amber-500":v?"text-emerald-500":"text-primary-theme"}`,children:m(s.timeRemaining)}),o.jsx("span",{className:"text-[11px] font-semibold text-muted",children:v?t==="zh"?"🎉 时间已截止!":"Time is up!":s.isPaused?t==="zh"?"⏸️ 老师已暂停计时":"Paused":t==="zh"?"与全班同步中":"Synced"})]}),o.jsx("div",{className:"w-full h-1.5 bg-surface-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:`h-full transition-all duration-500 ${g?"bg-rose-500":y?"bg-amber-500":v?"bg-emerald-500":"bg-primary-theme"}`,style:{width:`${h}%`}})}),o.jsx(Bi,{slot:"student.classroom.countdown",slotProps:{countdown:s,lang:t}})]})]})})}const a0={id:"core-q-1",question:"关于变力沿曲线轨道做功过程,下列说法严格正确的是:",options:[{key:"A",text:"可以直接利用恒力做功公式 W = F·s·cosθ 统一计算"},{key:"B",text:"可将位移划分为无限小微元 Δs,在每个微元内以恒代变累加求和"},{key:"C",text:"只要动能有变化,机械能一定严格守恒"},{key:"D",text:"变力做功的数值与运动路径完全无关"}],correctOption:"B",explanation:"变力方向或大小随位置改变,不能直接套用恒力公式;微元法(微分与积分思想)是求解变力功的根本物理方法。",scaffoldHint:"⚠️ 巩固支架提示:请回顾牛顿第二定律与微积分思想,变力无法一次求和,必须采用 F-s 面积或微元累加!"},l0={id:"challenge-q-1",title:"高阶思维跃迁:变力与非弹性碰撞复合临界",prompt:"若物块在变阻力 f = -kv 作用下滑动并与弹性挡板碰撞,下列守恒与极限关系成立的是:",options:[{key:"A",text:"全程动量守恒且机械能保持守恒"},{key:"B",text:"当速度衰减为 0 前,系统动量损耗率与瞬时阻力成正比"},{key:"C",text:"滑动阻力做功仅取决于物块最终停止位置与重力势能无关"},{key:"D",text:"以上均不正确"}],correctOption:"B",rewardBadge:"🏅 物理探究思维跃迁徽章"},c0=({isOpen:e,onClose:t,lessonId:n,studentName:s="我",lang:r="zh",coreQuestion:i=a0,challengeQuestion:a=l0,onSubmitSuccess:l})=>{const[c,u]=f.useState(null),[d,p]=f.useState(!1),[m,h]=f.useState(null),[g,y]=f.useState(null),[v,w]=f.useState(5),[P,S]=f.useState(""),[j,A]=f.useState(""),[E,R]=f.useState(!1),[F,D]=f.useState(!1),O=()=>{if(!c)return;const _=c===i.correctOption;h(_),p(!0)},k=async()=>{if(E)return;R(!0);const _=m?g?"challenge_done":"passed":"remediation";try{n&&await fetch(`/api/classroom/sessions/${n}/exit-ticket`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rating:v,puzzledConcept:P.trim(),feedback:j.trim(),coreAnswer:c,isCorrect:m,tierLevel:_,challengeAnswer:g})}),D(!0),l?.()}catch{D(!0)}finally{R(!1)}};return e?o.jsx("div",{"data-testid":"adaptive-exit-ticket-modal",className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-fade-in select-none",children:o.jsxs("div",{className:"bg-surface rounded-3xl border border-indigo-500/40 p-6 w-full max-w-lg shadow-2xl flex flex-col gap-4 max-h-[92vh] overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/80 pb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-2 text-indigo-500 font-extrabold text-base",children:[o.jsx(_t,{size:20}),o.jsx("span",{children:r==="zh"?"60 秒自适应结课通票 (Adaptive Exit Ticket)":"60s Adaptive Exit Ticket"})]}),o.jsx("button",{onClick:t,className:"text-muted hover:text-main rounded-lg p-1 cursor-pointer","aria-label":"Close",children:o.jsx(Ze,{size:18})})]}),F?o.jsxs("div",{className:"py-8 flex flex-col items-center justify-center text-center gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-full bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 flex items-center justify-center",children:o.jsx(_t,{size:32})}),o.jsx("h3",{className:"text-base font-black text-main",children:r==="zh"?"结课通票提交成功!":"Exit Ticket Submitted!"}),o.jsx("p",{className:"text-xs text-muted max-w-xs",children:r==="zh"?"你的学情反馈与梯级作答已实时同步至教师大屏与个人课后学情卡。":"Feedback synced to classroom dashboard."}),o.jsx("button",{onClick:t,className:"mt-2 px-6 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs transition-colors cursor-pointer",children:r==="zh"?"完成":"Done"})]}):o.jsxs("div",{className:"flex flex-col gap-4 text-xs",children:[o.jsxs("div",{className:"bg-surface-secondary/70 p-4 rounded-2xl border border-border/60 flex flex-col gap-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"font-extrabold text-main flex items-center gap-1.5 text-xs",children:[o.jsx("span",{className:"px-2 py-0.5 rounded bg-indigo-500 text-white font-mono text-[10px]",children:"必做诊断"}),o.jsx("span",{children:"1. 核心概念过关题"})]}),d&&o.jsx("span",{className:`text-2xs font-bold px-2 py-0.5 rounded-full ${m?"bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300":"bg-rose-100 text-rose-700 dark:bg-rose-950 dark:text-rose-300"}`,children:m?"✓ 概念通关":"需巩固"})]}),o.jsx("p",{className:"text-main font-semibold leading-relaxed",children:i.question}),o.jsx("div",{className:"space-y-1.5",children:i.options.map(_=>o.jsxs("button",{type:"button",disabled:d,onClick:()=>u(_.key),className:`w-full p-2.5 rounded-xl border text-left flex items-start gap-2.5 transition-all cursor-pointer ${c===_.key?"border-indigo-500 bg-indigo-50/50 dark:bg-indigo-950/40 font-bold text-indigo-700 dark:text-indigo-300":"border-border/60 hover:bg-surface text-main"} ${d?"cursor-default opacity-90":""}`,children:[o.jsx("span",{className:"w-5 h-5 rounded-full bg-surface-secondary border border-border flex items-center justify-center text-[10px] font-mono shrink-0",children:_.key}),o.jsx("span",{className:"text-2xs leading-relaxed",children:_.text})]},_.key))}),!d&&o.jsxs("button",{type:"button",disabled:!c,onClick:O,className:`mt-1 py-1.5 px-3 rounded-xl font-bold text-2xs transition-colors flex items-center justify-center gap-1 ${c?"bg-indigo-600 hover:bg-indigo-700 text-white cursor-pointer shadow-xs":"bg-surface-secondary text-muted cursor-not-allowed"}`,children:[o.jsx("span",{children:"确认本题答案"}),o.jsx(Ps,{size:12})]}),d&&m&&o.jsxs("div",{"data-testid":"challenge-branch",className:"mt-2 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-800 dark:text-emerald-200 space-y-2 animate-fade-in",children:[o.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs",children:[o.jsx(Ut,{size:14,className:"text-emerald-600 dark:text-emerald-400"}),o.jsx("span",{children:"太棒了!已解锁【Lv.2 进阶探究挑战题】(冲刺思维勋章)"})]}),o.jsx("p",{className:"text-2xs font-semibold text-main",children:a.prompt}),o.jsx("div",{className:"grid grid-cols-1 gap-1",children:a.options.map(_=>o.jsxs("button",{type:"button",onClick:()=>y(_.key),className:`p-2 rounded-lg border text-left text-2xs transition-colors ${g===_.key?"border-emerald-500 bg-emerald-100/60 dark:bg-emerald-950 font-bold text-emerald-800 dark:text-emerald-200":"border-emerald-500/20 bg-surface text-main hover:bg-surface-secondary"}`,children:[o.jsxs("span",{className:"font-mono font-bold mr-1.5",children:[_.key,"."]}),o.jsx("span",{children:_.text})]},_.key))})]}),d&&!m&&o.jsxs("div",{"data-testid":"scaffold-branch",className:"mt-2 p-3 rounded-xl bg-amber-500/10 border border-amber-500/30 text-amber-800 dark:text-amber-200 space-y-1.5 animate-fade-in",children:[o.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs text-amber-600 dark:text-amber-400",children:[o.jsx(Bs,{size:14}),o.jsx("span",{children:"核心概念支架提示卡"})]}),o.jsx("p",{className:"text-2xs leading-relaxed",children:i.scaffoldHint}),o.jsxs("p",{className:"text-3xs text-muted",children:["解析:",i.explanation]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"2. 今日课堂综合掌握感评估":"Rate Today Lesson"}),o.jsxs("div",{className:"flex items-center gap-2",children:[[1,2,3,4,5].map(_=>o.jsx("button",{type:"button",onClick:()=>w(_),className:"p-0.5 text-xl transition-transform hover:scale-125 cursor-pointer",children:o.jsx(gp,{size:20,className:_<=v?"text-amber-400 fill-amber-400":"text-slate-300"})},_)),o.jsxs("span",{className:"text-2xs font-bold text-amber-500 font-mono ml-1",children:[v,".0 星"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"3. 今天最困惑或没完全搞懂的知识点/卡点是什么?":"Most Confused Concept"}),o.jsx("input",{type:"text",value:P,onChange:_=>S(_.target.value),placeholder:r==="zh"?"例如:变力做功 F-s 面积法、临界滑动摩擦...":"e.g. friction boundary...",className:"w-full px-3 py-2 bg-surface-secondary border border-border rounded-xl text-xs text-main focus:outline-hidden focus:ring-2 focus:ring-indigo-500"})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{className:"text-2xs font-bold text-main",children:r==="zh"?"4. 给老师的一句小建议 (选填)":"Feedback (Optional)"}),o.jsx("input",{type:"text",value:j,onChange:_=>A(_.target.value),placeholder:r==="zh"?"例如:希望能补充一道微元积分经典例题...":"Feedback...",className:"w-full px-3 py-1.5 bg-surface-secondary border border-border rounded-xl text-xs text-main focus:outline-hidden focus:ring-2 focus:ring-indigo-500"})]}),o.jsx("button",{type:"button",disabled:E,onClick:k,className:"w-full py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-extrabold rounded-xl transition-colors cursor-pointer shadow-md text-xs flex items-center justify-center gap-1.5",children:o.jsx("span",{children:E?r==="zh"?"正在提交...":"Submitting...":r==="zh"?"提交自适应结课通票":"Submit Exit Ticket"})})]})]})}):null};function u0({lessonId:e,studentId:t="student_demo",studentName:n="我",lang:s="zh"}){const[r,i]=f.useState(null),[a,l]=f.useState(null),[c,u]=f.useState("IN_CLASS_TEACHING"),[d,p]=f.useState(null),[m,h]=f.useState(!1),[g,y]=f.useState("IDLE"),[v,w]=f.useState(null),[P,S]=f.useState(!1),[j,A]=f.useState(!1),[E,R]=f.useState(5),[F,D]=f.useState(""),[O,k]=f.useState(""),_=f.useRef(Date.now());if(f.useEffect(()=>{if(!e)return;let z=!0;const U=async()=>{try{const M=await fetch(`/api/classroom/sessions/${e}`);if(M.ok&&z){const x=await M.json();x.hasActiveSession&&(u(x.stage),x.stage==="WRAP_UP_EXIT_TICKET"&&!j&&S(!0),x.activePoll&&(!r||r.id!==x.activePoll.id)?(i(x.activePoll),p(null),h(!1)):x.activePoll||i(null),x.activeBuzzer&&(!a||a.id!==x.activeBuzzer.id)?(l(x.activeBuzzer),y("IDLE"),_.current=Date.now()):x.activeBuzzer&&a?(x.activeBuzzer.status==="LOCKED"&&(x.activeBuzzer.winner_student_id===t?y("WINNER"):y("MISSED")),l(x.activeBuzzer)):x.activeBuzzer||(l(null),y("IDLE")))}}catch{}};U();const T=setInterval(U,2500);return()=>{z=!1,clearInterval(T)}},[e,j,r,a,t]),!e)return null;const L=async z=>{try{await fetch(`/api/classroom/sessions/${e}/pacing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signal:z})}),w(z==="TOO_FAST"?"🐇 太快":z==="SLOW"?"🐢 太慢":z==="CONFUSED"?"❓ 困惑":"💡 听懂了"),setTimeout(()=>w(null),2e3)}catch{}},I=async z=>{if(!(!r||m))try{p(z),h(!0),await fetch(`/api/classroom/sessions/${e}/quick-poll/${r.id}/vote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({option:z})})}catch{}},N=async()=>{if(!a||a.status!=="READY"||g!=="IDLE")return;const z=Date.now()-_.current;y("BUZZED");try{const U=await fetch(`/api/classroom/sessions/${e}/buzzer/${a.id}/buzz`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentName:n,responseTimeMs:z})});U.ok&&((await U.json()).winner?y("WINNER"):y("MISSED"))}catch{y("MISSED")}};return o.jsxs(o.Fragment,{children:[o.jsx(o0,{lessonId:e,lang:s}),o.jsx(Bi,{slot:"student.classroom.overlay",slotProps:{studentId:t,lessonId:e}}),o.jsx(Bi,{slot:"student.fullscreen",slotProps:{studentId:t,lessonId:e}}),o.jsxs("aside",{"aria-label":s==="zh"?"课堂互动工具栏":"Classroom interaction toolbar",className:"fixed bottom-6 right-6 z-40 flex items-center gap-2 bg-surface/95 backdrop-blur-md border border-border/80 p-2 rounded-2xl shadow-xl transition-all",children:[v&&o.jsxs("span",{className:"text-xs font-bold text-primary-theme px-2 py-1 animate-fade-in",children:[v," 已传达给老师"]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("button",{onClick:()=>L("CLEAR"),className:"px-2.5 py-1.5 rounded-xl hover:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"听懂了,节奏适宜",children:[o.jsx("span",{children:"💡"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"听懂了":"Clear"})]}),o.jsxs("button",{onClick:()=>L("CONFUSED"),className:"px-2.5 py-1.5 rounded-xl hover:bg-amber-500/10 text-amber-600 dark:text-amber-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"有点困惑,希望老师点拨",children:[o.jsx("span",{children:"❓"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"有疑问":"Confused"})]}),o.jsxs("button",{onClick:()=>L("TOO_FAST"),className:"px-2.5 py-1.5 rounded-xl hover:bg-rose-500/10 text-rose-600 dark:text-rose-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"讲得太快了,希望能慢一点",children:[o.jsx("span",{children:"🐇"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太快":"Too Fast"})]}),o.jsxs("button",{onClick:()=>L("SLOW"),className:"px-2.5 py-1.5 rounded-xl hover:bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 font-bold text-xs transition-colors flex items-center gap-1 cursor-pointer",title:"讲太慢了,希望快一点",children:[o.jsx("span",{children:"🐢"}),o.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太慢":"Too Slow"})]})]})]}),r&&r.status==="ACTIVE"&&o.jsxs("div",{className:"fixed bottom-20 right-6 z-50 bg-surface rounded-2xl border border-amber-500/40 p-5 shadow-2xl w-80 flex flex-col gap-3 animate-slide-up",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[o.jsxs("span",{className:"text-xs font-extrabold text-amber-500 flex items-center gap-1.5",children:[o.jsx(Ut,{size:14}),s==="zh"?"极速答题进行中":"Quick Poll Active"]}),m&&o.jsxs("span",{className:"text-[11px] text-emerald-500 font-bold flex items-center gap-1",children:[o.jsx(_t,{size:12}),s==="zh"?"已提交":"Submitted"]})]}),o.jsx("p",{className:"font-bold text-sm text-foreground",children:r.title}),o.jsx("div",{className:"grid grid-cols-2 gap-2 mt-1",children:(r.options||["A","B","C","D"]).map(z=>{const U=d===z;return o.jsx("button",{disabled:m,onClick:()=>I(z),className:`p-3 rounded-xl font-bold text-center text-sm transition-all cursor-pointer ${U?"bg-primary-theme text-white ring-2 ring-primary-theme shadow-md scale-95":m?"bg-surface-secondary text-muted opacity-60 cursor-not-allowed":"bg-surface-secondary hover:bg-primary-theme/10 hover:border-primary-theme border border-border text-foreground"}`,children:z},z)})})]}),a&&o.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4",children:o.jsxs("div",{className:"bg-surface rounded-3xl border border-rose-500/50 p-8 w-full max-w-sm shadow-2xl flex flex-col items-center text-center gap-4 animate-scale-up",children:[o.jsxs("h3",{className:"text-xl font-black text-foreground flex items-center gap-2",children:[o.jsx(Yl,{size:22,className:"text-rose-500 animate-bounce"}),o.jsx("span",{children:a.title||"全班极速抢答"})]}),g==="IDLE"&&a.status==="READY"&&o.jsxs("div",{className:"my-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{onClick:N,className:"w-36 h-36 rounded-full bg-gradient-to-tr from-rose-600 to-rose-400 text-white font-black text-2xl shadow-xl hover:scale-105 active:scale-95 transition-all flex flex-col items-center justify-center border-4 border-white dark:border-slate-800 cursor-pointer animate-pulse",children:[o.jsx(xp,{size:32,className:"mb-1"}),o.jsx("span",{children:"抢!"})]}),o.jsx("span",{className:"text-xs text-muted",children:"点击红色大按钮抢得首答权"})]}),g==="WINNER"&&o.jsxs("div",{className:"my-4 p-6 bg-emerald-500/10 border border-emerald-500/30 rounded-2xl flex flex-col items-center text-center",children:[o.jsx("span",{className:"text-4xl mb-2",children:"🎉"}),o.jsx("span",{className:"text-lg font-black text-emerald-500",children:"恭喜你率先抢答!"}),o.jsx("span",{className:"text-xs text-muted mt-1",children:"请起立或开麦回答老师的问题"})]}),g==="MISSED"&&o.jsxs("div",{className:"my-4 p-6 bg-slate-800/20 border border-border rounded-2xl flex flex-col items-center text-center",children:[o.jsx("span",{className:"text-4xl mb-2",children:"⚡"}),o.jsxs("span",{className:"text-base font-bold text-foreground",children:["已被 ",a.winner_student_name||"其他同学"," 抢先一步!"]}),o.jsx("span",{className:"text-xs text-muted mt-1",children:"下次手速要更快哦"})]})]})}),o.jsx(c0,{isOpen:P&&!j,onClose:()=>S(!1),lessonId:e,studentName:n,lang:s,onSubmitSuccess:()=>{A(!0)}})]})}async function d0(e="all"){const t=await fetch(`/api/activities?role=${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load activities (${t.status})`);return(await t.json()).activities??[]}async function ul(){const e=await fetch("/api/activities/running",{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load running activities (${e.status})`);return(await e.json()).activities??[]}async function h0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/finish`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to finish activity (${t.status})`)}}async function f0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/pause`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to pause activity (${t.status})`)}}async function p0(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/resume`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to resume activity (${t.status})`)}}async function m0(e,t,n){const s=await fetch(`/api/activities/${encodeURIComponent(e)}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t??{},actorId:n})}),r=await s.json();if(!s.ok||r.ok===!1)throw new Error(r.error||`Failed to start activity (${s.status})`);return r}const rs={padding:"12px",color:"#e2e8f0",fontSize:"13px"},g0={HelpCircle:Cp,Vote:kp,BarChart3:vp,MessagesSquare:Sp,Users:Gl,FileText:ec,Trophy:wp,CheckCircle2:_t,BookOpen:Bs};function x0({name:e,className:t}){const n=e&&g0[e]||Ts;return o.jsx(n,{size:18,className:t})}function y0(e,t){if(!e)return t==="zh"?"进行中":"In progress";const n=Math.max(0,Math.floor((Date.now()-e)/1e3)),s=Math.floor(n/60),r=n%60;return t==="zh"?`${s} 分 ${r} 秒`:`${s}m ${r}s`}const Qc=({role:e,actorId:t,lang:n="en",classroomId:s,mode:r="launcher"})=>{const[i,a]=f.useState([]),[l,c]=f.useState(!0),[u,d]=f.useState(null),[p,m]=f.useState({}),[h,g]=f.useState([]),[y,v]=f.useState(!0),[w,P]=f.useState(null),[S,j]=f.useState(null),[A,E]=f.useState(!1),[R,F]=f.useState(null),D=he(T=>T.setTeacherTab),O=f.useMemo(()=>{const T=new Map;for(const M of i){const x=M.category;T.has(x)||T.set(x,[]),T.get(x).push(M)}return Array.from(T.entries())},[i]);f.useEffect(()=>{if(r!=="launcher")return;let T=!1;return c(!0),d0(e).then(M=>{T||a(M)}).catch(M=>{T||d(M instanceof Error?M.message:String(M))}).finally(()=>{T||c(!1)}),()=>{T=!0}},[e,r]),f.useEffect(()=>{if(r!=="status")return;let T=!1;const M=async()=>{try{const oe=await ul();T||g(oe)}catch(oe){T||P(oe instanceof Error?oe.message:String(oe))}finally{T||v(!1)}};M();const x=setInterval(M,5e3);return()=>{T=!0,clearInterval(x)}},[r]);const k=async T=>{if(S){E(!0),F(null);try{await T(S),g(await ul())}catch(M){F(M instanceof Error?M.message:String(M))}finally{E(!1)}}},_=()=>k(h0),L=()=>k(f0),I=()=>k(p0),N=()=>{j(null),D("live_class")};if(r==="status"){if(y)return o.jsx("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm h-24 animate-pulse"});if(w||h.length===0)return null;const T=h.find(M=>M.id===S)||null;return o.jsxs("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-slate-800 font-extrabold",children:[o.jsx("span",{children:"🧩"}),o.jsx("span",{children:n==="zh"?"进行中的活动":"Activities in Progress"})]}),o.jsx("span",{className:"text-xs font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full",children:h.length})]}),o.jsx("div",{className:"flex flex-col gap-2",children:h.map(M=>{const x=M.state==="running";return o.jsxs("button",{onClick:()=>j(M.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:[o.jsx(x0,{name:M.icon,className:"text-indigo-600 shrink-0"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"font-bold text-slate-800 truncate",children:M.name}),M.category&&o.jsx("div",{className:"text-xs text-slate-500 truncate",children:M.category})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[o.jsx("span",{className:`text-xs font-bold px-2 py-0.5 rounded-full ${x?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"}`,children:x?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"}),o.jsxs("span",{className:"text-xs text-slate-400 flex items-center gap-1",children:[o.jsx(Xl,{size:10})," ",y0(M.startedAt,n)]})]})]},M.id)})}),T&&o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4",onClick:()=>j(null),children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-sm p-5",onClick:M=>M.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"font-bold text-slate-800",children:T.name}),o.jsx("button",{onClick:()=>j(null),className:"text-slate-400 hover:text-slate-600","aria-label":"close",children:o.jsx(Ze,{size:18})})]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-1",children:[n==="zh"?"状态":"Status",":"," ",T.state==="running"?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-4",children:[n==="zh"?"开始时间":"Started",":"," ",T.startedAt?new Date(T.startedAt).toLocaleString():"-"]}),R&&o.jsx("div",{className:"text-xs text-rose-600 mb-2",children:R}),o.jsxs("div",{className:"flex gap-2",children:[T.state==="running"?o.jsxs("button",{disabled:A,onClick:L,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:[o.jsx(yp,{size:14})," ",n==="zh"?"暂停":"Pause"]}):o.jsxs("button",{disabled:A,onClick:I,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:[o.jsx(bp,{size:14})," ",n==="zh"?"恢复":"Resume"]}),o.jsx("button",{disabled:A,onClick:_,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:A?n==="zh"?"处理中…":"Working…":n==="zh"?"结束":"End"})]}),o.jsx("button",{onClick:N,className:"w-full mt-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg py-2 text-sm font-bold",children:n==="zh"?"进入课堂":"Enter Classroom"})]})})]})}const z=async T=>{m(M=>({...M,[T.id]:n==="zh"?"启动中…":"Starting…"}));try{const M=await m0(T.id,{classroomId:s,role:e},t);m(x=>({...x,[T.id]:M.dispatched?n==="zh"?"已启动 ✓":"Started ✓":n==="zh"?"已通知 ✓":"Notified ✓"}))}catch(M){m(x=>({...x,[T.id]:M instanceof Error?M.message:String(M)}))}};if(l)return o.jsx("div",{style:rs,children:n==="zh"?"加载活动中…":"Loading activities…"});if(u)return o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",n==="zh"?"活动中心":"Activity Center"]}),o.jsx("div",{style:{opacity:.7},children:u})]});const U=e==="teacher"?n==="zh"?"活动中心(教师)":"Activity Center":n==="zh"?"活动(学生)":"Activities";return i.length===0?o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",U]}),o.jsx("div",{style:{opacity:.7},children:n==="zh"?"暂无可用活动。":"No activities available."})]}):o.jsxs("div",{style:rs,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:8},children:["🧩 ",U]}),O.map(([T,M])=>o.jsxs("div",{style:{marginBottom:10},children:[o.jsx("div",{style:{opacity:.6,fontSize:12,textTransform:"uppercase",marginBottom:4},children:T}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:M.map(x=>o.jsxs("div",{style:{border:"1px solid #334155",borderRadius:8,padding:"8px 10px",minWidth:150,background:"#0f172a"},children:[o.jsxs("div",{style:{fontWeight:600},children:[x.icon?`${x.icon} `:"▫️ ",x.name]}),x.description&&o.jsx("div",{style:{opacity:.7,fontSize:12,margin:"2px 0 6px"},children:x.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("button",{onClick:()=>z(x),style:{cursor:"pointer",background:e==="teacher"?"#2563eb":"#0ea5e9",color:"#fff",border:"none",borderRadius:6,padding:"4px 10px",fontSize:12},children:e==="teacher"?n==="zh"?"启动":"Start":n==="zh"?"参与":"Open"}),p[x.id]&&o.jsx("span",{style:{fontSize:12,opacity:.85},children:p[x.id]})]}),o.jsx("div",{style:{opacity:.5,fontSize:12,marginTop:4},children:x.provider==="official"?"official":x.provider})]},x.id))})]},T))]})},b0=Object.freeze(Object.defineProperty({__proto__:null,ActivityWorkspaceWidget:Qc},Symbol.toStringTag,{value:"Module"}));let dl=!1;function w0(){if(dl)return;dl=!0;const e=()=>Ee(()=>Promise.resolve().then(()=>b0),void 0).then(t=>({default:()=>o.jsx(Qc,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,Ce.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}const hl="@openlearn/frontend:IFrontendAPI",fl="@openlearn/frontend:ISocketService",pl="@openlearn/frontend:IUIService",ml="@openlearn/frontend:IStorageService",S0="@openlearn/frontend:ISemesterGradeService";var we=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(we||{});const v0=f.lazy(()=>Ee(()=>import("./StudentView--uGxc5TJ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.StudentView}))),k0=f.lazy(()=>Ee(()=>import("./TeacherView-D4Zsc0eZ.js"),__vite__mapDeps([8,1,2,3,4,5,7,6])).then(e=>({default:e.TeacherView})));function C0(e){const{activeRole:t}=e;return o.jsx(f.Suspense,{fallback:o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-slate-400 gap-3",children:[o.jsx(Ki,{className:"w-8 h-8 animate-spin text-indigo-500"}),o.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?o.jsx(v0,{...e}):o.jsx(k0,{...e})})}const yo=f.createContext({});function bo(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const E0=typeof window<"u",Jc=E0?f.useLayoutEffect:f.useEffect,Gs=f.createContext(null),wo=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function gl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function j0(...e){return t=>{let n=!1;const s=e.map(r=>{const i=gl(r,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<s.length;r++){const i=s[r];typeof i=="function"?i():gl(e[r],null)}}}}function N0(...e){return f.useCallback(j0(...e),e)}class T0 extends f.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(qr(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,r=qr(s)&&s.offsetWidth||0,i=qr(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=r-l.width-l.left,l.bottom=i-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function P0({children:e,isPresent:t,anchorX:n,anchorY:s,root:r,pop:i}){const a=f.useId(),l=f.useRef(null),c=f.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:u}=f.useContext(wo),d=e.props?.ref??e?.ref,p=N0(l,d);return f.useInsertionEffect(()=>{const{width:m,height:h,top:g,left:y,right:v,bottom:w,direction:P}=c.current;if(t||i===!1||!l.current||!m||!h)return;const S=P==="rtl",j=n==="left"?S?`right: ${v}`:`left: ${y}`:S?`left: ${y}`:`right: ${v}`,A=s==="bottom"?`bottom: ${w}`:`top: ${g}`;l.current.dataset.motionPopId=a;const E=document.createElement("style");u&&(E.nonce=u);const R=r??document.head;return R.appendChild(E),E.sheet&&E.sheet.insertRule(`
126
126
  [data-motion-pop-id="${a}"] {
127
127
  position: absolute !important;
128
128
  width: ${m}px !important;
129
- height: ${f}px !important;
129
+ height: ${h}px !important;
130
130
  ${j}px !important;
131
131
  ${A}px !important;
132
132
  }
133
- `),()=>{l.current?.removeAttribute("data-motion-pop-id"),R.contains(E)&&R.removeChild(E)}},[t]),o.jsx(S0,{isPresent:t,childRef:l,sizeRef:c,pop:i,children:i===!1?e:p.cloneElement(e,{ref:h})})}const k0=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:i,mode:a,anchorX:l,anchorY:c,root:u})=>{const d=xo(C0),h=p.useId();let m=!0,f=p.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:r,onExitComplete:g=>{d.set(g,!0);for(const y of d.values())if(!y)return;s&&s()},register:g=>(d.set(g,!1),()=>d.delete(g))}),[n,d,s]);return i&&m&&(f={...f}),p.useMemo(()=>{d.forEach((g,y)=>d.set(y,!1))},[n]),p.useEffect(()=>{!n&&!d.size&&s&&s()},[n]),e=o.jsx(v0,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:u,children:e}),o.jsx(qs.Provider,{value:f,children:e})};function C0(){return new Map}function Hc(e=!0){const t=p.useContext(qs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,i=p.useId();p.useEffect(()=>{if(e)return r(i)},[e]);const a=p.useCallback(()=>e&&s&&s(i),[i,s,e]);return!n&&s?[!1,a]:[!0]}const is=e=>e.key||"";function hl(e){const t=[];return p.Children.forEach(e,n=>{p.isValidElement(n)&&t.push(n)}),t}const qc=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:i="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:u})=>{const[d,h]=Hc(a),m=p.useMemo(()=>hl(e),[e]),f=a&&!d?[]:m.map(is),g=p.useRef(!0),y=p.useRef(m),C=xo(()=>new Map),w=p.useRef(new Set),[P,S]=p.useState(m),[j,A]=p.useState(m);Uc(()=>{g.current=!1,y.current=m;for(let F=0;F<j.length;F++){const M=is(j[F]);f.includes(M)?(C.delete(M),w.current.delete(M)):C.get(M)!==!0&&C.set(M,!1)}},[j,f.length,f.join("-")]);const E=[];if(m!==P){let F=[...m];for(let M=0;M<j.length;M++){const O=j[M],v=is(O);f.includes(v)||(F.splice(M,0,O),E.push(O))}return i==="wait"&&E.length&&(F=E),A(hl(F)),S(m),null}const{forceRender:R}=p.useContext(go);return o.jsx(o.Fragment,{children:j.map(F=>{const M=is(F),O=a&&!d?!1:m===j||f.includes(M),v=()=>{if(w.current.has(M))return;if(C.has(M))w.current.add(M),C.set(M,!0);else return;let _=!0;C.forEach(L=>{L||(_=!1)}),_&&(R?.(),A(y.current),a&&h?.(),s&&s())};return o.jsx(k0,{isPresent:O,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:i,root:u,onExitComplete:O?void 0:v,anchorX:l,anchorY:c,children:F},M)})})},Wc=p.createContext({strict:!1}),fl={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let pl=!1;function E0(){if(pl)return;const e={};for(const t in fl)e[t]={isEnabled:n=>fl[t].some(s=>!!n[s])};Yl(e),pl=!0}function Gc(){return E0(),Tp()}function j0(e){const t=Gc();for(const n in e)t[n]={...t[n],...e[n]};Yl(t)}const N0=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function Os(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||N0.has(e)}let Qc=e=>!Os(e);function T0(e){typeof e=="function"&&(Qc=t=>t.startsWith("on")?!Os(t):e(t))}try{T0(require("@emotion/is-prop-valid").default)}catch{}function P0(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||Ki(e[r])||(Qc(r)||n===!0&&Os(r)||!t&&!Os(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Ws=p.createContext({});function I0(e,t){if(Kl(e)){const{initial:n,animate:s}=e;return{initial:n===!1||ua(n)?n:void 0,animate:ua(s)?s:void 0}}return e.inherit!==!1?t:{}}function A0(e){const{initial:t,animate:n}=I0(e,p.useContext(Ws));return p.useMemo(()=>({initial:t,animate:n}),[ml(t),ml(n)])}function ml(e){return Array.isArray(e)?e.join(" "):e}const bo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Jc(e,t,n){for(const s in t)!Ki(t[s])&&!Pp(s,n)&&(e[s]=t[s])}function z0({transformTemplate:e},t){return p.useMemo(()=>{const n=bo();return Ip(n,t,e),Object.assign({},n.vars,n.style)},[t])}function _0(e,t){const n=e.style||{},s={};return Jc(s,n,e),Object.assign(s,z0(e,t)),s}function L0(e,t){const n={},s=_0(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Zc=()=>({...bo(),attrs:{}});function R0(e,t,n,s){const r=p.useMemo(()=>{const i=Zc();return Ap(i,t,zp(s),e.transformTemplate,e.style),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};Jc(i,e.style,e),r.style={...i,...r.style}}return r}const O0=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function wo(e){return typeof e!="string"||e.includes("-")?!1:!!(O0.indexOf(e)>-1||/[A-Z]/u.test(e))}function D0(e,t,n,{latestValues:s},r,i=!1,a){const c=(a??wo(e)?R0:L0)(t,s,r,e),u=P0(t,typeof e=="string",i),d=e!==p.Fragment?{...u,...c,ref:n}:{},{children:h}=t,m=p.useMemo(()=>Ki(h)?h.get():h,[h]);return p.createElement(e,{...d,children:m})}function M0({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:F0(n,s,r,e),renderState:t()}}function F0(e,t,n,s){const r={},i=s(e,{});for(const m in i)r[m]=_p(i[m]);let{initial:a,animate:l}=e;const c=Kl(e),u=Lp(e);t&&u&&!c&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let d=n?n.initial===!1:!1;d=d||a===!1;const h=d?l:a;if(h&&typeof h!="boolean"&&!Xl(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f<m.length;f++){const g=Rp(e,m[f]);if(g){const{transitionEnd:y,transition:C,...w}=g;for(const P in w){let S=w[P];if(Array.isArray(S)){const j=d?S.length-1:0;S=S[j]}S!==null&&(r[P]=S)}for(const P in y)r[P]=y[P]}}}return r}const Yc=e=>(t,n)=>{const s=p.useContext(Ws),r=p.useContext(qs),i=()=>M0(e,t,s,r);return n?i():xo(i)},$0=Yc({scrapeMotionValuesFromProps:Op,createRenderState:bo}),B0=Yc({scrapeMotionValuesFromProps:Dp,createRenderState:Zc}),V0=Symbol.for("motionComponentSymbol");function U0(e,t,n){const s=p.useRef(n);p.useInsertionEffect(()=>{s.current=n});const r=p.useRef(null);return p.useCallback(i=>{i&&e.onMount?.(i),t&&(i?t.mount(i):t.unmount());const a=s.current;if(typeof a=="function")if(i){const l=a(i);typeof l=="function"&&(r.current=l)}else r.current?(r.current(),r.current=null):a(i);else a&&(a.current=i)},[t])}const Kc=p.createContext({});function rn(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function H0(e,t,n,s,r,i){const{visualElement:a}=p.useContext(Ws),l=p.useContext(Wc),c=p.useContext(qs),u=p.useContext(yo),d=u.reducedMotion,h=u.skipAnimations,m=p.useRef(null),f=p.useRef(!1);s=s||l.renderer,!m.current&&s&&(m.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:d,skipAnimations:h,isSVG:i}),f.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,y=p.useContext(Kc);g&&!g.projection&&r&&(g.type==="html"||g.type==="svg")&&q0(m.current,n,r,y);const C=p.useRef(!1);p.useInsertionEffect(()=>{g&&C.current&&g.update(n,c)});const w=n[Mp],P=p.useRef(!!w&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(w)&&window.MotionHasOptimisedAnimation?.(w));return Uc(()=>{f.current=!0,g&&(C.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),P.current&&g.animationState&&g.animationState.animateChanges())}),p.useEffect(()=>{g&&(!P.current&&g.animationState&&g.animationState.animateChanges(),P.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(w)}),P.current=!1),g.enteringChildren=void 0)}),g}function q0(e,t,n,s){const{layoutId:r,layout:i,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:u,layoutAnchor:d,layoutCrossfade:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Xc(e.parent)),e.projection.setOptions({layoutId:r,layout:i,alwaysMeasureLayout:!!a||l&&rn(l),visualElement:e,animationType:typeof i=="string"?i:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:c,layoutRoot:u,layoutAnchor:d})}function Xc(e){if(e)return e.options.allowProjection!==!1?e.projection:Xc(e.parent)}function di(e,{forwardMotionProps:t=!1,type:n}={},s,r){s&&j0(s);const i=n?n==="svg":wo(e),a=i?B0:$0;function l(u,d){let h;const m={...p.useContext(yo),...u,layoutId:W0(u)},{isStatic:f}=m,g=A0(u),y=a(u,f);if(!f&&typeof window<"u"){G0();const C=Q0(m);h=C.MeasureLayout,g.visualElement=H0(e,y,m,r,C.ProjectionNode,i)}return o.jsxs(Ws.Provider,{value:g,children:[h&&g.visualElement?o.jsx(h,{visualElement:g.visualElement,...m}):null,D0(e,u,U0(y,g.visualElement,d),y,f,t,i)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=p.forwardRef(l);return c[V0]=e,c}function W0({layoutId:e}){const t=p.useContext(go).id;return t&&e!==void 0?t+"-"+e:e}function G0(e,t){p.useContext(Wc).strict}function Q0(e){const t=Gc(),{drag:n,layout:s}=t;if(!n&&!s)return{};const r={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function J0(e,t){if(typeof Proxy>"u")return di;const n=new Map,s=(i,a)=>di(i,a,e,t),r=(i,a)=>s(i,a);return new Proxy(r,{get:(i,a)=>a==="create"?s:(n.has(a)||n.set(a,di(a,void 0,e,t)),n.get(a))})}const Z0=(e,t)=>t.isSVG??wo(e)?new Fp(t):new $p(t,{allowProjection:e!==p.Fragment});class Y0 extends Lt{constructor(t){super(t),t.animationState||(t.animationState=Bp(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Xl(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let K0=0;class X0 extends Lt{constructor(){super(...arguments),this.id=K0++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;if(t&&s===!1){if(this.isExitComplete){const{initial:i,custom:a}=this.node.getProps();if(typeof i=="string"||typeof i=="object"&&i!==null&&!Array.isArray(i)){const l=Vp(this.node,i,a);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const h in d)this.node.getValue(h)?.jump(d[h])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const ew={animation:{Feature:Y0},exit:{Feature:X0}};function Bn(e){return{point:{x:e.pageX,y:e.pageY}}}const tw=e=>t=>ec(t)&&e(t,Bn(t));function Rn(e,t,n,s){return Is(e,t,tw(n),s)}const eu=({current:e})=>e?e.ownerDocument.defaultView:null,gl=(e,t)=>Math.abs(e-t);function nw(e,t){const n=gl(e.x,t.x),s=gl(e.y,t.y);return Math.sqrt(n**2+s**2)}const xl=new Set(["auto","scroll"]);class tu{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:l}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=os(this.lastRawMoveEventInfo,this.transformPagePoint));const f=hi(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=nw(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:C}=f,{timestamp:w}=da;this.history.push({...C,timestamp:w});const{onStart:P,onMove:S}=this.handlers;g||(P&&P(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=os(g,this.transformPagePoint),nt.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:y,onSessionEnd:C,resumeAnimation:w}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const P=hi(f.type==="pointercancel"?this.lastMoveEventInfo:os(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,P),C&&C(f,P)},!ec(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=r||window;const c=Bn(t),u=os(c,this.transformPagePoint),{point:d}=u,{timestamp:h}=da;this.history=[{...d,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,hi(u,this.history)),this.removeListeners=tc(Rn(this.contextWindow,"pointermove",this.handlePointerMove),Rn(this.contextWindow,"pointerup",this.handlePointerUp),Rn(this.contextWindow,"pointercancel",this.handlePointerUp)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(xl.has(s.overflowX)||xl.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,r=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:r.x-n.x,y:r.y-n.y};i.x===0&&i.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,r),nt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Up(this.updatePoint)}}function os(e,t){return t?{point:t(e.point)}:e}function yl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function hi({point:e},t){return{point:e,delta:yl(e,nu(t)),offset:yl(e,sw(t)),velocity:rw(t,.1)}}function sw(e){return e[0]}function nu(e){return e[e.length-1]}function rw(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=nu(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>ha(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&r.timestamp-s.timestamp>ha(t)*2&&(s=e[1]);const i=Hp(r.timestamp-s.timestamp);if(i===0)return{x:0,y:0};const a={x:(r.x-s.x)/i,y:(r.y-s.y)/i};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function iw(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?As(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?As(n,e,s.max):Math.min(e,n)),e}function bl(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function ow(e,{top:t,left:n,bottom:s,right:r}){return{x:bl(e.x,n,r),y:bl(e.y,t,s)}}function wl(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function aw(e,t){return{x:wl(e.x,t.x),y:wl(e.y,t.y)}}function lw(e,t){let n=.5;const s=ji(e),r=ji(t);return r>s?n=fa(t.min,t.max-s,e.min):s>r&&(n=fa(e.min,e.max-r,t.min)),qp(0,1,n)}function cw(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Fi=.35;function uw(e=Fi){return e===!1?e=0:e===!0&&(e=Fi),{x:Sl(e,"left","right"),y:Sl(e,"top","bottom")}}function Sl(e,t,n){return{min:vl(e,t),max:vl(e,n)}}function vl(e,t){return typeof e=="number"?e:e[t]||0}const dw=new WeakMap;class hw{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Wp(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const i=h=>{n&&this.snapToCursor(Bn(h).point),this.stopAnimation()},a=(h,m)=>{const{drag:f,dragPropagation:g,onDragStart:y}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Yp(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Pt(w=>{let P=this.getAxisMotionValue(w).get()||0;if(Kp.test(P)){const{projection:S}=this.visualElement;if(S&&S.layout){const j=S.layout.layoutBox[w];j&&(P=ji(j)*(parseFloat(P)/100))}}this.originPoint[w]=P}),y&&nt.update(()=>y(h,m),!1,!0),pa(this.visualElement,"transform");const{animationState:C}=this.visualElement;C&&C.setActive("whileDrag",!0)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:y,onDrag:C}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:w}=m;if(g&&this.currentDirection===null){this.currentDirection=pw(w),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),C&&nt.update(()=>C(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:d}=this.getProps();this.panSession=new tu(t,{onSessionStart:i,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:eu(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!s)return;const{velocity:a}=r;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&nt.postRender(()=>l(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!as(t,r,this.currentDirection))return;const i=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=iw(a,this.constraints[t],this.elastic[t])),i.set(a)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&rn(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=ow(s.layoutBox,t):this.constraints=!1,this.elastic=uw(n),r!==this.constraints&&!rn(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Pt(i=>{this.constraints!==!1&&this.getAxisMotionValue(i)&&(this.constraints[i]=cw(s.layoutBox[i],this.constraints[i]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!rn(t))return!1;const s=t.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;r.root&&(r.root.scroll=void 0,r.root.updateScroll());const i=Gp(s,r.root,this.visualElement.getTransformPagePoint());let a=aw(r.layout.layoutBox,i);if(n){const l=n(Qp(a));this.hasMutatedConstraints=!!l,l&&(a=Jp(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},u=Pt(d=>{if(!as(d,n,this.currentDirection))return;let h=c&&c[d]||{};(a===!0||a===d)&&(h={min:0,max:0});const m=r?200:1e6,f=r?40:1e7,g={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(d,g)});return Promise.all(u).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return pa(this.visualElement,t),s.start(Zp(t,s,0,n,this.visualElement,!1))}stopAnimation(){Pt(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps()[n];return r||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){Pt(n=>{const{drag:s}=this.getProps();if(!as(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(n);if(r&&r.layout){const{min:a,max:l}=r.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-As(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!rn(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Pt(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();r[a]=lw({min:c,max:c},this.constraints[a])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.constraints=!1,this.resolveConstraints(),Pt(a=>{if(!as(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:u}=this.constraints[a];l.set(As(c,u,r[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;dw.set(this.visualElement,this);const t=this.visualElement.current,n=Rn(t,"pointerdown",u=>{const{drag:d,dragListener:h=!0}=this.getProps(),m=u.target,f=m!==t&&Xp(m);d&&h&&!f&&this.start(u)});let s;const r=()=>{const{dragConstraints:u}=this.getProps();rn(u)&&u.current&&(this.constraints=this.resolveRefConstraints(),s||(s=fw(t,u.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,a=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),nt.read(r);const l=Is(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",(({delta:u,hasLayoutChanged:d})=>{this.isDragging&&d&&(Pt(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=u[h].translate,m.set(m.get()+u[h].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Fi,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:l}}}function kl(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function fw(e,t,n){const s=ma(e,kl(n)),r=ma(t,kl(n));return()=>{s(),r()}}function as(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function pw(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class mw extends Lt{constructor(t){super(t),this.removeGroupControls=ps,this.removeListeners=ps,this.controls=new hw(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ps}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const fi=e=>(t,n)=>{e&&nt.update(()=>e(t,n),!1,!0)};class gw extends Lt{constructor(){super(...arguments),this.removePointerDownListener=ps}onPointerDown(t){this.session=new tu(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:eu(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:fi(t),onStart:fi(n),onMove:fi(s),onEnd:(i,a)=>{delete this.session,r&&nt.postRender(()=>r(i,a))}}}mount(){this.removePointerDownListener=Rn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pi=!1;class xw extends p.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),s&&s.register&&r&&s.register(i),pi&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),tm.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:i}=this.props,{projection:a}=s;return a&&(a.isPresent=i,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),pi=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==i?a.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?a.promote():a.relegate()||nt.postRender(()=>{const l=a.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),em.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;pi=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function su(e){const[t,n]=Hc(),s=p.useContext(go);return o.jsx(xw,{...e,layoutGroup:s,switchLayoutGroup:p.useContext(Kc),isPresent:t,safeToRemove:n})}const yw={pan:{Feature:gw},drag:{Feature:mw,ProjectionNode:nc,MeasureLayout:su}};function Cl(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,i=s[r];i&&nt.postRender(()=>i(t,Bn(t)))}class bw extends Lt{mount(){const{current:t}=this.node;t&&(this.unmount=nm(t,(n,s)=>(Cl(this.node,s,"Start"),r=>Cl(this.node,r,"End"))))}unmount(){}}class ww extends Lt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=tc(Is(this.node.current,"focus",()=>this.onFocus()),Is(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function El(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),i=s[r];i&&nt.postRender(()=>i(t,Bn(t)))}class Sw extends Lt{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=sm(t,(r,i)=>(El(this.node,i,"Start"),(a,{success:l})=>El(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const $i=new WeakMap,mi=new WeakMap,vw=e=>{const t=$i.get(e.target);t&&t(e)},kw=e=>{e.forEach(vw)};function Cw({root:e,...t}){const n=e||document;mi.has(n)||mi.set(n,{});const s=mi.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(kw,{root:e,...t})),s[r]}function Ew(e,t,n){const s=Cw(t);return $i.set(e,n),s.observe(e),()=>{$i.delete(e),s.unobserve(e)}}const jw={some:0,all:1};class Nw extends Lt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:i}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:jw[r]},l=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),m=u?d:h;m&&m(c)};this.stopObserver=Ew(this.node.current,a,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Tw(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function Tw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Pw={inView:{Feature:Nw},tap:{Feature:Sw},focus:{Feature:ww},hover:{Feature:bw}},Iw={layout:{ProjectionNode:nc,MeasureLayout:su}},Aw={...ew,...Pw,...yw,...Iw},ys=J0(Aw,Z0);async function Ds(e){if(typeof window>"u")return!1;try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(e),!0}catch{}try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",t.setAttribute("readonly",""),document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch(t){return console.error("[OpenLearn Clipboard] Failed to copy text to clipboard:",t),!1}}function zw(){const e=he(i=>i.toasts),[t,n]=p.useState(null),s=async(i,a)=>{i.stopPropagation();const l=`[${a.title}] ${a.message}`;await Ds(l)&&(n(a.id),setTimeout(()=>n(null),2e3))},r=i=>{switch(i){case"error":return{border:"border-l-4 border-rose-500",iconBg:"bg-rose-50 text-rose-600 dark:bg-rose-950/60 dark:text-rose-400",icon:o.jsx(vi,{size:16})};case"warning":return{border:"border-l-4 border-amber-500",iconBg:"bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400",icon:o.jsx(Ps,{size:16})};case"info":return{border:"border-l-4 border-blue-500",iconBg:"bg-blue-50 text-blue-600 dark:bg-blue-950/60 dark:text-blue-400",icon:o.jsx(bp,{size:16})};case"success":default:return{border:"border-l-4 border-emerald-500",iconBg:"bg-emerald-50 text-emerald-600 dark:bg-emerald-950/60 dark:text-emerald-400",icon:o.jsx(_t,{size:16})}}};return o.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:o.jsx(qc,{children:e.map(i=>{const a=r(i.type),l=t===i.id;return o.jsxs(ys.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 dark:bg-slate-900 ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 ${a.border} overflow-hidden text-gray-900 dark:text-gray-100`,id:`toast-${i.id}`,children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:`p-1 rounded-full shrink-0 ${a.iconBg}`,children:a.icon}),o.jsx("p",{className:"font-semibold text-sm font-sans truncate",children:i.title})]}),(i.type==="error"||i.type==="warning")&&o.jsxs("button",{type:"button",onClick:c=>s(c,i),className:`text-xs font-bold px-1.5 py-0.5 rounded transition-all flex items-center gap-1 cursor-pointer shrink-0 ${l?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-gray-600 dark:text-gray-300"}`,title:"复制错误内容",children:[l?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:l?"已复制":"复制"})]})]}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2 leading-relaxed font-sans break-words",children:i.message})]}),o.jsx("button",{type:"button",onClick:()=>_e.getState().removeToast(i.id),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-slate-800 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:o.jsx(Je,{size:14})})]},i.id)})})})}function _w({showRightSidebar:e,setShowRightSidebar:t,rightSidebarTab:n,setRightSidebarTab:s,effectiveAgentProviderId:r,agentProviderId:i,setAgentProviderId:a,aiProviders:l,selectedAgentProvider:c,chatLog:u,loading:d,input:h,setInput:m,handleSend:f,chatAttachments:g,setChatAttachments:y,handleChatFileChange:C,handleChatDrop:w,onClearAgentMemory:P,events:S,lang:j,t:A}){const E=p.useRef(null);return p.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[u]),o.jsx("div",{className:`transition-all duration-300 bg-white border-l border-gray-200 flex flex-col shadow-xl relative z-30 shrink-0 ${e?"w-96":"w-12 items-center cursor-pointer hover:bg-gray-50"}`,children:e?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[o.jsxs("button",{onClick:()=>s("agent"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="agent"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[o.jsx(Vr,{size:14})," Agent"]}),o.jsxs("button",{onClick:()=>s("shell"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="shell"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[o.jsx(fs,{size:14})," Shell"]}),o.jsx("button",{onClick:()=>t(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:o.jsx(wp,{size:14})})]}),n==="agent"?o.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[o.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:o.jsx(Vr,{size:16})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:A.agentTitle}),o.jsx("p",{className:"text-xs text-gray-500",children:A.agentSubtitle}),o.jsxs("button",{onClick:P,title:j==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",j==="zh"?"清除记忆":"Clear memory"]})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-gray-400",children:j==="zh"?"AI 提供商":"AI Provider"}),o.jsxs("div",{className:"relative w-full",children:[l.length===0?o.jsx("select",{disabled:!0,value:"",className:"w-full appearance-none rounded-xl border border-amber-200 bg-amber-50/50 px-3 py-2 pr-9 text-xs font-medium text-amber-700 shadow-xs outline-none cursor-not-allowed",children:o.jsx("option",{value:"",children:j==="zh"?"未配置 AI 提供商":"No AI Provider"})}):o.jsx("select",{value:r,onChange:R=>a(R.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-xs font-medium text-gray-700 shadow-xs outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:l.map(R=>o.jsx("option",{value:R.id,children:R.name},R.id))}),o.jsx(dn,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),o.jsx("div",{className:"text-xs text-gray-400 truncate w-full text-right",title:c?.model_name||"",children:c?`${c.model_name}`:j==="zh"?"未配置提供商":"No Provider"})]})]})}),l.length===0&&o.jsxs("div",{className:"mx-4 mt-3 p-3 bg-amber-50 border border-amber-200/80 rounded-xl text-xs text-amber-900 flex items-start gap-2 shadow-xs shrink-0",children:[o.jsx(Ps,{size:15,className:"shrink-0 text-amber-600 mt-0.5"}),o.jsxs("div",{className:"flex-1 leading-relaxed",children:[o.jsx("span",{className:"font-semibold",children:j==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),o.jsx("p",{className:"mt-0.5 text-amber-700",children:j==="zh"?"请前往「系统管理 -> AI 提供商管理」添加大模型服务(如 DeepSeek、Qwen、OpenAI 等)。":'Please configure an AI provider in "System Management -> AI Provider Management" to use the AI assistant.'})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[u.map((R,F)=>o.jsx("div",{className:`flex flex-col ${R.role==="user"?"items-end":"items-start"}`,children:o.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${R.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:R.content})},F)),d&&o.jsx("div",{className:"flex items-start",children:o.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:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),o.jsx("div",{ref:E})]}),o.jsxs("form",{onSubmit:f,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:R=>R.preventDefault(),onDrop:w,children:[g.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:g.map((R,F)=>o.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-xs",children:[o.jsx(Jl,{size:10,className:"shrink-0"}),o.jsx("span",{className:"truncate max-w-[100px]",title:R.name,children:R.name}),o.jsx("button",{type:"button",onClick:()=>y(M=>M.filter((O,v)=>v!==F)),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:o.jsx(Je,{size:10})})]},F))}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.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:[o.jsx(Sp,{size:14}),o.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:C,accept:".csv,.txt,.json,.md"})]}),o.jsxs("div",{className:"relative flex-1",children:[o.jsx("input",{type:"text",value:h,disabled:l.length===0,onChange:R=>m(R.target.value),placeholder:l.length===0?j==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":A.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 disabled:opacity-60 disabled:cursor-not-allowed"}),o.jsx("button",{type:"submit",disabled:d||!h.trim()||l.length===0,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 cursor-pointer disabled:cursor-not-allowed",children:o.jsx(vp,{size:10})})]})]})]})]}):o.jsxs("div",{className:"flex-1 flex flex-col bg-black text-green-400 font-mono text-xs min-h-0 mx-4 mb-4 rounded-xl shadow-inner border border-gray-800 overflow-hidden",children:[o.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:o.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[o.jsx(fs,{size:14}),o.jsx("span",{className:"text-xs",children:A.eventStream})]})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:S.length===0?o.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):S.map((R,F)=>o.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsxs("span",{className:"text-gray-500 shrink-0 text-xs",children:["[",new Date(R.timestamp).toLocaleTimeString(),"]"]}),o.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:R.source,children:R.source})]}),o.jsx("div",{className:"text-green-300 font-bold",children:R.type}),o.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:R.payload})]},F))})]})]}):o.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-gray-400 w-full",onClick:()=>t(!0),children:[o.jsx(Vr,{size:18,className:"mb-6 hover:text-indigo-500"}),o.jsx(fs,{size:18,className:"hover:text-indigo-500"}),o.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:o.jsx("div",{className:"uppercase tracking-widest text-xs rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const Lw=p.lazy(()=>Ee(()=>import("./ImportModal-D7L-KNhZ.js"),__vite__mapDeps([9,2,3,4])).then(e=>({default:e.ImportModal}))),Rw=p.lazy(()=>Ee(()=>import("./CourseWizardModal-B16QBckO.js"),__vite__mapDeps([10,2,3,4,1,5,7,6])).then(e=>({default:e.CourseWizardModal}))),Ow=p.lazy(()=>Ee(()=>import("./ImportLessonsModal-Dnx_QR0Z.js"),__vite__mapDeps([11,2,3,4,1,5,7,6])).then(e=>({default:e.ImportLessonsModal}))),Dw=p.lazy(()=>Ee(()=>import("./QuizGeneratorModal-BeaBRn1w.js"),__vite__mapDeps([12,2,3,4,1,5,7,6])).then(e=>({default:e.QuizGeneratorModal}))),Mw=p.lazy(()=>Ee(()=>import("./StudentPreviewModal-0QSLnD9u.js"),__vite__mapDeps([13,2,3,14,1,15,4,5,7,6])).then(e=>({default:e.StudentPreviewModal}))),Fw=p.lazy(()=>Ee(()=>import("./ProcessLogsModal-DmFXg9mG.js"),__vite__mapDeps([16,2,3,4])).then(e=>({default:e.ProcessLogsModal}))),$w=p.lazy(()=>Ee(()=>import("./CloudDriveModal-Dr4kDySU.js"),__vite__mapDeps([17,2,3,15,1,4,5,7,6])).then(e=>({default:e.CloudDriveModal}))),Bw=p.lazy(()=>Ee(()=>import("./SystemResourceLibraryModal-COrhUd53.js"),__vite__mapDeps([18,2,3,17,15,1,4,5,7,6])).then(e=>({default:e.SystemResourceLibraryModal}))),Vw=p.lazy(()=>Ee(()=>import("./BatchPickerModal-BobcoTtn.js"),__vite__mapDeps([19,2,3,4,1,5,7,6])).then(e=>({default:e.BatchPickerModal}))),Uw=p.lazy(()=>Ee(()=>import("./ExportWeightModal-UPsVax6L.js"),__vite__mapDeps([20,2,3,4,1,5,7,6])).then(e=>({default:e.ExportWeightModal}))),Hw=p.lazy(()=>Ee(()=>import("./NotificationDetailModal-CMKHpWX1.js"),__vite__mapDeps([21,2,3,4,1,5,7,6])).then(e=>({default:e.NotificationDetailModal}))),qw=p.lazy(()=>Ee(()=>import("./HelpTour-CMJbbGne.js"),__vite__mapDeps([22,2,3,4])).then(e=>({default:e.HelpTour}))),Ww=p.lazy(()=>Ee(()=>import("./CoursewareHubPanel-CaEizhxl.js"),__vite__mapDeps([23,2,3,4])).then(e=>({default:e.CoursewareHubPanel})));function Gw(e){const{lang:t,t:n,showImportModal:s=!1,setShowImportModal:r=()=>{},handleImportFile:i=()=>{},importError:a=null,importSuccess:l=null,isImporting:c=!1,downloadCSVTemplate:u=()=>{},addToast:d=()=>{},generateTemplateContent:h=()=>"",isImportLessonsOpen:m=!1,setIsImportLessonsOpen:f=()=>{},importStatus:g="idle",setIsDraggingImport:y=()=>{},handleCSVFileChange:C=()=>{},downloadCsvTemplate:w=()=>{},isDraggingImport:P=!1,previewImportData:S=[],setPreviewImportData:j=()=>{},setImportStatus:A=()=>{},importProgress:E=0,importProgressTotal:R=0,importErrorMsg:F="",setImportErrorMsg:M=()=>{},handleCSVImportSubmit:O=()=>{},lessons:v=[],fetchClassDashboard:_=()=>{},isLessonPreviewVisible:L=!1,setIsLessonPreviewVisible:I=()=>{},selectedLesson:N=null,previewFullscreenPanel:z="none",setPreviewFullscreenPanel:U=()=>{},previewLessonTab:T="whiteboard",setPreviewLessonTab:D=()=>{},activeRole:x="teacher",elements:oe=[],activeSegmentId:me=null,setActiveSegmentId:b=()=>{},fetchElements:Q=()=>{},currentVfsParent:X=null,setCurrentVfsParent:B=()=>{},vfsNodes:Z=[],previewSelectedCourseware:re=null,setPreviewSelectedCourseware:de=()=>{},showProcessLogs:xe=null,setShowProcessLogs:ae=()=>{},processLogsContent:je="",isCloudDriveOpen:St=!1,setIsCloudDriveOpen:qt=()=>{},cloudDrivePreviewNode:vt=null,setCloudDrivePreviewNode:kt=()=>{},isSystemResourceLibraryOpen:Ot=!1,setIsSystemResourceLibraryOpen:Y=()=>{},systemResourceTab:ne="system",setSystemResourceTab:le=()=>{},selectedLibraryResourceId:Ne=null,setSelectedLibraryResourceId:Ue=()=>{},loadingLibraryResources:He=!1,libraryResources:dt=[],fetchLibraryResources:Te=()=>{},classes:$=[],expandedClassId:q=null,isExportWeightModalOpen:K=!1,setIsExportWeightModalOpen:J=()=>{},quizzesWeight:ee=40,setQuizzesWeight:Pe=()=>{},assignmentsWeight:Ye=60,setAssignmentsWeight:$e=()=>{},handleQuizzesWeightChange:st=()=>{},handleAssignmentsWeightChange:ht=()=>{},customCategoryOverrides:ge={},setCustomCategoryOverrides:rt=()=>{},classDashboardMap:Re={},exportClassId:Js="",exportClassName:Vn="",csvPreviewData:Zs=null,handleExportGrades:Ct=()=>{},setSelectedAssignment:Wt=()=>{},setStudentViewStatus:mn=()=>{},setQuizStudentAnswers:Ys=()=>{},setSubAssignmentTab:Ks=()=>{},isTourOpen:Xs=!1,setIsTourOpen:er=()=>{},handleSeedSuccess:tr=()=>{},setTeacherTab:nr=()=>{},showCoursewareHub:sr=!1,setShowCoursewareHub:rr=()=>{}}=e,ke=e.courseWizard,ir=ke?.isCourseWizardOpen??e.isCourseWizardOpen??!1,or=ke?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),ar=ke?.wizardStep??e.wizardStep??1,gn=ke?.setWizardStep??e.setWizardStep??(()=>{}),xn=ke?.wizardIsSubmitting??e.wizardIsSubmitting??!1,Un=ke?.wizardCourseTitle??e.wizardCourseTitle??"",lr=ke?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),Gt=ke?.wizardCourseDescription??e.wizardCourseDescription??"",cr=ke?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Oe=ke?.wizardCourseCategory??e.wizardCourseCategory??"",Hn=ke?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),ur=ke?.wizardCourseTimeline??e.wizardCourseTimeline??[],qn=ke?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),dr=ke?.wizardCourseContent??e.wizardCourseContent??"",Qt=ke?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),hr=ke?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),ye=e.quizGenerator,fr=ye?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,pr=ye?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),mr=ye?.quizGenMode??e.quizGenMode??"scan_lesson",gr=ye?.setQuizGenMode??e.setQuizGenMode??(()=>{}),xr=ye?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",yr=ye?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),br=ye?.quizGenTopic??e.quizGenTopic??"",wr=ye?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),Dt=ye?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,Sr=ye?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),vr=ye?.suggestedObjectives??e.suggestedObjectives??[],kr=ye?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),Wn=ye?.suggestedQuestions??e.suggestedQuestions??[],Gn=ye?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),Cr=ye?.quizGenTimeLimit??e.quizGenTimeLimit??0,Er=ye?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),Qn=ye?.savingQuiz??e.savingQuiz??!1,yn=ye?.setSavingQuiz??e.setSavingQuiz??(()=>{}),bn=ye?.quizGeneratorClassId??e.quizGeneratorClassId??null,Ke=e.classBatch,jr=Ke?.batchPicker??e.batchPicker??null,be=Ke?.setBatchPicker??e.setBatchPicker??(()=>{}),Mt=Ke?.batchPickerLesson??e.batchPickerLesson??"",Jn=Ke?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),Zn=Ke?.batchPickerDate??e.batchPickerDate??"",ze=Ke?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),ft=Ke?.batchPickerTargetClass??e.batchPickerTargetClass??"",Nr=Ke?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Tr=Ke?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),Yn=e.studentNotificationsHook,Jt=Yn?.selectedNotificationForModal??e.selectedNotificationForModal??null,Pr=Yn?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return o.jsxs(p.Suspense,{fallback:null,children:[o.jsx(Lw,{show:s,onClose:()=>r(!1),lang:t,handleImportFile:i,importError:a,importSuccess:l,isImporting:c,downloadCSVTemplate:u}),o.jsx(Rw,{isCourseWizardOpen:ir,setIsCourseWizardOpen:or,lang:t,wizardStep:ar,setWizardStep:gn,wizardIsSubmitting:xn,wizardCourseTitle:Un,setWizardCourseTitle:lr,wizardCourseDescription:Gt,setWizardCourseDescription:cr,wizardCourseCategory:Oe,setWizardCourseCategory:Hn,wizardCourseTimeline:ur,setWizardCourseTimeline:qn,wizardCourseContent:dr,setWizardCourseContent:Qt,addToast:d,generateTemplateContent:h,handleDeployWizardCourse:hr}),o.jsx(Ow,{isImportLessonsOpen:m,setIsImportLessonsOpen:f,lang:t,importStatus:g,setIsDraggingImport:y,handleCSVFileChange:C,downloadCsvTemplate:w,isDraggingImport:P,previewImportData:S,setPreviewImportData:j,setImportStatus:A,importProgress:E,importProgressTotal:R,importErrorMsg:F,setImportErrorMsg:M,handleCSVImportSubmit:O}),o.jsx(Dw,{isQuizGeneratorOpen:fr,setIsQuizGeneratorOpen:pr,lessons:v,quizGenMode:mr,setQuizGenMode:gr,quizGenSelectedLessonId:xr,setQuizGenSelectedLessonId:yr,quizGenTopic:br,setQuizGenTopic:wr,isGeneratingSuggestions:Dt,setIsGeneratingSuggestions:Sr,suggestedObjectives:vr,setSuggestedObjectives:kr,suggestedQuestions:Wn,setSuggestedQuestions:Gn,quizGenTimeLimit:Cr,setQuizGenTimeLimit:Er,savingQuiz:Qn,setSavingQuiz:yn,quizGeneratorClassId:bn,fetchClassDashboard:_}),o.jsx(Mw,{isLessonPreviewVisible:L,setIsLessonPreviewVisible:I,lessons:v,selectedLesson:N,previewFullscreenPanel:z,setPreviewFullscreenPanel:U,previewLessonTab:T,setPreviewLessonTab:D,activeRole:x,elements:oe,activeSegmentId:me,setActiveSegmentId:b,fetchElements:Q,currentVfsParent:X,setCurrentVfsParent:B,vfsNodes:Z,previewSelectedCourseware:re,setPreviewSelectedCourseware:de}),o.jsx(Fw,{showProcessLogs:xe,setShowProcessLogs:ae,processLogsContent:je,t:n}),o.jsx($w,{isOpen:St,onClose:()=>qt(!1),vfsNodes:Z,currentVfsParent:X,setCurrentVfsParent:B,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:kt}),o.jsx(Bw,{isSystemResourceLibraryOpen:Ot,setIsSystemResourceLibraryOpen:Y,lang:t,systemResourceTab:ne,setSystemResourceTab:le,selectedLibraryResourceId:Ne,setSelectedLibraryResourceId:Ue,vfsNodes:Z,currentVfsParent:X,setCurrentVfsParent:B,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:kt,loadingLibraryResources:He,libraryResources:dt,fetchLibraryResources:Te}),o.jsx(Vw,{batchPicker:jr,setBatchPicker:be,batchPickerLesson:Mt,setBatchPickerLesson:Jn,batchPickerDate:Zn,setBatchPickerDate:ze,batchPickerTargetClass:ft,setBatchPickerTargetClass:Nr,lessons:v,classes:$,expandedClassId:q,confirmBatchPicker:Tr,lang:t}),o.jsx(Uw,{isExportWeightModalOpen:K,setIsExportWeightModalOpen:J,lang:t,quizzesWeight:ee,setQuizzesWeight:Pe,assignmentsWeight:Ye,setAssignmentsWeight:$e,handleQuizzesWeightChange:st,handleAssignmentsWeightChange:ht,customCategoryOverrides:ge,setCustomCategoryOverrides:rt,classDashboardMap:Re,exportClassId:Js,exportClassName:Vn,csvPreviewData:Zs,handleExportGrades:Ct}),o.jsx(Hw,{notification:Jt,onClose:()=>Pr(null),lang:t,onOpenWorkspace:pt=>{Wt(pt),mn("assignment"),Ys({}),Ks("quiz")}}),o.jsx(qw,{isOpen:Xs,onClose:()=>er(!1),lang:t,onSeedSuccess:tr,onJumpTab:pt=>nr(pt)}),sr&&o.jsx(Ww,{onClose:()=>rr(!1),lang:t})]})}const Qw=["whiteboard.","courseware.","quiz.","rollcall."];class Jw{constructor(){this.handlers=new Map}setSocketBridge(t){this.socketBridge=t}hasSocketBridge(){return!!this.socketBridge}subscribe(t,n){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(n),()=>{this.handlers.get(t)?.delete(n)}}async publish(t){const n=this.handlers.get(t.type);if(n)for(const s of n)try{s(t)}catch(r){console.error("[FrontendEventBus] handler error:",r)}this.socketBridge&&Qw.some(s=>t.type.startsWith(s))&&this.socketBridge(t)}}const ru=new Jw,jl=new Map;async function Zw(e){const t=jl.get(e);if(t)return t;try{const n=await fetch(`/api/courseware/attempts/${encodeURIComponent(e)}/adopt`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!n.ok)return n.status!==401&&console.warn(`[LMS Bridge] Attempt adopt failed: HTTP ${n.status}`),e;const s=await n.json();return typeof s?.attemptId=="string"&&s.attemptId?(jl.set(e,s.attemptId),s.attemptId):e}catch(n){return console.warn("[LMS Bridge] Attempt adopt request failed:",n),e}}async function iu(e){const t=e.data;if(!t||typeof t!="object")return;if(typeof window<"u"&&typeof document<"u"&&e.source)try{if(!Array.from(document.querySelectorAll("iframe")).some(u=>u.contentWindow===e.source)&&e.source!==window)return}catch{}let n=t.attempt_id;const s=t.type||"",r=t.payload||t;if(!n&&e.source)try{const l=Array.from(document.querySelectorAll("iframe")).find(c=>c.contentWindow===e.source);if(l&&l.contentWindow){const c=l.contentWindow;c.__LMS_STUDENT__?.attempt_id&&(n=c.__LMS_STUDENT__.attempt_id)}}catch{}if(!n||typeof n!="string")return;if(n=await Zw(n),s==="LMS_CONFIG"){ls("courseware.config_reported",n,t.config??r);return}if(s==="LMS_GET_PROGRESS"){const l=t.requestId,c=e.source;if(l&&c&&typeof c.postMessage=="function"){if(typeof document<"u"&&!Array.from(document.querySelectorAll("iframe")).some(f=>f.contentWindow===c)&&c!==window){console.warn("[LMS Bridge Security] Dropping response to untrusted window");return}let u;try{u=(await(await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/progress`)).json()).progress??null}catch{u=null}const d=e.origin&&e.origin!=="null"?e.origin:"*";c.postMessage({type:"LMS_PROGRESS_RESPONSE",requestId:l,progress:u},d)}return}const i=s==="LMS_SUBMIT"||s==="LMS_FINISH"||s==="submit"||s==="finish"||s==="completed"||r&&typeof r=="object"&&(r.score!==void 0||r.grade!==void 0||r.result!==void 0||r.points!==void 0),a=s==="LMS_SAVE_PROGRESS"||s==="saveProgress";if(i){ls("courseware.submitted",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??r?.note??void 0,completion:r?.completion??1,status:"completed",extra:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to submit attempt data to backend:",l)}}else if(a){ls("courseware.progress_saved",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??void 0,completion:r?.completion??void 0,status:"inprogress",extra:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to save progress to backend:",l)}}else{ls("courseware.event_logged",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:s||"log",payload:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to log event to backend:",l)}}}function ls(e,t,n){ru.publish({id:sc(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t});try{const s=n??{};Ee(async()=>{const{whiteboardEventSlot:r}=await Promise.resolve().then(()=>KS);return{whiteboardEventSlot:r}},void 0).then(({whiteboardEventSlot:r})=>{r.ingest({source:"iframe.bridge",type:e,attemptId:t,coursewareUuid:typeof s.courseware_uuid=="string"?s.courseware_uuid:void 0,payload:{...s,attemptId:t},raw:n})})}catch{}}function Yw(e,t,n,s){try{let r=s;if(!r&&e.src&&typeof window<"u")try{const i=new URL(e.src,window.location.href);i.origin&&i.origin!=="null"&&!e.src.startsWith("blob:")&&!e.src.startsWith("data:")&&(r=i.origin)}catch{}e.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:t,payload:n},r||"*")}catch{}}function ou(e){p.useEffect(()=>{if(!e)return;const t=n=>{iu(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function au(e,t={}){if(!(typeof document>"u"))try{document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"theme:changed",payload:{theme:e,tokens:t}},"*"),s.contentWindow?.postMessage({type:"LMS_THEME_CHANGED",theme:e,tokens:t},"*")}catch{}})}catch{}}function lu(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}},"*"),s.contentWindow?.postMessage({type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)},"*")}catch{}})}catch{}}const cu=Object.freeze(Object.defineProperty({__proto__:null,broadcastFontScaleToIframes:lu,broadcastThemeToIframes:au,processLmsMessage:iu,sendCommandToCourseware:Yw,useLmsBridge:ou},Symbol.toStringTag,{value:"Module"}));function Kw(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:r,selectedLesson:i,selectedAssignment:a,expandedClassId:l,fetchLessons:c,fetchPlugins:u,fetchRegisteredCommands:d,fetchEvents:h,fetchApprovals:m,fetchProcesses:f,fetchClasses:g,fetchTodaySchedules:y,fetchStudents:C,fetchLabs:w,fetchVfs:P,fetchProcessLogs:S,fetchClassStudents:j,fetchElements:A}=e,E=p.useRef(r),R=p.useRef(i),F=p.useRef(a),M=p.useRef(l);p.useEffect(()=>{E.current=r},[r]),p.useEffect(()=>{R.current=i},[i]),p.useEffect(()=>{F.current=a},[a]),p.useEffect(()=>{M.current=l},[l]),p.useEffect(()=>{if(!t)return;const O=t.role==="student",v=t.role==="teacher",_=v&&(t.subRole==="administrator"||t.username==="admin"||t.userId==="usr_admin");c(),u(),d(),y().catch(()=>{}),_&&(h(),m(),f()),v?(g(),C(),w(),P(E.current)):O&&E.current&&P(E.current);let L=!1;const I=setInterval(async()=>{if(!L){L=!0;try{if(_&&(await h(),await m(),await f(),n&&await S(n)),await c(),await d(),await y().catch(()=>{}),v&&(await g(),await C(),await w(),await P(E.current),M.current&&await j(M.current)),R.current&&await A(R.current),F.current){const N=s||F.current.student_id;await A(`assignment-${F.current.id}-student-${N}`)}}finally{L=!1}}},2e3);return()=>clearInterval(I)},[t,n,s]),p.useEffect(()=>{t&&(t.role==="teacher"||r)&&P(r)},[r,t]),p.useEffect(()=>{i&&A(i)},[i])}function Xw(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:r,expandedClassId:i,fetchLessons:a,fetchClasses:l,fetchStudents:c,fetchClassStudents:u,fetchClassProgress:d,fetchClassDashboard:h,fetchElements:m}=e,[f,g]=p.useState([{role:"agent",content:n.agentIntro||""}]),[y,C]=p.useState(""),[w,P]=p.useState(!1),[S,j]=p.useState([]);p.useEffect(()=>{f.length===1&&f[0].role==="agent"&&g([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const A=p.useCallback(async O=>{try{const v=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(O||"")}`);if(!v.ok)return;const _=await v.json(),L=Array.isArray(_.messages)?_.messages:[];L.length>0?g(L.map(I=>({role:I.role==="assistant"?"agent":"user",content:I.content}))):g([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),E=p.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(s||"")}`,{method:"DELETE"})}catch{}g([{role:"agent",content:n.agentIntro}])},[s,n.agentIntro]);return p.useEffect(()=>{A(s)},[s,A]),{chatLog:f,setChatLog:g,input:y,setInput:C,loading:w,setLoading:P,chatAttachments:S,setChatAttachments:j,handleChatFileChange:O=>{O.target.files&&Array.from(O.target.files).forEach(v=>{const _=new FileReader;_.onload=L=>{L.target?.result&&j(I=>[...I,{name:v.name,content:L.target.result}])},v.name.endsWith(".zip")?_.readAsDataURL(v):_.readAsText(v)})},handleChatDrop:O=>{O.preventDefault(),O.dataTransfer.files&&Array.from(O.dataTransfer.files).forEach(v=>{const _=new FileReader;_.onload=L=>{L.target?.result&&j(I=>[...I,{name:v.name,content:L.target.result}])},v.name.endsWith(".zip")?_.readAsDataURL(v):_.readAsText(v)})},handleSend:async O=>{if(O.preventDefault(),!y.trim()||w)return;const v=[...S];let _=y;v.length>0&&(_+=`
134
- (📁 ${t==="zh"?"附件":"Attachments"}: ${v.map(L=>L.name).join(", ")})`),g(L=>[...L,{role:"user",content:_}]),C(""),j([]),P(!0);try{const L=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:y,lang:t,currentLessonId:s,attachments:v,providerId:r||null})}),I=await L.json();let N="";!L.ok||I.success===!1?N=`⚠️ ${I.message||I.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(N=I.agentText||"",I.toolResults&&I.toolResults.length>0&&(N+=`
133
+ `),()=>{l.current?.removeAttribute("data-motion-pop-id"),R.contains(E)&&R.removeChild(E)}},[t]),o.jsx(T0,{isPresent:t,childRef:l,sizeRef:c,pop:i,children:i===!1?e:f.cloneElement(e,{ref:p})})}const I0=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:i,mode:a,anchorX:l,anchorY:c,root:u})=>{const d=bo(A0),p=f.useId();let m=!0,h=f.useMemo(()=>(m=!1,{id:p,initial:t,isPresent:n,custom:r,onExitComplete:g=>{d.set(g,!0);for(const y of d.values())if(!y)return;s&&s()},register:g=>(d.set(g,!1),()=>d.delete(g))}),[n,d,s]);return i&&m&&(h={...h}),f.useMemo(()=>{d.forEach((g,y)=>d.set(y,!1))},[n]),f.useEffect(()=>{!n&&!d.size&&s&&s()},[n]),e=o.jsx(P0,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:u,children:e}),o.jsx(Gs.Provider,{value:h,children:e})};function A0(){return new Map}function Zc(e=!0){const t=f.useContext(Gs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,i=f.useId();f.useEffect(()=>{if(e)return r(i)},[e]);const a=f.useCallback(()=>e&&s&&s(i),[i,s,e]);return!n&&s?[!1,a]:[!0]}const is=e=>e.key||"";function xl(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Yc=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:i="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:u})=>{const[d,p]=Zc(a),m=f.useMemo(()=>xl(e),[e]),h=a&&!d?[]:m.map(is),g=f.useRef(!0),y=f.useRef(m),v=bo(()=>new Map),w=f.useRef(new Set),[P,S]=f.useState(m),[j,A]=f.useState(m);Jc(()=>{g.current=!1,y.current=m;for(let F=0;F<j.length;F++){const D=is(j[F]);h.includes(D)?(v.delete(D),w.current.delete(D)):v.get(D)!==!0&&v.set(D,!1)}},[j,h.length,h.join("-")]);const E=[];if(m!==P){let F=[...m];for(let D=0;D<j.length;D++){const O=j[D],k=is(O);h.includes(k)||(F.splice(D,0,O),E.push(O))}return i==="wait"&&E.length&&(F=E),A(xl(F)),S(m),null}const{forceRender:R}=f.useContext(yo);return o.jsx(o.Fragment,{children:j.map(F=>{const D=is(F),O=a&&!d?!1:m===j||h.includes(D),k=()=>{if(w.current.has(D))return;if(v.has(D))w.current.add(D),v.set(D,!0);else return;let _=!0;v.forEach(L=>{L||(_=!1)}),_&&(R?.(),A(y.current),a&&p?.(),s&&s())};return o.jsx(I0,{isPresent:O,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:i,root:u,onExitComplete:O?void 0:k,anchorX:l,anchorY:c,children:F},D)})})},Kc=f.createContext({strict:!1}),yl={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let bl=!1;function z0(){if(bl)return;const e={};for(const t in yl)e[t]={isEnabled:n=>yl[t].some(s=>!!n[s])};nc(e),bl=!0}function Xc(){return z0(),Lp()}function _0(e){const t=Xc();for(const n in e)t[n]={...t[n],...e[n]};nc(t)}const L0=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function Ds(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||L0.has(e)}let eu=e=>!Ds(e);function R0(e){typeof e=="function"&&(eu=t=>t.startsWith("on")?!Ds(t):e(t))}try{R0(require("@emotion/is-prop-valid").default)}catch{}function O0(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||eo(e[r])||(eu(r)||n===!0&&Ds(r)||!t&&!Ds(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Qs=f.createContext({});function M0(e,t){if(sc(e)){const{initial:n,animate:s}=e;return{initial:n===!1||ha(n)?n:void 0,animate:ha(s)?s:void 0}}return e.inherit!==!1?t:{}}function D0(e){const{initial:t,animate:n}=M0(e,f.useContext(Qs));return f.useMemo(()=>({initial:t,animate:n}),[wl(t),wl(n)])}function wl(e){return Array.isArray(e)?e.join(" "):e}const So=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function tu(e,t,n){for(const s in t)!eo(t[s])&&!Rp(s,n)&&(e[s]=t[s])}function F0({transformTemplate:e},t){return f.useMemo(()=>{const n=So();return Op(n,t,e),Object.assign({},n.vars,n.style)},[t])}function $0(e,t){const n=e.style||{},s={};return tu(s,n,e),Object.assign(s,F0(e,t)),s}function B0(e,t){const n={},s=$0(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const nu=()=>({...So(),attrs:{}});function V0(e,t,n,s){const r=f.useMemo(()=>{const i=nu();return Mp(i,t,Dp(s),e.transformTemplate,e.style),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};tu(i,e.style,e),r.style={...i,...r.style}}return r}const U0=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function vo(e){return typeof e!="string"||e.includes("-")?!1:!!(U0.indexOf(e)>-1||/[A-Z]/u.test(e))}function H0(e,t,n,{latestValues:s},r,i=!1,a){const c=(a??vo(e)?V0:B0)(t,s,r,e),u=O0(t,typeof e=="string",i),d=e!==f.Fragment?{...u,...c,ref:n}:{},{children:p}=t,m=f.useMemo(()=>eo(p)?p.get():p,[p]);return f.createElement(e,{...d,children:m})}function q0({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:W0(n,s,r,e),renderState:t()}}function W0(e,t,n,s){const r={},i=s(e,{});for(const m in i)r[m]=Fp(i[m]);let{initial:a,animate:l}=e;const c=sc(e),u=$p(e);t&&u&&!c&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let d=n?n.initial===!1:!1;d=d||a===!1;const p=d?l:a;if(p&&typeof p!="boolean"&&!rc(p)){const m=Array.isArray(p)?p:[p];for(let h=0;h<m.length;h++){const g=Bp(e,m[h]);if(g){const{transitionEnd:y,transition:v,...w}=g;for(const P in w){let S=w[P];if(Array.isArray(S)){const j=d?S.length-1:0;S=S[j]}S!==null&&(r[P]=S)}for(const P in y)r[P]=y[P]}}}return r}const su=e=>(t,n)=>{const s=f.useContext(Qs),r=f.useContext(Gs),i=()=>q0(e,t,s,r);return n?i():bo(i)},G0=su({scrapeMotionValuesFromProps:Vp,createRenderState:So}),Q0=su({scrapeMotionValuesFromProps:Up,createRenderState:nu}),J0=Symbol.for("motionComponentSymbol");function Z0(e,t,n){const s=f.useRef(n);f.useInsertionEffect(()=>{s.current=n});const r=f.useRef(null);return f.useCallback(i=>{i&&e.onMount?.(i),t&&(i?t.mount(i):t.unmount());const a=s.current;if(typeof a=="function")if(i){const l=a(i);typeof l=="function"&&(r.current=l)}else r.current?(r.current(),r.current=null):a(i);else a&&(a.current=i)},[t])}const ru=f.createContext({});function rn(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Y0(e,t,n,s,r,i){const{visualElement:a}=f.useContext(Qs),l=f.useContext(Kc),c=f.useContext(Gs),u=f.useContext(wo),d=u.reducedMotion,p=u.skipAnimations,m=f.useRef(null),h=f.useRef(!1);s=s||l.renderer,!m.current&&s&&(m.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:d,skipAnimations:p,isSVG:i}),h.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,y=f.useContext(ru);g&&!g.projection&&r&&(g.type==="html"||g.type==="svg")&&K0(m.current,n,r,y);const v=f.useRef(!1);f.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const w=n[Hp],P=f.useRef(!!w&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(w)&&window.MotionHasOptimisedAnimation?.(w));return Jc(()=>{h.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),P.current&&g.animationState&&g.animationState.animateChanges())}),f.useEffect(()=>{g&&(!P.current&&g.animationState&&g.animationState.animateChanges(),P.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(w)}),P.current=!1),g.enteringChildren=void 0)}),g}function K0(e,t,n,s){const{layoutId:r,layout:i,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:u,layoutAnchor:d,layoutCrossfade:p}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:iu(e.parent)),e.projection.setOptions({layoutId:r,layout:i,alwaysMeasureLayout:!!a||l&&rn(l),visualElement:e,animationType:typeof i=="string"?i:"both",initialPromotionConfig:s,crossfade:p,layoutScroll:c,layoutRoot:u,layoutAnchor:d})}function iu(e){if(e)return e.options.allowProjection!==!1?e.projection:iu(e.parent)}function fi(e,{forwardMotionProps:t=!1,type:n}={},s,r){s&&_0(s);const i=n?n==="svg":vo(e),a=i?Q0:G0;function l(u,d){let p;const m={...f.useContext(wo),...u,layoutId:X0(u)},{isStatic:h}=m,g=D0(u),y=a(u,h);if(!h&&typeof window<"u"){ew();const v=tw(m);p=v.MeasureLayout,g.visualElement=Y0(e,y,m,r,v.ProjectionNode,i)}return o.jsxs(Qs.Provider,{value:g,children:[p&&g.visualElement?o.jsx(p,{visualElement:g.visualElement,...m}):null,H0(e,u,Z0(y,g.visualElement,d),y,h,t,i)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=f.forwardRef(l);return c[J0]=e,c}function X0({layoutId:e}){const t=f.useContext(yo).id;return t&&e!==void 0?t+"-"+e:e}function ew(e,t){f.useContext(Kc).strict}function tw(e){const t=Xc(),{drag:n,layout:s}=t;if(!n&&!s)return{};const r={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function nw(e,t){if(typeof Proxy>"u")return fi;const n=new Map,s=(i,a)=>fi(i,a,e,t),r=(i,a)=>s(i,a);return new Proxy(r,{get:(i,a)=>a==="create"?s:(n.has(a)||n.set(a,fi(a,void 0,e,t)),n.get(a))})}const sw=(e,t)=>t.isSVG??vo(e)?new qp(t):new Wp(t,{allowProjection:e!==f.Fragment});class rw extends Lt{constructor(t){super(t),t.animationState||(t.animationState=Gp(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();rc(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let iw=0;class ow extends Lt{constructor(){super(...arguments),this.id=iw++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;if(t&&s===!1){if(this.isExitComplete){const{initial:i,custom:a}=this.node.getProps();if(typeof i=="string"||typeof i=="object"&&i!==null&&!Array.isArray(i)){const l=Qp(this.node,i,a);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const p in d)this.node.getValue(p)?.jump(d[p])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const aw={animation:{Feature:rw},exit:{Feature:ow}};function Bn(e){return{point:{x:e.pageX,y:e.pageY}}}const lw=e=>t=>ic(t)&&e(t,Bn(t));function On(e,t,n,s){return As(e,t,lw(n),s)}const ou=({current:e})=>e?e.ownerDocument.defaultView:null,Sl=(e,t)=>Math.abs(e-t);function cw(e,t){const n=Sl(e.x,t.x),s=Sl(e.y,t.y);return Math.sqrt(n**2+s**2)}const vl=new Set(["auto","scroll"]);class au{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:l}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=h=>{this.handleScroll(h.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=os(this.lastRawMoveEventInfo,this.transformPagePoint));const h=pi(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=cw(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:v}=h,{timestamp:w}=fa;this.history.push({...v,timestamp:w});const{onStart:P,onMove:S}=this.handlers;g||(P&&P(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=os(g,this.transformPagePoint),nt.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:w}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const P=pi(h.type==="pointercancel"?this.lastMoveEventInfo:os(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(h,P),v&&v(h,P)},!ic(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=r||window;const c=Bn(t),u=os(c,this.transformPagePoint),{point:d}=u,{timestamp:p}=fa;this.history=[{...d,timestamp:p}];const{onSessionStart:m}=n;m&&m(t,pi(u,this.history)),this.removeListeners=oc(On(this.contextWindow,"pointermove",this.handlePointerMove),On(this.contextWindow,"pointerup",this.handlePointerUp),On(this.contextWindow,"pointercancel",this.handlePointerUp)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(vl.has(s.overflowX)||vl.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,r=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:r.x-n.x,y:r.y-n.y};i.x===0&&i.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,r),nt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Jp(this.updatePoint)}}function os(e,t){return t?{point:t(e.point)}:e}function kl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function pi({point:e},t){return{point:e,delta:kl(e,lu(t)),offset:kl(e,uw(t)),velocity:dw(t,.1)}}function uw(e){return e[0]}function lu(e){return e[e.length-1]}function dw(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=lu(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>pa(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&r.timestamp-s.timestamp>pa(t)*2&&(s=e[1]);const i=Zp(r.timestamp-s.timestamp);if(i===0)return{x:0,y:0};const a={x:(r.x-s.x)/i,y:(r.y-s.y)/i};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function hw(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?zs(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?zs(n,e,s.max):Math.min(e,n)),e}function Cl(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function fw(e,{top:t,left:n,bottom:s,right:r}){return{x:Cl(e.x,n,r),y:Cl(e.y,t,s)}}function El(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function pw(e,t){return{x:El(e.x,t.x),y:El(e.y,t.y)}}function mw(e,t){let n=.5;const s=Pi(e),r=Pi(t);return r>s?n=ma(t.min,t.max-s,e.min):s>r&&(n=ma(e.min,e.max-r,t.min)),Yp(0,1,n)}function gw(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Vi=.35;function xw(e=Vi){return e===!1?e=0:e===!0&&(e=Vi),{x:jl(e,"left","right"),y:jl(e,"top","bottom")}}function jl(e,t,n){return{min:Nl(e,t),max:Nl(e,n)}}function Nl(e,t){return typeof e=="number"?e:e[t]||0}const yw=new WeakMap;class bw{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Kp(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const i=p=>{n&&this.snapToCursor(Bn(p).point),this.stopAnimation()},a=(p,m)=>{const{drag:h,dragPropagation:g,onDragStart:y}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=sm(h),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Pt(w=>{let P=this.getAxisMotionValue(w).get()||0;if(rm.test(P)){const{projection:S}=this.visualElement;if(S&&S.layout){const j=S.layout.layoutBox[w];j&&(P=Pi(j)*(parseFloat(P)/100))}}this.originPoint[w]=P}),y&&nt.update(()=>y(p,m),!1,!0),ga(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(p,m)=>{this.latestPointerEvent=p,this.latestPanInfo=m;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:y,onDrag:v}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:w}=m;if(g&&this.currentDirection===null){this.currentDirection=Sw(w),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),v&&nt.update(()=>v(p,m),!1,!0)},c=(p,m)=>{this.latestPointerEvent=p,this.latestPanInfo=m,this.stop(p,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>{const{dragSnapToOrigin:p}=this.getProps();(p||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:d}=this.getProps();this.panSession=new au(t,{onSessionStart:i,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:ou(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!s)return;const{velocity:a}=r;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&nt.postRender(()=>l(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!as(t,r,this.currentDirection))return;const i=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=hw(a,this.constraints[t],this.elastic[t])),i.set(a)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&rn(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=fw(s.layoutBox,t):this.constraints=!1,this.elastic=xw(n),r!==this.constraints&&!rn(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Pt(i=>{this.constraints!==!1&&this.getAxisMotionValue(i)&&(this.constraints[i]=gw(s.layoutBox[i],this.constraints[i]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!rn(t))return!1;const s=t.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;r.root&&(r.root.scroll=void 0,r.root.updateScroll());const i=Xp(s,r.root,this.visualElement.getTransformPagePoint());let a=pw(r.layout.layoutBox,i);if(n){const l=n(em(a));this.hasMutatedConstraints=!!l,l&&(a=tm(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},u=Pt(d=>{if(!as(d,n,this.currentDirection))return;let p=c&&c[d]||{};(a===!0||a===d)&&(p={min:0,max:0});const m=r?200:1e6,h=r?40:1e7,g={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...p};return this.startAxisValueAnimation(d,g)});return Promise.all(u).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ga(this.visualElement,t),s.start(nm(t,s,0,n,this.visualElement,!1))}stopAnimation(){Pt(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps()[n];return r||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){Pt(n=>{const{drag:s}=this.getProps();if(!as(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(n);if(r&&r.layout){const{min:a,max:l}=r.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-zs(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!rn(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Pt(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();r[a]=mw({min:c,max:c},this.constraints[a])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.constraints=!1,this.resolveConstraints(),Pt(a=>{if(!as(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:u}=this.constraints[a];l.set(zs(c,u,r[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;yw.set(this.visualElement,this);const t=this.visualElement.current,n=On(t,"pointerdown",u=>{const{drag:d,dragListener:p=!0}=this.getProps(),m=u.target,h=m!==t&&im(m);d&&p&&!h&&this.start(u)});let s;const r=()=>{const{dragConstraints:u}=this.getProps();rn(u)&&u.current&&(this.constraints=this.resolveRefConstraints(),s||(s=ww(t,u.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,a=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),nt.read(r);const l=As(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",(({delta:u,hasLayoutChanged:d})=>{this.isDragging&&d&&(Pt(p=>{const m=this.getAxisMotionValue(p);m&&(this.originPoint[p]+=u[p].translate,m.set(m.get()+u[p].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Vi,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:l}}}function Tl(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function ww(e,t,n){const s=xa(e,Tl(n)),r=xa(t,Tl(n));return()=>{s(),r()}}function as(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sw(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class vw extends Lt{constructor(t){super(t),this.removeGroupControls=ps,this.removeListeners=ps,this.controls=new bw(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ps}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const mi=e=>(t,n)=>{e&&nt.update(()=>e(t,n),!1,!0)};class kw extends Lt{constructor(){super(...arguments),this.removePointerDownListener=ps}onPointerDown(t){this.session=new au(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:ou(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:mi(t),onStart:mi(n),onMove:mi(s),onEnd:(i,a)=>{delete this.session,r&&nt.postRender(()=>r(i,a))}}}mount(){this.removePointerDownListener=On(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let gi=!1;class Cw extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),s&&s.register&&r&&s.register(i),gi&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),am.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:i}=this.props,{projection:a}=s;return a&&(a.isPresent=i,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),gi=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==i?a.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?a.promote():a.relegate()||nt.postRender(()=>{const l=a.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),om.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;gi=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function cu(e){const[t,n]=Zc(),s=f.useContext(yo);return o.jsx(Cw,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(ru),isPresent:t,safeToRemove:n})}const Ew={pan:{Feature:kw},drag:{Feature:vw,ProjectionNode:ac,MeasureLayout:cu}};function Pl(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,i=s[r];i&&nt.postRender(()=>i(t,Bn(t)))}class jw extends Lt{mount(){const{current:t}=this.node;t&&(this.unmount=lm(t,(n,s)=>(Pl(this.node,s,"Start"),r=>Pl(this.node,r,"End"))))}unmount(){}}class Nw extends Lt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=oc(As(this.node.current,"focus",()=>this.onFocus()),As(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Il(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),i=s[r];i&&nt.postRender(()=>i(t,Bn(t)))}class Tw extends Lt{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=cm(t,(r,i)=>(Il(this.node,i,"Start"),(a,{success:l})=>Il(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Ui=new WeakMap,xi=new WeakMap,Pw=e=>{const t=Ui.get(e.target);t&&t(e)},Iw=e=>{e.forEach(Pw)};function Aw({root:e,...t}){const n=e||document;xi.has(n)||xi.set(n,{});const s=xi.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Iw,{root:e,...t})),s[r]}function zw(e,t,n){const s=Aw(t);return Ui.set(e,n),s.observe(e),()=>{Ui.delete(e),s.unobserve(e)}}const _w={some:0,all:1};class Lw extends Lt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:i}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:_w[r]},l=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:p}=this.node.getProps(),m=u?d:p;m&&m(c)};this.stopObserver=zw(this.node.current,a,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Rw(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function Rw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Ow={inView:{Feature:Lw},tap:{Feature:Tw},focus:{Feature:Nw},hover:{Feature:jw}},Mw={layout:{ProjectionNode:ac,MeasureLayout:cu}},Dw={...aw,...Ow,...Ew,...Mw},ys=nw(Dw,sw);async function Fs(e){if(typeof window>"u")return!1;try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(e),!0}catch{}try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",t.setAttribute("readonly",""),document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch(t){return console.error("[OpenLearn Clipboard] Failed to copy text to clipboard:",t),!1}}function Fw(){const e=he(i=>i.toasts),[t,n]=f.useState(null),s=async(i,a)=>{i.stopPropagation();const l=`[${a.title}] ${a.message}`;await Fs(l)&&(n(a.id),setTimeout(()=>n(null),2e3))},r=i=>{switch(i){case"error":return{border:"border-l-4 border-rose-500",iconBg:"bg-rose-50 text-rose-600 dark:bg-rose-950/60 dark:text-rose-400",icon:o.jsx(Ei,{size:16})};case"warning":return{border:"border-l-4 border-amber-500",iconBg:"bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400",icon:o.jsx(Is,{size:16})};case"info":return{border:"border-l-4 border-blue-500",iconBg:"bg-blue-50 text-blue-600 dark:bg-blue-950/60 dark:text-blue-400",icon:o.jsx(Ep,{size:16})};case"success":default:return{border:"border-l-4 border-emerald-500",iconBg:"bg-emerald-50 text-emerald-600 dark:bg-emerald-950/60 dark:text-emerald-400",icon:o.jsx(_t,{size:16})}}};return o.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:o.jsx(Yc,{children:e.map(i=>{const a=r(i.type),l=t===i.id;return o.jsxs(ys.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 dark:bg-slate-900 ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 ${a.border} overflow-hidden text-gray-900 dark:text-gray-100`,id:`toast-${i.id}`,children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:`p-1 rounded-full shrink-0 ${a.iconBg}`,children:a.icon}),o.jsx("p",{className:"font-semibold text-sm font-sans truncate",children:i.title})]}),(i.type==="error"||i.type==="warning")&&o.jsxs("button",{type:"button",onClick:c=>s(c,i),className:`text-xs font-bold px-1.5 py-0.5 rounded transition-all flex items-center gap-1 cursor-pointer shrink-0 ${l?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-gray-600 dark:text-gray-300"}`,title:"复制错误内容",children:[l?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:l?"已复制":"复制"})]})]}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2 leading-relaxed font-sans break-words",children:i.message})]}),o.jsx("button",{type:"button",onClick:()=>_e.getState().removeToast(i.id),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-slate-800 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:o.jsx(Ze,{size:14})})]},i.id)})})})}function $w({showRightSidebar:e,setShowRightSidebar:t,rightSidebarTab:n,setRightSidebarTab:s,effectiveAgentProviderId:r,agentProviderId:i,setAgentProviderId:a,aiProviders:l,selectedAgentProvider:c,chatLog:u,loading:d,input:p,setInput:m,handleSend:h,chatAttachments:g,setChatAttachments:y,handleChatFileChange:v,handleChatDrop:w,onClearAgentMemory:P,events:S,lang:j,t:A}){const E=f.useRef(null);return f.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[u]),o.jsx("div",{className:`transition-all duration-300 bg-white border-l border-gray-200 flex flex-col shadow-xl relative z-30 shrink-0 ${e?"w-96":"w-12 items-center cursor-pointer hover:bg-gray-50"}`,children:e?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[o.jsxs("button",{onClick:()=>s("agent"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="agent"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[o.jsx(Hr,{size:14})," Agent"]}),o.jsxs("button",{onClick:()=>s("shell"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="shell"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[o.jsx(fs,{size:14})," Shell"]}),o.jsx("button",{onClick:()=>t(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:o.jsx(jp,{size:14})})]}),n==="agent"?o.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[o.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:o.jsx(Hr,{size:16})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:A.agentTitle}),o.jsx("p",{className:"text-xs text-gray-500",children:A.agentSubtitle}),o.jsxs("button",{onClick:P,title:j==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",j==="zh"?"清除记忆":"Clear memory"]})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-gray-400",children:j==="zh"?"AI 提供商":"AI Provider"}),o.jsxs("div",{className:"relative w-full",children:[l.length===0?o.jsx("select",{disabled:!0,value:"",className:"w-full appearance-none rounded-xl border border-amber-200 bg-amber-50/50 px-3 py-2 pr-9 text-xs font-medium text-amber-700 shadow-xs outline-none cursor-not-allowed",children:o.jsx("option",{value:"",children:j==="zh"?"未配置 AI 提供商":"No AI Provider"})}):o.jsx("select",{value:r,onChange:R=>a(R.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-xs font-medium text-gray-700 shadow-xs outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:l.map(R=>o.jsx("option",{value:R.id,children:R.name},R.id))}),o.jsx(dn,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),o.jsx("div",{className:"text-xs text-gray-400 truncate w-full text-right",title:c?.model_name||"",children:c?`${c.model_name}`:j==="zh"?"未配置提供商":"No Provider"})]})]})}),l.length===0&&o.jsxs("div",{className:"mx-4 mt-3 p-3 bg-amber-50 border border-amber-200/80 rounded-xl text-xs text-amber-900 flex items-start gap-2 shadow-xs shrink-0",children:[o.jsx(Is,{size:15,className:"shrink-0 text-amber-600 mt-0.5"}),o.jsxs("div",{className:"flex-1 leading-relaxed",children:[o.jsx("span",{className:"font-semibold",children:j==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),o.jsx("p",{className:"mt-0.5 text-amber-700",children:j==="zh"?"请前往「系统管理 -> AI 提供商管理」添加大模型服务(如 DeepSeek、Qwen、OpenAI 等)。":'Please configure an AI provider in "System Management -> AI Provider Management" to use the AI assistant.'})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[u.map((R,F)=>o.jsx("div",{className:`flex flex-col ${R.role==="user"?"items-end":"items-start"}`,children:o.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${R.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:R.content})},F)),d&&o.jsx("div",{className:"flex items-start",children:o.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:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),o.jsx("div",{ref:E})]}),o.jsxs("form",{onSubmit:h,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:R=>R.preventDefault(),onDrop:w,children:[g.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:g.map((R,F)=>o.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-xs",children:[o.jsx(ec,{size:10,className:"shrink-0"}),o.jsx("span",{className:"truncate max-w-[100px]",title:R.name,children:R.name}),o.jsx("button",{type:"button",onClick:()=>y(D=>D.filter((O,k)=>k!==F)),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:o.jsx(Ze,{size:10})})]},F))}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.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:[o.jsx(Np,{size:14}),o.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:v,accept:".csv,.txt,.json,.md"})]}),o.jsxs("div",{className:"relative flex-1",children:[o.jsx("input",{type:"text",value:p,disabled:l.length===0,onChange:R=>m(R.target.value),placeholder:l.length===0?j==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":A.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 disabled:opacity-60 disabled:cursor-not-allowed"}),o.jsx("button",{type:"submit",disabled:d||!p.trim()||l.length===0,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 cursor-pointer disabled:cursor-not-allowed",children:o.jsx(Tp,{size:10})})]})]})]})]}):o.jsxs("div",{className:"flex-1 flex flex-col bg-black text-green-400 font-mono text-xs min-h-0 mx-4 mb-4 rounded-xl shadow-inner border border-gray-800 overflow-hidden",children:[o.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:o.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[o.jsx(fs,{size:14}),o.jsx("span",{className:"text-xs",children:A.eventStream})]})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:S.length===0?o.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):S.map((R,F)=>o.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsxs("span",{className:"text-gray-500 shrink-0 text-xs",children:["[",new Date(R.timestamp).toLocaleTimeString(),"]"]}),o.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:R.source,children:R.source})]}),o.jsx("div",{className:"text-green-300 font-bold",children:R.type}),o.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:R.payload})]},F))})]})]}):o.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-gray-400 w-full",onClick:()=>t(!0),children:[o.jsx(Hr,{size:18,className:"mb-6 hover:text-indigo-500"}),o.jsx(fs,{size:18,className:"hover:text-indigo-500"}),o.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:o.jsx("div",{className:"uppercase tracking-widest text-xs rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const Bw=f.lazy(()=>Ee(()=>import("./ImportModal-D7L-KNhZ.js"),__vite__mapDeps([9,2,3,4])).then(e=>({default:e.ImportModal}))),Vw=f.lazy(()=>Ee(()=>import("./CourseWizardModal-Ck_-M8pk.js"),__vite__mapDeps([10,2,3,4,1,5,7,6])).then(e=>({default:e.CourseWizardModal}))),Uw=f.lazy(()=>Ee(()=>import("./ImportLessonsModal-jBuIK453.js"),__vite__mapDeps([11,2,3,4,1,5,7,6])).then(e=>({default:e.ImportLessonsModal}))),Hw=f.lazy(()=>Ee(()=>import("./QuizGeneratorModal-BBEDssp7.js"),__vite__mapDeps([12,2,3,4,1,5,7,6])).then(e=>({default:e.QuizGeneratorModal}))),qw=f.lazy(()=>Ee(()=>import("./StudentPreviewModal-Bh8OZs0t.js"),__vite__mapDeps([13,2,3,14,1,15,4,5,7,6])).then(e=>({default:e.StudentPreviewModal}))),Ww=f.lazy(()=>Ee(()=>import("./ProcessLogsModal-DmFXg9mG.js"),__vite__mapDeps([16,2,3,4])).then(e=>({default:e.ProcessLogsModal}))),Gw=f.lazy(()=>Ee(()=>import("./CloudDriveModal-DEQ1nkNk.js"),__vite__mapDeps([17,2,3,15,1,4,5,7,6])).then(e=>({default:e.CloudDriveModal}))),Qw=f.lazy(()=>Ee(()=>import("./SystemResourceLibraryModal-BVCclcqA.js"),__vite__mapDeps([18,2,3,17,15,1,4,5,7,6])).then(e=>({default:e.SystemResourceLibraryModal}))),Jw=f.lazy(()=>Ee(()=>import("./BatchPickerModal-BpWu0Lil.js"),__vite__mapDeps([19,2,3,4,1,5,7,6])).then(e=>({default:e.BatchPickerModal}))),Zw=f.lazy(()=>Ee(()=>import("./ExportWeightModal-DW2bu9Zz.js"),__vite__mapDeps([20,2,3,4,1,5,7,6])).then(e=>({default:e.ExportWeightModal}))),Yw=f.lazy(()=>Ee(()=>import("./NotificationDetailModal-Baqnc5pU.js"),__vite__mapDeps([21,2,3,4,1,5,7,6])).then(e=>({default:e.NotificationDetailModal}))),Kw=f.lazy(()=>Ee(()=>import("./HelpTour-CMJbbGne.js"),__vite__mapDeps([22,2,3,4])).then(e=>({default:e.HelpTour}))),Xw=f.lazy(()=>Ee(()=>import("./CoursewareHubPanel-CaEizhxl.js"),__vite__mapDeps([23,2,3,4])).then(e=>({default:e.CoursewareHubPanel})));function eS(e){const{lang:t,t:n,showImportModal:s=!1,setShowImportModal:r=()=>{},handleImportFile:i=()=>{},importError:a=null,importSuccess:l=null,isImporting:c=!1,downloadCSVTemplate:u=()=>{},addToast:d=()=>{},generateTemplateContent:p=()=>"",isImportLessonsOpen:m=!1,setIsImportLessonsOpen:h=()=>{},importStatus:g="idle",setIsDraggingImport:y=()=>{},handleCSVFileChange:v=()=>{},downloadCsvTemplate:w=()=>{},isDraggingImport:P=!1,previewImportData:S=[],setPreviewImportData:j=()=>{},setImportStatus:A=()=>{},importProgress:E=0,importProgressTotal:R=0,importErrorMsg:F="",setImportErrorMsg:D=()=>{},handleCSVImportSubmit:O=()=>{},lessons:k=[],fetchClassDashboard:_=()=>{},isLessonPreviewVisible:L=!1,setIsLessonPreviewVisible:I=()=>{},selectedLesson:N=null,previewFullscreenPanel:z="none",setPreviewFullscreenPanel:U=()=>{},previewLessonTab:T="whiteboard",setPreviewLessonTab:M=()=>{},activeRole:x="teacher",elements:oe=[],activeSegmentId:me=null,setActiveSegmentId:b=()=>{},fetchElements:Q=()=>{},currentVfsParent:X=null,setCurrentVfsParent:B=()=>{},vfsNodes:Z=[],previewSelectedCourseware:re=null,setPreviewSelectedCourseware:de=()=>{},showProcessLogs:xe=null,setShowProcessLogs:ae=()=>{},processLogsContent:je="",isCloudDriveOpen:St=!1,setIsCloudDriveOpen:qt=()=>{},cloudDrivePreviewNode:vt=null,setCloudDrivePreviewNode:kt=()=>{},isSystemResourceLibraryOpen:Ot=!1,setIsSystemResourceLibraryOpen:Y=()=>{},systemResourceTab:ne="system",setSystemResourceTab:le=()=>{},selectedLibraryResourceId:Ne=null,setSelectedLibraryResourceId:He=()=>{},loadingLibraryResources:qe=!1,libraryResources:dt=[],fetchLibraryResources:Te=()=>{},classes:$=[],expandedClassId:q=null,isExportWeightModalOpen:K=!1,setIsExportWeightModalOpen:J=()=>{},quizzesWeight:ee=40,setQuizzesWeight:Pe=()=>{},assignmentsWeight:Ye=60,setAssignmentsWeight:Be=()=>{},handleQuizzesWeightChange:st=()=>{},handleAssignmentsWeightChange:ht=()=>{},customCategoryOverrides:ge={},setCustomCategoryOverrides:rt=()=>{},classDashboardMap:Re={},exportClassId:Ys="",exportClassName:Vn="",csvPreviewData:Ks=null,handleExportGrades:Ct=()=>{},setSelectedAssignment:Wt=()=>{},setStudentViewStatus:gn=()=>{},setQuizStudentAnswers:Xs=()=>{},setSubAssignmentTab:er=()=>{},isTourOpen:tr=!1,setIsTourOpen:nr=()=>{},handleSeedSuccess:sr=()=>{},setTeacherTab:rr=()=>{},showCoursewareHub:ir=!1,setShowCoursewareHub:or=()=>{}}=e,ke=e.courseWizard,ar=ke?.isCourseWizardOpen??e.isCourseWizardOpen??!1,lr=ke?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),cr=ke?.wizardStep??e.wizardStep??1,xn=ke?.setWizardStep??e.setWizardStep??(()=>{}),yn=ke?.wizardIsSubmitting??e.wizardIsSubmitting??!1,Un=ke?.wizardCourseTitle??e.wizardCourseTitle??"",ur=ke?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),Gt=ke?.wizardCourseDescription??e.wizardCourseDescription??"",dr=ke?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Oe=ke?.wizardCourseCategory??e.wizardCourseCategory??"",Hn=ke?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),hr=ke?.wizardCourseTimeline??e.wizardCourseTimeline??[],qn=ke?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),fr=ke?.wizardCourseContent??e.wizardCourseContent??"",Qt=ke?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),pr=ke?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),ye=e.quizGenerator,mr=ye?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,gr=ye?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),xr=ye?.quizGenMode??e.quizGenMode??"scan_lesson",yr=ye?.setQuizGenMode??e.setQuizGenMode??(()=>{}),br=ye?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",wr=ye?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),Sr=ye?.quizGenTopic??e.quizGenTopic??"",vr=ye?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),Mt=ye?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,kr=ye?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),Cr=ye?.suggestedObjectives??e.suggestedObjectives??[],Er=ye?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),Wn=ye?.suggestedQuestions??e.suggestedQuestions??[],Gn=ye?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),jr=ye?.quizGenTimeLimit??e.quizGenTimeLimit??0,Nr=ye?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),Qn=ye?.savingQuiz??e.savingQuiz??!1,bn=ye?.setSavingQuiz??e.setSavingQuiz??(()=>{}),wn=ye?.quizGeneratorClassId??e.quizGeneratorClassId??null,Ke=e.classBatch,Tr=Ke?.batchPicker??e.batchPicker??null,be=Ke?.setBatchPicker??e.setBatchPicker??(()=>{}),Dt=Ke?.batchPickerLesson??e.batchPickerLesson??"",Jn=Ke?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),Zn=Ke?.batchPickerDate??e.batchPickerDate??"",ze=Ke?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),ft=Ke?.batchPickerTargetClass??e.batchPickerTargetClass??"",Pr=Ke?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Ir=Ke?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),Yn=e.studentNotificationsHook,Jt=Yn?.selectedNotificationForModal??e.selectedNotificationForModal??null,Ar=Yn?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return o.jsxs(f.Suspense,{fallback:null,children:[o.jsx(Bw,{show:s,onClose:()=>r(!1),lang:t,handleImportFile:i,importError:a,importSuccess:l,isImporting:c,downloadCSVTemplate:u}),o.jsx(Vw,{isCourseWizardOpen:ar,setIsCourseWizardOpen:lr,lang:t,wizardStep:cr,setWizardStep:xn,wizardIsSubmitting:yn,wizardCourseTitle:Un,setWizardCourseTitle:ur,wizardCourseDescription:Gt,setWizardCourseDescription:dr,wizardCourseCategory:Oe,setWizardCourseCategory:Hn,wizardCourseTimeline:hr,setWizardCourseTimeline:qn,wizardCourseContent:fr,setWizardCourseContent:Qt,addToast:d,generateTemplateContent:p,handleDeployWizardCourse:pr}),o.jsx(Uw,{isImportLessonsOpen:m,setIsImportLessonsOpen:h,lang:t,importStatus:g,setIsDraggingImport:y,handleCSVFileChange:v,downloadCsvTemplate:w,isDraggingImport:P,previewImportData:S,setPreviewImportData:j,setImportStatus:A,importProgress:E,importProgressTotal:R,importErrorMsg:F,setImportErrorMsg:D,handleCSVImportSubmit:O}),o.jsx(Hw,{isQuizGeneratorOpen:mr,setIsQuizGeneratorOpen:gr,lessons:k,quizGenMode:xr,setQuizGenMode:yr,quizGenSelectedLessonId:br,setQuizGenSelectedLessonId:wr,quizGenTopic:Sr,setQuizGenTopic:vr,isGeneratingSuggestions:Mt,setIsGeneratingSuggestions:kr,suggestedObjectives:Cr,setSuggestedObjectives:Er,suggestedQuestions:Wn,setSuggestedQuestions:Gn,quizGenTimeLimit:jr,setQuizGenTimeLimit:Nr,savingQuiz:Qn,setSavingQuiz:bn,quizGeneratorClassId:wn,fetchClassDashboard:_}),o.jsx(qw,{isLessonPreviewVisible:L,setIsLessonPreviewVisible:I,lessons:k,selectedLesson:N,previewFullscreenPanel:z,setPreviewFullscreenPanel:U,previewLessonTab:T,setPreviewLessonTab:M,activeRole:x,elements:oe,activeSegmentId:me,setActiveSegmentId:b,fetchElements:Q,currentVfsParent:X,setCurrentVfsParent:B,vfsNodes:Z,previewSelectedCourseware:re,setPreviewSelectedCourseware:de}),o.jsx(Ww,{showProcessLogs:xe,setShowProcessLogs:ae,processLogsContent:je,t:n}),o.jsx(Gw,{isOpen:St,onClose:()=>qt(!1),vfsNodes:Z,currentVfsParent:X,setCurrentVfsParent:B,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:kt}),o.jsx(Qw,{isSystemResourceLibraryOpen:Ot,setIsSystemResourceLibraryOpen:Y,lang:t,systemResourceTab:ne,setSystemResourceTab:le,selectedLibraryResourceId:Ne,setSelectedLibraryResourceId:He,vfsNodes:Z,currentVfsParent:X,setCurrentVfsParent:B,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:kt,loadingLibraryResources:qe,libraryResources:dt,fetchLibraryResources:Te}),o.jsx(Jw,{batchPicker:Tr,setBatchPicker:be,batchPickerLesson:Dt,setBatchPickerLesson:Jn,batchPickerDate:Zn,setBatchPickerDate:ze,batchPickerTargetClass:ft,setBatchPickerTargetClass:Pr,lessons:k,classes:$,expandedClassId:q,confirmBatchPicker:Ir,lang:t}),o.jsx(Zw,{isExportWeightModalOpen:K,setIsExportWeightModalOpen:J,lang:t,quizzesWeight:ee,setQuizzesWeight:Pe,assignmentsWeight:Ye,setAssignmentsWeight:Be,handleQuizzesWeightChange:st,handleAssignmentsWeightChange:ht,customCategoryOverrides:ge,setCustomCategoryOverrides:rt,classDashboardMap:Re,exportClassId:Ys,exportClassName:Vn,csvPreviewData:Ks,handleExportGrades:Ct}),o.jsx(Yw,{notification:Jt,onClose:()=>Ar(null),lang:t,onOpenWorkspace:pt=>{Wt(pt),gn("assignment"),Xs({}),er("quiz")}}),o.jsx(Kw,{isOpen:tr,onClose:()=>nr(!1),lang:t,onSeedSuccess:sr,onJumpTab:pt=>rr(pt)}),ir&&o.jsx(Xw,{onClose:()=>or(!1),lang:t})]})}const tS=["whiteboard.","courseware.","quiz.","rollcall."];class nS{constructor(){this.handlers=new Map}setSocketBridge(t){this.socketBridge=t}hasSocketBridge(){return!!this.socketBridge}subscribe(t,n){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(n),()=>{this.handlers.get(t)?.delete(n)}}async publish(t){const n=this.handlers.get(t.type);if(n)for(const s of n)try{s(t)}catch(r){console.error("[FrontendEventBus] handler error:",r)}this.socketBridge&&tS.some(s=>t.type.startsWith(s))&&this.socketBridge(t)}}const uu=new nS,Al=new Map;async function sS(e){const t=Al.get(e);if(t)return t;try{const n=await fetch(`/api/courseware/attempts/${encodeURIComponent(e)}/adopt`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!n.ok)return n.status!==401&&console.warn(`[LMS Bridge] Attempt adopt failed: HTTP ${n.status}`),e;const s=await n.json();return typeof s?.attemptId=="string"&&s.attemptId?(Al.set(e,s.attemptId),s.attemptId):e}catch(n){return console.warn("[LMS Bridge] Attempt adopt request failed:",n),e}}async function du(e){const t=e.data;if(!t||typeof t!="object")return;if(typeof window<"u"&&typeof document<"u"&&e.source)try{if(!Array.from(document.querySelectorAll("iframe")).some(u=>u.contentWindow===e.source)&&e.source!==window)return}catch{}let n=t.attempt_id;const s=t.type||"",r=t.payload||t;if(!n&&e.source)try{const l=Array.from(document.querySelectorAll("iframe")).find(c=>c.contentWindow===e.source);if(l&&l.contentWindow){const c=l.contentWindow;c.__LMS_STUDENT__?.attempt_id&&(n=c.__LMS_STUDENT__.attempt_id)}}catch{}if(!n||typeof n!="string")return;if(n=await sS(n),s==="LMS_CONFIG"){ls("courseware.config_reported",n,t.config??r);return}if(s==="LMS_GET_PROGRESS"){const l=t.requestId,c=e.source;if(l&&c&&typeof c.postMessage=="function"){if(typeof document<"u"&&!Array.from(document.querySelectorAll("iframe")).some(h=>h.contentWindow===c)&&c!==window){console.warn("[LMS Bridge Security] Dropping response to untrusted window");return}let u;try{u=(await(await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/progress`)).json()).progress??null}catch{u=null}const d=e.origin&&e.origin!=="null"?e.origin:"*";c.postMessage({type:"LMS_PROGRESS_RESPONSE",requestId:l,progress:u},d)}return}const i=s==="LMS_SUBMIT"||s==="LMS_FINISH"||s==="submit"||s==="finish"||s==="completed"||r&&typeof r=="object"&&(r.score!==void 0||r.grade!==void 0||r.result!==void 0||r.points!==void 0),a=s==="LMS_SAVE_PROGRESS"||s==="saveProgress";if(i){ls("courseware.submitted",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??r?.note??void 0,completion:r?.completion??1,status:"completed",extra:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to submit attempt data to backend:",l)}}else if(a){ls("courseware.progress_saved",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??void 0,completion:r?.completion??void 0,status:"inprogress",extra:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to save progress to backend:",l)}}else{ls("courseware.event_logged",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:s||"log",payload:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to log event to backend:",l)}}}function ls(e,t,n){uu.publish({id:lc(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t});try{const s=n??{};Ee(async()=>{const{whiteboardEventSlot:r}=await Promise.resolve().then(()=>iv);return{whiteboardEventSlot:r}},void 0).then(({whiteboardEventSlot:r})=>{r.ingest({source:"iframe.bridge",type:e,attemptId:t,coursewareUuid:typeof s.courseware_uuid=="string"?s.courseware_uuid:void 0,payload:{...s,attemptId:t},raw:n})})}catch{}}function rS(e,t,n,s){try{let r=s;if(!r&&e.src&&typeof window<"u")try{const i=new URL(e.src,window.location.href);i.origin&&i.origin!=="null"&&!e.src.startsWith("blob:")&&!e.src.startsWith("data:")&&(r=i.origin)}catch{}e.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:t,payload:n},r||"*")}catch{}}function hu(e){f.useEffect(()=>{if(!e)return;const t=n=>{du(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function fu(e,t={}){if(!(typeof document>"u"))try{document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"theme:changed",payload:{theme:e,tokens:t}},"*"),s.contentWindow?.postMessage({type:"LMS_THEME_CHANGED",theme:e,tokens:t},"*")}catch{}})}catch{}}function pu(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}},"*"),s.contentWindow?.postMessage({type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)},"*")}catch{}})}catch{}}const mu=Object.freeze(Object.defineProperty({__proto__:null,broadcastFontScaleToIframes:pu,broadcastThemeToIframes:fu,processLmsMessage:du,sendCommandToCourseware:rS,useLmsBridge:hu},Symbol.toStringTag,{value:"Module"}));function iS(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:r,selectedLesson:i,selectedAssignment:a,expandedClassId:l,fetchLessons:c,fetchPlugins:u,fetchRegisteredCommands:d,fetchEvents:p,fetchApprovals:m,fetchProcesses:h,fetchClasses:g,fetchTodaySchedules:y,fetchStudents:v,fetchLabs:w,fetchVfs:P,fetchProcessLogs:S,fetchClassStudents:j,fetchElements:A}=e,E=f.useRef(r),R=f.useRef(i),F=f.useRef(a),D=f.useRef(l);f.useEffect(()=>{E.current=r},[r]),f.useEffect(()=>{R.current=i},[i]),f.useEffect(()=>{F.current=a},[a]),f.useEffect(()=>{D.current=l},[l]),f.useEffect(()=>{if(!t)return;const O=t.role==="student",k=t.role==="teacher",_=k&&(t.subRole==="administrator"||t.username==="admin"||t.userId==="usr_admin");c(),u(),d(),y().catch(()=>{}),_&&(p(),m(),h()),k?(g(),v(),w(),P(E.current)):O&&E.current&&P(E.current);let L=!1;const I=setInterval(async()=>{if(!L){L=!0;try{if(_&&(await p(),await m(),await h(),n&&await S(n)),await c(),await d(),await y().catch(()=>{}),k&&(await g(),await v(),await w(),await P(E.current),D.current&&await j(D.current)),R.current&&await A(R.current),F.current){const N=s||F.current.student_id;await A(`assignment-${F.current.id}-student-${N}`)}}finally{L=!1}}},2e3);return()=>clearInterval(I)},[t,n,s]),f.useEffect(()=>{t&&(t.role==="teacher"||r)&&P(r)},[r,t]),f.useEffect(()=>{i&&A(i)},[i])}function oS(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:r,expandedClassId:i,fetchLessons:a,fetchClasses:l,fetchStudents:c,fetchClassStudents:u,fetchClassProgress:d,fetchClassDashboard:p,fetchElements:m}=e,[h,g]=f.useState([{role:"agent",content:n.agentIntro||""}]),[y,v]=f.useState(""),[w,P]=f.useState(!1),[S,j]=f.useState([]);f.useEffect(()=>{h.length===1&&h[0].role==="agent"&&g([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const A=f.useCallback(async O=>{try{const k=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(O||"")}`);if(!k.ok)return;const _=await k.json(),L=Array.isArray(_.messages)?_.messages:[];L.length>0?g(L.map(I=>({role:I.role==="assistant"?"agent":"user",content:I.content}))):g([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),E=f.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(s||"")}`,{method:"DELETE"})}catch{}g([{role:"agent",content:n.agentIntro}])},[s,n.agentIntro]);return f.useEffect(()=>{A(s)},[s,A]),{chatLog:h,setChatLog:g,input:y,setInput:v,loading:w,setLoading:P,chatAttachments:S,setChatAttachments:j,handleChatFileChange:O=>{O.target.files&&Array.from(O.target.files).forEach(k=>{const _=new FileReader;_.onload=L=>{L.target?.result&&j(I=>[...I,{name:k.name,content:L.target.result}])},k.name.endsWith(".zip")?_.readAsDataURL(k):_.readAsText(k)})},handleChatDrop:O=>{O.preventDefault(),O.dataTransfer.files&&Array.from(O.dataTransfer.files).forEach(k=>{const _=new FileReader;_.onload=L=>{L.target?.result&&j(I=>[...I,{name:k.name,content:L.target.result}])},k.name.endsWith(".zip")?_.readAsDataURL(k):_.readAsText(k)})},handleSend:async O=>{if(O.preventDefault(),!y.trim()||w)return;const k=[...S];let _=y;k.length>0&&(_+=`
134
+ (📁 ${t==="zh"?"附件":"Attachments"}: ${k.map(L=>L.name).join(", ")})`),g(L=>[...L,{role:"user",content:_}]),v(""),j([]),P(!0);try{const L=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:y,lang:t,currentLessonId:s,attachments:k,providerId:r||null})}),I=await L.json();let N="";!L.ok||I.success===!1?N=`⚠️ ${I.message||I.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(N=I.agentText||"",I.toolResults&&I.toolResults.length>0&&(N+=`
135
135
 
136
- ${n.executedCommands}`+I.toolResults.map(z=>z.callName).join(", "))),g(z=>[...z,{role:"agent",content:N}]),await a(),await l(),await c(),i&&(await u(i),await d(i),await h(i)),s&&await m(s)}catch{g(L=>[...L,{role:"agent",content:n.simulationError}])}finally{P(!1)}},handleClearAgentMemory:E,restoreAgentMemory:A}}const ut=Object.create(null);ut.open="0";ut.close="1";ut.ping="2";ut.pong="3";ut.message="4";ut.upgrade="5";ut.noop="6";const bs=Object.create(null);Object.keys(ut).forEach(e=>{bs[ut[e]]=e});const Bi={type:"error",data:"parser error"},uu=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",du=typeof ArrayBuffer=="function",hu=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,So=({type:e,data:t},n,s)=>uu&&t instanceof Blob?n?s(t):Nl(t,s):du&&(t instanceof ArrayBuffer||hu(t))?n?s(t):Nl(new Blob([t]),s):s(ut[e]+(t||"")),Nl=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function Tl(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let gi;function eS(e,t){if(uu&&e.data instanceof Blob)return e.data.arrayBuffer().then(Tl).then(t);if(du&&(e.data instanceof ArrayBuffer||hu(e.data)))return t(Tl(e.data));So(e,!1,n=>{gi||(gi=new TextEncoder),t(gi.encode(n))})}const Pl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",In=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Pl.length;e++)In[Pl.charCodeAt(e)]=e;const tS=e=>{let t=e.length*.75,n=e.length,s,r=0,i,a,l,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(s=0;s<n;s+=4)i=In[e.charCodeAt(s)],a=In[e.charCodeAt(s+1)],l=In[e.charCodeAt(s+2)],c=In[e.charCodeAt(s+3)],d[r++]=i<<2|a>>4,d[r++]=(a&15)<<4|l>>2,d[r++]=(l&3)<<6|c&63;return u},nS=typeof ArrayBuffer=="function",vo=(e,t)=>{if(typeof e!="string")return{type:"message",data:fu(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:sS(e.substring(1),t)}:bs[n]?e.length>1?{type:bs[n],data:e.substring(1)}:{type:bs[n]}:Bi},sS=(e,t)=>{if(nS){const n=tS(e);return fu(n,t)}else return{base64:!0,data:e}},fu=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},pu="",rS=(e,t)=>{const n=e.length,s=new Array(n);let r=0;e.forEach((i,a)=>{So(i,!1,l=>{s[a]=l,++r===n&&t(s.join(pu))})})},iS=(e,t)=>{const n=e.split(pu),s=[];for(let r=0;r<n.length;r++){const i=vo(n[r],t);if(s.push(i),i.type==="error")break}return s};function oS(){return new TransformStream({transform(e,t){eS(e,n=>{const s=n.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let xi;function cs(e){return e.reduce((t,n)=>t+n.length,0)}function us(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)n[r]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function aS(e,t){xi||(xi=new TextDecoder);const n=[];let s=0,r=-1,i=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(s===0){if(cs(n)<1)break;const c=us(n,1);i=(c[0]&128)===128,r=c[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(cs(n)<2)break;const c=us(n,2);r=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(cs(n)<8)break;const c=us(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(Bi);break}r=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(cs(n)<r)break;const c=us(n,r);l.enqueue(vo(i?c:xi.decode(c),t)),s=0}if(r===0||r>e){l.enqueue(Bi);break}}}})}const mu=4;function ve(e){if(e)return lS(e)}function lS(e){for(var t in ve.prototype)e[t]=ve.prototype[t];return e}ve.prototype.on=ve.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ve.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};ve.prototype.off=ve.prototype.removeListener=ve.prototype.removeAllListeners=ve.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var s,r=0;r<n.length;r++)if(s=n[r],s===t||s.fn===t){n.splice(r,1);break}return n.length===0&&delete this._callbacks["$"+e],this};ve.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,r=n.length;s<r;++s)n[s].apply(this,t)}return this};ve.prototype.emitReserved=ve.prototype.emit;ve.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};ve.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Gs=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Qe=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),cS="arraybuffer";function gu(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const uS=Qe.setTimeout,dS=Qe.clearTimeout;function Qs(e,t){t.useNativeTimers?(e.setTimeoutFn=uS.bind(Qe),e.clearTimeoutFn=dS.bind(Qe)):(e.setTimeoutFn=Qe.setTimeout.bind(Qe),e.clearTimeoutFn=Qe.clearTimeout.bind(Qe))}const hS=1.33;function fS(e){return typeof e=="string"?pS(e):Math.ceil((e.byteLength||e.size)*hS)}function pS(e){let t=0,n=0;for(let s=0,r=e.length;s<r;s++)t=e.charCodeAt(s),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}function xu(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function mS(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function gS(e){let t={},n=e.split("&");for(let s=0,r=n.length;s<r;s++){let i=n[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class xS extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class ko extends ve{constructor(t){super(),this.writable=!1,Qs(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,s){return super.emitReserved("error",new xS(t,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=vo(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_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(t){const n=mS(t);return n.length?"?"+n:""}}class yS extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};iS(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,rS(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=xu()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let yu=!1;try{yu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const bS=yu;function wS(){}class SS extends yS{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,n){const s=this.request({method:"POST",data:t});s.on("success",n),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=t}}let un=class ws extends ve{constructor(t,n,s){super(),this.createRequest=t,Qs(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const n=gu(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ws.requestsCount++,ws.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=wS,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ws.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};un.requestsCount=0;un.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Il);else if(typeof addEventListener=="function"){const e="onpagehide"in Qe?"pagehide":"unload";addEventListener(e,Il,!1)}}function Il(){for(let e in un.requests)un.requests.hasOwnProperty(e)&&un.requests[e].abort()}const vS=(function(){const e=bu({xdomain:!1});return e&&e.responseType!==null})();class kS extends SS{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=vS&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new un(bu,this.uri(),t)}}function bu(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||bS))return new XMLHttpRequest}catch{}if(!t)try{return new Qe[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const wu=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class CS extends ko{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=wu?{}:gu(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;So(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Gs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=xu()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const yi=Qe.WebSocket||Qe.MozWebSocket;class ES extends CS{createSocket(t,n,s){return wu?new yi(t,n,s):n?new yi(t,n):new yi(t)}doWrite(t,n){this.ws.send(n)}}class jS extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=aS(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),r=oS();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:l,value:c})=>{l||(this.onPacket(c),i())}).catch(l=>{})};i();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;this._writer.write(s).then(()=>{r&&Gs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const NS={websocket:ES,webtransport:jS,polling:kS},TS=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,PS=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vi(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),s=e.indexOf("]");n!=-1&&s!=-1&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let r=TS.exec(e||""),i={},a=14;for(;a--;)i[PS[a]]=r[a]||"";return n!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=IS(i,i.path),i.queryKey=AS(i,i.query),i}function IS(e,t){const n=/\/{2,9}/g,s=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function AS(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(n[r]=i)}),n}const Ui=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ss=[];Ui&&addEventListener("offline",()=>{Ss.forEach(e=>e())},!1);class zt extends ve{constructor(t,n){if(super(),this.binaryType=cS,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const s=Vi(t);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=Vi(n.host).host);Qs(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),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},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=gS(this.opts.query)),Ui&&(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"})},Ss.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=mu,n.transport=t,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&zt.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",zt.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(n+=fS(r)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Gs(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,s){return this._sendPacket("message",t,n,s),this}send(t,n,s){return this._sendPacket("message",t,n,s),this}_sendPacket(t,n,s,r){if(typeof n=="function"&&(r=n,n=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:n,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(zt.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){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(),Ui&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Ss.indexOf(this._offlineEventListener);s!==-1&&Ss.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}zt.protocol=mu;class zS extends zt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),s=!1;zt.priorWebsocketSuccess=!1;const r=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",h=>{if(!s)if(h.type==="pong"&&h.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;zt.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){s||(s=!0,d(),n.close(),n=null)}const a=h=>{const m=new Error("probe error: "+h);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function l(){a("transport closed")}function c(){a("socket closed")}function u(h){n&&h.name!==n.name&&i()}const d=()=>{n.removeListener("open",r),n.removeListener("error",a),n.removeListener("close",l),this.off("close",c),this.off("upgrading",u)};n.once("open",r),n.once("error",a),n.once("close",l),this.once("close",c),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&n.push(t[s]);return n}}let _S=class extends zS{constructor(t,n={}){const s=typeof t=="object"?t:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>NS[r]).filter(r=>!!r)),super(t,s)}};function LS(e,t="",n){let s=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),s=Vi(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}const RS=typeof ArrayBuffer=="function",OS=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Su=Object.prototype.toString,DS=typeof Blob=="function"||typeof Blob<"u"&&Su.call(Blob)==="[object BlobConstructor]",MS=typeof File=="function"||typeof File<"u"&&Su.call(File)==="[object FileConstructor]";function Co(e){return RS&&(e instanceof ArrayBuffer||OS(e))||DS&&e instanceof Blob||MS&&e instanceof File}function vs(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(vs(e[n]))return!0;return!1}if(Co(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vs(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vs(e[n]))return!0;return!1}function FS(e){const t=[],n=e.data,s=e;return s.data=ks(n,t),s.attachments=t.length,{packet:s,buffers:t}}function ks(e,t,n){if(!e)return e;if(Co(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}else if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=ks(e[r],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return ks(e.toJSON(),t,!0);const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=ks(e[r],t));return s}return e}function $S(e,t){return e.data=Hi(e.data,t),delete e.attachments,e}function Hi(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Hi(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Hi(e[n],t));return e}const BS=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ie;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ie||(ie={}));class VS{constructor(t){this.replacer=t}encode(t){return(t.type===ie.EVENT||t.type===ie.ACK)&&vs(t)?this.encodeAsBinary({type:t.type===ie.EVENT?ie.BINARY_EVENT:ie.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ie.BINARY_EVENT||t.type===ie.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=FS(t),s=this.encodeAsString(n.packet),r=n.buffers;return r.unshift(s),r}}class Eo extends ve{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const s=n.type===ie.BINARY_EVENT;s||n.type===ie.BINARY_ACK?(n.type=s?ie.EVENT:ie.ACK,this.reconstructor=new US(n)):super.emitReserved("decoded",n)}else if(Co(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const s={type:Number(t.charAt(0))};if(ie[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ie.BINARY_EVENT||s.type===ie.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const a=t.substring(i,n);if(a!=Number(a)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!HS(l)||l<1)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););s.nsp=t.substring(i,n)}else s.nsp="/";const r=t.charAt(n+1);if(r!==""&&Number(r)==r){const i=n+1;for(;++n;){const a=t.charAt(n);if(a==null||Number(a)!=a){--n;break}if(n===t.length)break}s.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(Eo.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case ie.CONNECT:return Al(n);case ie.DISCONNECT:return n===void 0;case ie.CONNECT_ERROR:return typeof n=="string"||Al(n);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&BS.indexOf(n[0])===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class US{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=$S(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const HS=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Al(e){return Object.prototype.toString.call(e)==="[object Object]"}const qS=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Eo,Encoder:VS,get PacketType(){return ie}},Symbol.toStringTag,{value:"Module"}));function et(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const WS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class vu extends ve{constructor(t,n,s){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=t,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[et(t,"open",this.onopen.bind(this)),et(t,"packet",this.onpacket.bind(this)),et(t,"error",this.onerror.bind(this)),et(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var s,r,i;if(WS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const a={type:ie.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,h=n.pop();this._registerAckCallback(d,h),a.id=d}const l=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!l||(c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,n){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},r),a=(...l)=>{this.io.clearTimeoutFn(i),n.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((s,r)=>{const i=(a,l)=>a?r(a):s(l);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(r)):(this._queue.shift(),n&&n(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ie.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ie.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 ie.EVENT:case ie.BINARY_EVENT:this.onevent(t);break;case ie.ACK:case ie.BINARY_ACK:this.onack(t);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let s=!1;return function(...r){s||(s=!0,n.packet({type:ie.ACK,id:t,data:r}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ie.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,t.data)}}}function pn(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}pn.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(Math.floor(t*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};pn.prototype.reset=function(){this.attempts=0};pn.prototype.setMin=function(e){this.ms=e};pn.prototype.setMax=function(e){this.max=e};pn.prototype.setJitter=function(e){this.jitter=e};class qi extends ve{constructor(t,n){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Qs(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new pn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const r=n.parser||qS;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new _S(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=et(n,"open",function(){s.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=et(n,"error",i);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(r),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(et(t,"ping",this.onping.bind(this)),et(t,"data",this.ondata.bind(this)),et(t,"error",this.onerror.bind(this)),et(t,"close",this.onclose.bind(this)),et(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){Gs(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new vu(this,t,n),this.nsps[t]=s),s}_destroy(t){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let s=0;s<n.length;s++)this.engine.write(n[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Pn={};function Cs(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=LS(e,t.path||"/socket.io"),s=n.source,r=n.id,i=n.path,a=Pn[r]&&i in Pn[r].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let c;return l?c=new qi(s,t):(Pn[r]||(Pn[r]=new qi(s,t)),c=Pn[r]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Cs,{Manager:qi,Socket:vu,io:Cs,connect:Cs});class GS{constructor(t=""){this.baseUrl=t}async get(t){return this.request("GET",t)}async post(t,n){return this.request("POST",t,n)}async del(t){return this.request("DELETE",t)}async request(t,n,s){try{const r=`${this.baseUrl}${n}`,i={method:t,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return s!==void 0&&t!=="GET"&&t!=="DELETE"&&(i.body=JSON.stringify(s)),await(await fetch(r,i)).json()}catch(r){return{success:!1,error:r.message??"Network error"}}}}class QS{constructor(t){this.modalState=null,this.addToastFn=t??null}showToast(t,n,s="info"){this.addToastFn?this.addToastFn(t,n,s):console.warn("[UIService] No addToast callback registered — toast not shown:",t,n)}showModal(t,n){this.modalState={visible:!0,title:t,content:n}}closeModal(){this.modalState=null}getModalState(){return this.modalState}downloadFile(t,n,s="application/octet-stream"){const r=typeof t=="string"?new Blob([t],{type:s}):t,i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}}class JS{constructor(t){this.prefix=`edu_os_plugin:${t}:`}get(t){return localStorage.getItem(this.prefix+t)}set(t,n){localStorage.setItem(this.prefix+t,n)}delete(t){localStorage.removeItem(this.prefix+t)}clear(){this.prefix.length;const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);s&&s.startsWith(this.prefix)&&t.push(s)}for(const n of t)localStorage.removeItem(n)}}const ku=200;function ZS(e){return{id:e.id,type:e.type,source:`whiteboard.slot.${e.source}`,payload:{lessonId:e.lessonId,elementId:e.elementId,coursewareUuid:e.coursewareUuid,attemptId:e.attemptId,studentId:e.studentId,studentName:e.studentName,...e.payload,__raw:e.raw},timestamp:e.timestamp,correlationId:e.lessonId}}class Cu{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??ku,this.persist=t.persist??!1}ingest(t){const n={id:sc(),timestamp:Date.now(),...t};this.buffer.push(n),this.buffer.length>this.capacity&&this.buffer.shift(),this.dispatch(n);try{const s=ZS(n);ru.publish(s)}catch(s){typeof console<"u"&&console.warn("[WhiteboardEventSlot] frontendEventBus publish failed:",s)}return this.persist&&typeof indexedDB<"u"&&this.persistEvent(n),n}emit(t,n,s={}){return this.ingest({...s,type:t,source:s.source??"manual",payload:n})}subscribe(t,n,s={}){const r={filter:t,handler:n};if(this.subscriptions.push(r),t.types)for(const i of t.types)this.byType.has(i)||this.byType.set(i,new Set),this.byType.get(i).add(r);if(s.replay&&s.replay>0){const i=this.query(t,{limit:s.replay});queueMicrotask(()=>{for(const a of i)try{n(a)}catch(l){console.error("[WhiteboardEventSlot] replay handler error:",l)}})}return()=>{const i=this.subscriptions.indexOf(r);if(i>=0&&this.subscriptions.splice(i,1),t.types)for(const a of t.types)this.byType.get(a)?.delete(r)}}query(t={},n={}){const s=n.limit??this.capacity,r=n.since??0,i=[];for(let a=this.buffer.length-1;a>=0;a--){const l=this.buffer[a];if(l.timestamp<r||zl(l,t)&&(i.push(l),i.length>=s))break}return i}stats(){const t={},n={};for(const s of this.buffer)t[s.type]=(t[s.type]??0)+1,n[s.source]=(n[s.source]??0)+1;return{total:this.buffer.length,byType:t,bySource:n}}clear(){this.buffer=[]}size(){return this.buffer.length}dispatch(t){const n=t.type?this.byType.get(t.type):void 0,s=n?Array.from(n):this.subscriptions;for(const r of s)if(zl(t,r.filter))try{r.handler(t)}catch(i){console.error("[WhiteboardEventSlot] handler error:",i)}}async persistEvent(t){if(!(typeof indexedDB>"u"))try{const n=await YS(),s=n.transaction("events","readwrite");s.objectStore("events").put(t),await new Promise((i,a)=>{s.oncomplete=()=>i(),s.onerror=()=>a(s.error)}),n.close()}catch{}}}function zl(e,t){return!(t.types&&t.types.length>0&&!t.types.includes(e.type)||t.sources&&t.sources.length>0&&!t.sources.includes(e.source)||t.lessonId&&e.lessonId!==t.lessonId||t.elementId&&e.elementId!==t.elementId||t.coursewareUuid&&e.coursewareUuid!==t.coursewareUuid||t.studentId&&e.studentId!==t.studentId||t.predicate&&!t.predicate(e))}let ds=null;function YS(){return ds||(ds=new Promise((e,t)=>{const n=indexedDB.open("whiteboard-event-slot",1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains("events")||s.createObjectStore("events",{keyPath:"id"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),ds)}const At=new Cu({capacity:ku,persist:!1}),KS=Object.freeze(Object.defineProperty({__proto__:null,WhiteboardEventSlot:Cu,whiteboardEventSlot:At},Symbol.toStringTag,{value:"Module"})),Wi=new Set;function XS(e){return Wi.add(e),()=>{Wi.delete(e)}}const _l=30,Ll=(e,t)=>Math.min(e,t.length);function jo(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [${e.type.toUpperCase()}] ${e.title}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
137
- `)}function Eu(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [学生端异常] ${e.studentName||e.studentId} - ${e.title}`,`- **学生信息**: ${e.studentName||"未知"} (\`${e.studentId}\`)`,`- **关联课节**: ${e.lessonId||"未指定"}`,`- **关联班级**: ${e.classId||"未指定"}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
138
- `)}function ev(e,t=[]){const n=new Date().toLocaleString(),s=typeof window<"u"?window.location.href:"Unknown",r=typeof navigator<"u"?navigator.userAgent:"Unknown";if(e.length===0&&t.length===0)return`# 🛠️ OpenLearn 系统诊断报告
136
+ ${n.executedCommands}`+I.toolResults.map(z=>z.callName).join(", "))),g(z=>[...z,{role:"agent",content:N}]),await a(),await l(),await c(),i&&(await u(i),await d(i),await p(i)),s&&await m(s)}catch{g(L=>[...L,{role:"agent",content:n.simulationError}])}finally{P(!1)}},handleClearAgentMemory:E,restoreAgentMemory:A}}const ut=Object.create(null);ut.open="0";ut.close="1";ut.ping="2";ut.pong="3";ut.message="4";ut.upgrade="5";ut.noop="6";const bs=Object.create(null);Object.keys(ut).forEach(e=>{bs[ut[e]]=e});const Hi={type:"error",data:"parser error"},gu=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",xu=typeof ArrayBuffer=="function",yu=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ko=({type:e,data:t},n,s)=>gu&&t instanceof Blob?n?s(t):zl(t,s):xu&&(t instanceof ArrayBuffer||yu(t))?n?s(t):zl(new Blob([t]),s):s(ut[e]+(t||"")),zl=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function _l(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let yi;function aS(e,t){if(gu&&e.data instanceof Blob)return e.data.arrayBuffer().then(_l).then(t);if(xu&&(e.data instanceof ArrayBuffer||yu(e.data)))return t(_l(e.data));ko(e,!1,n=>{yi||(yi=new TextEncoder),t(yi.encode(n))})}const Ll="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",An=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Ll.length;e++)An[Ll.charCodeAt(e)]=e;const lS=e=>{let t=e.length*.75,n=e.length,s,r=0,i,a,l,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(s=0;s<n;s+=4)i=An[e.charCodeAt(s)],a=An[e.charCodeAt(s+1)],l=An[e.charCodeAt(s+2)],c=An[e.charCodeAt(s+3)],d[r++]=i<<2|a>>4,d[r++]=(a&15)<<4|l>>2,d[r++]=(l&3)<<6|c&63;return u},cS=typeof ArrayBuffer=="function",Co=(e,t)=>{if(typeof e!="string")return{type:"message",data:bu(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:uS(e.substring(1),t)}:bs[n]?e.length>1?{type:bs[n],data:e.substring(1)}:{type:bs[n]}:Hi},uS=(e,t)=>{if(cS){const n=lS(e);return bu(n,t)}else return{base64:!0,data:e}},bu=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},wu="",dS=(e,t)=>{const n=e.length,s=new Array(n);let r=0;e.forEach((i,a)=>{ko(i,!1,l=>{s[a]=l,++r===n&&t(s.join(wu))})})},hS=(e,t)=>{const n=e.split(wu),s=[];for(let r=0;r<n.length;r++){const i=Co(n[r],t);if(s.push(i),i.type==="error")break}return s};function fS(){return new TransformStream({transform(e,t){aS(e,n=>{const s=n.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let bi;function cs(e){return e.reduce((t,n)=>t+n.length,0)}function us(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)n[r]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function pS(e,t){bi||(bi=new TextDecoder);const n=[];let s=0,r=-1,i=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(s===0){if(cs(n)<1)break;const c=us(n,1);i=(c[0]&128)===128,r=c[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(cs(n)<2)break;const c=us(n,2);r=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(cs(n)<8)break;const c=us(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(Hi);break}r=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(cs(n)<r)break;const c=us(n,r);l.enqueue(Co(i?c:bi.decode(c),t)),s=0}if(r===0||r>e){l.enqueue(Hi);break}}}})}const Su=4;function ve(e){if(e)return mS(e)}function mS(e){for(var t in ve.prototype)e[t]=ve.prototype[t];return e}ve.prototype.on=ve.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ve.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};ve.prototype.off=ve.prototype.removeListener=ve.prototype.removeAllListeners=ve.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var s,r=0;r<n.length;r++)if(s=n[r],s===t||s.fn===t){n.splice(r,1);break}return n.length===0&&delete this._callbacks["$"+e],this};ve.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,r=n.length;s<r;++s)n[s].apply(this,t)}return this};ve.prototype.emitReserved=ve.prototype.emit;ve.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};ve.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Js=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Je=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),gS="arraybuffer";function vu(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const xS=Je.setTimeout,yS=Je.clearTimeout;function Zs(e,t){t.useNativeTimers?(e.setTimeoutFn=xS.bind(Je),e.clearTimeoutFn=yS.bind(Je)):(e.setTimeoutFn=Je.setTimeout.bind(Je),e.clearTimeoutFn=Je.clearTimeout.bind(Je))}const bS=1.33;function wS(e){return typeof e=="string"?SS(e):Math.ceil((e.byteLength||e.size)*bS)}function SS(e){let t=0,n=0;for(let s=0,r=e.length;s<r;s++)t=e.charCodeAt(s),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}function ku(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function vS(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function kS(e){let t={},n=e.split("&");for(let s=0,r=n.length;s<r;s++){let i=n[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class CS extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class Eo extends ve{constructor(t){super(),this.writable=!1,Zs(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,s){return super.emitReserved("error",new CS(t,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=Co(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_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(t){const n=vS(t);return n.length?"?"+n:""}}class ES extends Eo{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};hS(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,dS(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=ku()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let Cu=!1;try{Cu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const jS=Cu;function NS(){}class TS extends ES{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,n){const s=this.request({method:"POST",data:t});s.on("success",n),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=t}}let un=class ws extends ve{constructor(t,n,s){super(),this.createRequest=t,Zs(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const n=vu(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ws.requestsCount++,ws.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=NS,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ws.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};un.requestsCount=0;un.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Rl);else if(typeof addEventListener=="function"){const e="onpagehide"in Je?"pagehide":"unload";addEventListener(e,Rl,!1)}}function Rl(){for(let e in un.requests)un.requests.hasOwnProperty(e)&&un.requests[e].abort()}const PS=(function(){const e=Eu({xdomain:!1});return e&&e.responseType!==null})();class IS extends TS{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=PS&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new un(Eu,this.uri(),t)}}function Eu(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||jS))return new XMLHttpRequest}catch{}if(!t)try{return new Je[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ju=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class AS extends Eo{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=ju?{}:vu(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;ko(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Js(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=ku()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const wi=Je.WebSocket||Je.MozWebSocket;class zS extends AS{createSocket(t,n,s){return ju?new wi(t,n,s):n?new wi(t,n):new wi(t)}doWrite(t,n){this.ws.send(n)}}class _S extends Eo{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=pS(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),r=fS();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:l,value:c})=>{l||(this.onPacket(c),i())}).catch(l=>{})};i();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;this._writer.write(s).then(()=>{r&&Js(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const LS={websocket:zS,webtransport:_S,polling:IS},RS=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,OS=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function qi(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),s=e.indexOf("]");n!=-1&&s!=-1&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let r=RS.exec(e||""),i={},a=14;for(;a--;)i[OS[a]]=r[a]||"";return n!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=MS(i,i.path),i.queryKey=DS(i,i.query),i}function MS(e,t){const n=/\/{2,9}/g,s=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function DS(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(n[r]=i)}),n}const Wi=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ss=[];Wi&&addEventListener("offline",()=>{Ss.forEach(e=>e())},!1);class zt extends ve{constructor(t,n){if(super(),this.binaryType=gS,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const s=qi(t);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=qi(n.host).host);Zs(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),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},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=kS(this.opts.query)),Wi&&(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"})},Ss.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=Su,n.transport=t,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&zt.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",zt.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(n+=wS(r)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Js(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,s){return this._sendPacket("message",t,n,s),this}send(t,n,s){return this._sendPacket("message",t,n,s),this}_sendPacket(t,n,s,r){if(typeof n=="function"&&(r=n,n=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:n,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(zt.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){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(),Wi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Ss.indexOf(this._offlineEventListener);s!==-1&&Ss.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}zt.protocol=Su;class FS extends zt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),s=!1;zt.priorWebsocketSuccess=!1;const r=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!s)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;zt.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){s||(s=!0,d(),n.close(),n=null)}const a=p=>{const m=new Error("probe error: "+p);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function l(){a("transport closed")}function c(){a("socket closed")}function u(p){n&&p.name!==n.name&&i()}const d=()=>{n.removeListener("open",r),n.removeListener("error",a),n.removeListener("close",l),this.off("close",c),this.off("upgrading",u)};n.once("open",r),n.once("error",a),n.once("close",l),this.once("close",c),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&n.push(t[s]);return n}}let $S=class extends FS{constructor(t,n={}){const s=typeof t=="object"?t:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>LS[r]).filter(r=>!!r)),super(t,s)}};function BS(e,t="",n){let s=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),s=qi(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}const VS=typeof ArrayBuffer=="function",US=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Nu=Object.prototype.toString,HS=typeof Blob=="function"||typeof Blob<"u"&&Nu.call(Blob)==="[object BlobConstructor]",qS=typeof File=="function"||typeof File<"u"&&Nu.call(File)==="[object FileConstructor]";function jo(e){return VS&&(e instanceof ArrayBuffer||US(e))||HS&&e instanceof Blob||qS&&e instanceof File}function vs(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(vs(e[n]))return!0;return!1}if(jo(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vs(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vs(e[n]))return!0;return!1}function WS(e){const t=[],n=e.data,s=e;return s.data=ks(n,t),s.attachments=t.length,{packet:s,buffers:t}}function ks(e,t,n){if(!e)return e;if(jo(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}else if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=ks(e[r],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return ks(e.toJSON(),t,!0);const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=ks(e[r],t));return s}return e}function GS(e,t){return e.data=Gi(e.data,t),delete e.attachments,e}function Gi(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Gi(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Gi(e[n],t));return e}const QS=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ie;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ie||(ie={}));class JS{constructor(t){this.replacer=t}encode(t){return(t.type===ie.EVENT||t.type===ie.ACK)&&vs(t)?this.encodeAsBinary({type:t.type===ie.EVENT?ie.BINARY_EVENT:ie.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ie.BINARY_EVENT||t.type===ie.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=WS(t),s=this.encodeAsString(n.packet),r=n.buffers;return r.unshift(s),r}}class No extends ve{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const s=n.type===ie.BINARY_EVENT;s||n.type===ie.BINARY_ACK?(n.type=s?ie.EVENT:ie.ACK,this.reconstructor=new ZS(n)):super.emitReserved("decoded",n)}else if(jo(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const s={type:Number(t.charAt(0))};if(ie[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ie.BINARY_EVENT||s.type===ie.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const a=t.substring(i,n);if(a!=Number(a)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!YS(l)||l<1)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););s.nsp=t.substring(i,n)}else s.nsp="/";const r=t.charAt(n+1);if(r!==""&&Number(r)==r){const i=n+1;for(;++n;){const a=t.charAt(n);if(a==null||Number(a)!=a){--n;break}if(n===t.length)break}s.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(No.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case ie.CONNECT:return Ol(n);case ie.DISCONNECT:return n===void 0;case ie.CONNECT_ERROR:return typeof n=="string"||Ol(n);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&QS.indexOf(n[0])===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ZS{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=GS(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const YS=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Ol(e){return Object.prototype.toString.call(e)==="[object Object]"}const KS=Object.freeze(Object.defineProperty({__proto__:null,Decoder:No,Encoder:JS,get PacketType(){return ie}},Symbol.toStringTag,{value:"Module"}));function et(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const XS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Tu extends ve{constructor(t,n,s){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=t,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[et(t,"open",this.onopen.bind(this)),et(t,"packet",this.onpacket.bind(this)),et(t,"error",this.onerror.bind(this)),et(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var s,r,i;if(XS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const a={type:ie.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,p=n.pop();this._registerAckCallback(d,p),a.id=d}const l=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!l||(c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,n){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},r),a=(...l)=>{this.io.clearTimeoutFn(i),n.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((s,r)=>{const i=(a,l)=>a?r(a):s(l);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(r)):(this._queue.shift(),n&&n(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ie.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ie.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 ie.EVENT:case ie.BINARY_EVENT:this.onevent(t);break;case ie.ACK:case ie.BINARY_ACK:this.onack(t);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let s=!1;return function(...r){s||(s=!0,n.packet({type:ie.ACK,id:t,data:r}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ie.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,t.data)}}}function mn(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}mn.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(Math.floor(t*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};mn.prototype.reset=function(){this.attempts=0};mn.prototype.setMin=function(e){this.ms=e};mn.prototype.setMax=function(e){this.max=e};mn.prototype.setJitter=function(e){this.jitter=e};class Qi extends ve{constructor(t,n){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Zs(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new mn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const r=n.parser||KS;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new $S(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=et(n,"open",function(){s.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=et(n,"error",i);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(r),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(et(t,"ping",this.onping.bind(this)),et(t,"data",this.ondata.bind(this)),et(t,"error",this.onerror.bind(this)),et(t,"close",this.onclose.bind(this)),et(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){Js(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new Tu(this,t,n),this.nsps[t]=s),s}_destroy(t){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let s=0;s<n.length;s++)this.engine.write(n[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const In={};function Cs(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=BS(e,t.path||"/socket.io"),s=n.source,r=n.id,i=n.path,a=In[r]&&i in In[r].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let c;return l?c=new Qi(s,t):(In[r]||(In[r]=new Qi(s,t)),c=In[r]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Cs,{Manager:Qi,Socket:Tu,io:Cs,connect:Cs});class ev{constructor(t=""){this.baseUrl=t}async get(t){return this.request("GET",t)}async post(t,n){return this.request("POST",t,n)}async del(t){return this.request("DELETE",t)}async request(t,n,s){try{const r=`${this.baseUrl}${n}`,i={method:t,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return s!==void 0&&t!=="GET"&&t!=="DELETE"&&(i.body=JSON.stringify(s)),await(await fetch(r,i)).json()}catch(r){return{success:!1,error:r.message??"Network error"}}}}class tv{constructor(t){this.modalState=null,this.addToastFn=t??null}showToast(t,n,s="info"){this.addToastFn?this.addToastFn(t,n,s):console.warn("[UIService] No addToast callback registered — toast not shown:",t,n)}showModal(t,n){this.modalState={visible:!0,title:t,content:n}}closeModal(){this.modalState=null}getModalState(){return this.modalState}downloadFile(t,n,s="application/octet-stream"){const r=typeof t=="string"?new Blob([t],{type:s}):t,i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}}class nv{constructor(t){this.prefix=`edu_os_plugin:${t}:`}get(t){return localStorage.getItem(this.prefix+t)}set(t,n){localStorage.setItem(this.prefix+t,n)}delete(t){localStorage.removeItem(this.prefix+t)}clear(){this.prefix.length;const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);s&&s.startsWith(this.prefix)&&t.push(s)}for(const n of t)localStorage.removeItem(n)}}const Pu=200;function sv(e){return{id:e.id,type:e.type,source:`whiteboard.slot.${e.source}`,payload:{lessonId:e.lessonId,elementId:e.elementId,coursewareUuid:e.coursewareUuid,attemptId:e.attemptId,studentId:e.studentId,studentName:e.studentName,...e.payload,__raw:e.raw},timestamp:e.timestamp,correlationId:e.lessonId}}class Iu{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??Pu,this.persist=t.persist??!1}ingest(t){const n={id:lc(),timestamp:Date.now(),...t};this.buffer.push(n),this.buffer.length>this.capacity&&this.buffer.shift(),this.dispatch(n);try{const s=sv(n);uu.publish(s)}catch(s){typeof console<"u"&&console.warn("[WhiteboardEventSlot] frontendEventBus publish failed:",s)}return this.persist&&typeof indexedDB<"u"&&this.persistEvent(n),n}emit(t,n,s={}){return this.ingest({...s,type:t,source:s.source??"manual",payload:n})}subscribe(t,n,s={}){const r={filter:t,handler:n};if(this.subscriptions.push(r),t.types)for(const i of t.types)this.byType.has(i)||this.byType.set(i,new Set),this.byType.get(i).add(r);if(s.replay&&s.replay>0){const i=this.query(t,{limit:s.replay});queueMicrotask(()=>{for(const a of i)try{n(a)}catch(l){console.error("[WhiteboardEventSlot] replay handler error:",l)}})}return()=>{const i=this.subscriptions.indexOf(r);if(i>=0&&this.subscriptions.splice(i,1),t.types)for(const a of t.types)this.byType.get(a)?.delete(r)}}query(t={},n={}){const s=n.limit??this.capacity,r=n.since??0,i=[];for(let a=this.buffer.length-1;a>=0;a--){const l=this.buffer[a];if(l.timestamp<r||Ml(l,t)&&(i.push(l),i.length>=s))break}return i}stats(){const t={},n={};for(const s of this.buffer)t[s.type]=(t[s.type]??0)+1,n[s.source]=(n[s.source]??0)+1;return{total:this.buffer.length,byType:t,bySource:n}}clear(){this.buffer=[]}size(){return this.buffer.length}dispatch(t){const n=t.type?this.byType.get(t.type):void 0,s=n?Array.from(n):this.subscriptions;for(const r of s)if(Ml(t,r.filter))try{r.handler(t)}catch(i){console.error("[WhiteboardEventSlot] handler error:",i)}}async persistEvent(t){if(!(typeof indexedDB>"u"))try{const n=await rv(),s=n.transaction("events","readwrite");s.objectStore("events").put(t),await new Promise((i,a)=>{s.oncomplete=()=>i(),s.onerror=()=>a(s.error)}),n.close()}catch{}}}function Ml(e,t){return!(t.types&&t.types.length>0&&!t.types.includes(e.type)||t.sources&&t.sources.length>0&&!t.sources.includes(e.source)||t.lessonId&&e.lessonId!==t.lessonId||t.elementId&&e.elementId!==t.elementId||t.coursewareUuid&&e.coursewareUuid!==t.coursewareUuid||t.studentId&&e.studentId!==t.studentId||t.predicate&&!t.predicate(e))}let ds=null;function rv(){return ds||(ds=new Promise((e,t)=>{const n=indexedDB.open("whiteboard-event-slot",1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains("events")||s.createObjectStore("events",{keyPath:"id"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),ds)}const At=new Iu({capacity:Pu,persist:!1}),iv=Object.freeze(Object.defineProperty({__proto__:null,WhiteboardEventSlot:Iu,whiteboardEventSlot:At},Symbol.toStringTag,{value:"Module"})),Ji=new Set;function ov(e){return Ji.add(e),()=>{Ji.delete(e)}}const Dl=30,Fl=(e,t)=>Math.min(e,t.length);function To(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [${e.type.toUpperCase()}] ${e.title}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
137
+ `)}function Au(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [学生端异常] ${e.studentName||e.studentId} - ${e.title}`,`- **学生信息**: ${e.studentName||"未知"} (\`${e.studentId}\`)`,`- **关联课节**: ${e.lessonId||"未指定"}`,`- **关联班级**: ${e.classId||"未指定"}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
138
+ `)}function av(e,t=[]){const n=new Date().toLocaleString(),s=typeof window<"u"?window.location.href:"Unknown",r=typeof navigator<"u"?navigator.userAgent:"Unknown";if(e.length===0&&t.length===0)return`# 🛠️ OpenLearn 系统诊断报告
139
139
  - 生成时间: ${n}
140
140
  - 暂无记录的系统异常。`;const i=e.length+t.length,a=["# 🛠️ OpenLearn 系统异常诊断报告",`- **生成时间**: ${n}`,`- **当前页面**: ${s}`,`- **异常总数**: ${i} 项`,`- **本机异常数**: ${e.length} 项`,`- **学生端异常数**: ${t.length} 项`,`- **运行环境**: ${r}`,"","---",""].join(`
141
141
  `),l=e.length>0?`## 💻 本机异常记录 (${e.length})
142
142
 
143
143
  `+e.map((u,d)=>`#### 错误 #${d+1} (${u.type.toUpperCase()})
144
- `+jo(u)).join(`
144
+ `+To(u)).join(`
145
145
 
146
146
  ---
147
147
 
148
148
  `):"",c=t.length>0?`## 🎒 学生端异常记录 (${t.length})
149
149
 
150
150
  `+t.map((u,d)=>`#### 学生异常 #${d+1}
151
- `+Eu(u)).join(`
151
+ `+Au(u)).join(`
152
152
 
153
153
  ---
154
154
 
@@ -156,7 +156,7 @@ ${n.executedCommands}`+I.toolResults.map(z=>z.callName).join(", "))),g(z=>[...z,
156
156
 
157
157
  ---
158
158
 
159
- `)}const Bt=Mn((e,t)=>({errors:[],studentErrors:[],activeTab:"local",isErrorCenterOpen:!1,unreadCount:0,addError:n=>{const s=Date.now(),r=n.url||(typeof window<"u"?window.location.href:""),i=n.userAgent||(typeof navigator<"u"?navigator.userAgent:""),a=t().errors.findIndex(c=>c.type===n.type&&c.message===n.message&&s-c.timestamp<2e3);if(a>=0)return t().errors[a];const l={id:`err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:n.timestamp||s,url:r,userAgent:i,type:n.type,title:n.title,message:n.message,stack:n.stack,componentStack:n.componentStack,endpoint:n.endpoint,status:n.status};return e(c=>{const u=[l,...c.errors].slice(0,_l);return{errors:u,unreadCount:Ll(c.unreadCount+1,u)}}),Wi.forEach(c=>{try{c(l)}catch(u){console.error("[ErrorStore] Error in errorListener:",u)}}),l},removeError:n=>e(s=>{const r=s.errors.filter(i=>i.id!==n);return{errors:r,unreadCount:Ll(s.unreadCount,r)}}),clearErrors:()=>e({errors:[],unreadCount:0}),addStudentError:n=>{const s=Date.now(),r=n.timestamp||s;e(i=>i.studentErrors.some(u=>u.studentId===n.studentId&&u.type===n.type&&u.message===n.message&&Math.abs(r-u.timestamp)<2e3)?i:{studentErrors:[{...n,id:n.id||`st_err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:r},...i.studentErrors].slice(0,_l)})},removeStudentError:n=>e(s=>({studentErrors:s.studentErrors.filter(r=>r.id!==n)})),clearStudentErrors:()=>e({studentErrors:[]}),setIsErrorCenterOpen:n=>e({isErrorCenterOpen:n,unreadCount:n?0:t().unreadCount}),setActiveTab:n=>e({activeTab:n}),markAllRead:()=>e({unreadCount:0})}));function it(e){return $s(Bt,e||(t=>t))}function tv(e){const{session:t,host:n,activeRole:s,activeStudentId:r,selectedLesson:i,activeSegmentId:a,studentViewStatus:l,lang:c,students:u,addToast:d,setOnlineStudentIds:h,setActiveStudentLessons:m,setLessons:f,setActiveSegmentId:g,setLiveClassStudentProgress:y,setLiveClassAcknowledgedMap:C,setLiveClassFeed:w,setSelectedLesson:P,setStudentViewStatus:S,studentLessonTab:j,setStudentLessonTab:A,selectedAssignment:E,setSelectedAssignment:R,setLocalProgressPercent:F,fetchStudentDashboard:M,fetchStudents:O,fetchElements:v}=e,_=p.useRef(null),L=p.useRef(s),I=p.useRef(r),N=p.useRef(c),z=p.useRef(u),U=p.useRef(d),T=p.useRef(i),D=p.useRef(null),x=p.useRef(l),oe=p.useRef(j),me=p.useRef(null);return p.useEffect(()=>{L.current=s},[s]),p.useEffect(()=>{I.current=r},[r]),p.useEffect(()=>{N.current=c},[c]),p.useEffect(()=>{z.current=u},[u]),p.useEffect(()=>{U.current=d},[d]),p.useEffect(()=>{T.current=i},[i]),p.useEffect(()=>{x.current=l},[l]),p.useEffect(()=>{oe.current=j},[j]),p.useEffect(()=>{D.current=E},[E]),p.useEffect(()=>{if(!t)return;const b=Cs();_.current=b,ic(b),n.isInitialized()||n.initialize(new GS,new mm(b),new QS(U.current),new JS("__app__"));const Q=()=>{b.emit("join-room","whiteboard-broadcast"),L.current==="student"&&I.current?(b.emit("register-student",{studentId:I.current,name:z.current.find(B=>B.id===I.current)?.name||I.current}),x.current==="lesson"&&T.current&&b.emit("enter-lesson",{studentId:I.current,lessonId:T.current})):b.emit("request-presence")};Q(),b.on("presence-update",B=>{h(B.onlineStudentIds),m(B.activeStudentLessons)}),b.on("lesson-progress-mode-changed",B=>{const{lessonId:Z,progressMode:re,progressConditions:de}=B;f(xe=>xe.map(ae=>ae.id===Z?{...ae,progress_mode:re,progress_conditions:de}:ae))}),b.on("student-active-segment-changed",B=>{const{activeSegmentId:Z}=B;g(Z)}),b.on("student-pinged",B=>{const Z=B.message||(N.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");d(N.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",Z,"warning")}),b.on("student-progress-updated",B=>{const{studentId:Z,progressPercent:re,completed:de}=B;y(xe=>{const ae=xe.findIndex(je=>je.student_id===Z);if(ae!==-1){const je=[...xe];return je[ae]={...je[ae],progress_percent:re,completed:de?1:0},je}else return[...xe,{student_id:Z,progress_percent:re,completed:de?1:0}]})}),b.on("student-error-alert",B=>{if(!(!B||!B.error)&&(L.current==="teacher"||t?.role==="administrator")){Bt.getState().addStudentError({...B.error,studentId:B.studentId,studentName:B.studentName||B.studentId,lessonId:B.lessonId,classId:B.classId});const Z=B.studentName?`${B.studentName} (${B.studentId})`:B.studentId;d(N.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${Z}: ${B.error.title||B.error.message}`,"warning")}}),b.on("assignment-graded-toast",B=>{if(L.current==="student"&&I.current&&B.studentId===I.current){const Z=B.assignmentTitle||B.assignmentId,re=N.current==="zh"?`您的作业"${Z}"已完成评分!得分:${B.score}%。建议反馈已收到,快去查看。`:`Your assignment "${Z}" was graded. Score: ${B.score}%. Tutoring feedback has been posted.`;d(N.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",re,"success"),M(I.current)}}),b.on("student-picked",B=>{if(L.current==="student"&&I.current&&B.studentId===I.current){const Z=N.current==="zh"?"闪电警报!您已被老师在课程随机提问点名中抽中!请立即集中注意力参与课堂。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";d(N.current==="zh"?"⚡️ 随机点名提问":"⚡️ Classroom Pick Alert",Z,"warning"),M(I.current)}w(Z=>[{id:`feed-pick-${B.studentId}-${B.pickedTime||Date.now()}`,time:new Date(B.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:N.current==="zh"?`点名互动:随机抽中学生【${B.studentName}】。`:`Classroom Pick: Randomly selected student "${B.studentName}".`},...Z])}),b.on("student-acknowledged",B=>{const{studentId:Z}=B;C(re=>{const de=new Map(re);return de.set(Z,!0),de}),w(re=>[{id:`feed-ack-${Z}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:N.current==="zh"?`学生已确认收到提问点名(学生 ID: ${Z})。`:`Student acknowledged the classroom call (Student ID: ${Z}).`},...re]),O()}),b.on("class-lock-status-changed",B=>{const{lessonId:Z,locked:re}=B;L.current==="student"&&I.current?(Promise.resolve(O()).then(()=>{re&&Z&&(P(Z),S("lesson"),d(N.current==="zh"?"🔒 课程已被锁定":"🔒 Lesson Locked",N.current==="zh"?"老师已锁定当前授课,您将无法切换到其他页面。":"The teacher has locked the active lesson. You cannot leave this page.","info"))}),M(I.current)):O()}),b.on("student-lesson-tab-changed",B=>{L.current==="student"&&B?.tab&&(!B.lessonId||B.lessonId===T.current)&&A(B.tab)}),b.on("teacher-switched-lesson",B=>{L.current==="student"&&B?.lessonId&&(P(B.lessonId),S("lesson"))}),b.on("whiteboard-sync",B=>{const{roomId:Z,type:re}=B||{};re==="refresh"&&Z&&(v(Z),!T.current&&L.current==="student"&&(P(Z),S("lesson")),b.emit("join-room",Z))});const X=()=>{ln.getState().clearRemoteFullscreen();const B=me.current;me.current=null,B&&(A(B.lessonTab),B.viewStatus==="assignment"&&(R(B.assignment??null),B.lessonId&&P(B.lessonId),S("assignment")))};return b.on("whiteboard-fullscreen-changed",B=>{if(L.current!=="student")return;const Z=B?.lessonId,re=B?.elementId??null;if(!re){X();return}if(!Z)return;const de=x.current;(de==="lesson"?T.current===Z:de==="assignment")&&(ln.getState().remoteFullscreenElementId||(me.current={viewStatus:de,lessonTab:oe.current,lessonId:T.current,assignment:de==="assignment"?D.current:null}),ln.getState().setRemoteFullscreenElementId(re),de==="assignment"&&R(null),P(Z),v(Z),S("lesson"),A("whiteboard"))}),b.on("connect",()=>{Q(),X()}),b.io?.on("reconnect",()=>{Q()}),b.on("whiteboard-quiz-answered",B=>{try{if(!B)return;At.ingest({source:"widget.quiz",type:"quiz.answered",lessonId:B.lessonId,elementId:B.elementId,studentId:B.studentId,studentName:B.studentName,payload:{answer:B.answer,score:typeof B.score=="number"?B.score:void 0,isCorrect:!!B.isCorrect,correctAnswer:B.correctAnswer,question:B.question,time:B.time},raw:B})}catch(Z){console.error("[useClassroomSocket] quiz.answered ingest failed",Z)}}),b.on("courseware-attempt-updated",B=>{try{if(!B||typeof B.attemptId!="string")return;const Z=B.type==="log"?"courseware.event_logged":B.type==="submit"?"courseware.submitted":B.type==="promote"?"courseware.finished":"courseware.event_logged";At.ingest({source:"iframe.bridge",type:Z,attemptId:B.attemptId,payload:{attemptId:B.attemptId,attemptType:B.type},raw:B})}catch(Z){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",Z)}}),()=>{b.disconnect(),_.current=null}},[t,s,r]),p.useEffect(()=>{_.current&&s==="student"&&r&&(l==="lesson"&&i?(_.current.emit("enter-lesson",{studentId:r,lessonId:i}),fetch(`/api/students/${r}/progress`).then(b=>b.json()).then(b=>{if(Array.isArray(b)){const Q=b.find(X=>X.lesson_id===i);F(Q?Q.progress_percent:0)}}).catch(console.error)):_.current.emit("leave-lesson",{studentId:r}))},[l,i,s,r]),p.useEffect(()=>{s==="teacher"&&i&&a&&_.current&&_.current.emit("teacher-broadcast-segment",{lessonId:i,activeSegmentId:a})},[a,i,s]),{socketRef:_}}const nv=`exports.default = {
159
+ `)}const Bt=hn((e,t)=>({errors:[],studentErrors:[],activeTab:"local",isErrorCenterOpen:!1,unreadCount:0,addError:n=>{const s=Date.now(),r=n.url||(typeof window<"u"?window.location.href:""),i=n.userAgent||(typeof navigator<"u"?navigator.userAgent:""),a=t().errors.findIndex(c=>c.type===n.type&&c.message===n.message&&s-c.timestamp<2e3);if(a>=0)return t().errors[a];const l={id:`err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:n.timestamp||s,url:r,userAgent:i,type:n.type,title:n.title,message:n.message,stack:n.stack,componentStack:n.componentStack,endpoint:n.endpoint,status:n.status};return e(c=>{const u=[l,...c.errors].slice(0,Dl);return{errors:u,unreadCount:Fl(c.unreadCount+1,u)}}),Ji.forEach(c=>{try{c(l)}catch(u){console.error("[ErrorStore] Error in errorListener:",u)}}),l},removeError:n=>e(s=>{const r=s.errors.filter(i=>i.id!==n);return{errors:r,unreadCount:Fl(s.unreadCount,r)}}),clearErrors:()=>e({errors:[],unreadCount:0}),addStudentError:n=>{const s=Date.now(),r=n.timestamp||s;e(i=>i.studentErrors.some(u=>u.studentId===n.studentId&&u.type===n.type&&u.message===n.message&&Math.abs(r-u.timestamp)<2e3)?i:{studentErrors:[{...n,id:n.id||`st_err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:r},...i.studentErrors].slice(0,Dl)})},removeStudentError:n=>e(s=>({studentErrors:s.studentErrors.filter(r=>r.id!==n)})),clearStudentErrors:()=>e({studentErrors:[]}),setIsErrorCenterOpen:n=>e({isErrorCenterOpen:n,unreadCount:n?0:t().unreadCount}),setActiveTab:n=>e({activeTab:n}),markAllRead:()=>e({unreadCount:0})}));function it(e){return Vs(Bt,e||(t=>t))}function lv(e){const{session:t,host:n,activeRole:s,activeStudentId:r,selectedLesson:i,activeSegmentId:a,studentViewStatus:l,lang:c,students:u,addToast:d,setOnlineStudentIds:p,setActiveStudentLessons:m,setLessons:h,setActiveSegmentId:g,setLiveClassStudentProgress:y,setLiveClassAcknowledgedMap:v,setLiveClassFeed:w,setSelectedLesson:P,setStudentViewStatus:S,studentLessonTab:j,setStudentLessonTab:A,selectedAssignment:E,setSelectedAssignment:R,setLocalProgressPercent:F,fetchStudentDashboard:D,fetchStudents:O,fetchElements:k}=e,_=f.useRef(null),L=f.useRef(s),I=f.useRef(r),N=f.useRef(c),z=f.useRef(u),U=f.useRef(d),T=f.useRef(i),M=f.useRef(null),x=f.useRef(l),oe=f.useRef(j),me=f.useRef(null);return f.useEffect(()=>{L.current=s},[s]),f.useEffect(()=>{I.current=r},[r]),f.useEffect(()=>{N.current=c},[c]),f.useEffect(()=>{z.current=u},[u]),f.useEffect(()=>{U.current=d},[d]),f.useEffect(()=>{T.current=i},[i]),f.useEffect(()=>{x.current=l},[l]),f.useEffect(()=>{oe.current=j},[j]),f.useEffect(()=>{M.current=E},[E]),f.useEffect(()=>{if(!t)return;const b=Cs();_.current=b,uc(b),n.isInitialized()||n.initialize(new ev,new Sm(b),new tv(U.current),new nv("__app__"));const Q=()=>{b.emit("join-room","whiteboard-broadcast"),L.current==="student"&&I.current?(b.emit("register-student",{studentId:I.current,name:z.current.find(B=>B.id===I.current)?.name||I.current}),x.current==="lesson"&&T.current&&b.emit("enter-lesson",{studentId:I.current,lessonId:T.current})):b.emit("request-presence")};Q(),b.on("presence-update",B=>{p(B.onlineStudentIds),m(B.activeStudentLessons)}),b.on("lesson-progress-mode-changed",B=>{const{lessonId:Z,progressMode:re,progressConditions:de}=B;h(xe=>xe.map(ae=>ae.id===Z?{...ae,progress_mode:re,progress_conditions:de}:ae))}),b.on("student-active-segment-changed",B=>{const{activeSegmentId:Z}=B;g(Z)}),b.on("student-pinged",B=>{const Z=B.message||(N.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");d(N.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",Z,"warning")}),b.on("student-progress-updated",B=>{const{studentId:Z,progressPercent:re,completed:de}=B;y(xe=>{const ae=xe.findIndex(je=>je.student_id===Z);if(ae!==-1){const je=[...xe];return je[ae]={...je[ae],progress_percent:re,completed:de?1:0},je}else return[...xe,{student_id:Z,progress_percent:re,completed:de?1:0}]})}),b.on("student-error-alert",B=>{if(!(!B||!B.error)&&(L.current==="teacher"||t?.role==="administrator")){Bt.getState().addStudentError({...B.error,studentId:B.studentId,studentName:B.studentName||B.studentId,lessonId:B.lessonId,classId:B.classId});const Z=B.studentName?`${B.studentName} (${B.studentId})`:B.studentId;d(N.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${Z}: ${B.error.title||B.error.message}`,"warning")}}),b.on("assignment-graded-toast",B=>{if(L.current==="student"&&I.current&&B.studentId===I.current){const Z=B.assignmentTitle||B.assignmentId,re=N.current==="zh"?`您的作业"${Z}"已完成评分!得分:${B.score}%。建议反馈已收到,快去查看。`:`Your assignment "${Z}" was graded. Score: ${B.score}%. Tutoring feedback has been posted.`;d(N.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",re,"success"),D(I.current)}}),b.on("student-picked",B=>{if(L.current==="student"&&I.current&&B.studentId===I.current){const Z=N.current==="zh"?"闪电警报!您已被老师在课程随机提问点名中抽中!请立即集中注意力参与课堂。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";d(N.current==="zh"?"⚡️ 随机点名提问":"⚡️ Classroom Pick Alert",Z,"warning"),D(I.current)}w(Z=>[{id:`feed-pick-${B.studentId}-${B.pickedTime||Date.now()}`,time:new Date(B.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:N.current==="zh"?`点名互动:随机抽中学生【${B.studentName}】。`:`Classroom Pick: Randomly selected student "${B.studentName}".`},...Z])}),b.on("student-acknowledged",B=>{const{studentId:Z}=B;v(re=>{const de=new Map(re);return de.set(Z,!0),de}),w(re=>[{id:`feed-ack-${Z}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:N.current==="zh"?`学生已确认收到提问点名(学生 ID: ${Z})。`:`Student acknowledged the classroom call (Student ID: ${Z}).`},...re]),O()}),b.on("class-lock-status-changed",B=>{const{lessonId:Z,locked:re}=B;L.current==="student"&&I.current?(Promise.resolve(O()).then(()=>{re&&Z&&(P(Z),S("lesson"),d(N.current==="zh"?"🔒 课程已被锁定":"🔒 Lesson Locked",N.current==="zh"?"老师已锁定当前授课,您将无法切换到其他页面。":"The teacher has locked the active lesson. You cannot leave this page.","info"))}),D(I.current)):O()}),b.on("student-lesson-tab-changed",B=>{L.current==="student"&&B?.tab&&(!B.lessonId||B.lessonId===T.current)&&A(B.tab)}),b.on("teacher-switched-lesson",B=>{L.current==="student"&&B?.lessonId&&(P(B.lessonId),S("lesson"))}),b.on("whiteboard-sync",B=>{const{roomId:Z,type:re}=B||{};re==="refresh"&&Z&&(k(Z),!T.current&&L.current==="student"&&(P(Z),S("lesson")),b.emit("join-room",Z))});const X=()=>{ln.getState().clearRemoteFullscreen();const B=me.current;me.current=null,B&&(A(B.lessonTab),B.viewStatus==="assignment"&&(R(B.assignment??null),B.lessonId&&P(B.lessonId),S("assignment")))};return b.on("whiteboard-fullscreen-changed",B=>{if(L.current!=="student")return;const Z=B?.lessonId,re=B?.elementId??null;if(!re){X();return}if(!Z)return;const de=x.current;(de==="lesson"?T.current===Z:de==="assignment")&&(ln.getState().remoteFullscreenElementId||(me.current={viewStatus:de,lessonTab:oe.current,lessonId:T.current,assignment:de==="assignment"?M.current:null}),ln.getState().setRemoteFullscreenElementId(re),de==="assignment"&&R(null),P(Z),k(Z),S("lesson"),A("whiteboard"))}),b.on("connect",()=>{Q(),X()}),b.io?.on("reconnect",()=>{Q()}),b.on("whiteboard-quiz-answered",B=>{try{if(!B)return;At.ingest({source:"widget.quiz",type:"quiz.answered",lessonId:B.lessonId,elementId:B.elementId,studentId:B.studentId,studentName:B.studentName,payload:{answer:B.answer,score:typeof B.score=="number"?B.score:void 0,isCorrect:!!B.isCorrect,correctAnswer:B.correctAnswer,question:B.question,time:B.time},raw:B})}catch(Z){console.error("[useClassroomSocket] quiz.answered ingest failed",Z)}}),b.on("courseware-attempt-updated",B=>{try{if(!B||typeof B.attemptId!="string")return;const Z=B.type==="log"?"courseware.event_logged":B.type==="submit"?"courseware.submitted":B.type==="promote"?"courseware.finished":"courseware.event_logged";At.ingest({source:"iframe.bridge",type:Z,attemptId:B.attemptId,payload:{attemptId:B.attemptId,attemptType:B.type},raw:B})}catch(Z){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",Z)}}),()=>{b.disconnect(),_.current=null}},[t,s,r]),f.useEffect(()=>{_.current&&s==="student"&&r&&(l==="lesson"&&i?(_.current.emit("enter-lesson",{studentId:r,lessonId:i}),fetch(`/api/students/${r}/progress`).then(b=>b.json()).then(b=>{if(Array.isArray(b)){const Q=b.find(X=>X.lesson_id===i);F(Q?Q.progress_percent:0)}}).catch(console.error)):_.current.emit("leave-lesson",{studentId:r}))},[l,i,s,r]),f.useEffect(()=>{s==="teacher"&&i&&a&&_.current&&_.current.emit("teacher-broadcast-segment",{lessonId:i,activeSegmentId:a})},[a,i,s]),{socketRef:_}}const cv=`exports.default = {
160
160
  manifest: {
161
161
  id: "@my-scope/hello-world",
162
162
  name: "Hello World Plugin",
@@ -166,15 +166,15 @@ ${n.executedCommands}`+I.toolResults.map(z=>z.callName).join(", "))),g(z=>[...z,
166
166
  activate: async (ctx) => {
167
167
  ctx.log.info('Hello World plugin activated');
168
168
  }
169
- };`;function sv(e){const{session:t,host:n,lang:s,addToast:r,setChatLog:i,setTeacherTab:a,fetchLessons:l}=e,[c,u]=p.useState([]),[d,h]=p.useState([]),[m,f]=p.useState(!1),[g,y]=p.useState(null),[C,w]=p.useState(""),[P,S]=p.useState(""),[j,A]=p.useState(""),[E,R]=p.useState(""),[F,M]=p.useState(null),[O,v]=p.useState(!1),[_,L]=p.useState("store"),[I,N]=p.useState(nv),[z,U]=p.useState(!1),[T,D]=p.useState([]),[x,oe]=p.useState([]),[me,b]=p.useState({}),Q=p.useRef(new Set),X=p.useCallback(async()=>{try{const Y=await fetch("/api/plugins");if(Y.ok){const ne=await Y.json();u(ne)}}catch(Y){console.warn("Failed to fetch plugins",Y)}},[]),B=p.useCallback(async()=>{try{const Y=await fetch("/api/ai-providers");if(Y.ok){const ne=await Y.json();h(ne)}}catch(Y){console.warn("Failed to fetch AI Providers",Y)}},[]);p.useEffect(()=>{X(),t&&t.role!=="student"&&B()},[X,B,t?.role]);const Z=p.useCallback(async()=>{try{const Y=await fetch("/api/events");Y.ok&&D(await Y.json())}catch{}},[]),re=p.useCallback(async()=>{try{const Y=await fetch("/api/approvals");Y.ok&&oe(await Y.json())}catch{}},[]);return{plugins:c,setPlugins:u,fetchPlugins:X,aiProviders:d,setAiProviders:h,fetchAIProviders:B,isAIProviderModalOpen:m,setIsAIProviderModalOpen:f,editingAIProvider:g,setEditingAIProvider:y,providerName:C,setProviderName:w,providerApiUrl:P,setProviderApiUrl:S,providerApiKey:j,setProviderApiKey:A,providerModelName:E,setProviderModelName:R,testingProviderId:F,setTestingProviderId:M,showPluginModal:O,setShowPluginModal:v,storeTab:_,setStoreTab:L,pluginCode:I,setPluginCode:N,installingPlugin:z,setInstallingPlugin:U,events:T,setEvents:D,fetchEvents:Z,approvals:x,setApprovals:oe,fetchApprovals:re,scoreOverrides:me,setScoreOverrides:b,handleSaveAIProvider:async()=>{if(!C.trim()||!P.trim()||!E.trim()){r(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let Y;if(g?Y=await fetch(`/api/ai-providers/${g.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C,api_url:P,api_key:j,model_name:E})}):Y=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C,api_url:P,api_key:j,model_name:E})}),Y.ok)r(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${C}] 已保存。`:`AI Provider [${C}] has been updated.`,"success"),f(!1),y(null),w(""),S(""),A(""),R(""),B();else{const ne=await Y.json().catch(()=>({}));r(s==="zh"?"保存失败":"Failed to Save",ne.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(Y){console.error(Y),r(s==="zh"?"保存异常":"Execution Error",Y.message||"Error occurred","warning")}},handleDeleteAIProvider:async(Y,ne)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${ne}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${ne}]?`))try{(await fetch(`/api/ai-providers/${Y}`,{method:"DELETE"})).ok?(r(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${ne}] 已经被清除。`:`AI Provider [${ne}] has been removed.`,"success"),B()):r(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(le){console.error(le),r(s==="zh"?"操作异常":"Execution Error",le.message||"Error occurred","warning")}},handleTestAIProvider:async Y=>{M(Y.id);try{const ne=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:Y.api_url,api_key:Y.api_key,model_name:Y.model_name})}),le=await ne.json();ne.ok&&le.success?r(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${Y.name}]。${le.message}`:`Successfully connected to [${Y.name}]. ${le.message}`,"success"):r(s==="zh"?"测试失败":"Test Failed",le.error||"Connection error","warning")}catch(ne){console.error(ne),r(s==="zh"?"连接异常":"Connection Exception",ne.message||"Error occurred","warning")}finally{M(null)}},handleInstallPlugin:async()=>{if(I.trim()){U(!0);try{const ne=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:I})})).json();ne.success?(await X(),v(!1),i(le=>[...le,{role:"agent",content:`[System] Plugin "${ne.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+ne.error)}catch(Y){alert("Error: "+Y.message)}finally{U(!1)}}},handleZipPluginUpload:async(Y,ne,le)=>{U(!0);const Ne=le?.mode==="update";try{const Ue={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(Y.name),"X-Execution-Mode":ne,"X-Install-Mode":Ne?"update":"install","X-Allow-Downgrade":le?.allowDowngrade?"true":"false"};le?.targetPluginId&&(Ue["X-Target-Plugin-Id"]=encodeURIComponent(le.targetPluginId));const He=Ne&&le?.targetPluginId?`/api/plugins/${encodeURIComponent(le.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",dt=await fetch(He,{method:"POST",headers:Ue,body:Y}),Te=await dt.json().catch(()=>({}));if(!dt.ok||!Te.success){const J=Te.error||"Unknown error";throw r(s==="zh"?Ne?"更新失败":"安装失败":Ne?"Update Failed":"Installation Failed",J,"error"),new Error(J)}const $=Te.pluginId||Te.manifest?.pluginId||Te.manifest?.id,q=!!(Te.updated||Ne);if(!q&&$)await fetch(`/api/plugins/${encodeURIComponent($)}/toggle`,{method:"POST"}).catch(()=>{});else if(q&&Te.wasActive&&$)try{await n.deactivatePlugin($)}catch{}a("plugins"),L("store"),await X(),setTimeout(()=>{X()},1e3);const K=Te.manifest?.name||$||Y.name;if(q){const J=Te.oldVersion||"?",ee=Te.newVersion||Te.manifest?.version||"?";r(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${K}" 已从 v${J} 更新到 v${ee}(配置与数据已保留)`:`"${K}" updated v${J} → v${ee} (config & data preserved)`,"success"),i(Pe=>[...Pe,{role:"agent",content:`[System] Plugin "${K}" updated ${J} → ${ee}.`}])}else r(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${K}" 已成功上传并以 [${ne==="worker"?"Worker 隔离":"VM 嵌入"}] 模式激活运行!`:`Plugin "${K}" installed and activated in [${ne}] mode!`,"success"),i(J=>[...J,{role:"agent",content:`[System] Plugin "${K}" installed successfully from ZIP file.`}])}catch(Ue){const He=Ue?.message?String(Ue.message):"";throw He&&He!=="Failed to fetch"&&He!=="Network error"||r(s==="zh"?"网络错误":"Network Error",He||"Network error","error"),Ue}finally{U(!1)}},handleTogglePlugin:async Y=>{if(!Q.current.has(Y)){Q.current.add(Y);try{const ne=await fetch(`/api/plugins/${encodeURIComponent(Y)}/toggle`,{method:"POST"}),le=await ne.json().catch(()=>({}));if(ne.ok)await X();else{const Ne=le.error||"Unknown error";Ne.includes("requires human approval")||Ne.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await re()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+Ne)}}catch(ne){console.error("Failed to toggle plugin:",ne),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{Q.current.delete(Y)}}},handleDeletePlugin:async Y=>{if(window.confirm(s==="zh"?"确定要彻底删除该插件吗?删除后此插件相关的功能将无法使用。":"Are you sure you want to completely delete this plugin? This cannot be undone."))try{const ne=await fetch(`/api/plugins/${encodeURIComponent(Y)}`,{method:"DELETE"});if(ne.ok)a("plugins"),L("store"),await X(),i(le=>[...le,{role:"agent",content:"[System] Plugin uninstalled and deleted."}]);else{const le=await ne.json().catch(()=>({}));alert(le.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(ne){console.error("Failed to delete plugin:",ne),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},handleApprove:async(Y,ne)=>{try{const Ne=await(await fetch(`/api/approvals/${Y}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:ne})})).json();Ne.success?(await re(),await l(),await X()):alert("Action failed: "+Ne.error)}catch(le){console.error(le)}},handleReject:async Y=>{try{await fetch(`/api/approvals/${Y}/reject`,{method:"POST"}),await re(),await X()}catch(ne){console.error(ne)}}}}function rv(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:r,setTeacherTab:i}=e,[a,l]=p.useState(!1),[c,u]=p.useState(1),[d,h]=p.useState(""),[m,f]=p.useState("Mathematics"),[g,y]=p.useState(""),[C,w]=p.useState(""),[P,S]=p.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"}]),[j,A]=p.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:l,wizardStep:c,setWizardStep:u,wizardCourseTitle:d,setWizardCourseTitle:h,wizardCourseCategory:m,setWizardCourseCategory:f,wizardCourseDescription:g,setWizardCourseDescription:y,wizardCourseContent:C,setWizardCourseContent:w,wizardCourseTimeline:P,setWizardCourseTimeline:S,wizardIsSubmitting:j,setWizardIsSubmitting:A,handleDeployWizardCourse:async()=>{if(!d.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}A(!0);try{const R=C.trim()||`Course outline for ${d} (${m})`,F=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,content:R})});if(F.ok){const O=(await F.json()).result?.lessonId;O&&await fetch(`/api/lessons/${O}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:P})}),await s(),O&&(r(O),i("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${d}》已成功保存到核心SQLite并已自动激活!`:`Course "${d}" is now live in SQLite and auto-activated.`,"success"),l(!1),h(""),f("Mathematics"),y(""),w(""),u(1)}else n("Error","SQLite save failed","warning")}catch(R){console.error(R),n("Error","Launch Exception","warning")}finally{A(!1)}}}}function iv(){const[e,t]=p.useState(!1),[n,s]=p.useState(null),[r,i]=p.useState("scan_lesson"),[a,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(!1),[m,f]=p.useState([]),[g,y]=p.useState([]),[C,w]=p.useState(!1),[P,S]=p.useState({}),[j,A]=p.useState(10),[E,R]=p.useState("quiz"),F=p.useRef(P);return p.useEffect(()=>{F.current=P},[P]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:r,setQuizGenMode:i,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:l,quizGenTopic:c,setQuizGenTopic:u,isGeneratingSuggestions:d,setIsGeneratingSuggestions:h,suggestedObjectives:m,setSuggestedObjectives:f,suggestedQuestions:g,setSuggestedQuestions:y,savingQuiz:C,setSavingQuiz:w,quizStudentAnswers:P,setQuizStudentAnswers:S,quizGenTimeLimit:j,setQuizGenTimeLimit:A,quizStudentAnswersRef:F,subAssignmentTab:E,setSubAssignmentTab:R}}function ov(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:r,fetchClassStudents:i,handleExportAllClassesCombined:a}=e,[l,c]=p.useState(!1),[u,d]=p.useState(new Set),[h,m]=p.useState(new Set),[f,g]=p.useState(null),[y,C]=p.useState(""),[w,P]=p.useState(""),[S,j]=p.useState("");return{batchMode:l,setBatchMode:c,selectedClassIds:u,setSelectedClassIds:d,selectedStudentIds:h,setSelectedStudentIds:m,batchPicker:f,setBatchPicker:g,batchPickerLesson:y,setBatchPickerLesson:C,batchPickerDate:w,setBatchPickerDate:P,batchPickerTargetClass:S,setBatchPickerTargetClass:j,toggleClassSelection:T=>{d(D=>{const x=new Set(D);return x.has(T)?x.delete(T):x.add(T),x})},toggleSelectAllClasses:()=>{d(T=>T.size===n.length&&n.length>0?new Set:new Set(n.map(D=>D.id)))},toggleStudentSelection:T=>{m(D=>{const x=new Set(D);return x.has(T)?x.delete(T):x.add(T),x})},toggleSelectAllStudents:T=>{m(D=>D.size===T.length&&T.length>0?new Set:new Set(T.map(x=>x.id)))},handleBatchDeleteClasses:async()=>{if(u.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${u.size} 个班级吗?该操作不可恢复。`:`Delete ${u.size} selected classes permanently?`)){for(const T of u)await fetch(`/api/classes/${T}`,{method:"DELETE"});d(new Set),await r()}},handleBatchExportClasses:async()=>{u.size!==0&&await a(n.filter(T=>u.has(T.id)))},handleBatchSetPasscode:async()=>{if(u.size===0)return;const T=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(T!==null){for(const D of u)await fetch(`/api/classes/${D}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:T===""?null:T})});d(new Set),await r()}},handleBatchScheduleClasses:()=>{u.size!==0&&(C(""),P(new Date().toISOString().split("T")[0]),g("schedule"))},handleBatchDeleteStudents:async()=>{if(!(h.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${h.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${h.size} selected student accounts?`)){for(const T of h)await fetch(`/api/students/${T}`,{method:"DELETE"});m(new Set),await i(s)}},handleBatchResetPassword:async()=>{if(h.size===0||!s)return;const T=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(T===null||T.trim()==="")){for(const D of h)await fetch(`/api/students/${D}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:T})});m(new Set),await i(s)}},handleBatchTransferStudents:()=>{h.size===0||!s||(j(""),g("transfer"))},handleBatchSetLockedLesson:()=>{h.size===0||!s||(C(""),g("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(f==="schedule"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const T of u)await fetch(`/api/classes/${T}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:y,scheduledDate:w+" 09:00:00",status:"scheduled"})});d(new Set)}else if(f==="lockedLesson"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const T of h)await fetch(`/api/students/${T}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:y})});m(new Set)}else if(f==="transfer"){if(!S||S===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const T of h)await fetch(`/api/classes/${s}/students/${T}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:T})});m(new Set)}g(null),s&&await i(s)}}}}function av(){const[e,t]=p.useState([]),[n,s]=p.useState(!1),[r,i]=p.useState({lab_id:null,seats:[]}),[a,l]=p.useState(!1),[c,u]=p.useState([]),[d,h]=p.useState({}),[m,f]=p.useState({}),[g,y]=p.useState(null),[C,w]=p.useState(""),[P,S]=p.useState(""),j=p.useCallback(async()=>{try{s(!0);const M=await fetch("/api/labs");M.ok&&t(await M.json())}catch(M){console.error(M)}finally{s(!1)}},[]),A=p.useCallback(async M=>{try{const O=await fetch(`/api/classes/${M}/seats`);if(O.ok){const v=await O.json();i(v)}}catch(O){console.error(O)}},[]),E=p.useCallback(async()=>{try{const M=new Date().toISOString().split("T")[0],O=await fetch(`/api/schedules/today?date=${M}`);if(O.ok){const v=await O.json();v.success&&v.schedules&&u(v.schedules)}}catch(M){console.warn("Failed to fetch today schedules",M)}},[]),R=p.useCallback(async M=>{try{const O=await fetch(`/api/classes/${M}/schedules`);if(O.ok){const v=await O.json();h(_=>({..._,[M]:v}))}}catch{}},[]),F=p.useCallback(async M=>{try{const O=await fetch(`/api/schedules/${M}/attendance`);if(O.ok){const v=await O.json();f(_=>({..._,[M]:v}))}}catch{}},[]);return{computerLabs:e,setComputerLabs:t,loadingLabs:n,setLoadingLabs:s,fetchLabs:j,classSeats:r,setClassSeats:i,savingSeats:a,setSavingSeats:l,fetchClassSeats:A,todaySchedules:c,setTodaySchedules:u,fetchTodaySchedules:E,classSchedulesMap:d,setClassSchedulesMap:h,fetchClassSchedules:R,scheduleAttendanceMap:m,setScheduleAttendanceMap:f,fetchScheduleAttendance:F,expandedScheduleId:g,setExpandedScheduleId:y,newScheduleDate:C,setNewScheduleDate:w,newScheduleLessonId:P,setNewScheduleLessonId:S}}function lv(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[r,i]=p.useState([]),[a,l]=p.useState("seg-1"),[c,u]=p.useState(null),[d,h]=p.useState(null),[m,f]=p.useState("none"),[g,y]=p.useState(null),[C,w]=p.useState(!0),P=p.useRef(null),S=async(j,A)=>{f("saving");try{(await fetch(`/api/lessons/${j}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:A})})).ok?(s(R=>R.map(F=>F.id===j?{...F,timeline:JSON.stringify(A)}:F)),i(A),f("saved"),y(new Date)):f("error")}catch(E){console.error("Failed to save timeline:",E),f("error")}};return p.useEffect(()=>{if(t){const j=n.find(A=>A.id===t);if(j){let A=[];if(j.timeline)try{A=typeof j.timeline=="string"?JSON.parse(j.timeline):j.timeline}catch{A=[{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 A=[{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"}];i(A);const E=P.current!==t;P.current=t,A.length>0?(E||!A.some(R=>R.id===a))&&l(A[0].id):l(null)}}},[t,n]),{timelineSegments:r,setTimelineSegments:i,activeSegmentId:a,setActiveSegmentId:l,segmentToEdit:c,setSegmentToEdit:u,draggedSegmentIdx:d,setDraggedSegmentIdx:h,editorSaveStatus:m,setEditorSaveStatus:f,editorLastSavedTime:g,setEditorLastSavedTime:y,editorPanelsExpanded:C,setEditorPanelsExpanded:w,saveTimeline:S}}function cv(e,t,n){const[s,r]=p.useState(new Set),[i,a]=p.useState(null),[l,c]=p.useState(!1),u=p.useMemo(()=>{if(e!=="student"||!t)return[];const h=[],m=t.assignments||[];for(const g of m)if(!g.submission_status)h.push({id:`new-${g.id}`,type:"new_assignment",title:n==="zh"?"新发布作业":"New Assignment",message:n==="zh"?`您有一项新作业:"${g.title}"`:`You have a new assignment: ${g.title}`,date:g.created_at,relatedId:g.id});else if(g.submission_status==="graded"){const y=!!g.feedback;h.push({id:`graded-${g.id}`,type:"graded",title:y?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:y?n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%。反馈:"${g.feedback}"`:`Your assignment "${g.title}" was graded. Score: ${g.score}%. Teacher feedback: "${g.feedback}"`:n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%`:`Your assignment "${g.title}" was graded. Score: ${g.score}%`,date:g.submitted_at||g.created_at,relatedId:g.id})}const f=t.rollcalls||[];for(const g of f)h.push({id:g.id,type:"rollcall_picked",title:n==="zh"?"⚡️ 随机提问选中通知":"⚡️ Random Pick Notification",message:n==="zh"?`您已被老师在课程"${g.lesson_title||"课堂"}"中随机选中提问!请立即确认您的出勤与注意。`:`You have been randomly picked by the teacher in lesson "${g.lesson_title||"Class"}"! Please pay immediate attention.`,date:g.picked_time,relatedId:g.lesson_id});return h.sort((g,y)=>y.date-g.date)},[e,t,n]),d=p.useMemo(()=>u.filter(h=>!s.has(h.id)),[u,s]);return{studentNotifications:u,unreadNotifications:d,readNotifications:s,setReadNotifications:r,selectedNotificationForModal:i,setSelectedNotificationForModal:a,isNotificationsOpen:l,setIsNotificationsOpen:c}}function ju(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
170
- `)?`"${t.replace(/"/g,'""')}"`:t}async function uv(e){const{classId:t,className:n,students:s,dashData:r,lang:i,addToast:a,setIsGeneratingPDFReport:l}=e;l(c=>({...c,[t]:!0}));try{if(!r){a(i==="zh"?"暂无班级评分数据":"No Class Performance Data",i==="zh"?"请确保在此班级加载了作业与测验。":"Please check if assignments or quizzes are present for this class.","warning");return}const c=r.performance||[],u=r.assignments||[],d={};s.forEach(z=>{d[z.id]={id:z.id,name:z.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(z=>{const U=z.student_id;d[U]&&(d[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&d[U].submittedCount++,z.score!==null&&z.score!==void 0&&(d[U].totalGradesSum+=z.score,d[U].gradedCount++))});const h=Object.values(d).map(z=>{const U=z.gradedCount>0?z.totalGradesSum/z.gradedCount:0,T=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avgScore:U,submissionRate:T}});h.sort((z,U)=>U.avgScore-z.avgScore);let m=0,f=0,g=0,y=0;c.forEach(z=>{y++,(z.submission_status==="submitted"||z.submission_status==="graded")&&g++,z.score!==null&&z.score!==void 0&&(m+=z.score,f++)});const C=f>0?m/f:0,w=y>0?g/y*100:0,P={};u.forEach(z=>{P[z.id]={id:z.id,title:z.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(z=>{const U=z.assignment_id;P[U]&&(P[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&P[U].submittedCount++,z.score!==null&&z.score!==void 0&&P[U].scores.push(z.score))});const S=Object.values(P).map(z=>{const U=z.scores.length,T=z.scores.reduce((b,Q)=>b+Q,0),D=U>0?T/U:0,x=U>0?Math.max(...z.scores):0,oe=U>0?Math.min(...z.scores):0,me=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avg:D,max:x,min:oe,subRate:me}}),j=new Np({orientation:"p",unit:"mm",format:"a4"}),A=[15,23,42],E=[79,70,229],R=[51,65,85],F=[226,232,240],M=z=>{j.setDrawColor(F[0],F[1],F[2]),j.setLineWidth(.3),j.line(14,z,196,z)};j.setFillColor(A[0],A[1],A[2]),j.rect(0,0,210,42,"F"),j.setTextColor(255,255,255),j.setFont("helvetica","bold"),j.setFontSize(20),j.text("CLASS PERFORMANCE REPORT",14,18),j.setFont("helvetica","normal"),j.setFontSize(10),j.setTextColor(194,205,225),j.text("Academic Insights • Generative Report Summary",14,25),j.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),j.setFillColor(E[0],E[1],E[2]),j.rect(172,10,24,24,"F"),j.setFont("helvetica","bold"),j.setFontSize(14),j.setTextColor(255,255,255),j.text("OS",180,26);let O=52;j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("I. EXECUTIVE OVERVIEW",14,O),O+=6;const v=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${u.length} items`],["Global Assignment Submission Rate",`${w.toFixed(1)}%`],["Class Average Performance Score",`${C.toFixed(1)}%`]];j.autoTable({startY:O,head:[["Metric Indicator","Class-wide Metric Value"]],body:v,theme:"striped",headStyles:{fillColor:A,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:R,fontSize:9.5},margin:{left:14,right:14}}),O=j.lastAutoTable.finalY+12,j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("II. STUDENT RANKING DISTRIBUTION",14,O),O+=6;const _=h.map((z,U)=>{let T="Excellent";return z.avgScore>=90?T="Excellent (A)":z.avgScore>=75?T="Good (B)":z.avgScore>=60?T="Satisfactory (C)":T="Needs Improvement (D)",[`${U+1}`,z.name,`${z.submittedCount}/${z.totalCount} (${z.submissionRate.toFixed(0)}%)`,`${z.avgScore.toFixed(1)}%`,T]});j.autoTable({startY:O,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:_,theme:"grid",headStyles:{fillColor:E,textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},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}}),O=j.lastAutoTable.finalY+12,O>210&&(j.addPage(),O=20),j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("III. ASSIGNMENT PERFORMANCE METRICS",14,O),O+=6;const L=S.map(z=>[z.title,`${z.subRate.toFixed(0)}%`,`${z.avg.toFixed(1)}%`,`${z.min.toFixed(0)}% - ${z.max.toFixed(0)}%`]);j.autoTable({startY:O,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:L.length>0?L:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),O=j.lastAutoTable.finalY+15,M(275),j.setFontSize(8),j.setTextColor(148,163,184),j.text("Generated by OpenLearn Next • Educational Operating System",14,282),j.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const I=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),N=new Date().toISOString().split("T")[0];j.save(`Class_Report_${I}_${N}.pdf`),a(i==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",i==="zh"?`班级【${n}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${n} saved to your device.`,"success")}catch(c){console.error("PDF Generation Failed:",c),a(i==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",c.message||"Error occurred during PDF generation","warning")}finally{l(c=>({...c,[t]:!1}))}}function dv(e){const{className:t,students:n,dashData:s,qWeight:r=40,aWeight:i=60,overrides:a={}}=e;if(!s||!s.assignments){alert("No performance data available to export. Please open the dashboard to load class data first.");return}if(n.length===0){alert("No students in this class to export grades for.");return}const l=s.assignments||[],c=s.performance||[],u=l.map(S=>{let j="assignment";if(a[S.id])j=a[S.id];else{const A=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),E=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));j=A||E?"quiz":"assignment"}return{...S,category:j}}),d=["Student Name","Student Email"];u.forEach(S=>{const j=S.category==="quiz"?"Quiz":"Assignment";d.push(`${j}: ${S.title}`)}),d.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const h=[d];n.forEach(S=>{const j=[S.name,S.email];let A=0,E=0,R=0,F=0,M=0,O=0,v=0;u.forEach(T=>{const D=c.find(x=>x.assignment_id===T.id&&x.student_id===S.id);if(D&&D.score!==null&&D.score!==void 0){j.push(`${D.score}%`);const x=Number(D.score);T.category==="quiz"?(A+=x,E++):(R+=x,F++),M+=x,O++,v++}else D&&D.submission_status==="submitted"?(j.push("Pending Grade"),v++):j.push("Not Submitted")});const _=E>0?Math.round(A/E):null,L=F>0?Math.round(R/F):null;let I="N/A";if(_!==null&&L!==null){const T=_*(r/100)+L*(i/100);I=`${Math.round(T)}%`}else _!==null?I=`${_}%`:L!==null&&(I=`${L}%`);const N=_!==null?`${_}%`:"N/A",z=L!==null?`${L}%`:"N/A",U=O>0?`${Math.round(M/O)}%`:"N/A";j.push(N,z,I,U,`${v}`,`${l.length}`),h.push(j.map(ju))});const m=h.map(S=>S.join(",")).join(`
171
- `),f=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8;"}),g=URL.createObjectURL(f),y=document.createElement("a"),C=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),w=new Date().toISOString().split("T")[0],P=`${C}_grades_report_${w}.csv`;y.setAttribute("href",g),y.setAttribute("download",P),y.style.visibility="hidden",document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(g)}function hv(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:r,assignmentsWeight:i,customCategoryOverrides:a,lang:l}=e;if(!t)return null;const c=n[t]||[],u=s[t];if(!u||!u.assignments||c.length===0)return null;const d=u.assignments||[],h=u.performance||[],m=d.map(C=>{let w="assignment";if(a[C.id])w=a[C.id];else{const P=C.content&&C.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=C.title&&(C.title.toLowerCase().includes("quiz")||C.title.toLowerCase().includes("test")||C.title.includes("测验")||C.title.includes("测试"));w=P||S?"quiz":"assignment"}return{...C,category:w}}),f=["Student Name","Student Email"];m.forEach(C=>{const w=C.category==="quiz"?"Quiz":"Assignment";f.push(`${w}: ${C.title}`)}),f.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const g=[];return c.slice(0,5).forEach(C=>{const w=[C.name,C.email];let P=0,S=0,j=0,A=0,E=0,R=0,F=0;m.forEach(N=>{const z=h.find(U=>U.assignment_id===N.id&&U.student_id===C.id);if(z&&z.score!==null&&z.score!==void 0){w.push(`${z.score}%`);const U=Number(z.score);N.category==="quiz"?(P+=U,S++):(j+=U,A++),E+=U,R++,F++}else z&&z.submission_status==="submitted"?(w.push(l==="zh"?"待评分":"Pending Grade"),F++):w.push(l==="zh"?"未提交":"Not Submitted")});const M=S>0?Math.round(P/S):null,O=A>0?Math.round(j/A):null;let v="N/A";if(M!==null&&O!==null){const N=M*(r/100)+O*(i/100);v=`${Math.round(N)}%`}else M!==null?v=`${M}%`:O!==null&&(v=`${O}%`);const _=M!==null?`${M}%`:"N/A",L=O!==null?`${O}%`:"N/A",I=R>0?`${Math.round(E/R)}%`:"N/A";w.push(_,L,v,I,`${F}`,`${d.length}`),g.push(w)}),{headers:f,rows:g,totalStudents:c.length}}function fv(e){const{classes:t,classStudentsMap:n,classDashboardMap:s,lang:r}=e,a=[["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(t.forEach(d=>{const h=n[d.id]||[],m=s[d.id];if(!m||!m.assignments||h.length===0)return;const f=m.assignments||[],g=f.map(y=>{const C=y.content&&y.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=y.title&&(y.title.toLowerCase().includes("quiz")||y.title.toLowerCase().includes("test")||y.title.includes("测验")||y.title.includes("测试"));return{...y,category:C||w?"quiz":"assignment"}});h.forEach(y=>{let C=0,w=0,P=0,S=0,j=0,A=0;g.forEach(v=>{const _=m.performance?.find(L=>L.student_id===y.id&&L.assignment_id===v.id&&L.submission_status==="graded"&&L.score!==null);if(_){const L=Number(_.score);j+=L,A++,v.category==="quiz"?(C+=L,w++):(P+=L,S++)}});const E=w>0?Math.round(C/w):null,R=S>0?Math.round(P/S):null;let F=0;E!==null&&R!==null?F=Math.round(E*.4+R*.6):E!==null?F=Math.round(E):R!==null&&(F=Math.round(R));const M=A>0?Math.round(j/A):0,O=[d.name,y.name,y.email,E!==null?`${E}%`:"N/A",R!==null?`${R}%`:"N/A",`${F}%`,`${M}%`,`${A}`,`${f.length}`];a.push(O)})}),a.length<=1){alert(r==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const l="data:text/csv;charset=utf-8,\uFEFF"+a.map(d=>d.map(ju).join(",")).join(`
172
- `),c=encodeURI(l),u=document.createElement("a");u.setAttribute("href",c),u.setAttribute("download",`All_Classes_Combined_Grades_${new Date().toISOString().slice(0,10)}.csv`),document.body.appendChild(u),u.click(),document.body.removeChild(u)}function pv(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:r,fetchClassStudents:i,fetchClassDashboard:a,fetchClassProgress:l,addToast:c=()=>{}}=e,[u,d]=p.useState(!1),[h,m]=p.useState(""),[f,g]=p.useState(""),[y,C]=p.useState(40),[w,P]=p.useState(60),[S,j]=p.useState({}),[A,E]=p.useState(!1),[R,F]=p.useState(!1),[M,O]=p.useState(null),[v,_]=p.useState(!1),[L,I]=p.useState({}),N=p.useCallback(b=>{const Q=Math.min(100,Math.max(0,b));C(Q),P(100-Q)},[]),z=p.useCallback(b=>{const Q=Math.min(100,Math.max(0,b));P(Q),C(100-Q)},[]),U=p.useMemo(()=>hv({exportClassId:h,classStudentsMap:s,classDashboardMap:r,quizzesWeight:y,assignmentsWeight:w,customCategoryOverrides:S,lang:t}),[h,y,w,S,s,r,t]),T=p.useCallback(async(b,Q)=>{O(b);try{await i(b),await a(b),await l(b),m(b),g(Q),C(40),P(60),j({}),d(!0)}catch(X){console.error(X)}finally{O(null),E(!1)}},[i,a,l]),D=p.useCallback((b,Q,X=40,B=60,Z={})=>{dv({className:Q,students:s[b]||[],dashData:r[b],qWeight:X,aWeight:B,overrides:Z})},[s,r]),x=p.useCallback(async(b,Q)=>{await i(b),await a(b),await l(b),await uv({classId:b,className:Q,students:s[b]||[],dashData:r[b],lang:t,addToast:c,setIsGeneratingPDFReport:I})},[s,r,t,c,i,a,l]),oe=p.useCallback(async()=>{_(!0);try{await fv({classes:n,classStudentsMap:s,classDashboardMap:r,lang:t})}catch(b){console.error("Export all classes error:",b)}finally{_(!1),E(!1)}},[n,s,r,t]),me=p.useCallback((b,Q)=>{const X=r[Q];if(!X||!X.performance)return null;const B=Date.now()-2592e6,re=X.performance.filter(ae=>ae.student_id===b).filter(ae=>ae.submitted_at&&ae.submitted_at>=B&&ae.score!==null&&ae.score!==void 0);if(re.length===0)return null;const xe=re.reduce((ae,je)=>ae+Number(je.score),0)/re.length;return xe<60?Math.round(xe):null},[r]);return{isExportWeightModalOpen:u,setIsExportWeightModalOpen:d,exportClassId:h,setExportClassId:m,exportClassName:f,setExportClassName:g,quizzesWeight:y,setQuizzesWeight:C,assignmentsWeight:w,setAssignmentsWeight:P,customCategoryOverrides:S,setCustomCategoryOverrides:j,exportDropdownOpen:A,setExportDropdownOpen:E,exportTooltipOpen:R,setExportTooltipOpen:F,loadingExportClassId:M,setLoadingExportClassId:O,isExportingAllCombined:v,setIsExportingAllCombined:_,isGeneratingPDFReport:L,setIsGeneratingPDFReport:I,handleQuizzesWeightChange:N,handleAssignmentsWeightChange:z,csvPreviewData:U,triggerExportForClass:T,handleExportGrades:D,handleGeneratePDFReport:x,handleExportAllClassesCombined:oe,get30DayAverageWarning:me}}function mv(e){const[t,n]=p.useState(""),[s,r]=p.useState("recent"),[i,a]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(!1),[h,m]=p.useState(null),f=p.useMemo(()=>{let g=[...e];if(t.trim()){const y=t.toLowerCase();g=g.filter(C=>C.title.toLowerCase().includes(y)||C.content.toLowerCase().includes(y))}if(i&&(g=g.filter(y=>(y.enrollment_count||0)>0)),l&&(g=g.filter(y=>y.content&&y.content.trim().length>0)),u){const y=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();g=g.filter(C=>(C.created_at||0)>=y)}return s==="recent"?g.sort((y,C)=>(C.created_at||0)-(y.created_at||0)):s==="alphabetical"?g.sort((y,C)=>y.title.localeCompare(C.title)):s==="enrollment"&&g.sort((y,C)=>(C.enrollment_count||0)-(y.enrollment_count||0)),g},[e,t,s,i,l,u]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:r,filterEnrollment:i,setFilterEnrollment:a,filterHasContent:l,setFilterHasContent:c,filterThisMonth:u,setFilterThisMonth:d,copyingLessonId:h,setCopyingLessonId:m,filteredAndSortedLessons:f}}function Rl(e,t){let n="",s="",r="";e==="class"?(n=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",s="Class Name,Class Desc,Student Name,Student Email",r=t==="zh"?`高一A班,基础英语课程,李明,liming@example.com
169
+ };`;function uv(e){const{session:t,host:n,lang:s,addToast:r,setChatLog:i,setTeacherTab:a,fetchLessons:l}=e,[c,u]=f.useState([]),[d,p]=f.useState([]),[m,h]=f.useState(!1),[g,y]=f.useState(null),[v,w]=f.useState(""),[P,S]=f.useState(""),[j,A]=f.useState(""),[E,R]=f.useState(""),[F,D]=f.useState(null),[O,k]=f.useState(!1),[_,L]=f.useState("store"),[I,N]=f.useState(cv),[z,U]=f.useState(!1),[T,M]=f.useState([]),[x,oe]=f.useState([]),[me,b]=f.useState({}),Q=f.useRef(new Set),X=f.useCallback(async()=>{try{const Y=await fetch("/api/plugins");if(Y.ok){const ne=await Y.json();u(ne)}}catch(Y){console.warn("Failed to fetch plugins",Y)}},[]),B=f.useCallback(async()=>{try{const Y=await fetch("/api/ai-providers");if(Y.ok){const ne=await Y.json();p(ne)}}catch(Y){console.warn("Failed to fetch AI Providers",Y)}},[]);f.useEffect(()=>{X(),t&&t.role!=="student"&&B()},[X,B,t?.role]);const Z=f.useCallback(async()=>{try{const Y=await fetch("/api/events");Y.ok&&M(await Y.json())}catch{}},[]),re=f.useCallback(async()=>{try{const Y=await fetch("/api/approvals");Y.ok&&oe(await Y.json())}catch{}},[]);return{plugins:c,setPlugins:u,fetchPlugins:X,aiProviders:d,setAiProviders:p,fetchAIProviders:B,isAIProviderModalOpen:m,setIsAIProviderModalOpen:h,editingAIProvider:g,setEditingAIProvider:y,providerName:v,setProviderName:w,providerApiUrl:P,setProviderApiUrl:S,providerApiKey:j,setProviderApiKey:A,providerModelName:E,setProviderModelName:R,testingProviderId:F,setTestingProviderId:D,showPluginModal:O,setShowPluginModal:k,storeTab:_,setStoreTab:L,pluginCode:I,setPluginCode:N,installingPlugin:z,setInstallingPlugin:U,events:T,setEvents:M,fetchEvents:Z,approvals:x,setApprovals:oe,fetchApprovals:re,scoreOverrides:me,setScoreOverrides:b,handleSaveAIProvider:async()=>{if(!v.trim()||!P.trim()||!E.trim()){r(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let Y;if(g?Y=await fetch(`/api/ai-providers/${g.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:v,api_url:P,api_key:j,model_name:E})}):Y=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:v,api_url:P,api_key:j,model_name:E})}),Y.ok)r(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${v}] 已保存。`:`AI Provider [${v}] has been updated.`,"success"),h(!1),y(null),w(""),S(""),A(""),R(""),B();else{const ne=await Y.json().catch(()=>({}));r(s==="zh"?"保存失败":"Failed to Save",ne.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(Y){console.error(Y),r(s==="zh"?"保存异常":"Execution Error",Y.message||"Error occurred","warning")}},handleDeleteAIProvider:async(Y,ne)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${ne}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${ne}]?`))try{(await fetch(`/api/ai-providers/${Y}`,{method:"DELETE"})).ok?(r(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${ne}] 已经被清除。`:`AI Provider [${ne}] has been removed.`,"success"),B()):r(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(le){console.error(le),r(s==="zh"?"操作异常":"Execution Error",le.message||"Error occurred","warning")}},handleTestAIProvider:async Y=>{D(Y.id);try{const ne=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:Y.api_url,api_key:Y.api_key,model_name:Y.model_name})}),le=await ne.json();ne.ok&&le.success?r(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${Y.name}]。${le.message}`:`Successfully connected to [${Y.name}]. ${le.message}`,"success"):r(s==="zh"?"测试失败":"Test Failed",le.error||"Connection error","warning")}catch(ne){console.error(ne),r(s==="zh"?"连接异常":"Connection Exception",ne.message||"Error occurred","warning")}finally{D(null)}},handleInstallPlugin:async()=>{if(I.trim()){U(!0);try{const ne=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:I})})).json();ne.success?(await X(),k(!1),i(le=>[...le,{role:"agent",content:`[System] Plugin "${ne.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+ne.error)}catch(Y){alert("Error: "+Y.message)}finally{U(!1)}}},handleZipPluginUpload:async(Y,ne,le)=>{U(!0);const Ne=le?.mode==="update";try{const He={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(Y.name),"X-Execution-Mode":ne,"X-Install-Mode":Ne?"update":"install","X-Allow-Downgrade":le?.allowDowngrade?"true":"false"};le?.targetPluginId&&(He["X-Target-Plugin-Id"]=encodeURIComponent(le.targetPluginId));const qe=Ne&&le?.targetPluginId?`/api/plugins/${encodeURIComponent(le.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",dt=await fetch(qe,{method:"POST",headers:He,body:Y}),Te=await dt.json().catch(()=>({}));if(!dt.ok||!Te.success){const J=Te.error||"Unknown error";throw r(s==="zh"?Ne?"更新失败":"安装失败":Ne?"Update Failed":"Installation Failed",J,"error"),new Error(J)}const $=Te.pluginId||Te.manifest?.pluginId||Te.manifest?.id,q=!!(Te.updated||Ne);if(!q&&$)await fetch(`/api/plugins/${encodeURIComponent($)}/toggle`,{method:"POST"}).catch(()=>{});else if(q&&Te.wasActive&&$)try{await n.deactivatePlugin($)}catch{}a("plugins"),L("store"),await X(),setTimeout(()=>{X()},1e3);const K=Te.manifest?.name||$||Y.name;if(q){const J=Te.oldVersion||"?",ee=Te.newVersion||Te.manifest?.version||"?";r(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${K}" 已从 v${J} 更新到 v${ee}(配置与数据已保留)`:`"${K}" updated v${J} → v${ee} (config & data preserved)`,"success"),i(Pe=>[...Pe,{role:"agent",content:`[System] Plugin "${K}" updated ${J} → ${ee}.`}])}else r(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${K}" 已成功上传并以 [${ne==="worker"?"Worker 隔离":"VM 嵌入"}] 模式激活运行!`:`Plugin "${K}" installed and activated in [${ne}] mode!`,"success"),i(J=>[...J,{role:"agent",content:`[System] Plugin "${K}" installed successfully from ZIP file.`}])}catch(He){const qe=He?.message?String(He.message):"";throw qe&&qe!=="Failed to fetch"&&qe!=="Network error"||r(s==="zh"?"网络错误":"Network Error",qe||"Network error","error"),He}finally{U(!1)}},handleTogglePlugin:async Y=>{if(!Q.current.has(Y)){Q.current.add(Y);try{const ne=await fetch(`/api/plugins/${encodeURIComponent(Y)}/toggle`,{method:"POST"}),le=await ne.json().catch(()=>({}));if(ne.ok)await X();else{const Ne=le.error||"Unknown error";Ne.includes("requires human approval")||Ne.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await re()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+Ne)}}catch(ne){console.error("Failed to toggle plugin:",ne),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{Q.current.delete(Y)}}},handleDeletePlugin:async Y=>{if(window.confirm(s==="zh"?"确定要彻底删除该插件吗?删除后此插件相关的功能将无法使用。":"Are you sure you want to completely delete this plugin? This cannot be undone."))try{const ne=await fetch(`/api/plugins/${encodeURIComponent(Y)}`,{method:"DELETE"});if(ne.ok)a("plugins"),L("store"),await X(),i(le=>[...le,{role:"agent",content:"[System] Plugin uninstalled and deleted."}]);else{const le=await ne.json().catch(()=>({}));alert(le.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(ne){console.error("Failed to delete plugin:",ne),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},handleApprove:async(Y,ne)=>{try{const Ne=await(await fetch(`/api/approvals/${Y}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:ne})})).json();Ne.success?(await re(),await l(),await X()):alert("Action failed: "+Ne.error)}catch(le){console.error(le)}},handleReject:async Y=>{try{await fetch(`/api/approvals/${Y}/reject`,{method:"POST"}),await re(),await X()}catch(ne){console.error(ne)}}}}function dv(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:r,setTeacherTab:i}=e,[a,l]=f.useState(!1),[c,u]=f.useState(1),[d,p]=f.useState(""),[m,h]=f.useState("Mathematics"),[g,y]=f.useState(""),[v,w]=f.useState(""),[P,S]=f.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"}]),[j,A]=f.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:l,wizardStep:c,setWizardStep:u,wizardCourseTitle:d,setWizardCourseTitle:p,wizardCourseCategory:m,setWizardCourseCategory:h,wizardCourseDescription:g,setWizardCourseDescription:y,wizardCourseContent:v,setWizardCourseContent:w,wizardCourseTimeline:P,setWizardCourseTimeline:S,wizardIsSubmitting:j,setWizardIsSubmitting:A,handleDeployWizardCourse:async()=>{if(!d.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}A(!0);try{const R=v.trim()||`Course outline for ${d} (${m})`,F=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,content:R})});if(F.ok){const O=(await F.json()).result?.lessonId;O&&await fetch(`/api/lessons/${O}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:P})}),await s(),O&&(r(O),i("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${d}》已成功保存到核心SQLite并已自动激活!`:`Course "${d}" is now live in SQLite and auto-activated.`,"success"),l(!1),p(""),h("Mathematics"),y(""),w(""),u(1)}else n("Error","SQLite save failed","warning")}catch(R){console.error(R),n("Error","Launch Exception","warning")}finally{A(!1)}}}}function hv(){const[e,t]=f.useState(!1),[n,s]=f.useState(null),[r,i]=f.useState("scan_lesson"),[a,l]=f.useState(""),[c,u]=f.useState(""),[d,p]=f.useState(!1),[m,h]=f.useState([]),[g,y]=f.useState([]),[v,w]=f.useState(!1),[P,S]=f.useState({}),[j,A]=f.useState(10),[E,R]=f.useState("quiz"),F=f.useRef(P);return f.useEffect(()=>{F.current=P},[P]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:r,setQuizGenMode:i,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:l,quizGenTopic:c,setQuizGenTopic:u,isGeneratingSuggestions:d,setIsGeneratingSuggestions:p,suggestedObjectives:m,setSuggestedObjectives:h,suggestedQuestions:g,setSuggestedQuestions:y,savingQuiz:v,setSavingQuiz:w,quizStudentAnswers:P,setQuizStudentAnswers:S,quizGenTimeLimit:j,setQuizGenTimeLimit:A,quizStudentAnswersRef:F,subAssignmentTab:E,setSubAssignmentTab:R}}function fv(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:r,fetchClassStudents:i,handleExportAllClassesCombined:a}=e,[l,c]=f.useState(!1),[u,d]=f.useState(new Set),[p,m]=f.useState(new Set),[h,g]=f.useState(null),[y,v]=f.useState(""),[w,P]=f.useState(""),[S,j]=f.useState("");return{batchMode:l,setBatchMode:c,selectedClassIds:u,setSelectedClassIds:d,selectedStudentIds:p,setSelectedStudentIds:m,batchPicker:h,setBatchPicker:g,batchPickerLesson:y,setBatchPickerLesson:v,batchPickerDate:w,setBatchPickerDate:P,batchPickerTargetClass:S,setBatchPickerTargetClass:j,toggleClassSelection:T=>{d(M=>{const x=new Set(M);return x.has(T)?x.delete(T):x.add(T),x})},toggleSelectAllClasses:()=>{d(T=>T.size===n.length&&n.length>0?new Set:new Set(n.map(M=>M.id)))},toggleStudentSelection:T=>{m(M=>{const x=new Set(M);return x.has(T)?x.delete(T):x.add(T),x})},toggleSelectAllStudents:T=>{m(M=>M.size===T.length&&T.length>0?new Set:new Set(T.map(x=>x.id)))},handleBatchDeleteClasses:async()=>{if(u.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${u.size} 个班级吗?该操作不可恢复。`:`Delete ${u.size} selected classes permanently?`)){for(const T of u)await fetch(`/api/classes/${T}`,{method:"DELETE"});d(new Set),await r()}},handleBatchExportClasses:async()=>{u.size!==0&&await a(n.filter(T=>u.has(T.id)))},handleBatchSetPasscode:async()=>{if(u.size===0)return;const T=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(T!==null){for(const M of u)await fetch(`/api/classes/${M}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:T===""?null:T})});d(new Set),await r()}},handleBatchScheduleClasses:()=>{u.size!==0&&(v(""),P(new Date().toISOString().split("T")[0]),g("schedule"))},handleBatchDeleteStudents:async()=>{if(!(p.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${p.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${p.size} selected student accounts?`)){for(const T of p)await fetch(`/api/students/${T}`,{method:"DELETE"});m(new Set),await i(s)}},handleBatchResetPassword:async()=>{if(p.size===0||!s)return;const T=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(T===null||T.trim()==="")){for(const M of p)await fetch(`/api/students/${M}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:T})});m(new Set),await i(s)}},handleBatchTransferStudents:()=>{p.size===0||!s||(j(""),g("transfer"))},handleBatchSetLockedLesson:()=>{p.size===0||!s||(v(""),g("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(h==="schedule"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const T of u)await fetch(`/api/classes/${T}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:y,scheduledDate:w+" 09:00:00",status:"scheduled"})});d(new Set)}else if(h==="lockedLesson"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const T of p)await fetch(`/api/students/${T}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:y})});m(new Set)}else if(h==="transfer"){if(!S||S===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const T of p)await fetch(`/api/classes/${s}/students/${T}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:T})});m(new Set)}g(null),s&&await i(s)}}}}function pv(){const[e,t]=f.useState([]),[n,s]=f.useState(!1),[r,i]=f.useState({lab_id:null,seats:[]}),[a,l]=f.useState(!1),[c,u]=f.useState([]),[d,p]=f.useState({}),[m,h]=f.useState({}),[g,y]=f.useState(null),[v,w]=f.useState(""),[P,S]=f.useState(""),j=f.useCallback(async()=>{try{s(!0);const D=await fetch("/api/labs");D.ok&&t(await D.json())}catch(D){console.error(D)}finally{s(!1)}},[]),A=f.useCallback(async D=>{try{const O=await fetch(`/api/classes/${D}/seats`);if(O.ok){const k=await O.json();i(k)}}catch(O){console.error(O)}},[]),E=f.useCallback(async()=>{try{const D=new Date().toISOString().split("T")[0],O=await fetch(`/api/schedules/today?date=${D}`);if(O.ok){const k=await O.json();k.success&&k.schedules&&u(k.schedules)}}catch(D){console.warn("Failed to fetch today schedules",D)}},[]),R=f.useCallback(async D=>{try{const O=await fetch(`/api/classes/${D}/schedules`);if(O.ok){const k=await O.json();p(_=>({..._,[D]:k}))}}catch{}},[]),F=f.useCallback(async D=>{try{const O=await fetch(`/api/schedules/${D}/attendance`);if(O.ok){const k=await O.json();h(_=>({..._,[D]:k}))}}catch{}},[]);return{computerLabs:e,setComputerLabs:t,loadingLabs:n,setLoadingLabs:s,fetchLabs:j,classSeats:r,setClassSeats:i,savingSeats:a,setSavingSeats:l,fetchClassSeats:A,todaySchedules:c,setTodaySchedules:u,fetchTodaySchedules:E,classSchedulesMap:d,setClassSchedulesMap:p,fetchClassSchedules:R,scheduleAttendanceMap:m,setScheduleAttendanceMap:h,fetchScheduleAttendance:F,expandedScheduleId:g,setExpandedScheduleId:y,newScheduleDate:v,setNewScheduleDate:w,newScheduleLessonId:P,setNewScheduleLessonId:S}}function mv(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[r,i]=f.useState([]),[a,l]=f.useState("seg-1"),[c,u]=f.useState(null),[d,p]=f.useState(null),[m,h]=f.useState("none"),[g,y]=f.useState(null),[v,w]=f.useState(!0),P=f.useRef(null),S=async(j,A)=>{h("saving");try{(await fetch(`/api/lessons/${j}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:A})})).ok?(s(R=>R.map(F=>F.id===j?{...F,timeline:JSON.stringify(A)}:F)),i(A),h("saved"),y(new Date)):h("error")}catch(E){console.error("Failed to save timeline:",E),h("error")}};return f.useEffect(()=>{if(t){const j=n.find(A=>A.id===t);if(j){let A=[];if(j.timeline)try{A=typeof j.timeline=="string"?JSON.parse(j.timeline):j.timeline}catch{A=[{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 A=[{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"}];i(A);const E=P.current!==t;P.current=t,A.length>0?(E||!A.some(R=>R.id===a))&&l(A[0].id):l(null)}}},[t,n]),{timelineSegments:r,setTimelineSegments:i,activeSegmentId:a,setActiveSegmentId:l,segmentToEdit:c,setSegmentToEdit:u,draggedSegmentIdx:d,setDraggedSegmentIdx:p,editorSaveStatus:m,setEditorSaveStatus:h,editorLastSavedTime:g,setEditorLastSavedTime:y,editorPanelsExpanded:v,setEditorPanelsExpanded:w,saveTimeline:S}}function gv(e,t,n){const[s,r]=f.useState(new Set),[i,a]=f.useState(null),[l,c]=f.useState(!1),u=f.useMemo(()=>{if(e!=="student"||!t)return[];const p=[],m=t.assignments||[];for(const g of m)if(!g.submission_status)p.push({id:`new-${g.id}`,type:"new_assignment",title:n==="zh"?"新发布作业":"New Assignment",message:n==="zh"?`您有一项新作业:"${g.title}"`:`You have a new assignment: ${g.title}`,date:g.created_at,relatedId:g.id});else if(g.submission_status==="graded"){const y=!!g.feedback;p.push({id:`graded-${g.id}`,type:"graded",title:y?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:y?n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%。反馈:"${g.feedback}"`:`Your assignment "${g.title}" was graded. Score: ${g.score}%. Teacher feedback: "${g.feedback}"`:n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%`:`Your assignment "${g.title}" was graded. Score: ${g.score}%`,date:g.submitted_at||g.created_at,relatedId:g.id})}const h=t.rollcalls||[];for(const g of h)p.push({id:g.id,type:"rollcall_picked",title:n==="zh"?"⚡️ 随机提问选中通知":"⚡️ Random Pick Notification",message:n==="zh"?`您已被老师在课程"${g.lesson_title||"课堂"}"中随机选中提问!请立即确认您的出勤与注意。`:`You have been randomly picked by the teacher in lesson "${g.lesson_title||"Class"}"! Please pay immediate attention.`,date:g.picked_time,relatedId:g.lesson_id});return p.sort((g,y)=>y.date-g.date)},[e,t,n]),d=f.useMemo(()=>u.filter(p=>!s.has(p.id)),[u,s]);return{studentNotifications:u,unreadNotifications:d,readNotifications:s,setReadNotifications:r,selectedNotificationForModal:i,setSelectedNotificationForModal:a,isNotificationsOpen:l,setIsNotificationsOpen:c}}function zu(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
170
+ `)?`"${t.replace(/"/g,'""')}"`:t}async function xv(e){const{classId:t,className:n,students:s,dashData:r,lang:i,addToast:a,setIsGeneratingPDFReport:l}=e;l(c=>({...c,[t]:!0}));try{if(!r){a(i==="zh"?"暂无班级评分数据":"No Class Performance Data",i==="zh"?"请确保在此班级加载了作业与测验。":"Please check if assignments or quizzes are present for this class.","warning");return}const c=r.performance||[],u=r.assignments||[],d={};s.forEach(z=>{d[z.id]={id:z.id,name:z.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(z=>{const U=z.student_id;d[U]&&(d[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&d[U].submittedCount++,z.score!==null&&z.score!==void 0&&(d[U].totalGradesSum+=z.score,d[U].gradedCount++))});const p=Object.values(d).map(z=>{const U=z.gradedCount>0?z.totalGradesSum/z.gradedCount:0,T=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avgScore:U,submissionRate:T}});p.sort((z,U)=>U.avgScore-z.avgScore);let m=0,h=0,g=0,y=0;c.forEach(z=>{y++,(z.submission_status==="submitted"||z.submission_status==="graded")&&g++,z.score!==null&&z.score!==void 0&&(m+=z.score,h++)});const v=h>0?m/h:0,w=y>0?g/y*100:0,P={};u.forEach(z=>{P[z.id]={id:z.id,title:z.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(z=>{const U=z.assignment_id;P[U]&&(P[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&P[U].submittedCount++,z.score!==null&&z.score!==void 0&&P[U].scores.push(z.score))});const S=Object.values(P).map(z=>{const U=z.scores.length,T=z.scores.reduce((b,Q)=>b+Q,0),M=U>0?T/U:0,x=U>0?Math.max(...z.scores):0,oe=U>0?Math.min(...z.scores):0,me=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avg:M,max:x,min:oe,subRate:me}}),j=new _p({orientation:"p",unit:"mm",format:"a4"}),A=[15,23,42],E=[79,70,229],R=[51,65,85],F=[226,232,240],D=z=>{j.setDrawColor(F[0],F[1],F[2]),j.setLineWidth(.3),j.line(14,z,196,z)};j.setFillColor(A[0],A[1],A[2]),j.rect(0,0,210,42,"F"),j.setTextColor(255,255,255),j.setFont("helvetica","bold"),j.setFontSize(20),j.text("CLASS PERFORMANCE REPORT",14,18),j.setFont("helvetica","normal"),j.setFontSize(10),j.setTextColor(194,205,225),j.text("Academic Insights • Generative Report Summary",14,25),j.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),j.setFillColor(E[0],E[1],E[2]),j.rect(172,10,24,24,"F"),j.setFont("helvetica","bold"),j.setFontSize(14),j.setTextColor(255,255,255),j.text("OS",180,26);let O=52;j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("I. EXECUTIVE OVERVIEW",14,O),O+=6;const k=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${u.length} items`],["Global Assignment Submission Rate",`${w.toFixed(1)}%`],["Class Average Performance Score",`${v.toFixed(1)}%`]];j.autoTable({startY:O,head:[["Metric Indicator","Class-wide Metric Value"]],body:k,theme:"striped",headStyles:{fillColor:A,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:R,fontSize:9.5},margin:{left:14,right:14}}),O=j.lastAutoTable.finalY+12,j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("II. STUDENT RANKING DISTRIBUTION",14,O),O+=6;const _=p.map((z,U)=>{let T="Excellent";return z.avgScore>=90?T="Excellent (A)":z.avgScore>=75?T="Good (B)":z.avgScore>=60?T="Satisfactory (C)":T="Needs Improvement (D)",[`${U+1}`,z.name,`${z.submittedCount}/${z.totalCount} (${z.submissionRate.toFixed(0)}%)`,`${z.avgScore.toFixed(1)}%`,T]});j.autoTable({startY:O,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:_,theme:"grid",headStyles:{fillColor:E,textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},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}}),O=j.lastAutoTable.finalY+12,O>210&&(j.addPage(),O=20),j.setTextColor(A[0],A[1],A[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("III. ASSIGNMENT PERFORMANCE METRICS",14,O),O+=6;const L=S.map(z=>[z.title,`${z.subRate.toFixed(0)}%`,`${z.avg.toFixed(1)}%`,`${z.min.toFixed(0)}% - ${z.max.toFixed(0)}%`]);j.autoTable({startY:O,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:L.length>0?L:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),O=j.lastAutoTable.finalY+15,D(275),j.setFontSize(8),j.setTextColor(148,163,184),j.text("Generated by OpenLearn Next • Educational Operating System",14,282),j.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const I=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),N=new Date().toISOString().split("T")[0];j.save(`Class_Report_${I}_${N}.pdf`),a(i==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",i==="zh"?`班级【${n}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${n} saved to your device.`,"success")}catch(c){console.error("PDF Generation Failed:",c),a(i==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",c.message||"Error occurred during PDF generation","warning")}finally{l(c=>({...c,[t]:!1}))}}function yv(e){const{className:t,students:n,dashData:s,qWeight:r=40,aWeight:i=60,overrides:a={}}=e;if(!s||!s.assignments){alert("No performance data available to export. Please open the dashboard to load class data first.");return}if(n.length===0){alert("No students in this class to export grades for.");return}const l=s.assignments||[],c=s.performance||[],u=l.map(S=>{let j="assignment";if(a[S.id])j=a[S.id];else{const A=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),E=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));j=A||E?"quiz":"assignment"}return{...S,category:j}}),d=["Student Name","Student Email"];u.forEach(S=>{const j=S.category==="quiz"?"Quiz":"Assignment";d.push(`${j}: ${S.title}`)}),d.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const p=[d];n.forEach(S=>{const j=[S.name,S.email];let A=0,E=0,R=0,F=0,D=0,O=0,k=0;u.forEach(T=>{const M=c.find(x=>x.assignment_id===T.id&&x.student_id===S.id);if(M&&M.score!==null&&M.score!==void 0){j.push(`${M.score}%`);const x=Number(M.score);T.category==="quiz"?(A+=x,E++):(R+=x,F++),D+=x,O++,k++}else M&&M.submission_status==="submitted"?(j.push("Pending Grade"),k++):j.push("Not Submitted")});const _=E>0?Math.round(A/E):null,L=F>0?Math.round(R/F):null;let I="N/A";if(_!==null&&L!==null){const T=_*(r/100)+L*(i/100);I=`${Math.round(T)}%`}else _!==null?I=`${_}%`:L!==null&&(I=`${L}%`);const N=_!==null?`${_}%`:"N/A",z=L!==null?`${L}%`:"N/A",U=O>0?`${Math.round(D/O)}%`:"N/A";j.push(N,z,I,U,`${k}`,`${l.length}`),p.push(j.map(zu))});const m=p.map(S=>S.join(",")).join(`
171
+ `),h=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8;"}),g=URL.createObjectURL(h),y=document.createElement("a"),v=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),w=new Date().toISOString().split("T")[0],P=`${v}_grades_report_${w}.csv`;y.setAttribute("href",g),y.setAttribute("download",P),y.style.visibility="hidden",document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(g)}function bv(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:r,assignmentsWeight:i,customCategoryOverrides:a,lang:l}=e;if(!t)return null;const c=n[t]||[],u=s[t];if(!u||!u.assignments||c.length===0)return null;const d=u.assignments||[],p=u.performance||[],m=d.map(v=>{let w="assignment";if(a[v.id])w=a[v.id];else{const P=v.content&&v.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=v.title&&(v.title.toLowerCase().includes("quiz")||v.title.toLowerCase().includes("test")||v.title.includes("测验")||v.title.includes("测试"));w=P||S?"quiz":"assignment"}return{...v,category:w}}),h=["Student Name","Student Email"];m.forEach(v=>{const w=v.category==="quiz"?"Quiz":"Assignment";h.push(`${w}: ${v.title}`)}),h.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const g=[];return c.slice(0,5).forEach(v=>{const w=[v.name,v.email];let P=0,S=0,j=0,A=0,E=0,R=0,F=0;m.forEach(N=>{const z=p.find(U=>U.assignment_id===N.id&&U.student_id===v.id);if(z&&z.score!==null&&z.score!==void 0){w.push(`${z.score}%`);const U=Number(z.score);N.category==="quiz"?(P+=U,S++):(j+=U,A++),E+=U,R++,F++}else z&&z.submission_status==="submitted"?(w.push(l==="zh"?"待评分":"Pending Grade"),F++):w.push(l==="zh"?"未提交":"Not Submitted")});const D=S>0?Math.round(P/S):null,O=A>0?Math.round(j/A):null;let k="N/A";if(D!==null&&O!==null){const N=D*(r/100)+O*(i/100);k=`${Math.round(N)}%`}else D!==null?k=`${D}%`:O!==null&&(k=`${O}%`);const _=D!==null?`${D}%`:"N/A",L=O!==null?`${O}%`:"N/A",I=R>0?`${Math.round(E/R)}%`:"N/A";w.push(_,L,k,I,`${F}`,`${d.length}`),g.push(w)}),{headers:h,rows:g,totalStudents:c.length}}function wv(e){const{classes:t,classStudentsMap:n,classDashboardMap:s,lang:r}=e,a=[["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(t.forEach(d=>{const p=n[d.id]||[],m=s[d.id];if(!m||!m.assignments||p.length===0)return;const h=m.assignments||[],g=h.map(y=>{const v=y.content&&y.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=y.title&&(y.title.toLowerCase().includes("quiz")||y.title.toLowerCase().includes("test")||y.title.includes("测验")||y.title.includes("测试"));return{...y,category:v||w?"quiz":"assignment"}});p.forEach(y=>{let v=0,w=0,P=0,S=0,j=0,A=0;g.forEach(k=>{const _=m.performance?.find(L=>L.student_id===y.id&&L.assignment_id===k.id&&L.submission_status==="graded"&&L.score!==null);if(_){const L=Number(_.score);j+=L,A++,k.category==="quiz"?(v+=L,w++):(P+=L,S++)}});const E=w>0?Math.round(v/w):null,R=S>0?Math.round(P/S):null;let F=0;E!==null&&R!==null?F=Math.round(E*.4+R*.6):E!==null?F=Math.round(E):R!==null&&(F=Math.round(R));const D=A>0?Math.round(j/A):0,O=[d.name,y.name,y.email,E!==null?`${E}%`:"N/A",R!==null?`${R}%`:"N/A",`${F}%`,`${D}%`,`${A}`,`${h.length}`];a.push(O)})}),a.length<=1){alert(r==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const l="data:text/csv;charset=utf-8,\uFEFF"+a.map(d=>d.map(zu).join(",")).join(`
172
+ `),c=encodeURI(l),u=document.createElement("a");u.setAttribute("href",c),u.setAttribute("download",`All_Classes_Combined_Grades_${new Date().toISOString().slice(0,10)}.csv`),document.body.appendChild(u),u.click(),document.body.removeChild(u)}function Sv(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:r,fetchClassStudents:i,fetchClassDashboard:a,fetchClassProgress:l,addToast:c=()=>{}}=e,[u,d]=f.useState(!1),[p,m]=f.useState(""),[h,g]=f.useState(""),[y,v]=f.useState(40),[w,P]=f.useState(60),[S,j]=f.useState({}),[A,E]=f.useState(!1),[R,F]=f.useState(!1),[D,O]=f.useState(null),[k,_]=f.useState(!1),[L,I]=f.useState({}),N=f.useCallback(b=>{const Q=Math.min(100,Math.max(0,b));v(Q),P(100-Q)},[]),z=f.useCallback(b=>{const Q=Math.min(100,Math.max(0,b));P(Q),v(100-Q)},[]),U=f.useMemo(()=>bv({exportClassId:p,classStudentsMap:s,classDashboardMap:r,quizzesWeight:y,assignmentsWeight:w,customCategoryOverrides:S,lang:t}),[p,y,w,S,s,r,t]),T=f.useCallback(async(b,Q)=>{O(b);try{await i(b),await a(b),await l(b),m(b),g(Q),v(40),P(60),j({}),d(!0)}catch(X){console.error(X)}finally{O(null),E(!1)}},[i,a,l]),M=f.useCallback((b,Q,X=40,B=60,Z={})=>{yv({className:Q,students:s[b]||[],dashData:r[b],qWeight:X,aWeight:B,overrides:Z})},[s,r]),x=f.useCallback(async(b,Q)=>{await i(b),await a(b),await l(b),await xv({classId:b,className:Q,students:s[b]||[],dashData:r[b],lang:t,addToast:c,setIsGeneratingPDFReport:I})},[s,r,t,c,i,a,l]),oe=f.useCallback(async()=>{_(!0);try{await wv({classes:n,classStudentsMap:s,classDashboardMap:r,lang:t})}catch(b){console.error("Export all classes error:",b)}finally{_(!1),E(!1)}},[n,s,r,t]),me=f.useCallback((b,Q)=>{const X=r[Q];if(!X||!X.performance)return null;const B=Date.now()-2592e6,re=X.performance.filter(ae=>ae.student_id===b).filter(ae=>ae.submitted_at&&ae.submitted_at>=B&&ae.score!==null&&ae.score!==void 0);if(re.length===0)return null;const xe=re.reduce((ae,je)=>ae+Number(je.score),0)/re.length;return xe<60?Math.round(xe):null},[r]);return{isExportWeightModalOpen:u,setIsExportWeightModalOpen:d,exportClassId:p,setExportClassId:m,exportClassName:h,setExportClassName:g,quizzesWeight:y,setQuizzesWeight:v,assignmentsWeight:w,setAssignmentsWeight:P,customCategoryOverrides:S,setCustomCategoryOverrides:j,exportDropdownOpen:A,setExportDropdownOpen:E,exportTooltipOpen:R,setExportTooltipOpen:F,loadingExportClassId:D,setLoadingExportClassId:O,isExportingAllCombined:k,setIsExportingAllCombined:_,isGeneratingPDFReport:L,setIsGeneratingPDFReport:I,handleQuizzesWeightChange:N,handleAssignmentsWeightChange:z,csvPreviewData:U,triggerExportForClass:T,handleExportGrades:M,handleGeneratePDFReport:x,handleExportAllClassesCombined:oe,get30DayAverageWarning:me}}function vv(e){const[t,n]=f.useState(""),[s,r]=f.useState("recent"),[i,a]=f.useState(!1),[l,c]=f.useState(!1),[u,d]=f.useState(!1),[p,m]=f.useState(null),h=f.useMemo(()=>{let g=[...e];if(t.trim()){const y=t.toLowerCase();g=g.filter(v=>v.title.toLowerCase().includes(y)||v.content.toLowerCase().includes(y))}if(i&&(g=g.filter(y=>(y.enrollment_count||0)>0)),l&&(g=g.filter(y=>y.content&&y.content.trim().length>0)),u){const y=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();g=g.filter(v=>(v.created_at||0)>=y)}return s==="recent"?g.sort((y,v)=>(v.created_at||0)-(y.created_at||0)):s==="alphabetical"?g.sort((y,v)=>y.title.localeCompare(v.title)):s==="enrollment"&&g.sort((y,v)=>(v.enrollment_count||0)-(y.enrollment_count||0)),g},[e,t,s,i,l,u]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:r,filterEnrollment:i,setFilterEnrollment:a,filterHasContent:l,setFilterHasContent:c,filterThisMonth:u,setFilterThisMonth:d,copyingLessonId:p,setCopyingLessonId:m,filteredAndSortedLessons:h}}function $l(e,t){let n="",s="",r="";e==="class"?(n=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",s="Class Name,Class Desc,Student Name,Student Email",r=t==="zh"?`高一A班,基础英语课程,李明,liming@example.com
173
173
  高一A班,基础英语课程,王华,wanghua@example.com`:`Class 101,Introduction to English,John Doe,john@example.com
174
174
  Class 101,Introduction to English,Jane Smith,jane@example.com`):(n=t==="zh"?"学生批量导入模板.csv":"student_import_template.csv",s="Student Name,Student Email",r=t==="zh"?`张三,zhangsan@example.com
175
175
  李四,lisi@example.com`:`Alice Cooper,alice@example.com
176
176
  Bob Dylan,bob@example.com`);const i=new Blob(["\uFEFF"+s+`
177
- `+r],{type:"text/csv;charset=utf-8;"}),a=URL.createObjectURL(i),l=document.createElement("a");l.href=a,l.setAttribute("download",n),document.body.appendChild(l),l.click(),document.body.removeChild(l)}async function gv(e,t){const{lang:n,fetchClasses:s,fetchStudents:r}=t;return new Promise((i,a)=>{const l=new FileReader;l.onload=async c=>{try{const u=c.target?.result;if(!u)throw new Error("File content is empty");let d=[],h=[],m=!0;if(e.name.endsWith(".json")){const f=JSON.parse(u);if(!Array.isArray(f))throw new Error("JSON structure must be an array");f.some(y=>y.className||y.name&&(y.students||y.classDescription))?(m=!0,d=f.map(y=>{const C=y.name||y.className||y.class_name,w=y.description||y.classDescription||"",P=y.students||y.studentList||[],S=(Array.isArray(P)?P:[]).map(j=>({name:j.name||j.studentName||"",email:j.email||j.studentEmail||""})).filter(j=>j.name);return{name:C,description:w,students:S}}).filter(y=>y.name)):(m=!1,h=f.map(y=>({name:y.name||y.studentName||y.student_name||"",email:y.email||y.studentEmail||y.student_email||""})).filter(y=>y.name))}else{const f=u.split(/\r?\n/);if(f.length<2)throw new Error("CSV has empty or insufficient data");const g=f[0].split(",").map(S=>S.trim().toLowerCase()),y=g.findIndex(S=>S.includes("class name")||S.includes("班级名称")||S.includes("班级")||S.includes("classname")||S.includes("class_name")),C=g.findIndex(S=>S.includes("class desc")||S.includes("班级描述")||S.includes("描述")||S.includes("class_desc")),w=g.findIndex(S=>S.includes("student name")||S.includes("学生姓名")||S.includes("姓名")||S.includes("学生")||S.includes("studentname")||S.includes("student_name")),P=g.findIndex(S=>S.includes("student email")||S.includes("学生邮箱")||S.includes("邮箱")||S.includes("email")||S.includes("studentemail")||S.includes("student_email"));if(w===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');if(y!==-1){m=!0;const S={};for(let j=1;j<f.length;j++){const A=f[j].trim();if(!A)continue;const R=(A.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||A.split(",")).map(_=>_.replace(/^"|"$/g,"").trim()),F=R[y];if(!F)continue;const M=C!==-1&&R[C]||"",O=w!==-1&&R[w]||"",v=P!==-1&&R[P]||"";S[F]||(S[F]={name:F,description:M,students:[]}),O&&S[F].students.push({name:O,email:v})}d=Object.values(S)}else{m=!1;for(let S=1;S<f.length;S++){const j=f[S].trim();if(!j)continue;const E=(j.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||j.split(",")).map(M=>M.replace(/^"|"$/g,"").trim()),R=w!==-1&&E[w]||"",F=P!==-1&&E[P]||"";R&&h.push({name:R,email:F})}}}if(m){if(d.length===0)throw new Error("No valid class elements found inside file.");const f=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:d})});if(!f.ok){const y=await f.json();throw new Error(y.error||"Server importation failed")}const g=await f.json();await s(),await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.length} 个班级数据!`:`Successfully imported ${g.imported.length} classes data!`})}else{if(h.length===0)throw new Error("No valid student elements found inside file.");const f=await fetch("/api/students/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({students:h})});if(!f.ok){const y=await f.json();throw new Error(y.error||"Server student importation failed")}const g=await f.json();await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.filter(y=>y.new).length} 名新学者,匹配并更新了其中的 ${g.imported.filter(y=>!y.new).length} 名同学!`:`Successfully imported ${g.imported.filter(y=>y.new).length} new students and updated ${g.imported.filter(y=>!y.new).length} existing ones!`})}}catch(u){a(u)}},l.onerror=()=>{a(new Error("Failed to read file from disk."))},l.readAsText(e)})}function xv(e,t){return new Promise((n,s)=>{const r=new FileReader;r.onload=i=>{try{const a=i.target?.result;if(!a)throw new Error("Empty CSV file");const l=a.split(/\r?\n/);if(l.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const c=l[0].split(",").map(m=>m.trim().toLowerCase()),u=c.findIndex(m=>m.includes("title")||m.includes("标题")||m.includes("课程")),d=c.findIndex(m=>m.includes("content")||m.includes("内容")||m.includes("正文"));if(u===-1||d===-1)throw new Error(t==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const h=[];for(let m=1;m<l.length;m++){const f=l[m].trim();if(!f)continue;const y=(f.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||f.split(",")).map(P=>P.replace(/^"|"$/g,"").trim()),C=y[u],w=y[d];C&&w&&h.push({title:C,content:w})}if(h.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(h)}catch(a){s(a)}},r.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},r.readAsText(e)})}async function yv(e,t){const{lang:n,setImportProgress:s,fetchLessons:r}=t;let i=0;for(let a=0;a<e.length;a++){const l=e[a];try{const c=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:l.title,content:l.content})});if(c.ok)i++;else{const u=await c.json();console.warn(`Failed to import item ${a+1}:`,u)}}catch(c){console.warn(`Error importing item ${a+1}:`,c)}s(a+1)}return i>0?(await r(),{success:!0}):{success:!1,errorMsg:n==="zh"?"所有课程项导入均失败。请检查控制台或格式。":"Failed to import any of the courses. Please check your console or schema."}}function bv(){const e=he(v=>v.session),t=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),n=e?.role==="student"||t,s=it(v=>v.errors),r=it(v=>v.studentErrors),i=it(v=>v.activeTab),a=it(v=>v.setActiveTab),l=it(v=>v.isErrorCenterOpen),c=it(v=>v.setIsErrorCenterOpen),u=it(v=>v.clearErrors),d=it(v=>v.clearStudentErrors),h=it(v=>v.removeError),m=it(v=>v.removeStudentError),[f,g]=p.useState(!1),[y,C]=p.useState(null),[w,P]=p.useState(new Set),[S,j]=p.useState(!1),A=s.length+(n?0:r.length),E=s.length>0||!n&&r.length>0,R=v=>{P(_=>{const L=new Set(_);return L.has(v)?L.delete(v):L.add(v),L})},F=async()=>{const v=ev(s,n?[]:r);await Ds(v)&&(g(!0),setTimeout(()=>g(!1),2500))},M=async(v,_,L=!1)=>{v.stopPropagation();const I=L?Eu(_):jo(_);await Ds(I)&&(C(_.id),setTimeout(()=>C(null),2500))},O=v=>{switch(v){case"react":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800",children:"React"});case"api":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700 dark:bg-purple-950/60 dark:text-purple-400 border border-purple-200 dark:border-purple-800",children:"API 5xx"});case"promise":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-700 dark:bg-amber-950/60 dark:text-amber-400 border border-amber-200 dark:border-amber-800",children:"Promise"});default:return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700 dark:bg-blue-950/60 dark:text-blue-400 border border-blue-200 dark:border-blue-800",children:"Runtime"})}};return o.jsxs(o.Fragment,{children:[E&&!l&&!S&&(n?o.jsxs(ys.button,{type:"button",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},className:"fixed bottom-5 left-5 z-40 w-8 h-8 rounded-full bg-slate-900/80 hover:bg-slate-900 text-rose-400 border border-rose-500/40 shadow-lg flex items-center justify-center cursor-pointer transition-all hover:scale-105 select-none",onClick:()=>c(!0),id:"system-error-pill",title:`系统状态提示: ${s.length} 处异常`,children:[o.jsx(Ps,{size:15}),o.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center leading-none shadow-xs border border-slate-900",children:s.length})]}):o.jsxs(ys.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.9},className:"fixed bottom-5 left-5 z-40 flex items-center gap-2 bg-slate-900/90 hover:bg-slate-900 backdrop-blur-md text-white px-3.5 py-2 rounded-2xl shadow-xl border border-rose-500/40 cursor-pointer select-none transition-all group",onClick:()=>{s.length===0&&r.length>0&&a("student"),c(!0)},id:"system-error-pill",children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-3 w-3 rounded-full bg-rose-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-rose-500"})]}),o.jsx(Ps,{size:15,className:"text-rose-400 group-hover:scale-110 transition-transform"}),o.jsxs("div",{className:"text-xs font-semibold flex items-center gap-1.5",children:[o.jsx("span",{children:"捕获到"}),o.jsx("span",{className:"bg-rose-500/80 text-white font-mono px-1.5 py-0.2 rounded-md text-xs font-bold",children:A}),o.jsx("span",{children:"处系统异常"}),r.length>0&&o.jsxs("span",{className:"text-[10px] text-rose-300 font-normal",children:["(含学生端 ",r.length,")"]})]}),o.jsx("button",{type:"button",className:"text-xs font-bold text-rose-300 hover:text-white bg-white/10 hover:bg-white/20 px-2 py-0.5 rounded-lg transition-colors ml-1",children:"查看与复制"}),o.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),j(!0)},className:"text-gray-400 hover:text-gray-200 p-0.5 hover:bg-white/10 rounded transition-colors ml-0.5",title:"暂时隐藏胶囊",children:o.jsx(Je,{size:13})})]})),o.jsx(qc,{children:l&&o.jsx("div",{className:"fixed inset-0 bg-gray-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50 overflow-hidden select-text",children:o.jsxs(ys.div,{initial:{opacity:0,scale:.95,y:10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:10},className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden text-gray-900 dark:text-gray-100",children:[o.jsxs("div",{className:"px-5 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between bg-gray-50/80 dark:bg-slate-850/80 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-xl",children:o.jsx(kp,{size:18})}),o.jsxs("div",{children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2",children:[o.jsx("span",{children:"系统异常诊断中心 (System Diagnostics)"}),o.jsxs("span",{className:"text-xs font-normal text-gray-500 dark:text-gray-400",children:["(",A," 项记录)"]})]})}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:"自动捕获运行时、Promise 及接口 5xx 异常,支持一键导出 Markdown 格式排查报告。"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:F,disabled:A===0,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 shadow-xs cursor-pointer ${f?"bg-emerald-600 text-white":"bg-indigo-600 hover:bg-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed"}`,title:"复制所有异常报告为 Markdown 文本",children:[f?o.jsx(tt,{size:13}):o.jsx(an,{size:13}),o.jsx("span",{children:f?"已复制全部!":"一键复制全部诊断日志"})]}),o.jsx("button",{type:"button",onClick:()=>{!n&&i==="student"?d():u()},disabled:i==="student"?r.length===0:s.length===0,className:"p-1.5 text-gray-500 hover:text-rose-600 dark:text-gray-400 dark:hover:text-rose-400 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",title:i==="student"?"清空学生端异常记录":"清空记录",children:o.jsx(Ul,{size:16})}),o.jsx("button",{type:"button",onClick:()=>c(!1),className:"p-1.5 text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors cursor-pointer",children:o.jsx(Je,{size:16})})]})]}),!n&&o.jsxs("div",{className:"px-5 py-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-slate-900/50 flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>a("local"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="local"?"bg-white dark:bg-slate-800 text-indigo-600 dark:text-indigo-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(Cp,{size:13}),o.jsxs("span",{children:["本机异常 (",s.length,")"]})]}),o.jsxs("button",{type:"button",onClick:()=>a("student"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="student"?"bg-white dark:bg-slate-800 text-rose-600 dark:text-rose-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(Ns,{size:14}),o.jsxs("span",{children:["学生端异常 (",r.length,")"]}),r.length>0&&o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-rose-500 animate-pulse"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 bg-slate-50/50 dark:bg-slate-950/30",children:!n&&i==="student"?r.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(tt,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无学生端上报的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"全班学生端运行良好,未发生未捕获的前端崩溃或接口 5xx 故障。"})]}):r.map((v,_)=>{const L=w.has(v.id),I=y===v.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(v.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(dn,{size:15}):o.jsx(Ts,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800 flex items-center gap-1",children:[o.jsx(Ns,{size:11}),o.jsx("span",{children:v.studentName||v.studentId})]}),O(v.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",r.length-_," ",v.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(v.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:v.message}),o.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[o.jsxs("span",{children:["学生学号/ID: ",v.studentId]}),v.lessonId&&o.jsxs("span",{children:["课节: ",v.lessonId]}),v.classId&&o.jsxs("span",{children:["班级: ",v.classId]}),v.endpoint&&o.jsxs("span",{children:["接口: ",v.endpoint]})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:N=>M(N,v,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${I?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条学生错误报告",children:[I?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:I?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),m(v.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(Je,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["学生: ",v.studentName||"未知"," (",v.studentId,")"]}),o.jsxs("span",{children:["页面地址: ",v.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(v.timestamp).toLocaleString()]})]}),v.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:v.stack})]}),v.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:v.componentStack})]})]})]},v.id)}):s.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(tt,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无捕获到的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"系统运行顺畅,所有模块均在正常状态下运作。"})]}):s.map((v,_)=>{const L=w.has(v.id),I=y===v.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(v.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(dn,{size:15}):o.jsx(Ts,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[O(v.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-_," ",v.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(v.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:v.message}),v.endpoint&&o.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",v.endpoint]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:N=>M(N,v,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${I?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条错误报告",children:[I?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:I?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),h(v.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(Je,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["页面地址: ",v.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(v.timestamp).toLocaleString()]})]}),v.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:v.stack})]}),v.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:v.componentStack})]})]})]},v.id)})})]})})})]})}function wv(){p.useEffect(()=>{if(typeof window>"u")return;const e=i=>{const a=i.reason,l=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",c=a instanceof Error?a.stack:void 0;Bt.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:l,stack:c}),console.warn("[GlobalErrorCapture] Caught unhandled rejection:",a)},t=i=>{if(!i.message&&!i.error)return;const a=i.message||(i.error?.message??"Unknown script error"),l=i.error?.stack;Bt.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:l}),console.warn("[GlobalErrorCapture] Caught window error:",i.error||i.message)},n=window.fetch,s=async(...i)=>{try{const a=await n(...i);if(!a.ok&&a.status>=500)try{const c=await a.clone().text();let u="";try{const m=JSON.parse(c);u=m.error||m.message||m.details||c}catch{u=c.slice(0,300)}const d=i[0],h=typeof d=="string"?d:d instanceof Request?d.url:String(d);Bt.getState().addError({type:"api",title:`服务端接口错误 (HTTP ${a.status})`,message:u||`Request failed with status ${a.status}`,endpoint:h,status:a.status})}catch{}return a}catch(a){const l=i[0],c=typeof l=="string"?l:l instanceof Request?l.url:String(l);throw c&&(c.startsWith("/api")||c.includes("/api/"))&&Bt.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:c,stack:a?.stack}),a}},r=XS(i=>{try{const a=_e.getState(),l=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||l))return;const u=typeof window<"u"?new URLSearchParams(window.location.search):null,d=a.session?.userId||u?.get("studentId")||"anonymous_student",h=a.session?.name||a.session?.username||u?.get("studentName")||d,m=a.selectedLesson||u?.get("lessonId")||null,f=a.liveClassSelectedClassId||u?.get("classId")||null,g={studentId:d,studentName:h,lessonId:m,classId:f,error:i},y=wt();if(y&&y.connected)y.emit("student-client-error",g);else{const C="/api/diagnostics/report",w=JSON.stringify(g);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(C,new Blob([w],{type:"application/json"})):fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:w}).catch(()=>{})}}catch(a){console.warn("[GlobalErrorCapture] Failed to report student error:",a)}});return window.fetch=s,window.addEventListener("unhandledrejection",e),window.addEventListener("error",t),()=>{window.fetch=n,window.removeEventListener("unhandledrejection",e),window.removeEventListener("error",t),r()}},[])}function Sv(e){return"#/"+e}function Ol(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}f0();const Dl="openlearnv2.agentProviderId";function vv(){wv();const e=he(k=>k.lang),t=he(k=>k.setLang),n=xa[e]??xa.zh,[s,r]=p.useState(!1),i=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),a=typeof window<"u"?new URLSearchParams(window.location.search).get("studentId"):null,l=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null;typeof window<"u"&&new URLSearchParams(window.location.search).get("classId");const[c,u]=p.useState(!0),[d,h]=p.useState(null),m=he(k=>k.liveClassSelectedClassId),f=he(k=>k.setLiveClassSelectedClassId),g=he(k=>k.liveClassIsActive),y=he(k=>k.setLiveClassIsActive),[C,w]=p.useState(0),[P,S]=p.useState([]),[j,A]=p.useState(new Map),E=Hb(),[R,F]=p.useState([]),[M,O]=p.useState({}),[v,_]=p.useState([]),[L,I]=p.useState(0),[N,z]=p.useState(!1),[U,T]=p.useState(null),[D,x]=p.useState(!1),[oe,me]=p.useState("system"),[b,Q]=p.useState(null),[X,B]=p.useState([]),[Z,re]=p.useState(!1),[de,xe]=p.useState(!1),ae=async()=>{try{re(!0);const k=await fetch("/api/resources");if(k.ok){const V=await k.json();B(V)}}catch(k){console.warn("Error fetching library resources:",k)}finally{re(!1)}};Ze.useEffect(()=>{Bs.getState().initTheme(),on.getState().initFontSize();const k=V=>{(V.ctrlKey||V.metaKey)&&V.altKey&&(V.key==="+"||V.key==="="?(V.preventDefault(),on.getState().increaseScale()):V.key==="-"||V.key==="_"?(V.preventDefault(),on.getState().decreaseScale()):V.key==="0"&&(V.preventDefault(),on.getState().resetScale()))};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[]),Ze.useEffect(()=>{D&&ae()},[D]);const je=he(k=>k.lessons),St=he(k=>k.setLessons),{lessonsSearchQuery:qt,setLessonsSearchQuery:vt,lessonsSortOrder:kt,setLessonsSortOrder:Ot,filterEnrollment:Y,setFilterEnrollment:ne,filterHasContent:le,setFilterHasContent:Ne,filterThisMonth:Ue,setFilterThisMonth:He,copyingLessonId:dt,setCopyingLessonId:Te,filteredAndSortedLessons:$}=mv(je),[q,K]=p.useState([]),J=he(k=>k.selectedLesson),ee=he(k=>k.setSelectedLesson),Pe=he(k=>k.elements),Ye=he(k=>k.setElements),[$e,st]=p.useState(!1),[ht,ge]=p.useState("idle"),[rt,Re]=p.useState(0),[Js,Vn]=p.useState(0),[Zs,Ct]=p.useState(""),[Wt,mn]=p.useState([]),[Ys,Ks]=p.useState(!1),[Xs,er]=p.useState(!1),[tr,nr]=p.useState("agent"),[sr,rr]=p.useState(!1),[ke,ir]=p.useState([]),[or,ar]=p.useState([]),[gn,xn]=p.useState(null),[Un,lr]=p.useState(""),Gt=he(k=>k.classes),cr=he(k=>k.setClasses),Oe=he(k=>k.students),Hn=he(k=>k.setStudents),{computerLabs:ur,fetchLabs:qn,todaySchedules:dr,fetchTodaySchedules:Qt,classSchedulesMap:hr,fetchClassSchedules:ye,scheduleAttendanceMap:fr,fetchScheduleAttendance:pr,expandedScheduleId:mr,setExpandedScheduleId:gr,newScheduleDate:xr,setNewScheduleDate:yr,newScheduleLessonId:br,setNewScheduleLessonId:wr}=av(),[Dt,Sr]=p.useState(null),vr=p.useRef(null),kr=k=>{Sr(k),vr.current=k},[Wn,Gn]=p.useState({}),[Cr,Er]=p.useState(null),Qn=p.useRef(null),[yn,bn]=p.useState(null),Ke=k=>{const V=Sm(k);V&&bn({type:k,data:{...V.defaultData}})},jr=async k=>{yn&&await Qn.current?.addElementAtCenter(yn.type,k),bn(null)},be=he(k=>k.session),Mt=he(k=>k.setSession),Jn=he(k=>k.siteInfo),Zn=he(k=>k.setSiteInfo),[ze,ft]=p.useState("teacher"),[Nr,Tr]=p.useState(!0),[Yn,Jt]=p.useState(!0),[Pr,pt]=p.useState("normal");p.useEffect(()=>{if(!be)return;const k=async()=>{try{const W=await fetch("/api/db-status");if(W.ok){const G=await W.json().catch(()=>({}));G.status==="warning"||G.warning?pt("warning"):pt("normal"),Jt(!0)}else W.status===429||W.status===503?(pt("warning"),Jt(!0)):(pt("error"),Jt(!1))}catch{pt("error"),Jt(!1)}};k();const V=setInterval(k,5e3);return()=>clearInterval(V)},[be]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/auth/session");if(V.ok){const W=await V.json();if(W.session)if(Mt(W.session),i){ft("student"),We("lesson");const G=a||W.session.studentId;G&&Sn(G),l&&ee(l),Nt()}else ft(W.session.role),W.session.role==="student"&&W.session.studentId&&(Sn(W.session.studentId),Nt())}}catch(V){console.warn("Session check failed",V)}finally{Tr(!1)}})()},[]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/site-settings");if(V.ok){const W=await V.json();Zn({siteName:W.siteName||"",slogan:W.slogan||"",logoUrl:W.logoUrl||null})}}catch(V){console.warn("Failed to fetch site settings:",V)}})()},[]);const Zt=he(k=>k.teacherTab),Xe=he(k=>k.setTeacherTab);p.useEffect(()=>{const k=()=>{const W=Ol(window.location.hash);W&&W!==_e.getState().teacherTab&&Xe(W)};window.addEventListener("hashchange",k);const V=Ol(window.location.hash);return V&&Xe(V),()=>window.removeEventListener("hashchange",k)},[Xe]),p.useEffect(()=>{const k=Sv(Zt);window.location.hash!==k&&(window.location.hash=k)},[Zt,Xe]);const[Nu,Ir]=p.useState(!1),[Tu,Pu]=p.useState(!1),[Iu,Au]=p.useState(!1);p.useEffect(()=>{be?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&Ir(!0)},[be]);const zu=async k=>{await Kt(),await mt(),await Qt().catch(()=>{}),f(k.classId),ee(k.lessonId),y(!0),Ae(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")};p.useEffect(()=>{Zt==="live_class"&&r(!0)},[Zt]);const{timelineSegments:_u,activeSegmentId:Ar,setActiveSegmentId:wn,draggedSegmentIdx:Lu,setDraggedSegmentIdx:Ru,editorSaveStatus:Ou,setEditorSaveStatus:Du,editorLastSavedTime:Mu,setEditorLastSavedTime:Fu,editorPanelsExpanded:$u,setEditorPanelsExpanded:Bu,saveTimeline:Vu}=lv({selectedLesson:J,lessons:je,setLessons:St}),[ce,Sn]=p.useState(null),[zr,Uu]=p.useState(null),[Hu,qu]=p.useState(!1),Ae=(k,V,W="info")=>{const G=Math.random().toString(36).substring(2,9);_e.getState().addToast({id:G,title:k,message:V,type:W}),setTimeout(()=>{_e.getState().removeToast(G)},6e3)},qe=ze==="student"&&(!!ce&&!!Oe.find(k=>k.id===ce)?.locked_lesson_id||Hu),_r=()=>{Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Locked",e==="zh"?"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":"The teacher locked the class focus. Navigation is disabled — please follow the current lesson.","warning")},mt=async()=>{try{const k=await fetch("/api/lessons");if(k.ok){const V=await k.json();St(V),!_e.getState().selectedLesson&&V.length>0&&ee(V[0].id)}}catch(k){console.warn("Failed to fetch lessons",k)}},No=p.useRef(()=>{}),To=rv({lang:e,addToast:Ae,fetchLessons:mt,setSelectedLesson:ee,setTeacherTab:Xe}),{isCourseWizardOpen:Gv,setIsCourseWizardOpen:Wu,wizardStep:Qv,setWizardStep:Gu,wizardCourseTitle:Jv,setWizardCourseTitle:Zv,wizardCourseCategory:Yv,setWizardCourseCategory:Kv,wizardCourseDescription:Xv,setWizardCourseDescription:ek,wizardCourseContent:tk,setWizardCourseContent:nk,wizardCourseTimeline:sk,setWizardCourseTimeline:rk,wizardIsSubmitting:ik,handleDeployWizardCourse:ok}=To,{plugins:Et,fetchPlugins:Qu,aiProviders:gt,fetchAIProviders:Ju,testingProviderId:Zu,storeTab:Yu,setStoreTab:Ku,pluginCode:Xu,setPluginCode:ed,installingPlugin:td,events:nd,fetchEvents:sd,approvals:rd,fetchApprovals:id,scoreOverrides:od,setScoreOverrides:ad,handleInstallPlugin:ld,handleZipPluginUpload:cd,handleTogglePlugin:ud,handleDeletePlugin:dd,handleApprove:hd,handleReject:fd}=sv({session:be,host:E,lang:e,addToast:Ae,setChatLog:k=>No.current(k),setTeacherTab:Xe,fetchLessons:mt}),[Ft,Po]=p.useState(()=>typeof window>"u"?"":window.localStorage.getItem(Dl)||""),Lr=gt.some(k=>k.id===Ft)?Ft:gt[0]?.id||"",pd=gt.find(k=>k.id===Lr)||null,[jt,Io]=p.useState("dashboard"),Ao=p.useRef(qe),zo=p.useRef(jt);p.useEffect(()=>{Ao.current=qe,zo.current=jt},[qe,jt]),p.useEffect(()=>{qe&&(u(!0),Io("lesson"))},[qe]);const We=k=>{const V=typeof k=="function"?k(zo.current):k;if(Ao.current&&V!=="lesson"){_r();return}Io(k)},[_o,Yt]=p.useState("whiteboard"),[md,gd]=p.useState(null),[xt,Kn]=p.useState(null),[xd,Lo]=p.useState(!1),[yd,Ro]=p.useState(null),[bd,Oo]=p.useState("whiteboard"),[wd,Sd]=p.useState("none"),[vd,kd]=p.useState("none"),[Cd,Do]=p.useState(!0);p.useEffect(()=>{jt!=="lesson"&&Do(!0)},[jt]);const Mo=iv(),{isQuizGeneratorOpen:ak,setIsQuizGeneratorOpen:Ed,quizGeneratorClassId:lk,setQuizGeneratorClassId:jd,quizGenMode:ck,setQuizGenMode:Nd,quizGenSelectedLessonId:uk,setQuizGenSelectedLessonId:Td,quizGenTopic:dk,setQuizGenTopic:Pd,isGeneratingSuggestions:hk,setIsGeneratingSuggestions:fk,suggestedObjectives:pk,setSuggestedObjectives:Id,suggestedQuestions:mk,setSuggestedQuestions:Ad,savingQuiz:gk,setSavingQuiz:xk,quizStudentAnswers:zd,setQuizStudentAnswers:Fo,quizGenTimeLimit:yk,setQuizGenTimeLimit:bk,quizStudentAnswersRef:_d,subAssignmentTab:Ld,setSubAssignmentTab:$o}=Mo,[Rd,Od]=p.useState(""),[Dd,Md]=p.useState("all"),[Fd,$d]=p.useState("grid"),[Bd,Vd]=p.useState({}),[Ud,Hd]=p.useState({}),[qd,Wd]=p.useState({}),Bo=cv(ze,zr,e),{studentNotifications:Gd,unreadNotifications:Qd,readNotifications:Vo,setReadNotifications:Xn,selectedNotificationForModal:Jd,setSelectedNotificationForModal:Zd,isNotificationsOpen:Yd,setIsNotificationsOpen:Kd}=Bo;p.useEffect(()=>{ce&&fetch(`/api/students/${ce}/read_notifications`).then(k=>k.ok?k.json():[]).then(k=>{Xn(new Set(k))}).catch(k=>{console.warn("Failed to load read notifications from DB",k),Xn(new Set)})},[ce]);const Xd=p.useRef(null),eh=k=>{Er(k),Xd.current=k},[th,nh]=p.useState({}),[sh,rh]=p.useState({}),[wk,Sk]=p.useState({}),[vk,kk]=p.useState({}),[ih,Ck]=p.useState(null),[oh,ah]=p.useState("dueDate"),[Ek,jk]=p.useState(null),[lh,ch]=p.useState({}),[uh,Uo]=p.useState(!1),[dh,Ho]=p.useState(!1),[hh,Rr]=p.useState(null),[fh,Or]=p.useState(null),[Dr,ph]=p.useState(null),mh=p.useRef(null),qo=k=>{ph(k),mh.current=k};p.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(Dl,Ft)},[Ft]),p.useEffect(()=>{gt.length>0&&!gt.some(k=>k.id===Ft)&&Po(gt[0].id)},[gt,Ft]);const gh=async(k,V,W)=>{try{if((await fetch(`/api/classes/${k}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:V,scheduledDate:W})})).ok)return await ye(k),!0}catch(G){console.error("Quick schedule class failed",G)}return!1},xh=async(k,V,W)=>{try{const G=V||W||"Assignment",Ie=await fetch(`/api/classes/${k}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:G})});if(Ie.ok){const yt=await Ie.json().catch(()=>({}));return await vn(k),yt.id||"assignment-created"}}catch(G){console.error("Quick generate assignment failed",G)}return null},yh=async(k,V)=>{try{const W=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:k,content:V})});if(W.ok){const G=await W.json().catch(()=>({}));return await mt(),G.id||"lesson-created"}}catch(W){console.error("Quick create lesson failed",W)}return""},bh=()=>{Rl("class",e)},wh=async k=>{if(k){if(!k.name.toLowerCase().endsWith(".csv")){ge("error"),Ct(e==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}ge("parsing"),Ct("");try{const V=await xv(k,e);mn(V),ge("idle")}catch(V){ge("error"),Ct(V.message||String(V))}}},Sh=async()=>{if(Wt.length===0)return;ge("importing"),Re(0),Vn(Wt.length);const k=await yv(Wt,{lang:e,setImportProgress:Re,fetchLessons:mt});k.success?ge("success"):(ge("error"),Ct(k.errorMsg||""))},vh=async k=>{const V=await fetch(`/api/lessons/${k}`,{method:"DELETE"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to delete course")}await mt(),J===k&&ee(null),Ae(e==="zh"?"课程已删除":"Course Deleted",e==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},kh=async k=>{Te(k);try{const V=await fetch(`/api/lessons/${k}/clone`,{method:"POST"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to copy course")}await mt(),Ae(e==="zh"?"复制成功":"Course Copied",e==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(V){Ae(e==="zh"?"复制失败":"Copy Failed",V.message||(e==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{Te(null)}},Wo=async()=>{try{const k=await fetch("/api/commands/registered");if(!k.ok)return;const V=k.headers.get("content-type");if(V&&V.includes("application/json")){const W=await k.json();Array.isArray(W)&&K(W)}}catch(k){console.warn("Failed to fetch registered commands",k)}},Ch=async k=>{if(be)try{const V=await fetch(`/api/vfs${k?`?parentId=${k}`:""}`);if(V.ok){const W=await V.json();ir(W)}}catch(V){console.warn("Failed to fetch VFS nodes",V)}},Eh=async()=>{try{const k=await fetch("/api/processes");k.ok&&ar(await k.json())}catch{}},Kt=async()=>{try{const k=await fetch("/api/classes");k.ok&&cr(await k.json())}catch{}},Nt=async()=>{try{const k=await fetch("/api/students");k.ok&&Hn(await k.json())}catch{}},Xt=async k=>{try{const V=await fetch(`/api/classes/${k}/students`);if(V.ok){const W=await V.json();Gn(G=>({...G,[k]:W}))}}catch{}},Mr=async k=>{try{const V=await fetch(`/api/classes/${k}/progress`);if(V.ok){const W=await V.json();rh(G=>({...G,[k]:W}))}}catch{}},[Fr,jh]=p.useState({}),vn=async k=>{try{const V=await fetch(`/api/classes/${k}/dashboard`);if(V.ok){const W=await V.json();jh(G=>({...G,[k]:W}))}}catch{}},Nh=pv({lang:e,classes:Gt,classStudentsMap:Wn,classDashboardMap:Fr,fetchClassStudents:Xt,fetchClassDashboard:vn,fetchClassProgress:Mr}),{isExportWeightModalOpen:Th,setIsExportWeightModalOpen:Go,exportClassId:Ph,setExportClassId:Ih,exportClassName:Ah,setExportClassName:zh,quizzesWeight:_h,setQuizzesWeight:Qo,assignmentsWeight:Lh,setAssignmentsWeight:Jo,customCategoryOverrides:Rh,setCustomCategoryOverrides:Zo,exportDropdownOpen:Oh,setExportDropdownOpen:Dh,exportTooltipOpen:Mh,setExportTooltipOpen:Fh,loadingExportClassId:$h,isExportingAllCombined:Bh,isGeneratingPDFReport:Vh,handleQuizzesWeightChange:Uh,handleAssignmentsWeightChange:Hh,csvPreviewData:qh,triggerExportForClass:Wh,handleExportGrades:Gh,handleGeneratePDFReport:Qh,handleExportAllClassesCombined:Yo,get30DayAverageWarning:Jh}=Nh,Ko=ov({lang:e,classes:Gt,expandedClassId:Dt,fetchClasses:Kt,fetchClassStudents:Xt,handleExportAllClassesCombined:Yo}),{batchMode:Zh,setBatchMode:Yh,selectedClassIds:Kh,setSelectedClassIds:Xh,selectedStudentIds:ef,setSelectedStudentIds:tf,batchPicker:Nk,setBatchPicker:Tk,batchPickerLesson:Pk,setBatchPickerLesson:Ik,batchPickerDate:Ak,setBatchPickerDate:zk,batchPickerTargetClass:_k,setBatchPickerTargetClass:Lk,toggleClassSelection:nf,toggleSelectAllClasses:sf,toggleStudentSelection:rf,toggleSelectAllStudents:of,handleBatchDeleteClasses:af,handleBatchExportClasses:lf,handleBatchSetPasscode:cf,handleBatchScheduleClasses:uf,handleBatchDeleteStudents:df,handleBatchResetPassword:hf,handleBatchTransferStudents:ff,handleBatchSetLockedLesson:pf,confirmBatchPicker:Rk}=Ko,$r=async k=>{try{const V=await fetch(`/api/students/${k}/dashboard`);if(V.ok){const W=await V.json();Uu(W),W.profile&&W.profile.locked_lesson_id&&(ee(W.profile.locked_lesson_id),We("lesson"))}}catch{}},mf=async(k=!1)=>{if(!xt)return;const W=xt?.content&&xt.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(_d.current):"Submitted via Whiteboard";try{(await fetch(`/api/assignments/${xt.id}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:ce,content:W})})).ok&&(k&&alert("Time is up! Your assessment was successfully submitted automatically."),await $r(ce),We("dashboard"),Kn(null))}catch(G){console.error(G)}};p.useEffect(()=>{if(be&&ze==="student"&&ce){$r(ce);const k=Oe.find(V=>V.id===ce);k&&k.locked_lesson_id&&(ee(k.locked_lesson_id),We("lesson"))}},[be,ze,ce,Oe]);const gf=p.useRef(ze),xf=p.useRef(ce),yf=p.useRef(e),bf=p.useRef(Oe),wf=p.useRef(Ae),es=p.useRef(new Set);p.useRef(new Set),p.useEffect(()=>{gf.current=ze},[ze]),p.useEffect(()=>{xf.current=ce},[ce]),p.useEffect(()=>{yf.current=e},[e]),p.useEffect(()=>{bf.current=Oe},[Oe]),p.useEffect(()=>{wf.current=Ae},[Ae]),p.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const k=Ce.getState(),V=Et.filter(G=>G.status==="active");for(const G of V){if(!G.has_frontend||es.current.has(G.id))continue;const Ie=k.activePlugins.find(bt=>bt.id===G.id),yt=!!(Ie&&G.version&&Ie.version!==G.version);if(!(!Ie||yt||Ie.state!==we.ACTIVE&&Ie.state!==we.ACTIVATING))continue;es.current.add(G.id);const na=()=>{if(!k.activePlugins.find(bt=>bt.id===G.id))k.addPlugin({id:G.id,name:G.name,version:G.version,state:we.INSTALLED,executionMode:"inline"});else if(yt)try{Ce.setState(bt=>({activePlugins:bt.activePlugins.map(kn=>kn.id===G.id?{...kn,version:G.version,name:G.name}:kn)}))}catch{}try{const bt=JSON.parse(G.manifest);E.activateRemotePlugin(G.id,bt).catch(kn=>{console.error(`[App] Failed to activate remote plugin "${G.name}":`,kn)}).finally(()=>{es.current.delete(G.id)})}catch(bt){es.current.delete(G.id),console.error(`[App] Failed to parse manifest for plugin "${G.name}":`,bt)}};Ie&&Ie.state===we.ACTIVE&&yt?E.deactivatePlugin(G.id).catch(()=>{}).finally(na):na()}const W=Et.filter(G=>G.status!=="active");for(const G of W){if(!G.has_frontend)continue;const Ie=k.activePlugins.find(yt=>yt.id===G.id);Ie&&Ie.state===we.ACTIVE&&E.deactivatePlugin(G.id).catch(yt=>{console.error(`[App] Failed to deactivate remote plugin "${G.name}":`,yt)})}},[Et,E]),Ze.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const k=Ce.getState();for(const V of Et)V.status==="active"&&(k.dashboardVisibility.has(V.id)||k.setDashboardVisibility(V.id,!0))},[Et,E]);const Sf=async k=>{if(ze==="student"&&ce&&J)try{await fetch(`/api/students/${ce}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:J,completed:k===100,progressPercent:k})})}catch(V){console.error("Failed to update student progress:",V)}},vf=async(k,V)=>{try{const W=await fetch(`/api/classes/${k}/lessons/${V}/progress`);W.ok&&_(await W.json())}catch{}};p.useEffect(()=>{m&&J?vf(m,J):_([])},[m,J]),p.useEffect(()=>{m&&Xt(m)},[m]);const kf=async k=>{try{const V=await fetch(`/api/students/${k}/progress`);if(V.ok){const W=await V.json();nh(G=>({...G,[k]:W}))}}catch{}},Xo=async k=>{try{const V=await fetch(`/api/processes/${k}/logs`);if(V.ok){const W=await V.json();lr(W.logs||""),xn(k)}}catch{}},ea=p.useRef(""),Tt=async k=>{try{const V=await fetch(`/api/lessons/${k}/whiteboard`);if(!V.ok)return;const W=await V.json(),G=JSON.stringify(W);G!==ea.current&&(ea.current=G,Ye(W))}catch{}},Cf=p.useRef(null);p.useRef(null);const Ef=p.useRef(null);p.useEffect(()=>{Cf.current=J},[J]),p.useEffect(()=>{Ef.current=xt},[xt]),ou(be);const{chatLog:jf,setChatLog:Nf,input:Tf,setInput:Pf,loading:If,chatAttachments:Af,setChatAttachments:zf,handleChatFileChange:_f,handleChatDrop:Lf,handleSend:Rf,handleClearAgentMemory:Of}=Xw({lang:e,t:n,selectedLesson:J,effectiveAgentProviderId:Lr,expandedClassId:Dt,fetchLessons:mt,fetchClasses:Kt,fetchStudents:Nt,fetchClassStudents:Xt,fetchClassProgress:Mr,fetchClassDashboard:vn,fetchElements:Tt});No.current=Nf,Kw({session:be,showProcessLogs:gn,activeStudentId:ce,currentVfsParent:Dr,selectedLesson:J,selectedAssignment:xt,expandedClassId:Dt,fetchLessons:mt,fetchPlugins:Qu,fetchRegisteredCommands:Wo,fetchEvents:sd,fetchApprovals:id,fetchProcesses:Eh,fetchClasses:Kt,fetchTodaySchedules:Qt,fetchStudents:Nt,fetchLabs:qn,fetchVfs:Ch,fetchProcessLogs:Xo,fetchClassStudents:Xt,fetchElements:Tt});const{socketRef:Df}=tv({session:be,host:E,activeRole:ze,activeStudentId:ce,selectedLesson:J,activeSegmentId:Ar,studentViewStatus:jt,lang:e,students:Oe,addToast:Ae,setOnlineStudentIds:F,setActiveStudentLessons:O,setLessons:St,setActiveSegmentId:wn,setLiveClassStudentProgress:_,setLiveClassAcknowledgedMap:A,setLiveClassFeed:S,setSelectedLesson:ee,setStudentViewStatus:We,studentLessonTab:_o,setStudentLessonTab:Yt,selectedAssignment:xt,setSelectedAssignment:Kn,setLocalProgressPercent:I,fetchStudentDashboard:$r,fetchStudents:Nt,fetchElements:Tt}),Mf=k=>{Rl(k,e)},Ff=async k=>{Ho(!0),Rr(null),Or(null);try{const V=await gv(k,{lang:e,fetchClasses:Kt,fetchStudents:Nt});Or(V.message)}catch(V){Rr(V.message||String(V))}finally{Ho(!1)}},$f=()=>{t(e==="zh"?"en":"zh")},Bf=p.useCallback(k=>{Mt(k),k.role==="teacher"?(ft("teacher"),Xe("dashboard")):(ft("student"),Sn(k.studentId),Nt())},[]),ta=async()=>{try{await fetch("/api/auth/logout",{method:"POST"})}catch(k){console.error("Logout failed",k)}Mt(null)},[Vf,Br]=p.useState(!1);return p.useEffect(()=>{if(!i)return;const k=new Ni;k.requestHandshake();const V=k.onMessage(W=>{switch(W.type){case"TEACHER_INIT_STATE":{const G=W.payload;G.selectedLesson&&(ee(G.selectedLesson),Tt(G.selectedLesson)),G.activeSegmentId&&wn(G.activeSegmentId),G.activeTab&&Yt(G.activeTab),G.liveClassTimeRemaining!==void 0&&w(G.liveClassTimeRemaining),G.fullscreenElementId!==void 0&&(ln.getState().setRemoteFullscreenElementId(G.fullscreenElementId),G.fullscreenElementId&&Yt("whiteboard")),We("lesson");break}case"TEACHER_CHANGE_LESSON":{c&&W.payload.lessonId&&(ee(W.payload.lessonId),Tt(W.payload.lessonId),We("lesson"));break}case"TEACHER_CHANGE_SEGMENT":{c&&W.payload.segmentId&&wn(W.payload.segmentId);break}case"TEACHER_CHANGE_TAB":{c&&W.payload.tab&&Yt(W.payload.tab);break}case"TEACHER_LOCK_CLASS":{qu(!!W.payload.locked),W.payload.locked?(u(!0),We("lesson"),Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Lock",e==="zh"?"老师已开启全班专注锁定,界面将保持同步授课。":"Teacher locked screen for class.","warning")):Ae(e==="zh"?"🔓 屏幕已解锁":"🔓 Screen Unlocked",e==="zh"?"老师已解除锁定,您可以自由浏览或答题。":"Screen unlocked.","info");break}case"TEACHER_PICK_STUDENT":{(!ce||ce===W.payload.studentId||a===W.payload.studentId)&&h(W.payload);break}case"TEACHER_SYNC_TIMER":{w(W.payload.timeRemaining);break}case"TEACHER_BROADCAST_COUNTDOWN":{w(W.payload.timeRemaining);break}case"TEACHER_PING_STUDENT":{(!ce||ce===W.payload.studentId)&&Ae(e==="zh"?"⚠️ 课堂提醒":"⚠️ Classroom Alert",W.payload.message||(e==="zh"?"老师提醒您集中注意力跟上教学进度!":"Please keep up with class!"),"warning");break}case"TEACHER_BROADCAST_FULLSCREEN":{const{elementId:G,lessonId:Ie}=W.payload;ln.getState().setRemoteFullscreenElementId(G),G&&(Ie&&Ie!==J&&(ee(Ie),Tt(Ie)),We("lesson"),Yt("whiteboard"));break}}});return()=>{V(),k.destroy()}},[i,c,ce,a,e]),Nr?o.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[o.jsx(Zi,{size:48,className:"text-indigo-500 animate-spin"}),o.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:e==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]}):be?o.jsx(o.Fragment,{children:o.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[o.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[be?.role==="teacher"&&ze==="student"&&!i&&o.jsxs("div",{className:"bg-gradient-to-r from-amber-500 via-amber-600 to-orange-500 text-white px-6 py-1.5 flex items-center justify-between text-xs font-medium shadow-sm z-30 shrink-0 border-b border-amber-600/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("span",{className:"bg-black/20 text-amber-100 px-2 py-0.5 rounded font-bold uppercase tracking-wider text-xs flex items-center gap-1",children:[o.jsx(Ms,{size:12}),e==="zh"?"学生模拟模式":"Student View Mode"]}),o.jsx("span",{children:e==="zh"?`您当前正在以学生身份(${Oe.find(k=>k.id===ce)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${Oe.find(k=>k.id===ce)?.name||"None"}).`})]}),o.jsxs("button",{type:"button",onClick:()=>ft("teacher"),className:"bg-white text-amber-800 hover:bg-amber-50 active:bg-amber-100 font-bold px-3 py-1 rounded-md shadow-xs transition-all flex items-center gap-1.5 cursor-pointer text-xs",children:[o.jsx(Qi,{size:13}),e==="zh"?"退出模拟并返回教师端":"Exit Student View"]})]}),i?o.jsxs("header",{className:"h-13 bg-surface/95 backdrop-blur-md border-b border-theme px-4 flex items-center justify-between z-20 shrink-0 select-none shadow-xs",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-tr from-pink-500 to-rose-600 flex items-center justify-center text-white font-black shadow-sm text-sm",children:"🎓"}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h1",{className:"text-sm font-black text-main tracking-wide",children:e==="zh"?"互动课堂 · 学生端":"Interactive Classroom · Student Client"}),o.jsxs("span",{className:"flex items-center gap-1 text-xs font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full",children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"}),e==="zh"?"已与教师中控台实时联动":"Synced with Teacher"]})]}),o.jsxs("div",{className:"text-xs text-muted flex items-center gap-2",children:[o.jsx("span",{children:ce?`学生: ${Oe.find(k=>k.id===ce)?.name||ce}`:"学生端"}),o.jsx("span",{children:"•"}),o.jsx("span",{children:J?`课节: ${je.find(k=>k.id===J)?.title||J}`:"等待教师推流课节..."})]})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>{if(qe){_r();return}u(!c)},disabled:qe,className:`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 shadow-2xs ${qe?"cursor-not-allowed":"cursor-pointer"} ${c?"bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800":"bg-surface text-muted border-theme hover:text-main"} ${qe?"opacity-70":""}`,title:qe?e==="zh"?"全班专注锁定中,已强制跟随教师步调":"Class focus is locked; following the teacher is enforced":e==="zh"?"开启后,教师端切换课节/环节/Tab时,学生端将自动同步跟随":"Follow teacher navigation",children:[o.jsx(Zl,{size:12,className:c?"animate-spin":""}),o.jsx("span",{children:e==="zh"?`跟随教师步调: ${c?"开":"关"}`:`Follow Teacher: ${c?"ON":"OFF"}`})]}),o.jsx(rc,{lang:e}),o.jsx("button",{type:"button",onClick:()=>{document.fullscreenElement?document.exitFullscreen().catch(()=>{}):document.documentElement.requestFullscreen().catch(()=>{})},className:"p-1.5 text-muted hover:text-main rounded-lg border border-theme hover:bg-surface-secondary transition-colors cursor-pointer",title:e==="zh"?"切换全屏":"Toggle Fullscreen",children:o.jsx(Ep,{size:14})}),o.jsx("button",{type:"button",onClick:()=>window.close(),className:"px-2.5 py-1.5 text-xs font-bold text-rose-600 hover:text-rose-700 bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 rounded-lg transition-colors cursor-pointer",title:e==="zh"?"关闭学生端Tab":"Close Tab",children:e==="zh"?"关闭Tab":"Close Tab"})]})]}):o.jsx(fm,{activeRole:ze,setActiveRole:ft,lang:e,teacherTab:Zt,studentViewStatus:jt,session:be,activeStudentId:ce,students:Oe,studentDashboardData:zr,isNotificationsOpen:Yd,studentNotifications:Gd,unreadNotifications:Qd,readNotifications:Vo,selectedNotificationForModal:Jd,dbConnected:Yn,dbStatus:Pr,siteInfo:Jn,setActiveStudentId:Sn,setReadNotifications:Xn,setIsSystemResourceLibraryOpen:x,setProfileOpen:Br,setTeacherTab:Xe,setStudentViewStatus:We,setIsNotificationsOpen:Kd,setSelectedNotificationForModal:Zd,handleLogout:ta,toggleLanguage:$f,isStudentLocked:qe,onBlockedNavigate:_r}),o.jsx(xm,{open:Vf,session:be,lang:e,onClose:()=>Br(!1),onSaved:k=>{be&&Mt({...be,name:k}),Br(!1)},onAvatar:k=>{be&&Mt({...be,avatar:k??void 0})}}),o.jsx(x0,{students:Oe,activeStudentId:ce,isStudentLocked:qe,studentViewStatus:jt,studentDashboardData:zr,readNotifications:Vo,setReadNotifications:Xn,addToast:Ae,lang:e,setSelectedLesson:ee,setStudentViewStatus:We,setSelectedAssignment:Kn,setQuizStudentAnswers:Fo,setSubAssignmentTab:$o,lessons:je,selectedLesson:J,studentFullscreenPanel:vd,setStudentFullscreenPanel:kd,timelineSegments:_u,activeSegmentId:Ar,setActiveSegmentId:wn,localProgressPercent:L,setLocalProgressPercent:I,updateStudentProgress:Sf,isStudentLessonContentCollapsed:Cd,setIsStudentLessonContentCollapsed:Do,studentLessonTab:_o,setStudentLessonTab:Yt,elements:Pe,activeRole:ze,fetchElements:Tt,currentVfsParent:Dr,setCurrentVfsParent:qo,vfsNodes:ke,studentSelectedCourseware:md,setStudentSelectedCourseware:gd,selectedAssignment:xt,quizStudentAnswers:zd,submitQuizAssignment:mf,subAssignmentTab:Ld,mainNavCollapsed:s,setMainNavCollapsed:r,teacherTab:Zt,setTeacherTab:Xe,session:be,todaySchedules:dr,t:n,classes:Gt,approvals:rd,processes:or,isApprovalsCollapsed:Tu,setIsApprovalsCollapsed:Pu,isProcessesCollapsed:Iu,setIsProcessesCollapsed:Au,scoreOverrides:od,setScoreOverrides:ad,handleApprove:hd,handleReject:fd,showLogs:sr,setShowLogs:rr,processLogsContent:Un,showProcessLogs:gn,fetchProcessLogs:Xo,setShowProcessLogs:xn,handleQuickScheduleClass:gh,handleQuickGenerateAssignment:xh,handleQuickCreateLesson:yh,setActiveRole:ft,editorSaveStatus:Ou,setEditorSaveStatus:Du,editorLastSavedTime:Mu,setEditorLastSavedTime:Fu,setIsLessonPreviewVisible:Lo,setPreviewLessonTab:Oo,setPreviewSelectedCourseware:Ro,handlePaletteActivate:Ke,draggedSegmentIdx:Lu,setDraggedSegmentIdx:Ru,saveTimeline:Vu,editorPanelsExpanded:$u,setEditorPanelsExpanded:Bu,whiteboardRef:Qn,paletteEdit:yn,handlePaletteConfirm:jr,setPaletteEdit:bn,plugins:Et,liveClassSelectedClassId:m,setLiveClassSelectedClassId:f,liveClassIsActive:g,setLiveClassIsActive:y,liveClassTimeRemaining:C,setLiveClassTimeRemaining:w,liveClassFeed:P,setLiveClassFeed:S,liveClassAcknowledgedMap:j,setLiveClassAcknowledgedMap:A,onlineStudentIds:R,activeStudentLessons:M,liveClassStudentProgress:v,storeTab:Yu,setStoreTab:Ku,pluginCode:Xu,setPluginCode:ed,installingPlugin:td,onInstall:ld,onZipUpload:cd,onToggle:ud,onDelete:dd,lessonsSearchQuery:qt,setLessonsSearchQuery:vt,lessonsSortOrder:kt,setLessonsSortOrder:Ot,filteredLessons:$,onOpenImportLessons:()=>{ge("idle"),Re(0),Vn(0),Ct(""),mn([]),st(!0)},onOpenCourseWizard:()=>{Gu(1),Wu(!0)},onViewCourse:k=>{Xe("lesson_editor"),ee(k)},onDeleteCourse:vh,onCopyCourse:kh,filterEnrollment:Y,setFilterEnrollment:ne,filterHasContent:le,setFilterHasContent:Ne,filterThisMonth:Ue,setFilterThisMonth:He,copyingLessonId:dt,onSchedulesUpdated:Qt,onLogout:ta,aiProviders:gt,testingProviderId:Zu,onAIProvidersChanged:Ju,onTriggerTour:()=>Ir(!0),siteInfo:Jn,onSiteInfoChanged:Zn,computerLabs:ur,onRefresh:qn,registeredCommands:q,fetchRegisteredCommands:Wo,batchMode:Zh,selectedClassIds:Kh,setSelectedClassIds:Xh,setSelectedStudentIds:tf,setBatchMode:Yh,expandedClassId:Dt,setExpandedClassId:kr,exportTooltipOpen:Mh,setExportTooltipOpen:Fh,exportDropdownOpen:Oh,setExportDropdownOpen:Dh,isExportingAllCombined:Bh,loadingExportClassId:$h,classStudentsMap:Wn,setClassStudentsMap:Gn,expandedStudentId:Cr,setExpandedStudentId:eh,selectedStudentIds:ef,rosterViewMode:Fd,setRosterViewMode:$d,rosterSearchQuery:Rd,setRosterSearchQuery:Od,rosterTagFilter:Dd,setRosterTagFilter:Md,toggleSelectAllStudents:of,handleBatchDeleteStudents:df,handleBatchResetPassword:hf,handleBatchTransferStudents:ff,handleBatchSetLockedLesson:pf,toggleStudentSelection:rf,get30DayAverageWarning:Jh,studentProgressMap:th,studentActiveTabs:qd,setStudentActiveTabs:Wd,setStudents:Hn,fetchClassStudents:Xt,fetchStudents:Nt,parseCSV:rm,setImportError:Rr,setImportSuccess:Or,setShowImportModal:Uo,fetchClasses:Kt,classSubmissionFilters:Bd,setClassSubmissionFilters:Vd,classActiveTabs:Ud,setClassActiveTabs:Hd,classProgressMap:sh,classSchedulesMap:hr,classDashboardMap:Fr,assignmentSortOrder:oh,setAssignmentSortOrder:ah,isGeneratingPDFReport:Vh,handleGeneratePDFReport:Qh,setExportClassId:Ih,setExportClassName:zh,setQuizzesWeight:Qo,setAssignmentsWeight:Jo,setCustomCategoryOverrides:Zo,setIsExportWeightModalOpen:Go,isGeneratingAssignment:ih,setQuizGeneratorClassId:jd,setQuizGenMode:Nd,setQuizGenSelectedLessonId:Td,setQuizGenTopic:Pd,setSuggestedObjectives:Id,setSuggestedQuestions:Ad,setIsQuizGeneratorOpen:Ed,setActiveStudentId:Sn,isGrading:lh,setIsGrading:ch,fetchClassDashboard:vn,newScheduleDate:xr,setNewScheduleDate:yr,newScheduleLessonId:br,setNewScheduleLessonId:wr,expandedScheduleId:mr,setExpandedScheduleId:gr,fetchScheduleAttendance:pr,scheduleAttendanceMap:fr,toggleSelectAllClasses:sf,handleBatchDeleteClasses:af,handleBatchExportClasses:lf,handleBatchSetPasscode:cf,handleBatchScheduleClasses:uf,handleExportAllClassesCombined:Yo,triggerExportForClass:Wh,fetchClassProgress:Mr,fetchClassSchedules:ye,fetchStudentProgress:kf,toggleClassSelection:nf,socketRef:Df,setShowCoursewareHub:xe,fetchTodaySchedules:Qt})]}),o.jsx(_w,{showRightSidebar:Xs,setShowRightSidebar:er,rightSidebarTab:tr,setRightSidebarTab:nr,effectiveAgentProviderId:Lr,agentProviderId:Ft,setAgentProviderId:Po,aiProviders:gt,selectedAgentProvider:pd,chatLog:jf,loading:If,input:Tf,setInput:Pf,handleSend:Rf,chatAttachments:Af,setChatAttachments:zf,handleChatFileChange:_f,handleChatDrop:Lf,onClearAgentMemory:Of,events:nd,lang:e,t:n}),o.jsx(Gw,{lang:e,t:n,courseWizard:To,quizGenerator:Mo,classBatch:Ko,studentNotificationsHook:Bo,showImportModal:uh,setShowImportModal:Uo,handleImportFile:Ff,importError:hh,importSuccess:fh,isImporting:dh,downloadCSVTemplate:Mf,addToast:Ae,generateTemplateContent:Yb,isImportLessonsOpen:$e,setIsImportLessonsOpen:st,importStatus:ht,setIsDraggingImport:Ks,handleCSVFileChange:wh,downloadCsvTemplate:bh,isDraggingImport:Ys,previewImportData:Wt,setPreviewImportData:mn,setImportStatus:ge,importProgress:rt,importProgressTotal:Js,importErrorMsg:Zs,setImportErrorMsg:Ct,handleCSVImportSubmit:Sh,lessons:je,fetchClassDashboard:vn,isLessonPreviewVisible:xd,setIsLessonPreviewVisible:Lo,selectedLesson:J,previewFullscreenPanel:wd,setPreviewFullscreenPanel:Sd,previewLessonTab:bd,setPreviewLessonTab:Oo,activeRole:ze,elements:Pe,activeSegmentId:Ar,setActiveSegmentId:wn,fetchElements:Tt,currentVfsParent:Dr,setCurrentVfsParent:qo,vfsNodes:ke,previewSelectedCourseware:yd,setPreviewSelectedCourseware:Ro,showProcessLogs:gn,setShowProcessLogs:xn,processLogsContent:Un,isCloudDriveOpen:N,setIsCloudDriveOpen:z,cloudDrivePreviewNode:U,setCloudDrivePreviewNode:T,isSystemResourceLibraryOpen:D,setIsSystemResourceLibraryOpen:x,systemResourceTab:oe,setSystemResourceTab:me,selectedLibraryResourceId:b,setSelectedLibraryResourceId:Q,loadingLibraryResources:Z,libraryResources:X,fetchLibraryResources:ae,classes:Gt,expandedClassId:Dt,isExportWeightModalOpen:Th,setIsExportWeightModalOpen:Go,quizzesWeight:_h,setQuizzesWeight:Qo,assignmentsWeight:Lh,setAssignmentsWeight:Jo,handleQuizzesWeightChange:Uh,handleAssignmentsWeightChange:Hh,customCategoryOverrides:Rh,setCustomCategoryOverrides:Zo,classDashboardMap:Fr,exportClassId:Ph,exportClassName:Ah,csvPreviewData:qh,handleExportGrades:Gh,setSelectedAssignment:Kn,setStudentViewStatus:We,setQuizStudentAnswers:Fo,setSubAssignmentTab:$o,isTourOpen:Nu,setIsTourOpen:Ir,handleSeedSuccess:zu,setTeacherTab:Xe,showCoursewareHub:de,setShowCoursewareHub:xe}),d&&o.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200",children:o.jsxs("div",{className:"bg-surface border-2 border-amber-500 rounded-2xl shadow-2xl p-6 max-w-md w-full text-center space-y-4 animate-in zoom-in-95 duration-300",children:[o.jsx("div",{className:"w-16 h-16 bg-amber-500/20 text-amber-500 rounded-full flex items-center justify-center mx-auto animate-bounce",children:o.jsx(Ut,{size:36})}),o.jsx("h3",{className:"text-xl font-black text-main",children:e==="zh"?"⚡️ 闪电点名:老师选中了你!":"⚡️ Classroom Pick: Teacher Selected You!"}),o.jsx("p",{className:"text-sm text-muted",children:e==="zh"?o.jsxs(o.Fragment,{children:["老师在课堂点名中抽中了【",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName}),"】,请立即集中注意力参与课堂互动回答!"]}):o.jsxs(o.Fragment,{children:["The teacher selected"," ",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName})," ","to answer in class. Please respond now!"]})}),o.jsx("div",{className:"pt-2",children:o.jsxs("button",{type:"button",onClick:()=>{const k=new Ni;k.acknowledgePick(d.studentId),k.destroy(),h(null),Ae(e==="zh"?"🙋‍♂️ 已确认答到":"🙋‍♂️ Acknowledged",e==="zh"?"已向老师中控台发送举手答到信号!":"Sent acknowledge signal to teacher!","success")},className:"w-full py-3 bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-black text-sm rounded-xl shadow-lg shadow-amber-500/30 transition-all active:scale-95 cursor-pointer flex items-center justify-center gap-2",children:[o.jsx(_t,{size:18}),o.jsx("span",{children:e==="zh"?"🙋‍♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋‍♂️ Ready / Acknowledge to Teacher"})]})})]})}),(ze==="student"||i)&&o.jsx(s0,{lessonId:J,studentId:ce||a||void 0,studentName:Oe.find(k=>k.id===(ce||a))?.name||void 0,lang:e}),o.jsx(zw,{}),o.jsx(bv,{})]})}):o.jsx(im,{onLoginSuccess:Bf,lang:e})}class kv{constructor(){this.services=new Map}async register(t,n){if(this.services.has(t))throw new Error(`Service already registered: ${t}`);this.services.set(t,n)}async resolve(t){const n=this.services.get(t);if(!n)throw new Error(`No provider registered for token: ${t}`);return n}async unregister(t){this.services.delete(t)}has(t){return this.services.has(t)}list(){return Array.from(this.services.entries()).map(([t,n])=>({name:t,instance:n}))}}const Cv=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function Ev(e,t){const n=t+".";return e.startsWith(n)||Cv.test(e)?e:n+e}let jv=0;function Nv(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++jv}`},r={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
177
+ `+r],{type:"text/csv;charset=utf-8;"}),a=URL.createObjectURL(i),l=document.createElement("a");l.href=a,l.setAttribute("download",n),document.body.appendChild(l),l.click(),document.body.removeChild(l)}async function kv(e,t){const{lang:n,fetchClasses:s,fetchStudents:r}=t;return new Promise((i,a)=>{const l=new FileReader;l.onload=async c=>{try{const u=c.target?.result;if(!u)throw new Error("File content is empty");let d=[],p=[],m=!0;if(e.name.endsWith(".json")){const h=JSON.parse(u);if(!Array.isArray(h))throw new Error("JSON structure must be an array");h.some(y=>y.className||y.name&&(y.students||y.classDescription))?(m=!0,d=h.map(y=>{const v=y.name||y.className||y.class_name,w=y.description||y.classDescription||"",P=y.students||y.studentList||[],S=(Array.isArray(P)?P:[]).map(j=>({name:j.name||j.studentName||"",email:j.email||j.studentEmail||""})).filter(j=>j.name);return{name:v,description:w,students:S}}).filter(y=>y.name)):(m=!1,p=h.map(y=>({name:y.name||y.studentName||y.student_name||"",email:y.email||y.studentEmail||y.student_email||""})).filter(y=>y.name))}else{const h=u.split(/\r?\n/);if(h.length<2)throw new Error("CSV has empty or insufficient data");const g=h[0].split(",").map(S=>S.trim().toLowerCase()),y=g.findIndex(S=>S.includes("class name")||S.includes("班级名称")||S.includes("班级")||S.includes("classname")||S.includes("class_name")),v=g.findIndex(S=>S.includes("class desc")||S.includes("班级描述")||S.includes("描述")||S.includes("class_desc")),w=g.findIndex(S=>S.includes("student name")||S.includes("学生姓名")||S.includes("姓名")||S.includes("学生")||S.includes("studentname")||S.includes("student_name")),P=g.findIndex(S=>S.includes("student email")||S.includes("学生邮箱")||S.includes("邮箱")||S.includes("email")||S.includes("studentemail")||S.includes("student_email"));if(w===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');if(y!==-1){m=!0;const S={};for(let j=1;j<h.length;j++){const A=h[j].trim();if(!A)continue;const R=(A.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||A.split(",")).map(_=>_.replace(/^"|"$/g,"").trim()),F=R[y];if(!F)continue;const D=v!==-1&&R[v]||"",O=w!==-1&&R[w]||"",k=P!==-1&&R[P]||"";S[F]||(S[F]={name:F,description:D,students:[]}),O&&S[F].students.push({name:O,email:k})}d=Object.values(S)}else{m=!1;for(let S=1;S<h.length;S++){const j=h[S].trim();if(!j)continue;const E=(j.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||j.split(",")).map(D=>D.replace(/^"|"$/g,"").trim()),R=w!==-1&&E[w]||"",F=P!==-1&&E[P]||"";R&&p.push({name:R,email:F})}}}if(m){if(d.length===0)throw new Error("No valid class elements found inside file.");const h=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:d})});if(!h.ok){const y=await h.json();throw new Error(y.error||"Server importation failed")}const g=await h.json();await s(),await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.length} 个班级数据!`:`Successfully imported ${g.imported.length} classes data!`})}else{if(p.length===0)throw new Error("No valid student elements found inside file.");const h=await fetch("/api/students/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({students:p})});if(!h.ok){const y=await h.json();throw new Error(y.error||"Server student importation failed")}const g=await h.json();await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.filter(y=>y.new).length} 名新学者,匹配并更新了其中的 ${g.imported.filter(y=>!y.new).length} 名同学!`:`Successfully imported ${g.imported.filter(y=>y.new).length} new students and updated ${g.imported.filter(y=>!y.new).length} existing ones!`})}}catch(u){a(u)}},l.onerror=()=>{a(new Error("Failed to read file from disk."))},l.readAsText(e)})}function Cv(e,t){return new Promise((n,s)=>{const r=new FileReader;r.onload=i=>{try{const a=i.target?.result;if(!a)throw new Error("Empty CSV file");const l=a.split(/\r?\n/);if(l.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const c=l[0].split(",").map(m=>m.trim().toLowerCase()),u=c.findIndex(m=>m.includes("title")||m.includes("标题")||m.includes("课程")),d=c.findIndex(m=>m.includes("content")||m.includes("内容")||m.includes("正文"));if(u===-1||d===-1)throw new Error(t==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const p=[];for(let m=1;m<l.length;m++){const h=l[m].trim();if(!h)continue;const y=(h.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||h.split(",")).map(P=>P.replace(/^"|"$/g,"").trim()),v=y[u],w=y[d];v&&w&&p.push({title:v,content:w})}if(p.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(p)}catch(a){s(a)}},r.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},r.readAsText(e)})}async function Ev(e,t){const{lang:n,setImportProgress:s,fetchLessons:r}=t;let i=0;for(let a=0;a<e.length;a++){const l=e[a];try{const c=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:l.title,content:l.content})});if(c.ok)i++;else{const u=await c.json();console.warn(`Failed to import item ${a+1}:`,u)}}catch(c){console.warn(`Error importing item ${a+1}:`,c)}s(a+1)}return i>0?(await r(),{success:!0}):{success:!1,errorMsg:n==="zh"?"所有课程项导入均失败。请检查控制台或格式。":"Failed to import any of the courses. Please check your console or schema."}}function jv(){const e=he(k=>k.session),t=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),n=e?.role==="student"||t,s=it(k=>k.errors),r=it(k=>k.studentErrors),i=it(k=>k.activeTab),a=it(k=>k.setActiveTab),l=it(k=>k.isErrorCenterOpen),c=it(k=>k.setIsErrorCenterOpen),u=it(k=>k.clearErrors),d=it(k=>k.clearStudentErrors),p=it(k=>k.removeError),m=it(k=>k.removeStudentError),[h,g]=f.useState(!1),[y,v]=f.useState(null),[w,P]=f.useState(new Set),[S,j]=f.useState(!1),A=s.length+(n?0:r.length),E=s.length>0||!n&&r.length>0,R=k=>{P(_=>{const L=new Set(_);return L.has(k)?L.delete(k):L.add(k),L})},F=async()=>{const k=av(s,n?[]:r);await Fs(k)&&(g(!0),setTimeout(()=>g(!1),2500))},D=async(k,_,L=!1)=>{k.stopPropagation();const I=L?Au(_):To(_);await Fs(I)&&(v(_.id),setTimeout(()=>v(null),2500))},O=k=>{switch(k){case"react":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800",children:"React"});case"api":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700 dark:bg-purple-950/60 dark:text-purple-400 border border-purple-200 dark:border-purple-800",children:"API 5xx"});case"promise":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-700 dark:bg-amber-950/60 dark:text-amber-400 border border-amber-200 dark:border-amber-800",children:"Promise"});default:return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700 dark:bg-blue-950/60 dark:text-blue-400 border border-blue-200 dark:border-blue-800",children:"Runtime"})}};return o.jsxs(o.Fragment,{children:[E&&!l&&!S&&(n?o.jsxs(ys.button,{type:"button",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},className:"fixed bottom-5 left-5 z-40 w-8 h-8 rounded-full bg-slate-900/80 hover:bg-slate-900 text-rose-400 border border-rose-500/40 shadow-lg flex items-center justify-center cursor-pointer transition-all hover:scale-105 select-none",onClick:()=>c(!0),id:"system-error-pill",title:`系统状态提示: ${s.length} 处异常`,children:[o.jsx(Is,{size:15}),o.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center leading-none shadow-xs border border-slate-900",children:s.length})]}):o.jsxs(ys.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.9},className:"fixed bottom-5 left-5 z-40 flex items-center gap-2 bg-slate-900/90 hover:bg-slate-900 backdrop-blur-md text-white px-3.5 py-2 rounded-2xl shadow-xl border border-rose-500/40 cursor-pointer select-none transition-all group",onClick:()=>{s.length===0&&r.length>0&&a("student"),c(!0)},id:"system-error-pill",children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-3 w-3 rounded-full bg-rose-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-rose-500"})]}),o.jsx(Is,{size:15,className:"text-rose-400 group-hover:scale-110 transition-transform"}),o.jsxs("div",{className:"text-xs font-semibold flex items-center gap-1.5",children:[o.jsx("span",{children:"捕获到"}),o.jsx("span",{className:"bg-rose-500/80 text-white font-mono px-1.5 py-0.2 rounded-md text-xs font-bold",children:A}),o.jsx("span",{children:"处系统异常"}),r.length>0&&o.jsxs("span",{className:"text-[10px] text-rose-300 font-normal",children:["(含学生端 ",r.length,")"]})]}),o.jsx("button",{type:"button",className:"text-xs font-bold text-rose-300 hover:text-white bg-white/10 hover:bg-white/20 px-2 py-0.5 rounded-lg transition-colors ml-1",children:"查看与复制"}),o.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),j(!0)},className:"text-gray-400 hover:text-gray-200 p-0.5 hover:bg-white/10 rounded transition-colors ml-0.5",title:"暂时隐藏胶囊",children:o.jsx(Ze,{size:13})})]})),o.jsx(Yc,{children:l&&o.jsx("div",{className:"fixed inset-0 bg-gray-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50 overflow-hidden select-text",children:o.jsxs(ys.div,{initial:{opacity:0,scale:.95,y:10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:10},className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden text-gray-900 dark:text-gray-100",children:[o.jsxs("div",{className:"px-5 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between bg-gray-50/80 dark:bg-slate-850/80 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-xl",children:o.jsx(Pp,{size:18})}),o.jsxs("div",{children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2",children:[o.jsx("span",{children:"系统异常诊断中心 (System Diagnostics)"}),o.jsxs("span",{className:"text-xs font-normal text-gray-500 dark:text-gray-400",children:["(",A," 项记录)"]})]})}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:"自动捕获运行时、Promise 及接口 5xx 异常,支持一键导出 Markdown 格式排查报告。"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:F,disabled:A===0,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 shadow-xs cursor-pointer ${h?"bg-emerald-600 text-white":"bg-indigo-600 hover:bg-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed"}`,title:"复制所有异常报告为 Markdown 文本",children:[h?o.jsx(tt,{size:13}):o.jsx(an,{size:13}),o.jsx("span",{children:h?"已复制全部!":"一键复制全部诊断日志"})]}),o.jsx("button",{type:"button",onClick:()=>{!n&&i==="student"?d():u()},disabled:i==="student"?r.length===0:s.length===0,className:"p-1.5 text-gray-500 hover:text-rose-600 dark:text-gray-400 dark:hover:text-rose-400 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",title:i==="student"?"清空学生端异常记录":"清空记录",children:o.jsx(Ql,{size:16})}),o.jsx("button",{type:"button",onClick:()=>c(!1),className:"p-1.5 text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors cursor-pointer",children:o.jsx(Ze,{size:16})})]})]}),!n&&o.jsxs("div",{className:"px-5 py-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-slate-900/50 flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>a("local"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="local"?"bg-white dark:bg-slate-800 text-indigo-600 dark:text-indigo-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(Ip,{size:13}),o.jsxs("span",{children:["本机异常 (",s.length,")"]})]}),o.jsxs("button",{type:"button",onClick:()=>a("student"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="student"?"bg-white dark:bg-slate-800 text-rose-600 dark:text-rose-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(Ns,{size:14}),o.jsxs("span",{children:["学生端异常 (",r.length,")"]}),r.length>0&&o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-rose-500 animate-pulse"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 bg-slate-50/50 dark:bg-slate-950/30",children:!n&&i==="student"?r.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(tt,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无学生端上报的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"全班学生端运行良好,未发生未捕获的前端崩溃或接口 5xx 故障。"})]}):r.map((k,_)=>{const L=w.has(k.id),I=y===k.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(k.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(dn,{size:15}):o.jsx(Ps,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800 flex items-center gap-1",children:[o.jsx(Ns,{size:11}),o.jsx("span",{children:k.studentName||k.studentId})]}),O(k.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",r.length-_," ",k.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(k.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:k.message}),o.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[o.jsxs("span",{children:["学生学号/ID: ",k.studentId]}),k.lessonId&&o.jsxs("span",{children:["课节: ",k.lessonId]}),k.classId&&o.jsxs("span",{children:["班级: ",k.classId]}),k.endpoint&&o.jsxs("span",{children:["接口: ",k.endpoint]})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:N=>D(N,k,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${I?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条学生错误报告",children:[I?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:I?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),m(k.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(Ze,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["学生: ",k.studentName||"未知"," (",k.studentId,")"]}),o.jsxs("span",{children:["页面地址: ",k.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(k.timestamp).toLocaleString()]})]}),k.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:k.stack})]}),k.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:k.componentStack})]})]})]},k.id)}):s.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(tt,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无捕获到的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"系统运行顺畅,所有模块均在正常状态下运作。"})]}):s.map((k,_)=>{const L=w.has(k.id),I=y===k.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(k.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(dn,{size:15}):o.jsx(Ps,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[O(k.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-_," ",k.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(k.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:k.message}),k.endpoint&&o.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",k.endpoint]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:N=>D(N,k,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${I?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条错误报告",children:[I?o.jsx(tt,{size:11}):o.jsx(an,{size:11}),o.jsx("span",{children:I?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),p(k.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(Ze,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["页面地址: ",k.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(k.timestamp).toLocaleString()]})]}),k.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:k.stack})]}),k.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:k.componentStack})]})]})]},k.id)})})]})})})]})}function Nv(){f.useEffect(()=>{if(typeof window>"u")return;const e=i=>{const a=i.reason,l=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",c=a instanceof Error?a.stack:void 0;Bt.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:l,stack:c}),console.warn("[GlobalErrorCapture] Caught unhandled rejection:",a)},t=i=>{if(!i.message&&!i.error)return;const a=i.message||(i.error?.message??"Unknown script error"),l=i.error?.stack;Bt.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:l}),console.warn("[GlobalErrorCapture] Caught window error:",i.error||i.message)},n=window.fetch,s=async(...i)=>{try{const a=await n(...i);if(!a.ok&&a.status>=500)try{const c=await a.clone().text();let u="";try{const m=JSON.parse(c);u=m.error||m.message||m.details||c}catch{u=c.slice(0,300)}const d=i[0],p=typeof d=="string"?d:d instanceof Request?d.url:String(d);Bt.getState().addError({type:"api",title:`服务端接口错误 (HTTP ${a.status})`,message:u||`Request failed with status ${a.status}`,endpoint:p,status:a.status})}catch{}return a}catch(a){const l=i[0],c=typeof l=="string"?l:l instanceof Request?l.url:String(l);throw c&&(c.startsWith("/api")||c.includes("/api/"))&&Bt.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:c,stack:a?.stack}),a}},r=ov(i=>{try{const a=_e.getState(),l=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||l))return;const u=typeof window<"u"?new URLSearchParams(window.location.search):null,d=a.session?.userId||u?.get("studentId")||"anonymous_student",p=a.session?.name||a.session?.username||u?.get("studentName")||d,m=a.selectedLesson||u?.get("lessonId")||null,h=a.liveClassSelectedClassId||u?.get("classId")||null,g={studentId:d,studentName:p,lessonId:m,classId:h,error:i},y=wt();if(y&&y.connected)y.emit("student-client-error",g);else{const v="/api/diagnostics/report",w=JSON.stringify(g);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(v,new Blob([w],{type:"application/json"})):fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:w}).catch(()=>{})}}catch(a){console.warn("[GlobalErrorCapture] Failed to report student error:",a)}});return window.fetch=s,window.addEventListener("unhandledrejection",e),window.addEventListener("error",t),()=>{window.fetch=n,window.removeEventListener("unhandledrejection",e),window.removeEventListener("error",t),r()}},[])}function Tv(e){return"#/"+e}function Bl(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}w0();const Vl="openlearnv2.agentProviderId";function Pv(){Nv();const e=he(C=>C.lang),t=he(C=>C.setLang),n=ba[e]??ba.zh,[s,r]=f.useState(!1),i=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),a=typeof window<"u"?new URLSearchParams(window.location.search).get("studentId"):null,l=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null;typeof window<"u"&&new URLSearchParams(window.location.search).get("classId");const[c,u]=f.useState(!0),[d,p]=f.useState(null),m=he(C=>C.liveClassSelectedClassId),h=he(C=>C.setLiveClassSelectedClassId),g=he(C=>C.liveClassIsActive),y=he(C=>C.setLiveClassIsActive),[v,w]=f.useState(0),[P,S]=f.useState([]),[j,A]=f.useState(new Map),E=Zb(),[R,F]=f.useState([]),[D,O]=f.useState({}),[k,_]=f.useState([]),[L,I]=f.useState(0),[N,z]=f.useState(!1),[U,T]=f.useState(null),[M,x]=f.useState(!1),[oe,me]=f.useState("system"),[b,Q]=f.useState(null),[X,B]=f.useState([]),[Z,re]=f.useState(!1),[de,xe]=f.useState(!1),ae=async()=>{try{re(!0);const C=await fetch("/api/resources");if(C.ok){const V=await C.json();B(V)}}catch(C){console.warn("Error fetching library resources:",C)}finally{re(!1)}};De.useEffect(()=>{Us.getState().initTheme(),on.getState().initFontSize();const C=V=>{(V.ctrlKey||V.metaKey)&&V.altKey&&(V.key==="+"||V.key==="="?(V.preventDefault(),on.getState().increaseScale()):V.key==="-"||V.key==="_"?(V.preventDefault(),on.getState().decreaseScale()):V.key==="0"&&(V.preventDefault(),on.getState().resetScale()))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[]),De.useEffect(()=>{M&&ae()},[M]);const je=he(C=>C.lessons),St=he(C=>C.setLessons),{lessonsSearchQuery:qt,setLessonsSearchQuery:vt,lessonsSortOrder:kt,setLessonsSortOrder:Ot,filterEnrollment:Y,setFilterEnrollment:ne,filterHasContent:le,setFilterHasContent:Ne,filterThisMonth:He,setFilterThisMonth:qe,copyingLessonId:dt,setCopyingLessonId:Te,filteredAndSortedLessons:$}=vv(je),[q,K]=f.useState([]),J=he(C=>C.selectedLesson),ee=he(C=>C.setSelectedLesson),Pe=he(C=>C.elements),Ye=he(C=>C.setElements),[Be,st]=f.useState(!1),[ht,ge]=f.useState("idle"),[rt,Re]=f.useState(0),[Ys,Vn]=f.useState(0),[Ks,Ct]=f.useState(""),[Wt,gn]=f.useState([]),[Xs,er]=f.useState(!1),[tr,nr]=f.useState(!1),[sr,rr]=f.useState("agent"),[ir,or]=f.useState(!1),[ke,ar]=f.useState([]),[lr,cr]=f.useState([]),[xn,yn]=f.useState(null),[Un,ur]=f.useState(""),Gt=he(C=>C.classes),dr=he(C=>C.setClasses),Oe=he(C=>C.students),Hn=he(C=>C.setStudents),{computerLabs:hr,fetchLabs:qn,todaySchedules:fr,fetchTodaySchedules:Qt,classSchedulesMap:pr,fetchClassSchedules:ye,scheduleAttendanceMap:mr,fetchScheduleAttendance:gr,expandedScheduleId:xr,setExpandedScheduleId:yr,newScheduleDate:br,setNewScheduleDate:wr,newScheduleLessonId:Sr,setNewScheduleLessonId:vr}=pv(),[Mt,kr]=f.useState(null),Cr=f.useRef(null),Er=C=>{kr(C),Cr.current=C},[Wn,Gn]=f.useState({}),[jr,Nr]=f.useState(null),Qn=f.useRef(null),[bn,wn]=f.useState(null),Ke=C=>{const V=Nm(C);V&&wn({type:C,data:{...V.defaultData}})},Tr=async C=>{bn&&await Qn.current?.addElementAtCenter(bn.type,C),wn(null)},be=he(C=>C.session),Dt=he(C=>C.setSession),Jn=he(C=>C.siteInfo),Zn=he(C=>C.setSiteInfo),[ze,ft]=f.useState("teacher"),[Pr,Ir]=f.useState(!0),[Yn,Jt]=f.useState(!0),[Ar,pt]=f.useState("normal");f.useEffect(()=>{if(!be)return;const C=async()=>{try{const W=await fetch("/api/db-status");if(W.ok){const G=await W.json().catch(()=>({}));G.status==="warning"||G.warning?pt("warning"):pt("normal"),Jt(!0)}else W.status===429||W.status===503?(pt("warning"),Jt(!0)):(pt("error"),Jt(!1))}catch{pt("error"),Jt(!1)}};C();const V=setInterval(C,5e3);return()=>clearInterval(V)},[be]),f.useEffect(()=>{(async()=>{try{const V=await fetch("/api/auth/session");if(V.ok){const W=await V.json();if(W.session)if(Dt(W.session),i){ft("student"),Ge("lesson");const G=a||W.session.studentId;G&&vn(G),l&&ee(l),Nt()}else ft(W.session.role),W.session.role==="student"&&W.session.studentId&&(vn(W.session.studentId),Nt())}}catch(V){console.warn("Session check failed",V)}finally{Ir(!1)}})()},[]),f.useEffect(()=>{(async()=>{try{const V=await fetch("/api/site-settings");if(V.ok){const W=await V.json();Zn({siteName:W.siteName||"",slogan:W.slogan||"",logoUrl:W.logoUrl||null})}}catch(V){console.warn("Failed to fetch site settings:",V)}})()},[]);const Zt=he(C=>C.teacherTab),Xe=he(C=>C.setTeacherTab);f.useEffect(()=>{const C=()=>{const W=Bl(window.location.hash);W&&W!==_e.getState().teacherTab&&Xe(W)};window.addEventListener("hashchange",C);const V=Bl(window.location.hash);return V&&Xe(V),()=>window.removeEventListener("hashchange",C)},[Xe]),f.useEffect(()=>{const C=Tv(Zt);window.location.hash!==C&&(window.location.hash=C)},[Zt,Xe]);const[_u,zr]=f.useState(!1),[Lu,Ru]=f.useState(!1),[Ou,Mu]=f.useState(!1);f.useEffect(()=>{be?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&zr(!0)},[be]);const Du=async C=>{await Kt(),await mt(),await Qt().catch(()=>{}),h(C.classId),ee(C.lessonId),y(!0),Ae(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")};f.useEffect(()=>{Zt==="live_class"&&r(!0)},[Zt]);const{timelineSegments:Fu,activeSegmentId:_r,setActiveSegmentId:Sn,draggedSegmentIdx:$u,setDraggedSegmentIdx:Bu,editorSaveStatus:Vu,setEditorSaveStatus:Uu,editorLastSavedTime:Hu,setEditorLastSavedTime:qu,editorPanelsExpanded:Wu,setEditorPanelsExpanded:Gu,saveTimeline:Qu}=mv({selectedLesson:J,lessons:je,setLessons:St}),[ce,vn]=f.useState(null),[Lr,Ju]=f.useState(null),[Zu,Yu]=f.useState(!1),Ae=(C,V,W="info")=>{const G=Math.random().toString(36).substring(2,9);_e.getState().addToast({id:G,title:C,message:V,type:W}),setTimeout(()=>{_e.getState().removeToast(G)},6e3)},We=ze==="student"&&(!!ce&&!!Oe.find(C=>C.id===ce)?.locked_lesson_id||Zu),Rr=()=>{Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Locked",e==="zh"?"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":"The teacher locked the class focus. Navigation is disabled — please follow the current lesson.","warning")},mt=async()=>{try{const C=await fetch("/api/lessons");if(C.ok){const V=await C.json();St(V),!_e.getState().selectedLesson&&V.length>0&&ee(V[0].id)}}catch(C){console.warn("Failed to fetch lessons",C)}},Po=f.useRef(()=>{}),Io=dv({lang:e,addToast:Ae,fetchLessons:mt,setSelectedLesson:ee,setTeacherTab:Xe}),{isCourseWizardOpen:tk,setIsCourseWizardOpen:Ku,wizardStep:nk,setWizardStep:Xu,wizardCourseTitle:sk,setWizardCourseTitle:rk,wizardCourseCategory:ik,setWizardCourseCategory:ok,wizardCourseDescription:ak,setWizardCourseDescription:lk,wizardCourseContent:ck,setWizardCourseContent:uk,wizardCourseTimeline:dk,setWizardCourseTimeline:hk,wizardIsSubmitting:fk,handleDeployWizardCourse:pk}=Io,{plugins:Et,fetchPlugins:ed,aiProviders:gt,fetchAIProviders:td,testingProviderId:nd,storeTab:sd,setStoreTab:rd,pluginCode:id,setPluginCode:od,installingPlugin:ad,events:ld,fetchEvents:cd,approvals:ud,fetchApprovals:dd,scoreOverrides:hd,setScoreOverrides:fd,handleInstallPlugin:pd,handleZipPluginUpload:md,handleTogglePlugin:gd,handleDeletePlugin:xd,handleApprove:yd,handleReject:bd}=uv({session:be,host:E,lang:e,addToast:Ae,setChatLog:C=>Po.current(C),setTeacherTab:Xe,fetchLessons:mt}),[Ft,Ao]=f.useState(()=>typeof window>"u"?"":window.localStorage.getItem(Vl)||""),Or=gt.some(C=>C.id===Ft)?Ft:gt[0]?.id||"",wd=gt.find(C=>C.id===Or)||null,[jt,zo]=f.useState("dashboard"),_o=f.useRef(We),Lo=f.useRef(jt);f.useEffect(()=>{_o.current=We,Lo.current=jt},[We,jt]),f.useEffect(()=>{We&&(u(!0),zo("lesson"))},[We]);const Ge=C=>{const V=typeof C=="function"?C(Lo.current):C;if(_o.current&&V!=="lesson"){Rr();return}zo(C)},[Ro,Yt]=f.useState("whiteboard"),[Sd,vd]=f.useState(null),[xt,Kn]=f.useState(null),[kd,Oo]=f.useState(!1),[Cd,Mo]=f.useState(null),[Ed,Do]=f.useState("whiteboard"),[jd,Nd]=f.useState("none"),[Td,Pd]=f.useState("none"),[Id,Fo]=f.useState(!0);f.useEffect(()=>{jt!=="lesson"&&Fo(!0)},[jt]);const $o=hv(),{isQuizGeneratorOpen:mk,setIsQuizGeneratorOpen:Ad,quizGeneratorClassId:gk,setQuizGeneratorClassId:zd,quizGenMode:xk,setQuizGenMode:_d,quizGenSelectedLessonId:yk,setQuizGenSelectedLessonId:Ld,quizGenTopic:bk,setQuizGenTopic:Rd,isGeneratingSuggestions:wk,setIsGeneratingSuggestions:Sk,suggestedObjectives:vk,setSuggestedObjectives:Od,suggestedQuestions:kk,setSuggestedQuestions:Md,savingQuiz:Ck,setSavingQuiz:Ek,quizStudentAnswers:Dd,setQuizStudentAnswers:Bo,quizGenTimeLimit:jk,setQuizGenTimeLimit:Nk,quizStudentAnswersRef:Fd,subAssignmentTab:$d,setSubAssignmentTab:Vo}=$o,[Bd,Vd]=f.useState(""),[Ud,Hd]=f.useState("all"),[qd,Wd]=f.useState("grid"),[Gd,Qd]=f.useState({}),[Jd,Zd]=f.useState({}),[Yd,Kd]=f.useState({}),Uo=gv(ze,Lr,e),{studentNotifications:Xd,unreadNotifications:eh,readNotifications:Ho,setReadNotifications:Xn,selectedNotificationForModal:th,setSelectedNotificationForModal:nh,isNotificationsOpen:sh,setIsNotificationsOpen:rh}=Uo;f.useEffect(()=>{ce&&fetch(`/api/students/${ce}/read_notifications`).then(C=>C.ok?C.json():[]).then(C=>{Xn(new Set(C))}).catch(C=>{console.warn("Failed to load read notifications from DB",C),Xn(new Set)})},[ce]);const ih=f.useRef(null),oh=C=>{Nr(C),ih.current=C},[ah,lh]=f.useState({}),[ch,uh]=f.useState({}),[Tk,Pk]=f.useState({}),[Ik,Ak]=f.useState({}),[dh,zk]=f.useState(null),[hh,fh]=f.useState("dueDate"),[_k,Lk]=f.useState(null),[ph,mh]=f.useState({}),[gh,qo]=f.useState(!1),[xh,Wo]=f.useState(!1),[yh,Mr]=f.useState(null),[bh,Dr]=f.useState(null),[Fr,wh]=f.useState(null),Sh=f.useRef(null),Go=C=>{wh(C),Sh.current=C};f.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(Vl,Ft)},[Ft]),f.useEffect(()=>{gt.length>0&&!gt.some(C=>C.id===Ft)&&Ao(gt[0].id)},[gt,Ft]);const vh=async(C,V,W)=>{try{if((await fetch(`/api/classes/${C}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:V,scheduledDate:W})})).ok)return await ye(C),!0}catch(G){console.error("Quick schedule class failed",G)}return!1},kh=async(C,V,W)=>{try{const G=V||W||"Assignment",Ie=await fetch(`/api/classes/${C}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:G})});if(Ie.ok){const yt=await Ie.json().catch(()=>({}));return await kn(C),yt.id||"assignment-created"}}catch(G){console.error("Quick generate assignment failed",G)}return null},Ch=async(C,V)=>{try{const W=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:C,content:V})});if(W.ok){const G=await W.json().catch(()=>({}));return await mt(),G.id||"lesson-created"}}catch(W){console.error("Quick create lesson failed",W)}return""},Eh=()=>{$l("class",e)},jh=async C=>{if(C){if(!C.name.toLowerCase().endsWith(".csv")){ge("error"),Ct(e==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}ge("parsing"),Ct("");try{const V=await Cv(C,e);gn(V),ge("idle")}catch(V){ge("error"),Ct(V.message||String(V))}}},Nh=async()=>{if(Wt.length===0)return;ge("importing"),Re(0),Vn(Wt.length);const C=await Ev(Wt,{lang:e,setImportProgress:Re,fetchLessons:mt});C.success?ge("success"):(ge("error"),Ct(C.errorMsg||""))},Th=async C=>{const V=await fetch(`/api/lessons/${C}`,{method:"DELETE"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to delete course")}await mt(),J===C&&ee(null),Ae(e==="zh"?"课程已删除":"Course Deleted",e==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},Ph=async C=>{Te(C);try{const V=await fetch(`/api/lessons/${C}/clone`,{method:"POST"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to copy course")}await mt(),Ae(e==="zh"?"复制成功":"Course Copied",e==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(V){Ae(e==="zh"?"复制失败":"Copy Failed",V.message||(e==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{Te(null)}},Qo=async()=>{try{const C=await fetch("/api/commands/registered");if(!C.ok)return;const V=C.headers.get("content-type");if(V&&V.includes("application/json")){const W=await C.json();Array.isArray(W)&&K(W)}}catch(C){console.warn("Failed to fetch registered commands",C)}},Ih=async C=>{if(be)try{const V=await fetch(`/api/vfs${C?`?parentId=${C}`:""}`);if(V.ok){const W=await V.json();ar(W)}}catch(V){console.warn("Failed to fetch VFS nodes",V)}},Ah=async()=>{try{const C=await fetch("/api/processes");C.ok&&cr(await C.json())}catch{}},Kt=async()=>{try{const C=await fetch("/api/classes");C.ok&&dr(await C.json())}catch{}},Nt=async()=>{try{const C=await fetch("/api/students");C.ok&&Hn(await C.json())}catch{}},Xt=async C=>{try{const V=await fetch(`/api/classes/${C}/students`);if(V.ok){const W=await V.json();Gn(G=>({...G,[C]:W}))}}catch{}},$r=async C=>{try{const V=await fetch(`/api/classes/${C}/progress`);if(V.ok){const W=await V.json();uh(G=>({...G,[C]:W}))}}catch{}},[Br,zh]=f.useState({}),kn=async C=>{try{const V=await fetch(`/api/classes/${C}/dashboard`);if(V.ok){const W=await V.json();zh(G=>({...G,[C]:W}))}}catch{}},_h=Sv({lang:e,classes:Gt,classStudentsMap:Wn,classDashboardMap:Br,fetchClassStudents:Xt,fetchClassDashboard:kn,fetchClassProgress:$r}),{isExportWeightModalOpen:Lh,setIsExportWeightModalOpen:Jo,exportClassId:Rh,setExportClassId:Oh,exportClassName:Mh,setExportClassName:Dh,quizzesWeight:Fh,setQuizzesWeight:Zo,assignmentsWeight:$h,setAssignmentsWeight:Yo,customCategoryOverrides:Bh,setCustomCategoryOverrides:Ko,exportDropdownOpen:Vh,setExportDropdownOpen:Uh,exportTooltipOpen:Hh,setExportTooltipOpen:qh,loadingExportClassId:Wh,isExportingAllCombined:Gh,isGeneratingPDFReport:Qh,handleQuizzesWeightChange:Jh,handleAssignmentsWeightChange:Zh,csvPreviewData:Yh,triggerExportForClass:Kh,handleExportGrades:Xh,handleGeneratePDFReport:ef,handleExportAllClassesCombined:Xo,get30DayAverageWarning:tf}=_h,ea=fv({lang:e,classes:Gt,expandedClassId:Mt,fetchClasses:Kt,fetchClassStudents:Xt,handleExportAllClassesCombined:Xo}),{batchMode:nf,setBatchMode:sf,selectedClassIds:rf,setSelectedClassIds:of,selectedStudentIds:af,setSelectedStudentIds:lf,batchPicker:Rk,setBatchPicker:Ok,batchPickerLesson:Mk,setBatchPickerLesson:Dk,batchPickerDate:Fk,setBatchPickerDate:$k,batchPickerTargetClass:Bk,setBatchPickerTargetClass:Vk,toggleClassSelection:cf,toggleSelectAllClasses:uf,toggleStudentSelection:df,toggleSelectAllStudents:hf,handleBatchDeleteClasses:ff,handleBatchExportClasses:pf,handleBatchSetPasscode:mf,handleBatchScheduleClasses:gf,handleBatchDeleteStudents:xf,handleBatchResetPassword:yf,handleBatchTransferStudents:bf,handleBatchSetLockedLesson:wf,confirmBatchPicker:Uk}=ea,Vr=async C=>{try{const V=await fetch(`/api/students/${C}/dashboard`);if(V.ok){const W=await V.json();Ju(W),W.profile&&W.profile.locked_lesson_id&&(ee(W.profile.locked_lesson_id),Ge("lesson"))}}catch{}},Sf=async(C=!1)=>{if(!xt)return;const W=xt?.content&&xt.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(Fd.current):"Submitted via Whiteboard";try{(await fetch(`/api/assignments/${xt.id}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:ce,content:W})})).ok&&(C&&alert("Time is up! Your assessment was successfully submitted automatically."),await Vr(ce),Ge("dashboard"),Kn(null))}catch(G){console.error(G)}};f.useEffect(()=>{if(be&&ze==="student"&&ce){Vr(ce);const C=Oe.find(V=>V.id===ce);C&&C.locked_lesson_id&&(ee(C.locked_lesson_id),Ge("lesson"))}},[be,ze,ce,Oe]);const vf=f.useRef(ze),kf=f.useRef(ce),Cf=f.useRef(e),Ef=f.useRef(Oe),jf=f.useRef(Ae),es=f.useRef(new Set);f.useRef(new Set),f.useEffect(()=>{vf.current=ze},[ze]),f.useEffect(()=>{kf.current=ce},[ce]),f.useEffect(()=>{Cf.current=e},[e]),f.useEffect(()=>{Ef.current=Oe},[Oe]),f.useEffect(()=>{jf.current=Ae},[Ae]),f.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const C=Ce.getState(),V=Et.filter(G=>G.status==="active");for(const G of V){if(!G.has_frontend||es.current.has(G.id))continue;const Ie=C.activePlugins.find(bt=>bt.id===G.id),yt=!!(Ie&&G.version&&Ie.version!==G.version);if(!(!Ie||yt||Ie.state!==we.ACTIVE&&Ie.state!==we.ACTIVATING))continue;es.current.add(G.id);const ra=()=>{if(!C.activePlugins.find(bt=>bt.id===G.id))C.addPlugin({id:G.id,name:G.name,version:G.version,state:we.INSTALLED,executionMode:"inline"});else if(yt)try{Ce.setState(bt=>({activePlugins:bt.activePlugins.map(Cn=>Cn.id===G.id?{...Cn,version:G.version,name:G.name}:Cn)}))}catch{}try{const bt=JSON.parse(G.manifest);E.activateRemotePlugin(G.id,bt).catch(Cn=>{console.error(`[App] Failed to activate remote plugin "${G.name}":`,Cn)}).finally(()=>{es.current.delete(G.id)})}catch(bt){es.current.delete(G.id),console.error(`[App] Failed to parse manifest for plugin "${G.name}":`,bt)}};Ie&&Ie.state===we.ACTIVE&&yt?E.deactivatePlugin(G.id).catch(()=>{}).finally(ra):ra()}const W=Et.filter(G=>G.status!=="active");for(const G of W){if(!G.has_frontend)continue;const Ie=C.activePlugins.find(yt=>yt.id===G.id);Ie&&Ie.state===we.ACTIVE&&E.deactivatePlugin(G.id).catch(yt=>{console.error(`[App] Failed to deactivate remote plugin "${G.name}":`,yt)})}},[Et,E]),De.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const C=Ce.getState();for(const V of Et)V.status==="active"&&(C.dashboardVisibility.has(V.id)||C.setDashboardVisibility(V.id,!0))},[Et,E]);const Nf=async C=>{if(ze==="student"&&ce&&J)try{await fetch(`/api/students/${ce}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:J,completed:C===100,progressPercent:C})})}catch(V){console.error("Failed to update student progress:",V)}},Tf=async(C,V)=>{try{const W=await fetch(`/api/classes/${C}/lessons/${V}/progress`);W.ok&&_(await W.json())}catch{}};f.useEffect(()=>{m&&J?Tf(m,J):_([])},[m,J]),f.useEffect(()=>{m&&Xt(m)},[m]);const Pf=async C=>{try{const V=await fetch(`/api/students/${C}/progress`);if(V.ok){const W=await V.json();lh(G=>({...G,[C]:W}))}}catch{}},ta=async C=>{try{const V=await fetch(`/api/processes/${C}/logs`);if(V.ok){const W=await V.json();ur(W.logs||""),yn(C)}}catch{}},na=f.useRef(""),Tt=async C=>{try{const V=await fetch(`/api/lessons/${C}/whiteboard`);if(!V.ok)return;const W=await V.json(),G=JSON.stringify(W);G!==na.current&&(na.current=G,Ye(W))}catch{}},If=f.useRef(null);f.useRef(null);const Af=f.useRef(null);f.useEffect(()=>{If.current=J},[J]),f.useEffect(()=>{Af.current=xt},[xt]),hu(be);const{chatLog:zf,setChatLog:_f,input:Lf,setInput:Rf,loading:Of,chatAttachments:Mf,setChatAttachments:Df,handleChatFileChange:Ff,handleChatDrop:$f,handleSend:Bf,handleClearAgentMemory:Vf}=oS({lang:e,t:n,selectedLesson:J,effectiveAgentProviderId:Or,expandedClassId:Mt,fetchLessons:mt,fetchClasses:Kt,fetchStudents:Nt,fetchClassStudents:Xt,fetchClassProgress:$r,fetchClassDashboard:kn,fetchElements:Tt});Po.current=_f,iS({session:be,showProcessLogs:xn,activeStudentId:ce,currentVfsParent:Fr,selectedLesson:J,selectedAssignment:xt,expandedClassId:Mt,fetchLessons:mt,fetchPlugins:ed,fetchRegisteredCommands:Qo,fetchEvents:cd,fetchApprovals:dd,fetchProcesses:Ah,fetchClasses:Kt,fetchTodaySchedules:Qt,fetchStudents:Nt,fetchLabs:qn,fetchVfs:Ih,fetchProcessLogs:ta,fetchClassStudents:Xt,fetchElements:Tt});const{socketRef:Uf}=lv({session:be,host:E,activeRole:ze,activeStudentId:ce,selectedLesson:J,activeSegmentId:_r,studentViewStatus:jt,lang:e,students:Oe,addToast:Ae,setOnlineStudentIds:F,setActiveStudentLessons:O,setLessons:St,setActiveSegmentId:Sn,setLiveClassStudentProgress:_,setLiveClassAcknowledgedMap:A,setLiveClassFeed:S,setSelectedLesson:ee,setStudentViewStatus:Ge,studentLessonTab:Ro,setStudentLessonTab:Yt,selectedAssignment:xt,setSelectedAssignment:Kn,setLocalProgressPercent:I,fetchStudentDashboard:Vr,fetchStudents:Nt,fetchElements:Tt}),Hf=C=>{$l(C,e)},qf=async C=>{Wo(!0),Mr(null),Dr(null);try{const V=await kv(C,{lang:e,fetchClasses:Kt,fetchStudents:Nt});Dr(V.message)}catch(V){Mr(V.message||String(V))}finally{Wo(!1)}},Wf=()=>{t(e==="zh"?"en":"zh")},Gf=f.useCallback(C=>{Dt(C),C.role==="teacher"?(ft("teacher"),Xe("dashboard")):(ft("student"),vn(C.studentId),Nt())},[]),sa=async()=>{try{await fetch("/api/auth/logout",{method:"POST"})}catch(C){console.error("Logout failed",C)}Dt(null)},[Qf,Ur]=f.useState(!1);return f.useEffect(()=>{if(!i)return;const C=new Ii;C.requestHandshake();const V=C.onMessage(W=>{switch(W.type){case"TEACHER_INIT_STATE":{const G=W.payload;G.selectedLesson&&(ee(G.selectedLesson),Tt(G.selectedLesson)),G.activeSegmentId&&Sn(G.activeSegmentId),G.activeTab&&Yt(G.activeTab),G.liveClassTimeRemaining!==void 0&&w(G.liveClassTimeRemaining),G.fullscreenElementId!==void 0&&(ln.getState().setRemoteFullscreenElementId(G.fullscreenElementId),G.fullscreenElementId&&Yt("whiteboard")),Ge("lesson");break}case"TEACHER_CHANGE_LESSON":{c&&W.payload.lessonId&&(ee(W.payload.lessonId),Tt(W.payload.lessonId),Ge("lesson"));break}case"TEACHER_CHANGE_SEGMENT":{c&&W.payload.segmentId&&Sn(W.payload.segmentId);break}case"TEACHER_CHANGE_TAB":{c&&W.payload.tab&&Yt(W.payload.tab);break}case"TEACHER_LOCK_CLASS":{Yu(!!W.payload.locked),W.payload.locked?(u(!0),Ge("lesson"),Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Lock",e==="zh"?"老师已开启全班专注锁定,界面将保持同步授课。":"Teacher locked screen for class.","warning")):Ae(e==="zh"?"🔓 屏幕已解锁":"🔓 Screen Unlocked",e==="zh"?"老师已解除锁定,您可以自由浏览或答题。":"Screen unlocked.","info");break}case"TEACHER_PICK_STUDENT":{(!ce||ce===W.payload.studentId||a===W.payload.studentId)&&p(W.payload);break}case"TEACHER_SYNC_TIMER":{w(W.payload.timeRemaining);break}case"TEACHER_BROADCAST_COUNTDOWN":{w(W.payload.timeRemaining);break}case"TEACHER_PING_STUDENT":{(!ce||ce===W.payload.studentId)&&Ae(e==="zh"?"⚠️ 课堂提醒":"⚠️ Classroom Alert",W.payload.message||(e==="zh"?"老师提醒您集中注意力跟上教学进度!":"Please keep up with class!"),"warning");break}case"TEACHER_BROADCAST_FULLSCREEN":{const{elementId:G,lessonId:Ie}=W.payload;ln.getState().setRemoteFullscreenElementId(G),G&&(Ie&&Ie!==J&&(ee(Ie),Tt(Ie)),Ge("lesson"),Yt("whiteboard"));break}}});return()=>{V(),C.destroy()}},[i,c,ce,a,e]),Pr?o.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[o.jsx(Ki,{size:48,className:"text-indigo-500 animate-spin"}),o.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:e==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]}):be?o.jsx(o.Fragment,{children:o.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[o.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[be?.role==="teacher"&&ze==="student"&&!i&&o.jsxs("div",{className:"bg-gradient-to-r from-amber-500 via-amber-600 to-orange-500 text-white px-6 py-1.5 flex items-center justify-between text-xs font-medium shadow-sm z-30 shrink-0 border-b border-amber-600/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("span",{className:"bg-black/20 text-amber-100 px-2 py-0.5 rounded font-bold uppercase tracking-wider text-xs flex items-center gap-1",children:[o.jsx($s,{size:12}),e==="zh"?"学生模拟模式":"Student View Mode"]}),o.jsx("span",{children:e==="zh"?`您当前正在以学生身份(${Oe.find(C=>C.id===ce)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${Oe.find(C=>C.id===ce)?.name||"None"}).`})]}),o.jsxs("button",{type:"button",onClick:()=>ft("teacher"),className:"bg-white text-amber-800 hover:bg-amber-50 active:bg-amber-100 font-bold px-3 py-1 rounded-md shadow-xs transition-all flex items-center gap-1.5 cursor-pointer text-xs",children:[o.jsx(Yi,{size:13}),e==="zh"?"退出模拟并返回教师端":"Exit Student View"]})]}),i?o.jsxs("header",{className:"h-13 bg-surface/95 backdrop-blur-md border-b border-theme px-4 flex items-center justify-between z-20 shrink-0 select-none shadow-xs",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-tr from-pink-500 to-rose-600 flex items-center justify-center text-white font-black shadow-sm text-sm",children:"🎓"}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h1",{className:"text-sm font-black text-main tracking-wide",children:e==="zh"?"互动课堂 · 学生端":"Interactive Classroom · Student Client"}),o.jsxs("span",{className:"flex items-center gap-1 text-xs font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full",children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"}),e==="zh"?"已与教师中控台实时联动":"Synced with Teacher"]})]}),o.jsxs("div",{className:"text-xs text-muted flex items-center gap-2",children:[o.jsx("span",{children:ce?`学生: ${Oe.find(C=>C.id===ce)?.name||ce}`:"学生端"}),o.jsx("span",{children:"•"}),o.jsx("span",{children:J?`课节: ${je.find(C=>C.id===J)?.title||J}`:"等待教师推流课节..."})]})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>{if(We){Rr();return}u(!c)},disabled:We,className:`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 shadow-2xs ${We?"cursor-not-allowed":"cursor-pointer"} ${c?"bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800":"bg-surface text-muted border-theme hover:text-main"} ${We?"opacity-70":""}`,title:We?e==="zh"?"全班专注锁定中,已强制跟随教师步调":"Class focus is locked; following the teacher is enforced":e==="zh"?"开启后,教师端切换课节/环节/Tab时,学生端将自动同步跟随":"Follow teacher navigation",children:[o.jsx(tc,{size:12,className:c?"animate-spin":""}),o.jsx("span",{children:e==="zh"?`跟随教师步调: ${c?"开":"关"}`:`Follow Teacher: ${c?"ON":"OFF"}`})]}),o.jsx(cc,{lang:e}),o.jsx("button",{type:"button",onClick:()=>{document.fullscreenElement?document.exitFullscreen().catch(()=>{}):document.documentElement.requestFullscreen().catch(()=>{})},className:"p-1.5 text-muted hover:text-main rounded-lg border border-theme hover:bg-surface-secondary transition-colors cursor-pointer",title:e==="zh"?"切换全屏":"Toggle Fullscreen",children:o.jsx(Ap,{size:14})}),o.jsx("button",{type:"button",onClick:()=>window.close(),className:"px-2.5 py-1.5 text-xs font-bold text-rose-600 hover:text-rose-700 bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 rounded-lg transition-colors cursor-pointer",title:e==="zh"?"关闭学生端Tab":"Close Tab",children:e==="zh"?"关闭Tab":"Close Tab"})]})]}):o.jsx(bm,{activeRole:ze,setActiveRole:ft,lang:e,teacherTab:Zt,studentViewStatus:jt,session:be,activeStudentId:ce,students:Oe,studentDashboardData:Lr,isNotificationsOpen:sh,studentNotifications:Xd,unreadNotifications:eh,readNotifications:Ho,selectedNotificationForModal:th,dbConnected:Yn,dbStatus:Ar,siteInfo:Jn,setActiveStudentId:vn,setReadNotifications:Xn,setIsSystemResourceLibraryOpen:x,setProfileOpen:Ur,setTeacherTab:Xe,setStudentViewStatus:Ge,setIsNotificationsOpen:rh,setSelectedNotificationForModal:nh,handleLogout:sa,toggleLanguage:Wf,isStudentLocked:We,onBlockedNavigate:Rr}),o.jsx(km,{open:Qf,session:be,lang:e,onClose:()=>Ur(!1),onSaved:C=>{be&&Dt({...be,name:C}),Ur(!1)},onAvatar:C=>{be&&Dt({...be,avatar:C??void 0})}}),o.jsx(C0,{students:Oe,activeStudentId:ce,isStudentLocked:We,studentViewStatus:jt,studentDashboardData:Lr,readNotifications:Ho,setReadNotifications:Xn,addToast:Ae,lang:e,setSelectedLesson:ee,setStudentViewStatus:Ge,setSelectedAssignment:Kn,setQuizStudentAnswers:Bo,setSubAssignmentTab:Vo,lessons:je,selectedLesson:J,studentFullscreenPanel:Td,setStudentFullscreenPanel:Pd,timelineSegments:Fu,activeSegmentId:_r,setActiveSegmentId:Sn,localProgressPercent:L,setLocalProgressPercent:I,updateStudentProgress:Nf,isStudentLessonContentCollapsed:Id,setIsStudentLessonContentCollapsed:Fo,studentLessonTab:Ro,setStudentLessonTab:Yt,elements:Pe,activeRole:ze,fetchElements:Tt,currentVfsParent:Fr,setCurrentVfsParent:Go,vfsNodes:ke,studentSelectedCourseware:Sd,setStudentSelectedCourseware:vd,selectedAssignment:xt,quizStudentAnswers:Dd,submitQuizAssignment:Sf,subAssignmentTab:$d,mainNavCollapsed:s,setMainNavCollapsed:r,teacherTab:Zt,setTeacherTab:Xe,session:be,todaySchedules:fr,t:n,classes:Gt,approvals:ud,processes:lr,isApprovalsCollapsed:Lu,setIsApprovalsCollapsed:Ru,isProcessesCollapsed:Ou,setIsProcessesCollapsed:Mu,scoreOverrides:hd,setScoreOverrides:fd,handleApprove:yd,handleReject:bd,showLogs:ir,setShowLogs:or,processLogsContent:Un,showProcessLogs:xn,fetchProcessLogs:ta,setShowProcessLogs:yn,handleQuickScheduleClass:vh,handleQuickGenerateAssignment:kh,handleQuickCreateLesson:Ch,setActiveRole:ft,editorSaveStatus:Vu,setEditorSaveStatus:Uu,editorLastSavedTime:Hu,setEditorLastSavedTime:qu,setIsLessonPreviewVisible:Oo,setPreviewLessonTab:Do,setPreviewSelectedCourseware:Mo,handlePaletteActivate:Ke,draggedSegmentIdx:$u,setDraggedSegmentIdx:Bu,saveTimeline:Qu,editorPanelsExpanded:Wu,setEditorPanelsExpanded:Gu,whiteboardRef:Qn,paletteEdit:bn,handlePaletteConfirm:Tr,setPaletteEdit:wn,plugins:Et,liveClassSelectedClassId:m,setLiveClassSelectedClassId:h,liveClassIsActive:g,setLiveClassIsActive:y,liveClassTimeRemaining:v,setLiveClassTimeRemaining:w,liveClassFeed:P,setLiveClassFeed:S,liveClassAcknowledgedMap:j,setLiveClassAcknowledgedMap:A,onlineStudentIds:R,activeStudentLessons:D,liveClassStudentProgress:k,storeTab:sd,setStoreTab:rd,pluginCode:id,setPluginCode:od,installingPlugin:ad,onInstall:pd,onZipUpload:md,onToggle:gd,onDelete:xd,lessonsSearchQuery:qt,setLessonsSearchQuery:vt,lessonsSortOrder:kt,setLessonsSortOrder:Ot,filteredLessons:$,onOpenImportLessons:()=>{ge("idle"),Re(0),Vn(0),Ct(""),gn([]),st(!0)},onOpenCourseWizard:()=>{Xu(1),Ku(!0)},onViewCourse:C=>{Xe("lesson_editor"),ee(C)},onDeleteCourse:Th,onCopyCourse:Ph,filterEnrollment:Y,setFilterEnrollment:ne,filterHasContent:le,setFilterHasContent:Ne,filterThisMonth:He,setFilterThisMonth:qe,copyingLessonId:dt,onSchedulesUpdated:Qt,onLogout:sa,aiProviders:gt,testingProviderId:nd,onAIProvidersChanged:td,onTriggerTour:()=>zr(!0),siteInfo:Jn,onSiteInfoChanged:Zn,computerLabs:hr,onRefresh:qn,registeredCommands:q,fetchRegisteredCommands:Qo,batchMode:nf,selectedClassIds:rf,setSelectedClassIds:of,setSelectedStudentIds:lf,setBatchMode:sf,expandedClassId:Mt,setExpandedClassId:Er,exportTooltipOpen:Hh,setExportTooltipOpen:qh,exportDropdownOpen:Vh,setExportDropdownOpen:Uh,isExportingAllCombined:Gh,loadingExportClassId:Wh,classStudentsMap:Wn,setClassStudentsMap:Gn,expandedStudentId:jr,setExpandedStudentId:oh,selectedStudentIds:af,rosterViewMode:qd,setRosterViewMode:Wd,rosterSearchQuery:Bd,setRosterSearchQuery:Vd,rosterTagFilter:Ud,setRosterTagFilter:Hd,toggleSelectAllStudents:hf,handleBatchDeleteStudents:xf,handleBatchResetPassword:yf,handleBatchTransferStudents:bf,handleBatchSetLockedLesson:wf,toggleStudentSelection:df,get30DayAverageWarning:tf,studentProgressMap:ah,studentActiveTabs:Yd,setStudentActiveTabs:Kd,setStudents:Hn,fetchClassStudents:Xt,fetchStudents:Nt,parseCSV:um,setImportError:Mr,setImportSuccess:Dr,setShowImportModal:qo,fetchClasses:Kt,classSubmissionFilters:Gd,setClassSubmissionFilters:Qd,classActiveTabs:Jd,setClassActiveTabs:Zd,classProgressMap:ch,classSchedulesMap:pr,classDashboardMap:Br,assignmentSortOrder:hh,setAssignmentSortOrder:fh,isGeneratingPDFReport:Qh,handleGeneratePDFReport:ef,setExportClassId:Oh,setExportClassName:Dh,setQuizzesWeight:Zo,setAssignmentsWeight:Yo,setCustomCategoryOverrides:Ko,setIsExportWeightModalOpen:Jo,isGeneratingAssignment:dh,setQuizGeneratorClassId:zd,setQuizGenMode:_d,setQuizGenSelectedLessonId:Ld,setQuizGenTopic:Rd,setSuggestedObjectives:Od,setSuggestedQuestions:Md,setIsQuizGeneratorOpen:Ad,setActiveStudentId:vn,isGrading:ph,setIsGrading:mh,fetchClassDashboard:kn,newScheduleDate:br,setNewScheduleDate:wr,newScheduleLessonId:Sr,setNewScheduleLessonId:vr,expandedScheduleId:xr,setExpandedScheduleId:yr,fetchScheduleAttendance:gr,scheduleAttendanceMap:mr,toggleSelectAllClasses:uf,handleBatchDeleteClasses:ff,handleBatchExportClasses:pf,handleBatchSetPasscode:mf,handleBatchScheduleClasses:gf,handleExportAllClassesCombined:Xo,triggerExportForClass:Kh,fetchClassProgress:$r,fetchClassSchedules:ye,fetchStudentProgress:Pf,toggleClassSelection:cf,socketRef:Uf,setShowCoursewareHub:xe,fetchTodaySchedules:Qt})]}),o.jsx($w,{showRightSidebar:tr,setShowRightSidebar:nr,rightSidebarTab:sr,setRightSidebarTab:rr,effectiveAgentProviderId:Or,agentProviderId:Ft,setAgentProviderId:Ao,aiProviders:gt,selectedAgentProvider:wd,chatLog:zf,loading:Of,input:Lf,setInput:Rf,handleSend:Bf,chatAttachments:Mf,setChatAttachments:Df,handleChatFileChange:Ff,handleChatDrop:$f,onClearAgentMemory:Vf,events:ld,lang:e,t:n}),o.jsx(eS,{lang:e,t:n,courseWizard:Io,quizGenerator:$o,classBatch:ea,studentNotificationsHook:Uo,showImportModal:gh,setShowImportModal:qo,handleImportFile:qf,importError:yh,importSuccess:bh,isImporting:xh,downloadCSVTemplate:Hf,addToast:Ae,generateTemplateContent:r0,isImportLessonsOpen:Be,setIsImportLessonsOpen:st,importStatus:ht,setIsDraggingImport:er,handleCSVFileChange:jh,downloadCsvTemplate:Eh,isDraggingImport:Xs,previewImportData:Wt,setPreviewImportData:gn,setImportStatus:ge,importProgress:rt,importProgressTotal:Ys,importErrorMsg:Ks,setImportErrorMsg:Ct,handleCSVImportSubmit:Nh,lessons:je,fetchClassDashboard:kn,isLessonPreviewVisible:kd,setIsLessonPreviewVisible:Oo,selectedLesson:J,previewFullscreenPanel:jd,setPreviewFullscreenPanel:Nd,previewLessonTab:Ed,setPreviewLessonTab:Do,activeRole:ze,elements:Pe,activeSegmentId:_r,setActiveSegmentId:Sn,fetchElements:Tt,currentVfsParent:Fr,setCurrentVfsParent:Go,vfsNodes:ke,previewSelectedCourseware:Cd,setPreviewSelectedCourseware:Mo,showProcessLogs:xn,setShowProcessLogs:yn,processLogsContent:Un,isCloudDriveOpen:N,setIsCloudDriveOpen:z,cloudDrivePreviewNode:U,setCloudDrivePreviewNode:T,isSystemResourceLibraryOpen:M,setIsSystemResourceLibraryOpen:x,systemResourceTab:oe,setSystemResourceTab:me,selectedLibraryResourceId:b,setSelectedLibraryResourceId:Q,loadingLibraryResources:Z,libraryResources:X,fetchLibraryResources:ae,classes:Gt,expandedClassId:Mt,isExportWeightModalOpen:Lh,setIsExportWeightModalOpen:Jo,quizzesWeight:Fh,setQuizzesWeight:Zo,assignmentsWeight:$h,setAssignmentsWeight:Yo,handleQuizzesWeightChange:Jh,handleAssignmentsWeightChange:Zh,customCategoryOverrides:Bh,setCustomCategoryOverrides:Ko,classDashboardMap:Br,exportClassId:Rh,exportClassName:Mh,csvPreviewData:Yh,handleExportGrades:Xh,setSelectedAssignment:Kn,setStudentViewStatus:Ge,setQuizStudentAnswers:Bo,setSubAssignmentTab:Vo,isTourOpen:_u,setIsTourOpen:zr,handleSeedSuccess:Du,setTeacherTab:Xe,showCoursewareHub:de,setShowCoursewareHub:xe}),d&&o.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200",children:o.jsxs("div",{className:"bg-surface border-2 border-amber-500 rounded-2xl shadow-2xl p-6 max-w-md w-full text-center space-y-4 animate-in zoom-in-95 duration-300",children:[o.jsx("div",{className:"w-16 h-16 bg-amber-500/20 text-amber-500 rounded-full flex items-center justify-center mx-auto animate-bounce",children:o.jsx(Ut,{size:36})}),o.jsx("h3",{className:"text-xl font-black text-main",children:e==="zh"?"⚡️ 闪电点名:老师选中了你!":"⚡️ Classroom Pick: Teacher Selected You!"}),o.jsx("p",{className:"text-sm text-muted",children:e==="zh"?o.jsxs(o.Fragment,{children:["老师在课堂点名中抽中了【",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName}),"】,请立即集中注意力参与课堂互动回答!"]}):o.jsxs(o.Fragment,{children:["The teacher selected"," ",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName})," ","to answer in class. Please respond now!"]})}),o.jsx("div",{className:"pt-2",children:o.jsxs("button",{type:"button",onClick:()=>{const C=new Ii;C.acknowledgePick(d.studentId),C.destroy(),p(null),Ae(e==="zh"?"🙋‍♂️ 已确认答到":"🙋‍♂️ Acknowledged",e==="zh"?"已向老师中控台发送举手答到信号!":"Sent acknowledge signal to teacher!","success")},className:"w-full py-3 bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-black text-sm rounded-xl shadow-lg shadow-amber-500/30 transition-all active:scale-95 cursor-pointer flex items-center justify-center gap-2",children:[o.jsx(_t,{size:18}),o.jsx("span",{children:e==="zh"?"🙋‍♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋‍♂️ Ready / Acknowledge to Teacher"})]})})]})}),(ze==="student"||i)&&o.jsx(u0,{lessonId:J,studentId:ce||a||void 0,studentName:Oe.find(C=>C.id===(ce||a))?.name||void 0,lang:e}),o.jsx(Fw,{}),o.jsx(jv,{})]})}):o.jsx(dm,{onLoginSuccess:Gf,lang:e})}class Iv{constructor(){this.services=new Map}async register(t,n){if(this.services.has(t))throw new Error(`Service already registered: ${t}`);this.services.set(t,n)}async resolve(t){const n=this.services.get(t);if(!n)throw new Error(`No provider registered for token: ${t}`);return n}async unregister(t){this.services.delete(t)}has(t){return this.services.has(t)}list(){return Array.from(this.services.entries()).map(([t,n])=>({name:t,instance:n}))}}const Av=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function zv(e,t){const n=t+".";return e.startsWith(n)||Av.test(e)?e:n+e}let _v=0;function Lv(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++_v}`},r={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
178
178
  <html><head>
179
179
  <script>
180
180
  window.__LMS_STUDENT__ = ${JSON.stringify(s)};
@@ -214,4 +214,4 @@ Bob Dylan,bob@example.com`);const i=new Blob(["\uFEFF"+s+`
214
214
  <script src="/bridge.js?cw=${encodeURIComponent(t||"")}"><\/script>
215
215
  </head><body>
216
216
  ${e||""}
217
- </body></html>`}class Tv{constructor(){this.loaders=new Map}register(t,n){this.loaders.set(t.id,{impl:t,pluginId:n})}unregister(t,n){const s=this.loaders.get(t);s&&(n&&s.pluginId!==n||this.loaders.delete(t))}unregisterPlugin(t){for(const[n,s]of this.loaders)s.pluginId===t&&this.loaders.delete(n)}resolve(t,n){for(const{impl:s}of this.loaders.values())try{const r=s.resolve(t,n);if(r)return r}catch{}return null}}const Es=new Tv,Pv=4;let hs=0;const Gi=new Set;function Ml(){return hs>=Pv?null:(hs+=1,()=>{hs=Math.max(0,hs-1);for(const e of Gi)e()})}function Iv(e){return Gi.add(e),()=>{Gi.delete(e)}}function Av(e,t){const[n,s]=p.useState(!e),[r,i]=p.useState(!1),a=p.useRef(null);return p.useEffect(()=>{if(!e||n)return;const l=t.current;if(!l)return;if(typeof IntersectionObserver>"u"){s(!0);return}const c=new IntersectionObserver(u=>{u.some(d=>d.isIntersecting)&&(s(!0),c.disconnect())},{rootMargin:"200px"});return c.observe(l),()=>c.disconnect()},[e,n,t]),p.useEffect(()=>{if(!n){a.current?.(),a.current=null,i(!1);return}const l=Ml();if(l)a.current=l,i(!0);else{const c=Iv(()=>{const u=Ml();u&&(c(),a.current=u,i(!0))});return()=>c()}},[n]),p.useEffect(()=>()=>{a.current?.()},[]),r}function $t(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);return Number.isFinite(t)?t:void 0}}const zv=new Set(["guest","teacher","teacher_preview"]);function _v(e){const t=e.filter(i=>typeof i.score=="number").slice().sort((i,a)=>a.score-i.score),n=new Map;let s=0,r=null;return t.forEach((i,a)=>{const l=i.score;(r===null||l<r)&&(s=a+1,r=l),n.set(i.attemptId,s)}),n}function Lv(e,t){return e.slice().sort((n,s)=>{const r=t.get(n.attemptId)??Number.MAX_SAFE_INTEGER,i=t.get(s.attemptId)??Number.MAX_SAFE_INTEGER;return r!==i?r-i:(n.studentName||n.studentId).localeCompare(s.studentName||s.studentId,"zh-Hans-CN")})}function Rv({data:e,lessonId:t,elementId:n,className:s,title:r,lazy:i=!0}){const a=Ze.useRef(null),l=Av(i,a),{theme:c}=Bs(),{scale:u}=on(),d=he(I=>I.session),[h,m]=p.useState([]),[f,g]=p.useState(!1);p.useEffect(()=>{const I=e.coursewareUuid;if(!I)return;let N=!1;const z=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(I)}`).then(x=>x.ok?x.json():[]).then(x=>{N||m(Array.isArray(x)?x:[])}).catch(()=>{})};z();let U=null,T=null;const D=()=>z();try{U=pm(),U.on("courseware-attempt-updated",D)}catch{T=setInterval(z,5e3)}return()=>{N=!0,U&&U.off("courseware-attempt-updated",D),T&&clearInterval(T)}},[e.coursewareUuid]);const y=()=>{au(c,Xi(c)),lu(u)};p.useEffect(()=>{const I=n??e.title??void 0,N=e.coursewareUuid;if(!I&&!N||!l)return;const z=a.current?.querySelector("iframe");if(!z||!(z instanceof HTMLIFrameElement)||!z.contentWindow)return;const U=T=>{if(T.source!==z.contentWindow)return;const D=T.data;if(!(!D||typeof D!="object"))if(D.type==="LMS_SUBMIT"){const x=D.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof D.attempt_id=="string"?D.attempt_id:void 0,payload:{score:$t(x.score??x.grade),total:$t(x.total??x.fullScore),completion:$t(x.completion??x.progress),comment:typeof x.comment=="string"?x.comment:void 0},raw:D})}else if(D.type==="LMS_SAVE_PROGRESS"){const x=D.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof D.attempt_id=="string"?D.attempt_id:void 0,payload:{score:$t(x.score),completion:$t(x.completion??x.progress)},raw:D})}else if(D.type==="LMS_FINISH")At.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof D.attempt_id=="string"?D.attempt_id:void 0,payload:{},raw:D});else if(D.type==="courseware:score"||D.type==="openlearn-cw-sdk:score"){const x=D.payload??D;At.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:I,coursewareUuid:N,payload:{score:$t(x.score),total:$t(x.total),detail:x.detail,source:typeof D.source=="string"?D.source:"openlearn-cw-sdk"},raw:D})}else typeof D.type=="string"&&D.type.startsWith("LMS_")&&At.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:I,coursewareUuid:N,payload:{originalType:D.type},raw:D})};return window.addEventListener("message",U),()=>window.removeEventListener("message",U)},[l,n,e.title,e.coursewareUuid,t]);const C=Es.resolve(e,{lessonId:t}),w=e.coursewareUuid?`/runtime/${e.coursewareUuid}/`:e.resourceId?`/api/resources/${e.resourceId}/`:C??void 0,P=h.filter(I=>I.finished_at!==null&&I.finished_at!==void 0),S=P.filter(I=>I.score!==null&&I.score!==void 0),j=S.length>0?S.reduce((I,N)=>I+(N.score||0),0)/S.length:null,A=60,E=d?.role==="student"&&(d.studentId||d.userId)||null,R=_v(h),F=P.filter(I=>!zv.has(I.studentId)||I.studentId===E),M=Lv(F,R),O=E?F.find(I=>I.studentId===E)??null:null,v=O?R.get(O.attemptId)??null:null,_=R.size,L=!!e.coursewareUuid&&h.length>0;return o.jsxs("div",{ref:a,className:(s??"w-full h-full")+" relative",children:[l?o.jsx("iframe",{className:"w-full h-full border-none",src:w,srcDoc:w?void 0:Nv(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",title:r??e.title??"Interactive Courseware",credentialless:"true",onLoad:y}):o.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"}),L&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>g(I=>!I),"data-testid":"courseware-scores-toggle",className:"absolute top-2 right-2 z-[60] px-3 py-1.5 bg-white/95 backdrop-blur-sm rounded-lg shadow-lg border border-gray-200 text-xs font-medium text-gray-700 hover:bg-white transition-colors",children:f?"隐藏成绩":`查看成绩 (${M.length})`}),f&&o.jsxs("div",{"data-testid":"courseware-scores-panel",className:"absolute top-12 right-2 z-[60] w-72 max-h-96 overflow-auto bg-white/95 backdrop-blur-sm rounded-xl shadow-lg border border-gray-200 p-3",children:[o.jsx("div",{className:"text-xs text-gray-400 mb-2 flex items-center justify-between",children:o.jsxs("span",{children:[M.length," 人已提交",j!==null&&` · 均分 ${j.toFixed(1)}`]})}),E&&o.jsx("div",{"data-testid":"courseware-my-score",className:"text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded-lg px-2 py-1.5 mb-2",children:O?`我的成绩 ${typeof O.score=="number"?O.score:"—"}${v!==null?` · 全班第 ${v}/${_} 名`:""}`:"我还没有提交"}),M.length===0?o.jsx("div",{className:"text-xs text-gray-400 text-center py-4",children:"暂无提交"}):o.jsx("div",{className:"space-y-1.5",children:M.map(I=>{const N=typeof I.score=="number"?I.score:null,z=typeof I.completion=="number"?Math.round(I.completion*100):null,U=R.get(I.attemptId),T=!!E&&I.studentId===E;return o.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${T?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${I.attemptId}`,children:[o.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:U??"-"}),o.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[I.studentName||I.studentId,T&&o.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),o.jsxs("span",{className:`font-mono font-bold ${N!==null&&N>=A?"text-green-600":"text-red-500"}`,children:[N!==null?N:"-",z!==null&&o.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[z,"%"]})]})]},I.attemptId)})})]})]})]})}class Ov{constructor(){this.renderers=new Map}register(t,n,s){this.renderers.set(t,{impl:n,pluginId:s})}get(t){return this.renderers.get(t)?.impl}has(t){return this.renderers.has(t)}unregister(t,n){const s=this.renderers.get(t);s&&(n&&s.pluginId!==n||this.renderers.delete(t))}unregisterPlugin(t){for(const[n,s]of this.renderers)s.pluginId===t&&this.renderers.delete(n)}}const js=new Ov,Jk=({type:e,title:t,data:n,containerSize:s,onClose:r,lessonId:i,elementId:a,dismissible:l=!0,readOnly:c=!1})=>{Ze.useEffect(()=>{if(!l)return;const g=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,l]);const u=l?r:()=>{},d=js.get(e),[h,m]=p.useState({width:window.innerWidth,height:window.innerHeight});p.useEffect(()=>{const g=()=>m({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[]);const f=o.jsx("div",{className:"fixed inset-0 z-[99999] bg-black/60 flex items-center justify-center",style:{pointerEvents:"auto"},children:o.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col",style:{width:Math.max(400,h.width-32),height:Math.max(300,h.height-32)},children:[o.jsxs("div",{className:"bg-indigo-50 text-indigo-700 px-4 py-2 flex justify-between items-center text-sm font-semibold border-b border-indigo-100 shrink-0",children:[o.jsx("span",{className:"truncate",children:t}),l?o.jsxs("button",{onClick:r,className:"p-1.5 hover:bg-indigo-200/50 rounded-lg text-indigo-600 hover:text-indigo-900 transition-colors cursor-pointer flex items-center gap-1 text-xs",children:[o.jsx(la,{size:14})," 退出全屏"]}):o.jsx("span",{className:`px-2 py-1 rounded-md text-xs font-bold flex items-center gap-1 select-none ${c?"bg-amber-100 text-amber-800 border border-amber-300":"bg-indigo-100 text-indigo-600"}`,title:c?"教师已开启全班专注锁定,当前为只读演示视图":"由教师端控制,无法在本地退出",children:c?"🔒 全班专注锁定中 · 演示视图":o.jsxs(o.Fragment,{children:[o.jsx(la,{size:12})," 教师同步视图"]})})]}),l&&o.jsx("div",{className:"absolute top-3 right-3 z-10",children:o.jsx("button",{onClick:r,className:"w-8 h-8 flex items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer",title:"关闭 (ESC)",children:o.jsx(Je,{size:16})})}),o.jsxs("div",{className:"flex-1 overflow-auto p-6 relative",style:{pointerEvents:c?"none":"auto"},children:[d?o.jsx(d,{elementType:e,data:n,onClose:u,containerSize:h,lessonId:i,elementId:a}):o.jsx(Mv,{elementType:e,data:n,onClose:u,containerSize:h,lessonId:i}),c&&o.jsx("div",{"data-testid":"fullscreen-readonly-lock-cover",className:"absolute inset-0 z-50 cursor-not-allowed bg-transparent select-none",style:{pointerEvents:"auto"},title:"🔒 全班专注锁定中:组件为只读跟随模式",onClick:g=>{g.stopPropagation(),g.preventDefault()},onPointerDown:g=>{g.stopPropagation(),g.preventDefault()}})]})]})});return Hf.createPortal(f,document.body)},Dv=[{field:"text",icon:"📝",label:"文本"},{field:"markdown",icon:"📄",label:"Markdown"},{field:"code",icon:"💻",label:"代码"},{field:"question",icon:"❓",label:"测验",extra:["options"]},{field:"equation",icon:"📐",label:"公式"},{field:"url",icon:"🔗",label:"链接"},{field:"src",icon:"🖼",label:"图片"},{field:"coursewareUuid",icon:"📚",label:"课件"}];function Mv({data:e,lessonId:t}){const n=Dv.find(l=>e[l.field]!==void 0&&e[l.field]!==null&&e[l.field]!=="");if(!n)return o.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-gray-500",children:[o.jsx(Fs,{size:48,className:"opacity-30"}),o.jsx("div",{className:"text-sm font-medium",children:"自动识别渲染"}),o.jsx("pre",{className:"text-xs text-left bg-gray-50 border rounded-lg p-4 max-w-full max-h-80 overflow-auto font-mono",children:JSON.stringify(e,null,2)})]});const{field:s,icon:r,label:i,extra:a}=n;if(s==="markdown")return o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(Mb,{children:String(e.markdown)})});if(s==="code")return o.jsx("textarea",{value:String(e.code),readOnly:!0,className:"w-full h-full p-4 bg-gray-900 text-green-400 font-mono text-sm rounded-xl resize-none"});if(s==="text")return o.jsx("div",{className:"flex items-start h-full",children:o.jsx("div",{className:"text-lg whitespace-pre-wrap leading-relaxed",children:String(e.text)})});if(s==="question"){const l=Array.isArray(e.options)?e.options:[];return o.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[o.jsx("h3",{className:"text-xl font-bold text-gray-800",children:e.question}),o.jsx("div",{className:"flex flex-col gap-3",children:l.map((c,u)=>o.jsxs("div",{className:"px-5 py-4 text-left bg-gray-50 border-2 border-gray-200 rounded-xl text-base",children:[o.jsxs("span",{className:"font-bold text-indigo-600 mr-3",children:["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[u],"."]}),c]},u))})]})}return s==="url"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("a",{href:String(e.url),target:"_blank",rel:"noopener noreferrer",className:"text-indigo-600 underline text-lg",children:String(e.url)})}):s==="src"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("img",{src:String(e.src),alt:"",className:"max-w-full max-h-full object-contain rounded-lg"})}):s==="coursewareUuid"?o.jsx(Rv,{data:{coursewareUuid:String(e.coursewareUuid)},lessonId:t,className:"w-full h-full rounded-xl border"}):s==="equation"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("div",{className:"text-2xl font-mono text-gray-800 bg-gray-50 px-8 py-4 rounded-xl border",children:String(e.equation)})}):o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-4xl mb-2",children:r}),o.jsx("div",{className:"text-lg font-semibold text-gray-800",children:i}),o.jsx("pre",{className:"mt-4 text-xs text-gray-500 max-w-md overflow-auto",children:JSON.stringify(e,null,2)})]})})}class Fv{constructor(){this.editors=new Map}register(t,n,s){this.editors.set(t,{impl:n,pluginId:s})}get(t){return this.editors.get(t)?.impl}has(t){return this.editors.has(t)}unregister(t,n){const s=this.editors.get(t);s&&(n&&s.pluginId!==n||this.editors.delete(t))}unregisterPlugin(t){for(const[n,s]of this.editors)s.pluginId===t&&this.editors.delete(n)}}const bi=new Fv,$v=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class Bv{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.moduleLoader=t?.moduleLoader??this.defaultModuleLoader}setWorkerManager(t){this.workerManager=t}async initialize(t,n,s,r){const i=new kv;await i.register(al,t),await i.register(ll,n),await i.register(cl,s),await i.register(ul,r),await i.register(p0,new Vv(t)),this.registry=i,this.initialized=!0,Ce.getState().initialize(i)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),Ce.getState().addPlugin({id:t.id,name:t.name,version:t.version,state:we.INSTALLED,executionMode:"inline"})}async activateRemotePlugin(t,n){const s=Ce.getState(),r=s.activePlugins.find(i=>i.id===t);if(!(r&&(r.state===we.ACTIVE||r.state===we.ACTIVATING))){s.updatePluginState(t,we.ACTIVATING);try{const i=`/plugins/${t}/frontend.js`,a=await fetch(i);if(!a.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${a.status}`);let l=await a.text();window.HostSharedDeps&&(l=Hv(l));const c=new Blob([l],{type:"text/javascript"}),u=URL.createObjectURL(c);let d;try{d=await import(u)}finally{URL.revokeObjectURL(u)}const h=d.default??d;if(typeof h.activate!="function")throw new Error("Invalid remote frontend plugin: missing activate function");const m=await this.buildContext(t,n);await Promise.race([h.activate(m),new Promise((f,g)=>setTimeout(()=>g(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:h.activate,deactivate:typeof h.deactivate=="function"?h.deactivate:void 0}),s.updatePluginState(t,we.ACTIVE)}catch(i){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,i),s.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),i}}}async activatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(r=>r.id===t);if(!s)throw new Error(`Plugin not found: ${t}`);if(s.executionMode==="worker")return this.activateWorkerPlugin(t,s);if(s.executionMode!=="inline")throw new Error(`Unsupported execution mode for activation: ${s.executionMode}`);n.updatePluginState(t,we.ACTIVATING);try{const r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i=await this.moduleLoader(r),a=i.default??i,l=a.manifest??i.manifest,c=a.activate??i.activate,u=a.deactivate??i.deactivate;if(!l||typeof c!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(l.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${l.id}"`);if(l.classroomTools)for(const h of l.classroomTools)n.registerExtensionPoint("classroom.tool",{id:h.id,label:h.name,icon:h.icon,component:()=>Promise.resolve({default:(()=>null)}),pluginId:t});const d=await this.buildContext(t,l);await Promise.race([c(d),new Promise((h,m)=>setTimeout(()=>m(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:l,activate:c,deactivate:typeof u=="function"?u:void 0}),n.updatePluginState(t,we.ACTIVE)}catch(r){throw n.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),r}}async activateWorkerPlugin(t,n){if(!this.workerManager)throw new Error(`Cannot activate plugin "${t}" in worker mode: BrowserWorkerManager not set. Call setWorkerManager() first.`);const s=Ce.getState(),r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i={id:t,name:n.name,version:n.version};s.updatePluginState(t,we.ACTIVATING);try{let a;if(this.registry)try{a=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:l}=await this.workerManager.createWorker(t,i,r,$v,a);this.pluginModules.set(t,{manifest:i,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(t)}}),s.updatePluginState(t,we.ACTIVE)}catch(a){throw s.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),a}}async deactivatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(r=>r.id===t);if(!(!s||s.state!==we.ACTIVE)){n.updatePluginState(t,we.DEACTIVATING);try{const r=this.pluginModules.get(t);r?.deactivate&&await Promise.race([r.deactivate(),new Promise((i,a)=>setTimeout(()=>a(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(r){console.error(`[FrontendPluginHost] Deactivation error for "${t}":`,r)}finally{this.unregisterPluginResources(t),this.pluginModules.delete(t),n.updatePluginState(t,we.INACTIVE)}}}async uninstallPlugin(t){const n=Ce.getState();n.activePlugins.find(r=>r.id===t)?.state===we.ACTIVE&&await this.deactivatePlugin(t);try{await fetch(`/api/plugins/${t}`,{method:"DELETE"})}catch(r){console.error(`[FrontendPluginHost] Failed to DELETE plugin "${t}" on server:`,r)}this.sourceCodes.delete(t),this.pluginModules.delete(t),this.unregisterPluginResources(t),n.removePlugin(t)}getExtensions(t){return Ce.getState().getExtensions(t)}unregisterPluginResources(t){Ce.getState().unregisterPluginExtensionPoints(t),js.unregisterPlugin(t),bi.unregisterPlugin(t),Es.unregisterPlugin(t),An.unregisterPlugin(t)}async defaultModuleLoader(t){const n=new Blob([t],{type:"text/javascript"}),s=URL.createObjectURL(n);try{return await import(s)}finally{URL.revokeObjectURL(s)}}async buildContext(t,n){if(!this.registry)throw new Error("FrontendPluginHost not initialized");const s=await this.registry.resolve(al),r=await this.registry.resolve(ll),i=await this.registry.resolve(cl),a=await this.registry.resolve(ul);return{services:{frontendApi:s,socketService:r,uiService:i,storageService:a},pluginId:t,manifest:n,ui:{registerExtensionPoint:(l,c)=>{Ce.getState().registerExtensionPoint(l,{...c,pluginId:t})},unregisterExtensionPoint:(l,c)=>{Ce.getState().unregisterExtensionPoint(l,c)},registerFullscreenRenderer:(l,c)=>{js.register(l,c,t)},unregisterFullscreenRenderer:l=>{js.unregister(l,t)},registerPropertyEditor:(l,c)=>{bi.register(l,c,t)},unregisterPropertyEditor:l=>{bi.unregister(l,t)},registerCoursewareSource:l=>{Es.register(l,t)},unregisterCoursewareSource:l=>{Es.unregister(l,t)},registerPaletteItem:l=>{An.register(l,t)},unregisterPaletteItem:l=>{An.unregister(l,t)}},navigation:{getTeacherTab:()=>_e.getState().teacherTab,setTeacherTab:l=>_e.getState().setTeacherTab(l),setSelectedLesson:l=>_e.getState().setSelectedLesson(l),subscribeTeacherTab:l=>{let c=_e.getState().teacherTab;return _e.subscribe(u=>{const d=u.teacherTab;d!==c&&(c=d,l(d))})}},context:{get:()=>{const l=_e.getState();return{lessonId:l.selectedLesson,classId:l.liveClassSelectedClassId}},subscribe:l=>{const c=_e.getState();let u={lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId};return _e.subscribe(d=>{const h={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};(h.lessonId!==u.lessonId||h.classId!==u.classId)&&(u=h,l(h))})}},invokeCommand:async(l,c)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=Ev(l,n.id),d=await s.post("/api/plugins/execute-command",{type:u,payload:c});if(d.success&&d.result!==void 0)return d.result;throw new Error(d.error||"Command execution failed")},registerPanel:l=>{const c=l.slot||"teacher.dashboard.widget";Ce.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerMenu:l=>{const c=l.slot||"teacher.panel";Ce.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerToolbarButton:l=>{Ce.getState().registerExtensionPoint("classroom.tool",{...l,pluginId:t})}}}}class Vv{constructor(t){this.frontendApi=t}async saveSemesterGrade(t,n,s){const r=await this.frontendApi.post("/api/grade-sync",{lessonId:t,studentId:n,grade:s});if(!r.success)throw new Error(r.error||"Failed to sync semester grade")}}const Fl={react:"window.HostSharedDeps.React","react-dom":"window.HostSharedDeps.ReactDOM","react-dom/client":"(window.HostSharedDeps.ReactDOMClient || window.HostSharedDeps.ReactDOM)","react/jsx-runtime":"window.HostSharedDeps.jsxRuntime",recharts:"window.HostSharedDeps.Recharts","lucide-react":"window.HostSharedDeps.LucideReact"};function $l(e){return e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.replace(/^type\s+/,"")).map(t=>t.replace(/\s+as\s+/,": ")).join(", ")}function Uv(e,t){e=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").trim();const n=[],s=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(s)return n.push(`const ${s[1]} = ${t}?.default ?? ${t};`),n.push(`const ${s[2]} = ${t};`),n.join(" ");const r=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\{([\s\S]*)\}$/);if(r){const c=r[1],u=$l(r[2]);return n.push(`const ${c} = ${t}?.default ?? ${t};`),u&&n.push(`const { ${u} } = ${t};`),n.join(" ")}const i=e.match(/^\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(i)return`const ${i[1]} = ${t};`;const a=e.match(/^\{([\s\S]*)\}$/);if(a)return`const { ${$l(a[1])} } = ${t};`;const l=e.match(/^([a-zA-Z_$][\w$]*)$/);return l?`const ${l[1]} = ${t}?.default ?? ${t};`:null}function Hv(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>Fl[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,r)=>{const i=Fl[r];if(!i)return n;const a=Uv(s,i);return a||n}),t}class qv extends Ze.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1},this.handleCopy=async()=>{const{error:n,errorInfo:s}=this.state;if(!n)return;const r=jo({type:"react",title:"React 组件渲染致命异常",message:n.message||String(n),stack:n.stack,componentStack:s?.componentStack||void 0,timestamp:Date.now(),url:typeof window<"u"?window.location.href:""});await Ds(r)&&(this.setState({copied:!0}),setTimeout(()=>this.setState({copied:!1}),2500))},this.handleReset=()=>{this.setState({hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1})},this.handleGoHome=()=>{typeof window<"u"&&(window.location.href="/")}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({errorInfo:n}),Bt.getState().addError({type:"react",title:"React 组件渲染异常",message:t?.message||String(t),stack:t?.stack,componentStack:n?.componentStack||void 0}),console.error("[GlobalErrorBoundary] Unhandled React render exception:",t,n)}render(){if(this.state.hasError){const{error:t,errorInfo:n,copied:s,showDetails:r}=this.state,i=this.props.fallbackTitle||"界面渲染遇到意外错误";return o.jsx("div",{className:"min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4 select-text",children:o.jsxs("div",{className:"max-w-2xl w-full bg-white dark:bg-slate-900 rounded-2xl shadow-xl border border-rose-200 dark:border-rose-900/60 overflow-hidden",children:[o.jsxs("div",{className:"bg-gradient-to-r from-rose-500 to-red-600 px-6 py-5 text-white flex items-center gap-3.5",children:[o.jsx("div",{className:"p-2.5 bg-white/20 rounded-xl backdrop-blur-xs shrink-0",children:o.jsx(jp,{size:24,className:"text-white"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-lg font-bold leading-snug",children:i}),o.jsx("p",{className:"text-xs text-rose-100 mt-0.5",children:"OpenLearn 捕获到界面异常,已阻止整页崩溃并为您保留了诊断报告。"})]})]}),o.jsxs("div",{className:"p-6 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider block mb-1.5",children:"错误摘要 (Error Summary)"}),o.jsxs("div",{className:"bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-900/50 rounded-xl p-3.5 text-rose-900 dark:text-rose-200 text-sm font-mono break-all",children:[t?.name,": ",t?.message||"未知异常"]})]}),o.jsxs("div",{className:"border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden",children:[o.jsxs("button",{type:"button",onClick:()=>this.setState({showDetails:!r}),className:"w-full px-4 py-2.5 bg-gray-50 dark:bg-slate-800/60 hover:bg-gray-100 dark:hover:bg-slate-800 flex items-center justify-between text-xs font-semibold text-gray-700 dark:text-gray-300 transition-colors cursor-pointer",children:[o.jsx("span",{children:"查看调用堆栈与排查信息"}),r?o.jsx(dn,{size:14}):o.jsx(Ts,{size:14})]}),r&&o.jsxs("div",{className:"p-4 bg-slate-900 text-slate-200 text-xs font-mono max-h-64 overflow-y-auto space-y-3 leading-relaxed",children:[t?.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-90",children:t.stack})]}),n?.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-80",children:n.componentStack})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:this.handleCopy,className:`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm cursor-pointer ${s?"bg-emerald-600 text-white shadow-emerald-600/30":"bg-indigo-600 hover:bg-indigo-700 text-white shadow-indigo-600/30"}`,children:[s?o.jsx(tt,{size:14}):o.jsx(an,{size:14}),o.jsx("span",{children:s?"✓ 诊断报告已复制!":"一键复制错误报告"})]}),o.jsxs("button",{type:"button",onClick:this.handleReset,className:"px-3.5 py-2 rounded-xl text-xs font-semibold bg-gray-100 dark:bg-slate-800 hover:bg-gray-200 dark:hover:bg-slate-700 text-gray-700 dark:text-gray-200 transition-colors flex items-center gap-1.5 cursor-pointer",children:[o.jsx(Zl,{size:14}),o.jsx("span",{children:"重新加载界面"})]})]}),o.jsxs("button",{type:"button",onClick:this.handleGoHome,className:"px-3 py-2 rounded-xl text-xs font-medium text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100 transition-colors flex items-center gap-1 cursor-pointer",children:[o.jsx(ql,{size:14}),o.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}window.React=wi;window.ReactDOM=Si;window.HostSharedDeps={React:wi,ReactDOM:Si,ReactDOMClient:ra,Recharts:ga,LucideReact:ca,jsxRuntime:sa,react:wi,"react-dom":Si,"react-dom/client":ra,"react/jsx-runtime":sa,recharts:ga,"lucide-react":ca};const Wv=new Bv;qf.createRoot(document.getElementById("root")).render(o.jsx(p.StrictMode,{children:o.jsx(qv,{children:o.jsx(Ub,{host:Wv,children:o.jsx(vv,{})})})}));export{qc as A,Wk as C,Jb as D,Mi as E,Jk as F,Rv as H,Mb as M,bm as P,he as a,qk as b,Gk as c,Ni as d,wt as e,ru as f,Sm as g,ju as h,it as i,gm as j,Bt as k,Cs as l,ys as m,Yb as n,Bs as o,on as p,Hk as q,Ev as r,pm as s,An as t,Ce as u,bi as v,At as w,js as x,au as y,Xi as z};
217
+ </body></html>`}class Rv{constructor(){this.loaders=new Map}register(t,n){this.loaders.set(t.id,{impl:t,pluginId:n})}unregister(t,n){const s=this.loaders.get(t);s&&(n&&s.pluginId!==n||this.loaders.delete(t))}unregisterPlugin(t){for(const[n,s]of this.loaders)s.pluginId===t&&this.loaders.delete(n)}resolve(t,n){for(const{impl:s}of this.loaders.values())try{const r=s.resolve(t,n);if(r)return r}catch{}return null}}const Es=new Rv,Ov=4;let hs=0;const Zi=new Set;function Ul(){return hs>=Ov?null:(hs+=1,()=>{hs=Math.max(0,hs-1);for(const e of Zi)e()})}function Mv(e){return Zi.add(e),()=>{Zi.delete(e)}}function Dv(e,t){const[n,s]=f.useState(!e),[r,i]=f.useState(!1),a=f.useRef(null);return f.useEffect(()=>{if(!e||n)return;const l=t.current;if(!l)return;if(typeof IntersectionObserver>"u"){s(!0);return}const c=new IntersectionObserver(u=>{u.some(d=>d.isIntersecting)&&(s(!0),c.disconnect())},{rootMargin:"200px"});return c.observe(l),()=>c.disconnect()},[e,n,t]),f.useEffect(()=>{if(!n){a.current?.(),a.current=null,i(!1);return}const l=Ul();if(l)a.current=l,i(!0);else{const c=Mv(()=>{const u=Ul();u&&(c(),a.current=u,i(!0))});return()=>c()}},[n]),f.useEffect(()=>()=>{a.current?.()},[]),r}function $t(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);return Number.isFinite(t)?t:void 0}}const Fv=new Set(["guest","teacher","teacher_preview"]);function $v(e){const t=e.filter(i=>typeof i.score=="number").slice().sort((i,a)=>a.score-i.score),n=new Map;let s=0,r=null;return t.forEach((i,a)=>{const l=i.score;(r===null||l<r)&&(s=a+1,r=l),n.set(i.attemptId,s)}),n}function Bv(e,t){return e.slice().sort((n,s)=>{const r=t.get(n.attemptId)??Number.MAX_SAFE_INTEGER,i=t.get(s.attemptId)??Number.MAX_SAFE_INTEGER;return r!==i?r-i:(n.studentName||n.studentId).localeCompare(s.studentName||s.studentId,"zh-Hans-CN")})}function Vv({data:e,lessonId:t,elementId:n,className:s,title:r,lazy:i=!0}){const a=De.useRef(null),l=Dv(i,a),{theme:c}=Us(),{scale:u}=on(),d=he(I=>I.session),[p,m]=f.useState([]),[h,g]=f.useState(!1);f.useEffect(()=>{const I=e.coursewareUuid;if(!I)return;let N=!1;const z=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(I)}`).then(x=>x.ok?x.json():[]).then(x=>{N||m(Array.isArray(x)?x:[])}).catch(()=>{})};z();let U=null,T=null;const M=()=>z();try{U=wm(),U.on("courseware-attempt-updated",M)}catch{T=setInterval(z,5e3)}return()=>{N=!0,U&&U.off("courseware-attempt-updated",M),T&&clearInterval(T)}},[e.coursewareUuid]);const y=()=>{fu(c,to(c)),pu(u)};f.useEffect(()=>{const I=n??e.title??void 0,N=e.coursewareUuid;if(!I&&!N||!l)return;const z=a.current?.querySelector("iframe");if(!z||!(z instanceof HTMLIFrameElement)||!z.contentWindow)return;const U=T=>{if(T.source!==z.contentWindow)return;const M=T.data;if(!(!M||typeof M!="object"))if(M.type==="LMS_SUBMIT"){const x=M.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof M.attempt_id=="string"?M.attempt_id:void 0,payload:{score:$t(x.score??x.grade),total:$t(x.total??x.fullScore),completion:$t(x.completion??x.progress),comment:typeof x.comment=="string"?x.comment:void 0},raw:M})}else if(M.type==="LMS_SAVE_PROGRESS"){const x=M.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof M.attempt_id=="string"?M.attempt_id:void 0,payload:{score:$t(x.score),completion:$t(x.completion??x.progress)},raw:M})}else if(M.type==="LMS_FINISH")At.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:I,coursewareUuid:N,attemptId:typeof M.attempt_id=="string"?M.attempt_id:void 0,payload:{},raw:M});else if(M.type==="courseware:score"||M.type==="openlearn-cw-sdk:score"){const x=M.payload??M;At.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:I,coursewareUuid:N,payload:{score:$t(x.score),total:$t(x.total),detail:x.detail,source:typeof M.source=="string"?M.source:"openlearn-cw-sdk"},raw:M})}else typeof M.type=="string"&&M.type.startsWith("LMS_")&&At.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:I,coursewareUuid:N,payload:{originalType:M.type},raw:M})};return window.addEventListener("message",U),()=>window.removeEventListener("message",U)},[l,n,e.title,e.coursewareUuid,t]);const v=Es.resolve(e,{lessonId:t}),w=e.coursewareUuid?`/runtime/${e.coursewareUuid}/`:e.resourceId?`/api/resources/${e.resourceId}/`:v??void 0,P=p.filter(I=>I.finished_at!==null&&I.finished_at!==void 0),S=P.filter(I=>I.score!==null&&I.score!==void 0),j=S.length>0?S.reduce((I,N)=>I+(N.score||0),0)/S.length:null,A=60,E=d?.role==="student"&&(d.studentId||d.userId)||null,R=$v(p),F=P.filter(I=>!Fv.has(I.studentId)||I.studentId===E),D=Bv(F,R),O=E?F.find(I=>I.studentId===E)??null:null,k=O?R.get(O.attemptId)??null:null,_=R.size,L=!!e.coursewareUuid&&p.length>0;return o.jsxs("div",{ref:a,className:(s??"w-full h-full")+" relative",children:[l?o.jsx("iframe",{className:"w-full h-full border-none",src:w,srcDoc:w?void 0:Lv(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",title:r??e.title??"Interactive Courseware",credentialless:"true",onLoad:y}):o.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"}),L&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>g(I=>!I),"data-testid":"courseware-scores-toggle",className:"absolute top-2 right-2 z-[60] px-3 py-1.5 bg-white/95 backdrop-blur-sm rounded-lg shadow-lg border border-gray-200 text-xs font-medium text-gray-700 hover:bg-white transition-colors",children:h?"隐藏成绩":`查看成绩 (${D.length})`}),h&&o.jsxs("div",{"data-testid":"courseware-scores-panel",className:"absolute top-12 right-2 z-[60] w-72 max-h-96 overflow-auto bg-white/95 backdrop-blur-sm rounded-xl shadow-lg border border-gray-200 p-3",children:[o.jsx("div",{className:"text-xs text-gray-400 mb-2 flex items-center justify-between",children:o.jsxs("span",{children:[D.length," 人已提交",j!==null&&` · 均分 ${j.toFixed(1)}`]})}),E&&o.jsx("div",{"data-testid":"courseware-my-score",className:"text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded-lg px-2 py-1.5 mb-2",children:O?`我的成绩 ${typeof O.score=="number"?O.score:"—"}${k!==null?` · 全班第 ${k}/${_} 名`:""}`:"我还没有提交"}),D.length===0?o.jsx("div",{className:"text-xs text-gray-400 text-center py-4",children:"暂无提交"}):o.jsx("div",{className:"space-y-1.5",children:D.map(I=>{const N=typeof I.score=="number"?I.score:null,z=typeof I.completion=="number"?Math.round(I.completion*100):null,U=R.get(I.attemptId),T=!!E&&I.studentId===E;return o.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${T?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${I.attemptId}`,children:[o.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:U??"-"}),o.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[I.studentName||I.studentId,T&&o.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),o.jsxs("span",{className:`font-mono font-bold ${N!==null&&N>=A?"text-green-600":"text-red-500"}`,children:[N!==null?N:"-",z!==null&&o.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[z,"%"]})]})]},I.attemptId)})})]})]})]})}class Uv{constructor(){this.renderers=new Map}register(t,n,s){this.renderers.set(t,{impl:n,pluginId:s})}get(t){return this.renderers.get(t)?.impl}has(t){return this.renderers.has(t)}unregister(t,n){const s=this.renderers.get(t);s&&(n&&s.pluginId!==n||this.renderers.delete(t))}unregisterPlugin(t){for(const[n,s]of this.renderers)s.pluginId===t&&this.renderers.delete(n)}}const js=new Uv,sC=({type:e,title:t,data:n,containerSize:s,onClose:r,lessonId:i,elementId:a,dismissible:l=!0,readOnly:c=!1})=>{De.useEffect(()=>{if(!l)return;const g=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,l]);const u=l?r:()=>{},d=js.get(e),[p,m]=f.useState({width:window.innerWidth,height:window.innerHeight});f.useEffect(()=>{const g=()=>m({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[]);const h=o.jsx("div",{className:"fixed inset-0 z-[99999] bg-black/60 flex items-center justify-center",style:{pointerEvents:"auto"},children:o.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col",style:{width:Math.max(400,p.width-32),height:Math.max(300,p.height-32)},children:[o.jsxs("div",{className:"bg-indigo-50 text-indigo-700 px-4 py-2 flex justify-between items-center text-sm font-semibold border-b border-indigo-100 shrink-0",children:[o.jsx("span",{className:"truncate",children:t}),l?o.jsxs("button",{onClick:r,className:"p-1.5 hover:bg-indigo-200/50 rounded-lg text-indigo-600 hover:text-indigo-900 transition-colors cursor-pointer flex items-center gap-1 text-xs",children:[o.jsx(ua,{size:14})," 退出全屏"]}):o.jsx("span",{className:`px-2 py-1 rounded-md text-xs font-bold flex items-center gap-1 select-none ${c?"bg-amber-100 text-amber-800 border border-amber-300":"bg-indigo-100 text-indigo-600"}`,title:c?"教师已开启全班专注锁定,当前为只读演示视图":"由教师端控制,无法在本地退出",children:c?"🔒 全班专注锁定中 · 演示视图":o.jsxs(o.Fragment,{children:[o.jsx(ua,{size:12})," 教师同步视图"]})})]}),l&&o.jsx("div",{className:"absolute top-3 right-3 z-10",children:o.jsx("button",{onClick:r,className:"w-8 h-8 flex items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer",title:"关闭 (ESC)",children:o.jsx(Ze,{size:16})})}),o.jsxs("div",{className:"flex-1 overflow-auto p-6 relative",style:{pointerEvents:c?"none":"auto"},children:[d?o.jsx(d,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:i,elementId:a}):o.jsx(qv,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:i}),c&&o.jsx("div",{"data-testid":"fullscreen-readonly-lock-cover",className:"absolute inset-0 z-50 cursor-not-allowed bg-transparent select-none",style:{pointerEvents:"auto"},title:"🔒 全班专注锁定中:组件为只读跟随模式",onClick:g=>{g.stopPropagation(),g.preventDefault()},onPointerDown:g=>{g.stopPropagation(),g.preventDefault()}})]})]})});return Zf.createPortal(h,document.body)},Hv=[{field:"text",icon:"📝",label:"文本"},{field:"markdown",icon:"📄",label:"Markdown"},{field:"code",icon:"💻",label:"代码"},{field:"question",icon:"❓",label:"测验",extra:["options"]},{field:"equation",icon:"📐",label:"公式"},{field:"url",icon:"🔗",label:"链接"},{field:"src",icon:"🖼",label:"图片"},{field:"coursewareUuid",icon:"📚",label:"课件"}];function qv({data:e,lessonId:t}){const n=Hv.find(l=>e[l.field]!==void 0&&e[l.field]!==null&&e[l.field]!=="");if(!n)return o.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-gray-500",children:[o.jsx(Bs,{size:48,className:"opacity-30"}),o.jsx("div",{className:"text-sm font-medium",children:"自动识别渲染"}),o.jsx("pre",{className:"text-xs text-left bg-gray-50 border rounded-lg p-4 max-w-full max-h-80 overflow-auto font-mono",children:JSON.stringify(e,null,2)})]});const{field:s,icon:r,label:i,extra:a}=n;if(s==="markdown")return o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(Hb,{children:String(e.markdown)})});if(s==="code")return o.jsx("textarea",{value:String(e.code),readOnly:!0,className:"w-full h-full p-4 bg-gray-900 text-green-400 font-mono text-sm rounded-xl resize-none"});if(s==="text")return o.jsx("div",{className:"flex items-start h-full",children:o.jsx("div",{className:"text-lg whitespace-pre-wrap leading-relaxed",children:String(e.text)})});if(s==="question"){const l=Array.isArray(e.options)?e.options:[];return o.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[o.jsx("h3",{className:"text-xl font-bold text-gray-800",children:e.question}),o.jsx("div",{className:"flex flex-col gap-3",children:l.map((c,u)=>o.jsxs("div",{className:"px-5 py-4 text-left bg-gray-50 border-2 border-gray-200 rounded-xl text-base",children:[o.jsxs("span",{className:"font-bold text-indigo-600 mr-3",children:["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[u],"."]}),c]},u))})]})}return s==="url"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("a",{href:String(e.url),target:"_blank",rel:"noopener noreferrer",className:"text-indigo-600 underline text-lg",children:String(e.url)})}):s==="src"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("img",{src:String(e.src),alt:"",className:"max-w-full max-h-full object-contain rounded-lg"})}):s==="coursewareUuid"?o.jsx(Vv,{data:{coursewareUuid:String(e.coursewareUuid)},lessonId:t,className:"w-full h-full rounded-xl border"}):s==="equation"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("div",{className:"text-2xl font-mono text-gray-800 bg-gray-50 px-8 py-4 rounded-xl border",children:String(e.equation)})}):o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-4xl mb-2",children:r}),o.jsx("div",{className:"text-lg font-semibold text-gray-800",children:i}),o.jsx("pre",{className:"mt-4 text-xs text-gray-500 max-w-md overflow-auto",children:JSON.stringify(e,null,2)})]})})}class Wv{constructor(){this.editors=new Map}register(t,n,s){this.editors.set(t,{impl:n,pluginId:s})}get(t){return this.editors.get(t)?.impl}has(t){return this.editors.has(t)}unregister(t,n){const s=this.editors.get(t);s&&(n&&s.pluginId!==n||this.editors.delete(t))}unregisterPlugin(t){for(const[n,s]of this.editors)s.pluginId===t&&this.editors.delete(n)}}const Si=new Wv;class Gv{constructor(){this.store=hn(()=>({items:new Map}))}register(t,n){if(!t?.quizType||!t.quizType.trim())throw new Error("[AssignmentQuestionRendererRegistry] quizType is required");if(typeof t.render!="function")throw new Error("[AssignmentQuestionRendererRegistry] render must be a function");const s=t.quizType.trim();this.store.setState(r=>{const i=new Map(r.items);return i.set(s,{config:{...t,quizType:s},pluginId:n||t.quizType}),{items:i}})}unregister(t,n){const s=t.trim(),r=this.store.getState().items.get(s);r&&n&&r.pluginId!==n||this.store.setState(i=>{const a=new Map(i.items);return a.delete(s),{items:a}})}match(t){if(!t||!t.startsWith("{"))return null;try{const n=String(JSON.parse(t).quizType??"").trim();if(!n||n==="mcq_learning_objectives")return null;const s=this.store.getState().items.get(n);return s?{config:s.config}:null}catch{return null}}clearOwned(t){t&&this.store.setState(n=>{const s=new Map(n.items);for(const[r,i]of s)i.pluginId===t&&s.delete(r);return{items:s}})}list(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}clear(){this.store.setState(()=>({items:new Map}))}}const vi=new Gv,Qv=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class Jv{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.moduleLoader=t?.moduleLoader??this.defaultModuleLoader}setWorkerManager(t){this.workerManager=t}async initialize(t,n,s,r){const i=new Iv;await i.register(hl,t),await i.register(fl,n),await i.register(pl,s),await i.register(ml,r),await i.register(S0,new Zv(t)),this.registry=i,this.initialized=!0,Ce.getState().initialize(i)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),Ce.getState().addPlugin({id:t.id,name:t.name,version:t.version,state:we.INSTALLED,executionMode:"inline"})}async activateRemotePlugin(t,n){const s=Ce.getState(),r=s.activePlugins.find(i=>i.id===t);if(!(r&&(r.state===we.ACTIVE||r.state===we.ACTIVATING))){s.updatePluginState(t,we.ACTIVATING);try{const i=`/plugins/${t}/frontend.js`,a=await fetch(i);if(!a.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${a.status}`);let l=await a.text();window.HostSharedDeps&&(l=Kv(l));const c=new Blob([l],{type:"text/javascript"}),u=URL.createObjectURL(c);let d;try{d=await import(u)}finally{URL.revokeObjectURL(u)}const p=d.default??d;if(typeof p.activate!="function")throw new Error("Invalid remote frontend plugin: missing activate function");const m=await this.buildContext(t,n);await Promise.race([p.activate(m),new Promise((h,g)=>setTimeout(()=>g(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:p.activate,deactivate:typeof p.deactivate=="function"?p.deactivate:void 0}),s.updatePluginState(t,we.ACTIVE)}catch(i){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,i),s.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),i}}}async activatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(r=>r.id===t);if(!s)throw new Error(`Plugin not found: ${t}`);if(s.executionMode==="worker")return this.activateWorkerPlugin(t,s);if(s.executionMode!=="inline")throw new Error(`Unsupported execution mode for activation: ${s.executionMode}`);n.updatePluginState(t,we.ACTIVATING);try{const r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i=await this.moduleLoader(r),a=i.default??i,l=a.manifest??i.manifest,c=a.activate??i.activate,u=a.deactivate??i.deactivate;if(!l||typeof c!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(l.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${l.id}"`);if(l.classroomTools)for(const p of l.classroomTools)n.registerExtensionPoint("classroom.tool",{id:p.id,label:p.name,icon:p.icon,component:()=>Promise.resolve({default:(()=>null)}),pluginId:t});const d=await this.buildContext(t,l);await Promise.race([c(d),new Promise((p,m)=>setTimeout(()=>m(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:l,activate:c,deactivate:typeof u=="function"?u:void 0}),n.updatePluginState(t,we.ACTIVE)}catch(r){throw n.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),r}}async activateWorkerPlugin(t,n){if(!this.workerManager)throw new Error(`Cannot activate plugin "${t}" in worker mode: BrowserWorkerManager not set. Call setWorkerManager() first.`);const s=Ce.getState(),r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i={id:t,name:n.name,version:n.version};s.updatePluginState(t,we.ACTIVATING);try{let a;if(this.registry)try{a=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:l}=await this.workerManager.createWorker(t,i,r,Qv,a);this.pluginModules.set(t,{manifest:i,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(t)}}),s.updatePluginState(t,we.ACTIVE)}catch(a){throw s.updatePluginState(t,we.ERROR),this.unregisterPluginResources(t),a}}async deactivatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(r=>r.id===t);if(!(!s||s.state!==we.ACTIVE)){n.updatePluginState(t,we.DEACTIVATING);try{const r=this.pluginModules.get(t);r?.deactivate&&await Promise.race([r.deactivate(),new Promise((i,a)=>setTimeout(()=>a(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(r){console.error(`[FrontendPluginHost] Deactivation error for "${t}":`,r)}finally{this.unregisterPluginResources(t),this.pluginModules.delete(t),n.updatePluginState(t,we.INACTIVE)}}}async uninstallPlugin(t){const n=Ce.getState();n.activePlugins.find(r=>r.id===t)?.state===we.ACTIVE&&await this.deactivatePlugin(t);try{await fetch(`/api/plugins/${t}`,{method:"DELETE"})}catch(r){console.error(`[FrontendPluginHost] Failed to DELETE plugin "${t}" on server:`,r)}this.sourceCodes.delete(t),this.pluginModules.delete(t),this.unregisterPluginResources(t),n.removePlugin(t)}getExtensions(t){return Ce.getState().getExtensions(t)}unregisterPluginResources(t){Ce.getState().unregisterPluginExtensionPoints(t),js.unregisterPlugin(t),Si.unregisterPlugin(t),Es.unregisterPlugin(t),zn.unregisterPlugin(t),vi.clearOwned(t)}async defaultModuleLoader(t){const n=new Blob([t],{type:"text/javascript"}),s=URL.createObjectURL(n);try{return await import(s)}finally{URL.revokeObjectURL(s)}}async buildContext(t,n){if(!this.registry)throw new Error("FrontendPluginHost not initialized");const s=await this.registry.resolve(hl),r=await this.registry.resolve(fl),i=await this.registry.resolve(pl),a=await this.registry.resolve(ml);return{services:{frontendApi:s,socketService:r,uiService:i,storageService:a},pluginId:t,manifest:n,ui:{registerExtensionPoint:(l,c)=>{Ce.getState().registerExtensionPoint(l,{...c,pluginId:t})},unregisterExtensionPoint:(l,c)=>{Ce.getState().unregisterExtensionPoint(l,c)},registerFullscreenRenderer:(l,c)=>{js.register(l,c,t)},unregisterFullscreenRenderer:l=>{js.unregister(l,t)},registerPropertyEditor:(l,c)=>{Si.register(l,c,t)},unregisterPropertyEditor:l=>{Si.unregister(l,t)},registerCoursewareSource:l=>{Es.register(l,t)},unregisterCoursewareSource:l=>{Es.unregister(l,t)},registerPaletteItem:l=>{zn.register(l,t)},unregisterPaletteItem:l=>{zn.unregister(l,t)},registerAssignmentQuestionRenderer:l=>{vi.register(l,t)},unregisterAssignmentQuestionRenderer:l=>{vi.unregister(l,t)}},navigation:{getTeacherTab:()=>_e.getState().teacherTab,setTeacherTab:l=>_e.getState().setTeacherTab(l),setSelectedLesson:l=>_e.getState().setSelectedLesson(l),subscribeTeacherTab:l=>{let c=_e.getState().teacherTab;return _e.subscribe(u=>{const d=u.teacherTab;d!==c&&(c=d,l(d))})}},context:{get:()=>{const l=_e.getState();return{lessonId:l.selectedLesson,classId:l.liveClassSelectedClassId}},subscribe:l=>{const c=_e.getState();let u={lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId};return _e.subscribe(d=>{const p={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};(p.lessonId!==u.lessonId||p.classId!==u.classId)&&(u=p,l(p))})}},invokeCommand:async(l,c)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=zv(l,n.id),d=await s.post("/api/plugins/execute-command",{type:u,payload:c});if(d.success&&d.result!==void 0)return d.result;throw new Error(d.error||"Command execution failed")},registerPanel:l=>{const c=l.slot||"teacher.dashboard.widget";Ce.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerMenu:l=>{const c=l.slot||"teacher.panel";Ce.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerToolbarButton:l=>{Ce.getState().registerExtensionPoint("classroom.tool",{...l,pluginId:t})}}}}class Zv{constructor(t){this.frontendApi=t}async saveSemesterGrade(t,n,s){const r=await this.frontendApi.post("/api/grade-sync",{lessonId:t,studentId:n,grade:s});if(!r.success)throw new Error(r.error||"Failed to sync semester grade")}}const Hl={react:"window.HostSharedDeps.React","react-dom":"window.HostSharedDeps.ReactDOM","react-dom/client":"(window.HostSharedDeps.ReactDOMClient || window.HostSharedDeps.ReactDOM)","react/jsx-runtime":"window.HostSharedDeps.jsxRuntime",recharts:"window.HostSharedDeps.Recharts","lucide-react":"window.HostSharedDeps.LucideReact"};function ql(e){return e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.replace(/^type\s+/,"")).map(t=>t.replace(/\s+as\s+/,": ")).join(", ")}function Yv(e,t){e=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").trim();const n=[],s=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(s)return n.push(`const ${s[1]} = ${t}?.default ?? ${t};`),n.push(`const ${s[2]} = ${t};`),n.join(" ");const r=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\{([\s\S]*)\}$/);if(r){const c=r[1],u=ql(r[2]);return n.push(`const ${c} = ${t}?.default ?? ${t};`),u&&n.push(`const { ${u} } = ${t};`),n.join(" ")}const i=e.match(/^\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(i)return`const ${i[1]} = ${t};`;const a=e.match(/^\{([\s\S]*)\}$/);if(a)return`const { ${ql(a[1])} } = ${t};`;const l=e.match(/^([a-zA-Z_$][\w$]*)$/);return l?`const ${l[1]} = ${t}?.default ?? ${t};`:null}function Kv(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>Hl[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,r)=>{const i=Hl[r];if(!i)return n;const a=Yv(s,i);return a||n}),t}class Xv extends De.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1},this.handleCopy=async()=>{const{error:n,errorInfo:s}=this.state;if(!n)return;const r=To({type:"react",title:"React 组件渲染致命异常",message:n.message||String(n),stack:n.stack,componentStack:s?.componentStack||void 0,timestamp:Date.now(),url:typeof window<"u"?window.location.href:""});await Fs(r)&&(this.setState({copied:!0}),setTimeout(()=>this.setState({copied:!1}),2500))},this.handleReset=()=>{this.setState({hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1})},this.handleGoHome=()=>{typeof window<"u"&&(window.location.href="/")}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({errorInfo:n}),Bt.getState().addError({type:"react",title:"React 组件渲染异常",message:t?.message||String(t),stack:t?.stack,componentStack:n?.componentStack||void 0}),console.error("[GlobalErrorBoundary] Unhandled React render exception:",t,n)}render(){if(this.state.hasError){const{error:t,errorInfo:n,copied:s,showDetails:r}=this.state,i=this.props.fallbackTitle||"界面渲染遇到意外错误";return o.jsx("div",{className:"min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4 select-text",children:o.jsxs("div",{className:"max-w-2xl w-full bg-white dark:bg-slate-900 rounded-2xl shadow-xl border border-rose-200 dark:border-rose-900/60 overflow-hidden",children:[o.jsxs("div",{className:"bg-gradient-to-r from-rose-500 to-red-600 px-6 py-5 text-white flex items-center gap-3.5",children:[o.jsx("div",{className:"p-2.5 bg-white/20 rounded-xl backdrop-blur-xs shrink-0",children:o.jsx(zp,{size:24,className:"text-white"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-lg font-bold leading-snug",children:i}),o.jsx("p",{className:"text-xs text-rose-100 mt-0.5",children:"OpenLearn 捕获到界面异常,已阻止整页崩溃并为您保留了诊断报告。"})]})]}),o.jsxs("div",{className:"p-6 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider block mb-1.5",children:"错误摘要 (Error Summary)"}),o.jsxs("div",{className:"bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-900/50 rounded-xl p-3.5 text-rose-900 dark:text-rose-200 text-sm font-mono break-all",children:[t?.name,": ",t?.message||"未知异常"]})]}),o.jsxs("div",{className:"border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden",children:[o.jsxs("button",{type:"button",onClick:()=>this.setState({showDetails:!r}),className:"w-full px-4 py-2.5 bg-gray-50 dark:bg-slate-800/60 hover:bg-gray-100 dark:hover:bg-slate-800 flex items-center justify-between text-xs font-semibold text-gray-700 dark:text-gray-300 transition-colors cursor-pointer",children:[o.jsx("span",{children:"查看调用堆栈与排查信息"}),r?o.jsx(dn,{size:14}):o.jsx(Ps,{size:14})]}),r&&o.jsxs("div",{className:"p-4 bg-slate-900 text-slate-200 text-xs font-mono max-h-64 overflow-y-auto space-y-3 leading-relaxed",children:[t?.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-90",children:t.stack})]}),n?.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-80",children:n.componentStack})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:this.handleCopy,className:`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm cursor-pointer ${s?"bg-emerald-600 text-white shadow-emerald-600/30":"bg-indigo-600 hover:bg-indigo-700 text-white shadow-indigo-600/30"}`,children:[s?o.jsx(tt,{size:14}):o.jsx(an,{size:14}),o.jsx("span",{children:s?"✓ 诊断报告已复制!":"一键复制错误报告"})]}),o.jsxs("button",{type:"button",onClick:this.handleReset,className:"px-3.5 py-2 rounded-xl text-xs font-semibold bg-gray-100 dark:bg-slate-800 hover:bg-gray-200 dark:hover:bg-slate-700 text-gray-700 dark:text-gray-200 transition-colors flex items-center gap-1.5 cursor-pointer",children:[o.jsx(tc,{size:14}),o.jsx("span",{children:"重新加载界面"})]})]}),o.jsxs("button",{type:"button",onClick:this.handleGoHome,className:"px-3 py-2 rounded-xl text-xs font-medium text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100 transition-colors flex items-center gap-1 cursor-pointer",children:[o.jsx(Zl,{size:14}),o.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}window.React=ki;window.ReactDOM=Ci;window.HostSharedDeps={React:ki,ReactDOM:Ci,ReactDOMClient:oa,Recharts:ya,LucideReact:da,jsxRuntime:ia,react:ki,"react-dom":Ci,"react-dom/client":oa,"react/jsx-runtime":ia,recharts:ya,"lucide-react":da};const ek=new Jv;Yf.createRoot(document.getElementById("root")).render(o.jsx(f.StrictMode,{children:o.jsx(Xv,{children:o.jsx(Jb,{host:ek,children:o.jsx(Pv,{})})})}));export{Yc as A,to as B,eC as C,s0 as D,Bi as E,sC as F,Vv as H,Hb as M,Em as P,he as a,vi as b,Xk as c,tC as d,Ii as e,uu as f,Nm as g,wt as h,zu as i,it as j,vm as k,Cs as l,ys as m,Bt as n,r0 as o,Us as p,on as q,zv as r,Kk as s,wm as t,Ce as u,zn as v,At as w,Si as x,js as y,fu as z};