openlearn-next 0.7.10 → 0.7.12

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 (54) hide show
  1. package/README.md +9 -2
  2. package/dist/assets/{ActivityWorkspaceWidget-BU88GGUG.js → ActivityWorkspaceWidget-TtBuNORs.js} +1 -1
  3. package/dist/assets/AdminDirectoryView-D03WOMc-.js +5 -0
  4. package/dist/assets/{AssessmentCenter-BoSWbJMt.js → AssessmentCenter-MUvoJySb.js} +1 -1
  5. package/dist/assets/{AssignmentFilePreview-D_POvLmv.js → AssignmentFilePreview-dVhnTYmq.js} +1 -1
  6. package/dist/assets/{BatchPickerModal-DiHd_6Tg.js → BatchPickerModal-QALdhrX6.js} +1 -1
  7. package/dist/assets/{ClassesView-CWKqzWH0.js → ClassesView-CKwlRz-A.js} +5 -5
  8. package/dist/assets/{ClassroomCountdownWidget-B5-KUVU8.js → ClassroomCountdownWidget-DyWyForY.js} +1 -1
  9. package/dist/assets/{CloudDriveModal-CjcvdDiw.js → CloudDriveModal-C8UAn3MO.js} +1 -1
  10. package/dist/assets/{ComputerLabView-CNTcmWAh.js → ComputerLabView-E5b3XTkk.js} +1 -1
  11. package/dist/assets/{CourseManagement-ha_iSnLU.js → CourseManagement-3jSlq7lV.js} +1 -1
  12. package/dist/assets/{CourseWizardModal-oVT9mYSG.js → CourseWizardModal-BAkW5VJX.js} +1 -1
  13. package/dist/assets/{CoursewareHubPanel-BuKp0mmW.js → CoursewareHubPanel-BkjcusjZ.js} +1 -1
  14. package/dist/assets/{Dashboard-Vb9coh9_.js → Dashboard-Ha2fZAqD.js} +2 -2
  15. package/dist/assets/{ExportWeightModal-BEesz6rd.js → ExportWeightModal-D2Y13384.js} +1 -1
  16. package/dist/assets/{HelpTour-D3QcGDUz.js → HelpTour-DBq2otcV.js} +1 -1
  17. package/dist/assets/{HelpView--Um9DFYx.js → HelpView-BVLRnMxl.js} +4 -4
  18. package/dist/assets/{ImportLessonsModal-DXGopj4j.js → ImportLessonsModal-CQlq4b81.js} +1 -1
  19. package/dist/assets/ImportModal-Ct0I5cAL.js +3 -0
  20. package/dist/assets/{InteractiveCoursewareViewer-DzgF9_LU.js → InteractiveCoursewareViewer-DGKh1gO8.js} +1 -1
  21. package/dist/assets/InteractiveWhiteboard-BbZlYpRu.js +65 -0
  22. package/dist/assets/{LazyCourseware-6yb_QiYS.js → LazyCourseware-zONqinCM.js} +2 -2
  23. package/dist/assets/{LazyWhiteboard-CsF9GB6J.js → LazyWhiteboard-BV98LEZ8.js} +2 -2
  24. package/dist/assets/{LessonEditorView-CZTZ7Q0B.js → LessonEditorView-LXRkKxdY.js} +1 -1
  25. package/dist/assets/LiveClassroomView-TaHtHWkY.js +63 -0
  26. package/dist/assets/{NotificationDetailModal-mUeIQP4R.js → NotificationDetailModal-BF_-pn0c.js} +1 -1
  27. package/dist/assets/{PluginView-CT3-zS2n.js → PluginView-sVMPXae9.js} +1 -1
  28. package/dist/assets/{ProcessLogsModal-DmsOrZnV.js → ProcessLogsModal-D97xLgnL.js} +1 -1
  29. package/dist/assets/{QuizGeneratorModal-ViKxNX5Q.js → QuizGeneratorModal-CNY8ISjR.js} +1 -1
  30. package/dist/assets/{StudentAssignmentEvalPanel-BRxHMABY.js → StudentAssignmentEvalPanel-CUmM5DbT.js} +1 -1
  31. package/dist/assets/{StudentAssignmentView-g-ewJIS3.js → StudentAssignmentView-B-1MtwKj.js} +1 -1
  32. package/dist/assets/{StudentLessonView-Dbvr3Xlo.js → StudentLessonView-CqrcvVND.js} +1 -1
  33. package/dist/assets/{StudentView-20vfEk4v.js → StudentView-Bi9kgSrN.js} +2 -2
  34. package/dist/assets/{SystemResourceLibraryModal-CDKeaKf8.js → SystemResourceLibraryModal-DDALKrJC.js} +1 -1
  35. package/dist/assets/{TeacherView-KIKuhXGF.js → TeacherView-C5JmoKHk.js} +2 -2
  36. package/dist/assets/{TimetableView-7V2AwWml.js → TimetableView-BOLB-kZC.js} +4 -4
  37. package/dist/assets/index-Bc9003lB.js +131 -0
  38. package/dist/assets/index-D4aq9poS.css +1 -0
  39. package/dist/assets/pluginParsers-DD3QL1Xl.js +1 -0
  40. package/dist/assets/{student-workspace-DstiW0pM.js → student-workspace-C4UgD58C.js} +1 -1
  41. package/dist/assets/{vendor-icons-DLOPlM4i.js → vendor-icons-CaXLq01o.js} +1 -1
  42. package/dist/index.html +3 -3
  43. package/dist/server.cjs +630 -433
  44. package/migrations/045_ai_providers_owner_and_scope.sql +20 -0
  45. package/migrations/README.md +1 -0
  46. package/migrations/schema-golden.json +13 -3
  47. package/package.json +4 -2
  48. package/dist/assets/AdminDirectoryView-Cdsk9Mdr.js +0 -5
  49. package/dist/assets/ImportModal-h5ShIMzO.js +0 -2
  50. package/dist/assets/InteractiveWhiteboard-DJqgP_tU.js +0 -65
  51. package/dist/assets/LiveClassroomView-D2ugupT9.js +0 -61
  52. package/dist/assets/index-C4cHQZyx.css +0 -1
  53. package/dist/assets/index-XduPa2-x.js +0 -131
  54. package/dist/assets/pluginParsers-BO6U1E-h.js +0 -1
@@ -0,0 +1,131 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/student-workspace-C4UgD58C.js","assets/vendor-react-DHoBZpn2.js","assets/vendor-utils-BxOuk3id.js","assets/LazyWhiteboard-BV98LEZ8.js","assets/StudentAssignmentEvalPanel-CUmM5DbT.js","assets/AssignmentFilePreview-dVhnTYmq.js","assets/vendor-icons-CaXLq01o.js","assets/ActivityWorkspaceWidget-TtBuNORs.js","assets/vendor-motion-BFAPOs-b.js","assets/StudentView-Bi9kgSrN.js","assets/TeacherView-C5JmoKHk.js","assets/ImportModal-Ct0I5cAL.js","assets/CourseWizardModal-BAkW5VJX.js","assets/ImportLessonsModal-CQlq4b81.js","assets/QuizGeneratorModal-CNY8ISjR.js","assets/ProcessLogsModal-D97xLgnL.js","assets/CloudDriveModal-C8UAn3MO.js","assets/LazyCourseware-zONqinCM.js","assets/SystemResourceLibraryModal-DDALKrJC.js","assets/BatchPickerModal-QALdhrX6.js","assets/ExportWeightModal-D2Y13384.js","assets/NotificationDetailModal-BF_-pn0c.js","assets/HelpTour-DBq2otcV.js","assets/CoursewareHubPanel-BkjcusjZ.js"])))=>i.map(i=>d[i]);
2
+ import{r as f,j as r,R as De,g as Xc,b as Vp,u as ed,d as no,h as so,J as nl,i as sl,k as Wp}from"./vendor-react-DHoBZpn2.js";import{G as kr,K as Br,S as td,U as Jo,C as Cs,a as sn,L as ro,A as Nr,b as Hp,c as mt,d as Ur,X as Re,e as Ko,T as Bt,P as Vr,I as Cr,M as io,B as Is,f as qp,g as Wr,W as Gp,h as lt,i as nd,j as sd,E as rd,R as Hr,k as En,l as id,m as Qp,n as Yo,o as Jp,H as Kp,F as Zo,p as Yp,q as Xo,r as ea,s as od,t as Er,u as ta,v as ad,w as Zp,x as Xp,y as Ps,z as ai,D as ld,J as oo,N as eg,O as ao,Q as tg,V as wt,Y as lo,Z as ng,_ as cd,$ as rl,a0 as dd,a1 as sg,a2 as rg,a3 as ud,a4 as zs,a5 as ig,a6 as og,a7 as na,a8 as ag,a9 as lg,aa as Tn,ab as co,ac as il,ad as ot,ae as cg,af as qr,ag as hd,ah as dg,ai as jn,aj as ug,ak as hg,al as fg,am as mg,an as Gr,ao as fd,ap as md,aq as An,ar as Tr,as as pg,at as pd,au as ol,av as gg,aw as xg,ax as li,ay as or,az as bg,aA as yg,aB as wg,aC as vg,aD as sa,aE as Sg,aF as jg,aG as kg,aH as Ng,aI as Cg,aJ as Eg}from"./vendor-icons-CaXLq01o.js";import{f as jt,h as Ut,j as ra}from"./vendor-utils-BxOuk3id.js";import{_ as He}from"./vendor-pdf-DVWGghIL.js";import{i as ci,g as Tg,s as gd,a as ia,b as xd,c as al,d as Ag,e as Ig,f as Pg,h as zg,r as Lg,j as Rg,k as bd,l as _g,m as Og,n as Dg,o as Mg,S as $g,H as Fg,F as Vt,p as Bg,q as Ug,t as yd,u as Ar,v as ll,w as ft,x as wd,y as Vg,z as cl,A as Wg,B as Ir,C as uo,D as dl,E as Hg,G as qg,I as Rt,J as Gg,K as Qg,L as Jg,M as ul,N as Kg,O as Yg,P as hl,Q as Zg,R as Xg,T as ar,U as ex,V as tx,W as vd,X as nx,Y as sx}from"./vendor-motion-BFAPOs-b.js";import{R as fl}from"./vendor-charts-skggaP9D.js";const oa=f.createContext(null);function Fs({value:e,children:t}){return r.jsx(oa.Provider,{value:e,children:t})}function vE(){const e=f.useContext(oa);if(!e)throw new Error("useAppData must be used within <AppDataProvider>");return e}function kt(){return f.useContext(oa)}async function rx(){const e=await fetch("/api/resources");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function ix(){const e=await fetch("/api/db-status");let t;try{t=await e.json()}catch{t={}}return{ok:e.ok,status:e.status,data:t}}async function ox(){const e=await fetch("/api/auth/session");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Sd(){const e=await fetch("/api/site-settings");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function ax(){await fetch("/api/auth/logout",{method:"POST"})}const jd=f.createContext(null),ho="openlearn_academic_year";function lx(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get("academicYear");return t||null}function cx(){if(typeof window>"u")return null;try{return window.localStorage.getItem(ho)}catch{return null}}function dx(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(ho,e):window.localStorage.removeItem(ho)}catch{}}function Bs({children:e}){const[t,n]=f.useState(()=>lx()||cx()||null),[s,i]=f.useState(null),[o,a]=f.useState(!0);f.useEffect(()=>{let u=!0;return(async()=>{try{const m=await Sd();if(!u)return;if(m.ok&&m.data){const p=m.data.currentAcademicYear||null;i(p),!t&&p&&n(p)}}catch{}finally{u&&a(!1)}})(),()=>{u=!1}},[]);const c=u=>{const m=u==="all"?null:u;if(n(m),dx(m),typeof window<"u"){const p=new URL(window.location.href);m?p.searchParams.set("academicYear",m):p.searchParams.delete("academicYear"),window.history.replaceState({},"",p.toString())}},l=t==="all"||t===null?null:t,d=f.useMemo(()=>({academicYear:t,setAcademicYear:c,apiAcademicYear:l,currentAcademicYear:s,loading:o}),[t,l,s,o]);return r.jsx(jd.Provider,{value:d,children:e})}function ux(){return f.useContext(jd)}function In(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.data)?e.data:[]}const hx=De.memo(function({onLoginSuccess:t,lang:n}){const[s,i]=f.useState("teacher"),[o,a]=f.useState(null),[c,l]=f.useState([]),[d,u]=f.useState(""),[m,p]=f.useState(""),[h,g]=f.useState(""),[y,x]=f.useState(!1),[b,v]=f.useState([]),[S,T]=f.useState(""),[k,w]=f.useState(""),[I,_]=f.useState(""),[R,L]=f.useState(""),[E,A]=f.useState(!1);f.useEffect(()=>{(async()=>{try{const $=await fetch("/api/students?pageSize=all");if($.ok){const V=In(await $.json());v(V),V.length>0&&T(V[0].id)}}catch($){console.warn("Failed to fetch student roster for login selection:",$)}})()},[]),f.useEffect(()=>{(async()=>{try{const $=await fetch("/api/site-settings");if($.ok){const V=await $.json();a(V)}}catch($){console.warn("Failed to fetch site settings for login branding:",$)}})()},[]),f.useEffect(()=>{(async()=>{try{const $=await fetch("/api/auth/seed-status");if(!$.ok)return;const V=await $.json();V?.active&&Array.isArray(V.accounts)&&l(V.accounts.filter(z=>typeof z=="string"))}catch{}})()},[]);const D=async P=>{if(P.preventDefault(),!d.trim()||!m){g(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{g(""),x(!0);const $=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:d.trim(),password:m})});if($.ok){const V=await $.json();t(V.session)}else{const V=await $.json();g(V.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{g(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{x(!1)}},F=async P=>{P.preventDefault();const $=S||k.trim();if(!$){L(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!I.trim()){L(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{L(""),A(!0);const V=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:$,password:I.trim()})});if(V.ok){const z=await V.json();t(z.session)}else{const z=await V.json();L(z.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{L(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{A(!1)}};return r.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",id:"login_page_container",children:[r.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),r.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),r.jsxs("div",{className:"w-full max-w-md bg-slate-950/85 backdrop-blur-md rounded-2xl border border-slate-800 shadow-2xl p-6 sm:p-8",id:"login_card",children:[r.jsxs("div",{className:"text-center mb-8",children:[o?.logoUrl?r.jsx("img",{src:o.logoUrl,alt:o.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):r.jsx("div",{className:"inline-flex items-center justify-center p-3 bg-gradient-to-tr from-indigo-500 to-indigo-600 rounded-2xl shadow-lg border border-indigo-400/20 mb-4 text-white",children:r.jsx(kr,{size:32})}),r.jsxs("h1",{className:"text-2xl sm:text-3xl font-black text-white tracking-tight flex items-center justify-center gap-2",children:[o?.siteName||"OpenLearn Next"," ",r.jsx("span",{className:"text-indigo-400 font-medium text-xs bg-indigo-500/20 px-2 py-0.5 rounded-full border border-indigo-400/20",children:"V2.0"})]}),r.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:o?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),c.length>0&&r.jsxs("div",{className:"mb-5 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-200 flex items-start gap-2",id:"login_default_credential_hint",children:[r.jsx(Br,{size:14,className:"shrink-0 mt-0.5"}),r.jsxs("div",{className:"space-y-1 min-w-0",children:[r.jsx("p",{className:"font-bold",children:n==="zh"?"首次安装?可以直接用默认口令登录":"First run? Sign in with the default password"}),r.jsx("p",{className:"font-mono text-amber-100 break-all",children:c.map(P=>`${P} / ${P}`).join(" · ")}),r.jsx("p",{className:"text-amber-300/80 leading-relaxed",children:n==="zh"?"口令与账号名相同。登录后会强制你改密,改完这条提示自动消失。":"Password equals the username. You will be required to change it right after signing in."})]})]}),r.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[r.jsxs("button",{onClick:()=>i("teacher"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${s==="teacher"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[r.jsx(td,{size:14}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),r.jsxs("button",{onClick:()=>i("student"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${s==="student"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[r.jsx(Jo,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?r.jsxs("form",{onSubmit:D,className:"space-y-4",children:[h&&r.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Cs,{size:15,className:"shrink-0"}),r.jsx("span",{children:h})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(sn,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),r.jsx("input",{type:"text",value:d,onChange:P=>u(P.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})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(ro,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),r.jsx("input",{type:"password",value:m,onChange:P=>p(P.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})]}),r.jsxs("button",{type:"submit",disabled:y,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:y?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),r.jsx(Nr,{size:15})]})]}):r.jsxs("form",{onSubmit:F,className:"space-y-4",children:[R&&r.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Cs,{size:15,className:"shrink-0"}),r.jsx("span",{children:R})]}),b.length>0?r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(kr,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),r.jsx("select",{value:S,onChange:P=>{T(P.target.value),w("")},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:b.map(P=>r.jsxs("option",{value:P.id,children:[P.name," (",P.student_number||P.id,")"]},P.id))}),r.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,r.jsxs("div",{className:"relative flex py-2 items-center",children:[r.jsx("div",{className:"flex-grow border-t border-slate-850"}),r.jsx("span",{className:"flex-shrink mx-3 text-xs font-bold text-slate-500 uppercase tracking-wider",children:n==="zh"?"或手动输入学号":"Or input key manually"}),r.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(sn,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),r.jsx("input",{type:"text",value:k,onChange:P=>{w(P.target.value),T("")},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"})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(ro,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),r.jsx("input",{type:"password",required:!0,value:I,onChange:P=>_(P.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"})]}),r.jsxs("button",{type:"submit",disabled:E,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:E?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),r.jsx(Nr,{size:15})]})]})]})]})});function fx({lang:e,username:t,onDone:n,onLogout:s}){const[i,o]=f.useState(""),[a,c]=f.useState(""),[l,d]=f.useState(""),[u,m]=f.useState(null),[p,h]=f.useState(!1),g=e==="zh",y=()=>!i||!a||!l?g?"请填写完整":"All fields are required":a.length<8?g?"新密码至少 8 位":"Password must be at least 8 characters long":!/[a-zA-Z]/.test(a)||!/[0-9]/.test(a)?g?"新密码需同时包含字母和数字":"Password must contain both letters and numbers":a===i?g?"新密码不能与当前密码相同":"New password must differ from the current one":a!==l?g?"两次输入的新密码不一致":"Passwords do not match":null,x=async()=>{const v=y();if(v){m(v);return}h(!0),m(null);try{const S=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:i,newPassword:a})}),T=await S.json().catch(()=>({}));if(!S.ok){m(T.error||(g?"修改失败,请重试":"Change failed, please retry"));return}n()}catch{m(g?"网络异常,请重试":"Network error, please retry")}finally{h(!1)}},b="w-full px-3 py-2 rounded-lg bg-white border border-slate-300 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent";return r.jsx("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 font-sans",children:r.jsxs("div",{className:"w-full max-w-md bg-white rounded-2xl shadow-xl p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[r.jsx("div",{className:"p-2 rounded-lg bg-amber-100",children:r.jsx(Hp,{size:20,className:"text-amber-600"})}),r.jsx("h1",{className:"text-lg font-bold text-slate-800",children:g?"安全要求:修改默认密码":"Security: Change Default Password"})]}),r.jsx("p",{className:"text-xs text-slate-500 leading-relaxed mb-5",children:g?`当前账号${t?`(${t})`:""}仍在使用初始默认密码,存在被接管的风险。请设置新密码后继续使用平台;修改前所有数据变更已被暂时冻结。`:`This account${t?` (${t})`:""} still uses the initial default password. Set a new password to continue; data changes are frozen until then.`}),r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:g?"当前密码":"Current password"}),r.jsx("input",{type:"password",value:i,onChange:v=>o(v.target.value),className:b,autoComplete:"current-password"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:g?"新密码(至少 8 位,含字母和数字)":"New password (8+ chars, letters & numbers)"}),r.jsx("input",{type:"password",value:a,onChange:v=>c(v.target.value),className:b,autoComplete:"new-password"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:g?"确认新密码":"Confirm new password"}),r.jsx("input",{type:"password",value:l,onChange:v=>d(v.target.value),className:b,autoComplete:"new-password"})]})]}),u&&r.jsx("div",{"data-testid":"force-change-error",className:"mt-3 text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:u}),r.jsxs("button",{type:"button",onClick:x,disabled:p,"data-testid":"force-change-submit",className:"mt-5 w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 disabled:opacity-60 text-white text-sm font-semibold transition-colors cursor-pointer",children:[p?r.jsx(mt,{size:16,className:"animate-spin"}):r.jsx(Br,{size:16}),g?"修改密码并继续":"Change password and continue"]}),r.jsxs("button",{type:"button",onClick:s,className:"mt-2 w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-slate-500 hover:text-slate-700 hover:bg-slate-100 text-xs font-medium transition-colors cursor-pointer",children:[r.jsx(Ur,{size:13}),g?"退出登录":"Log out"]})]})})}async function mx(){const e=await fetch("/api/lessons?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function px(e){const t=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?{ok:!0,data:await t.json().catch(()=>({}))}:{ok:!1}}async function gx(e){const t=await fetch(`/api/lessons/${e}`,{method:"DELETE"});return t.ok?{ok:!0,data:await t.json().catch(()=>({}))}:{ok:!1,data:await t.json().catch(()=>({}))}}async function xx(e){const t=await fetch(`/api/lessons/${e}/clone`,{method:"POST"});return t.ok?{ok:!0,data:await t.json().catch(()=>({}))}:{ok:!1,data:await t.json().catch(()=>({}))}}async function bx(e){const t=await fetch(`/api/lessons/${e}/whiteboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const yx=(e,t)=>({lessons:[],selectedLesson:null,elements:[],vfsNodes:[],setLessons:n=>e(s=>({lessons:typeof n=="function"?n(s.lessons):n})),setSelectedLesson:n=>e({selectedLesson:n}),setElements:n=>e({elements:n}),setVfsNodes:n=>e({vfsNodes:n}),loadLessons:async()=>{try{const{ok:n,data:s}=await mx();if(n){const i=In(s);e(o=>({lessons:i,selectedLesson:o.selectedLesson??(wx(t())&&i.length>0?i[0].id:o.selectedLesson)}))}}catch(n){console.warn("Failed to fetch lessons",n)}}});function wx(e){return e.session?.role==="teacher"}async function vx(){const e=await fetch("/api/classes?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Sx(){const e=await fetch("/api/students?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function jx(e){const t=await fetch(`/api/classes/${e}/students`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const kx=e=>({classes:[],students:[],classStudentsMap:{},classDashboardMap:{},studentProgressMap:{},classSchedulesMap:{},scheduleAttendanceMap:{},assignmentSubmissionsMap:{},classAssignmentsMap:{},classProgressMap:{},classSeats:{lab_id:null,seats:[]},dataVersion:0,setClasses:t=>e({classes:t}),setStudents:t=>e({students: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}),loadClasses:async()=>{try{const{ok:t,data:n}=await vx();t&&e(s=>({classes:In(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch classes",t)}},loadStudents:async()=>{try{const{ok:t,data:n}=await Sx();t&&e(s=>({students:In(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch students",t)}}}),Nx=e=>({liveClassSelectedClassId:null,liveClassIsActive:!1,liveClassFeed:[],liveClassTimeRemaining:0,liveClassAcknowledgedMap:new Map,liveClassStudentProgress:[],onlineStudentIds:[],activeStudentLessons:{},setLiveClassSelectedClassId:t=>e({liveClassSelectedClassId:t}),setLiveClassIsActive:t=>e({liveClassIsActive: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}),setOnlineStudentIds:t=>e({onlineStudentIds:t}),setActiveStudentLessons:t=>e({activeStudentLessons:t})}),Cx=e=>({session:null,sessionLoading:!0,dbConnected:!1,setSession:t=>e({session:t}),setSessionLoading:t=>e({sessionLoading:t}),setDbConnected:t=>e({dbConnected:t})}),Ex=e=>({aiProviders:[],plugins:[],registeredCommands:[],events:[],approvals:[],processes:[],todaySchedules:[],computerLabs:[],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}),setTodaySchedules:t=>e({todaySchedules:t}),setComputerLabs:t=>e({computerLabs:t})}),Tx=e=>({studentDashboardData:null,notifications:[],setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t})});function kd(e){return"#/"+e}function ys(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}function Ax(e){return window.location.pathname+window.location.search+kd(e)}function Ix(e){const t=Ax(e);window.open(t,"_blank","noopener,noreferrer")}function Px(){if(typeof window<"u"&&window.location?.hash){const e=ys(window.location.hash);if(e)return e}return"live_class"}const Ve=jt(e=>({lang:"zh",activeRole:"teacher",teacherTab:Px(),pendingTimetableSubTab:null,pendingLiveClassLaunch:null,profileOpen:!1,isCourseWizardOpen:!1,isImportLessonsOpen:!1,isQuizGeneratorOpen:!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}),setPendingTimetableSubTab:t=>e({pendingTimetableSubTab:t}),setPendingLiveClassLaunch:t=>e({pendingLiveClassLaunch:t}),setProfileOpen:t=>e({profileOpen:t}),setIsCourseWizardOpen:t=>e({isCourseWizardOpen:t}),setIsImportLessonsOpen:t=>e({isImportLessonsOpen:t}),setIsQuizGeneratorOpen:t=>e({isQuizGeneratorOpen: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})})),zx=e=>Ut(Ve,e),Lx=e=>({lang:Ve.getState().lang,teacherTab:Ve.getState().teacherTab,toasts:Ve.getState().toasts,siteInfo:Ve.getState().siteInfo,setLang:t=>{Ve.getState().setLang(t),e({lang:t})},setTeacherTab:t=>{Ve.getState().setTeacherTab(t),e({teacherTab:t})},addToast:t=>{Ve.getState().addToast(t),e({toasts:Ve.getState().toasts})},removeToast:t=>{Ve.getState().removeToast(t),e({toasts:Ve.getState().toasts})},setSiteInfo:t=>{Ve.getState().setSiteInfo(t),e({siteInfo:t})}}),Se=jt()((...e)=>({...yx(...e),...kx(...e),...Nx(...e),...Cx(...e),...Ex(...e),...Tx(...e),...Lx(...e)})),ae=e=>Ut(Se,e);class Rx{constructor(){this.handlers=new Map,this.subscribers=new Map,this.middlewares=[],this.activeModals=[],this.modalListeners=new Set,this.registerBuiltinHandlers()}async dispatch(t,n){const s="act_"+Math.random().toString(36).slice(2,10),i={action:t,sourcePluginId:n?.sourcePluginId,timestamp:Date.now(),correlationId:s},o=async()=>{const l=this.handlers.get(t.type);if(l&&l.size>0){const d=Array.from(l);if(d.length===1)return await d[0](i);const u=await Promise.all(d.map(m=>m(i)));if(t.type==="host:refresh"){const m=new Set;for(const p of u)p&&Array.isArray(p.refreshed)&&p.refreshed.forEach(h=>m.add(h));return{success:!0,refreshed:Array.from(m)}}return u[u.length-1]}};let c=(async()=>{let l=-1;const d=async u=>{if(u<=l)throw new Error("next() called multiple times in middleware");if(l=u,u<this.middlewares.length){const m=this.middlewares[u];return m(i,()=>d(u+1))}return o()};return d(0)})();if(n?.timeoutMs&&n.timeoutMs>0){let l;const d=new Promise((u,m)=>{l=setTimeout(()=>{m(new Error(`Action "${t.type}" timed out after ${n.timeoutMs}ms`))},n.timeoutMs)});c=Promise.race([c,d]).finally(()=>{clearTimeout(l)})}try{const l=await c;return this.notifySubscribers(i,l,void 0),l}catch(l){throw this.notifySubscribers(i,void 0,l),l}}registerHandler(t,n){this.handlers.has(t)||this.handlers.set(t,new Set);const s=this.handlers.get(t);return s.add(n),{dispose:()=>{s.delete(n),s.size===0&&this.handlers.delete(t)}}}subscribe(t,n){this.subscribers.has(t)||this.subscribers.set(t,new Set);const s=this.subscribers.get(t);return s.add(n),{dispose:()=>{s.delete(n),s.size===0&&this.subscribers.delete(t)}}}use(t){return this.middlewares.push(t),{dispose:()=>{const n=this.middlewares.indexOf(t);n!==-1&&this.middlewares.splice(n,1)}}}getActiveModals(){return[...this.activeModals]}subscribeModals(t){return this.modalListeners.add(t),t(this.getActiveModals()),{dispose:()=>{this.modalListeners.delete(t)}}}resolveModal(t,n){const s=this.activeModals.findIndex(i=>i.id===t);if(s!==-1){const[i]=this.activeModals.splice(s,1);i.resolve(n),this.notifyModalListeners()}}closeAllModals(){for(;this.activeModals.length>0;)this.activeModals.pop().resolve({closed:!0,confirmed:!1});this.notifyModalListeners()}notifyModalListeners(){const t=this.getActiveModals();this.modalListeners.forEach(n=>{try{n(t)}catch(s){console.error("[HostActionDispatcher] Error notifying modal listener:",s)}})}createScopedDispatcher(t){return{dispatch:(n,s)=>this.dispatch(n,{sourcePluginId:t,...s}),registerHandler:(n,s)=>this.registerHandler(n,s),subscribe:(n,s)=>this.subscribe(n,s),use:n=>this.use(n)}}registerBuiltinHandlers(){this.registerHandler("host:refresh",async t=>{const s=t.action.payload.target,i=[];try{const a=Se.getState();(s==="classes"||s==="all")&&typeof a.loadClasses=="function"&&(await a.loadClasses(),i.push("classes")),(s==="lessons"||s==="all")&&typeof a.loadLessons=="function"&&(await a.loadLessons(),i.push("lessons")),(s==="students"||s==="all")&&typeof a.loadStudents=="function"&&(await a.loadStudents(),i.push("students"))}catch(a){console.warn("[HostActionDispatcher] Builtin refresh failed:",a)}return{success:!0,refreshed:i}}),this.registerHandler("host:modal:confirm",t=>{const n=t.action.payload,s=n.id||"modal_confirm_"+Math.random().toString(36).slice(2,9);return new Promise(i=>{const o={id:s,type:"confirm",title:n.title,message:n.message,confirmText:n.confirmText,cancelText:n.cancelText,variant:n.variant||"primary",sourcePluginId:t.sourcePluginId,createdAt:Date.now(),resolve:a=>{const c=typeof a?.confirmed=="boolean"?a.confirmed:!1;i({confirmed:c})}};this.activeModals.push(o),this.notifyModalListeners()})}),this.registerHandler("host:modal:open",t=>{const n=t.action.payload,s=n.id||"modal_open_"+Math.random().toString(36).slice(2,9);return new Promise(i=>{const o={id:s,type:"open",title:n.title,content:n.content,size:n.size||"md",showCloseButton:n.showCloseButton!==!1,closableByBackdrop:n.closableByBackdrop!==!1,actions:n.actions,sourcePluginId:t.sourcePluginId,createdAt:Date.now(),resolve:a=>{i({actionId:a?.actionId,closed:a?.closed??!0})}};this.activeModals.push(o),this.notifyModalListeners()})}),this.registerHandler("host:modal:close",t=>{const n=t.action.payload;if(n.id)this.resolveModal(n.id,n.result??{closed:!0});else if(this.activeModals.length>0){const s=this.activeModals[this.activeModals.length-1];this.resolveModal(s.id,n.result??{closed:!0})}return{closed:!0}}),this.registerHandler("host:toast",t=>{const n=t.action.payload,s="toast_"+Math.random().toString(36).slice(2,9);try{Se.getState().addToast({id:s,title:n.title,message:n.message,type:n.type||"info"})}catch(o){console.warn("[HostActionDispatcher] Failed to add toast:",o)}return{delivered:!0}}),this.registerHandler("host:navigate",t=>{const n=t.action.payload;try{Se.getState().setTeacherTab(n.tab)}catch(i){console.warn("[HostActionDispatcher] Failed to navigate:",i)}return{navigated:!0}})}notifySubscribers(t,n,s){const i=o=>{o&&o.forEach(a=>{try{a(t,n,s)}catch(c){console.error("[HostActionDispatcher] Subscriber threw error:",c)}})};i(this.subscribers.get(t.action.type)),i(this.subscribers.get("*"))}}const Nd=new Rx,_x=({dispatcher:e})=>{const t=e||Nd,[n,s]=f.useState([]);if(f.useEffect(()=>{const y=t;if(typeof y.subscribeModals=="function"){const x=y.subscribeModals(b=>{s([...b])});return()=>{x.dispose()}}},[t]),f.useEffect(()=>{if(n.length===0)return;const y=x=>{if(x.key==="Escape"){const b=n[n.length-1],v=t;v.resolveModal&&(b.type==="confirm"?v.resolveModal(b.id,{confirmed:!1}):v.resolveModal(b.id,{closed:!0}))}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n,t]),n.length===0)return null;const i=n[n.length-1],o=t,a=()=>{o.resolveModal?.(i.id,{confirmed:!0})},c=()=>{o.resolveModal?.(i.id,{confirmed:!1})},l=()=>{i.type==="confirm"?o.resolveModal?.(i.id,{confirmed:!1}):o.resolveModal?.(i.id,{closed:!0})},d=(y,x)=>{o.resolveModal?.(i.id,{actionId:y,closed:!!x})},m={sm:"max-w-sm",md:"max-w-md",lg:"max-w-xl",xl:"max-w-3xl",full:"max-w-5xl"}[i.size||"md"]||"max-w-md",p=()=>{switch(i.variant){case"danger":return r.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 text-red-600 flex items-center justify-center shrink-0",children:r.jsx(Bt,{size:20})});case"warning":return r.jsx("div",{className:"w-10 h-10 rounded-full bg-amber-100 text-amber-600 flex items-center justify-center shrink-0",children:r.jsx(Cs,{size:20})});case"primary":default:return r.jsx("div",{className:"w-10 h-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0",children:r.jsx(Ko,{size:20})})}},h=()=>{switch(i.variant){case"danger":return"bg-red-600 hover:bg-red-700 text-white shadow-xs focus:ring-red-500";case"warning":return"bg-amber-600 hover:bg-amber-700 text-white shadow-xs focus:ring-amber-500";case"primary":default:return"bg-indigo-600 hover:bg-indigo-700 text-white shadow-xs focus:ring-indigo-500"}},g=y=>{switch(y){case"danger":return"bg-red-600 hover:bg-red-700 text-white";case"secondary":return"bg-gray-100 hover:bg-gray-200 text-gray-700";case"ghost":return"hover:bg-gray-100 text-gray-600";case"primary":default:return"bg-indigo-600 hover:bg-indigo-700 text-white"}};return r.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"host-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-xs transition-opacity",onClick:y=>{y.target===y.currentTarget&&i.closableByBackdrop!==!1&&l()},children:r.jsxs("div",{className:`w-full ${m} bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden flex flex-col transform transition-all animate-in fade-in zoom-in-95 duration-150`,onClick:y=>y.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-100",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[i.type==="confirm"&&p(),r.jsx("h3",{id:"host-modal-title",className:"text-base font-bold text-gray-900 truncate",children:i.title})]}),i.showCloseButton!==!1&&r.jsx("button",{onClick:l,className:"p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer","aria-label":"关闭",children:r.jsx(Re,{size:18})})]}),r.jsx("div",{className:"px-6 py-4 overflow-y-auto max-h-[70vh]",children:i.type==="confirm"?r.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:i.message}):i.content}),r.jsx("div",{className:"flex items-center justify-end gap-2.5 px-6 py-3.5 bg-gray-50/80 border-t border-gray-100",children:i.type==="confirm"?r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:c,className:"px-4 py-2 text-xs font-bold text-gray-600 bg-white border border-gray-200 hover:bg-gray-50 rounded-xl transition-all cursor-pointer shadow-2xs",children:i.cancelText||"取消"}),r.jsx("button",{onClick:a,className:`px-4 py-2 text-xs font-bold rounded-xl transition-all cursor-pointer focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${h()}`,children:i.confirmText||"确定"})]}):i.actions&&i.actions.length>0?i.actions.map(y=>r.jsx("button",{onClick:()=>d(y.actionId,y.isClose),className:`px-4 py-2 text-xs font-bold rounded-xl transition-all cursor-pointer ${g(y.variant)}`,children:y.label},y.actionId)):r.jsx("button",{onClick:l,className:"px-4 py-2 text-xs font-bold text-gray-600 bg-white border border-gray-200 hover:bg-gray-50 rounded-xl transition-all cursor-pointer shadow-2xs",children:"关闭"})})]})})},aa=f.createContext(null);function Ox({children:e,host:t}){return r.jsxs(aa.Provider,{value:t,children:[e,r.jsx(_x,{dispatcher:t?.getDispatcher?.()})]})}function Dx(){const e=f.useContext(aa);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}function Cd(){return f.useContext(aa)}typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("storage",e=>{e.key===la&&Ce.setState({dashboardVisibility:Ed()})});const la="openlearn:dashboardVisibility";function Ed(){try{const e=localStorage.getItem(la);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function ml(e){try{localStorage.setItem(la,JSON.stringify([...e.entries()]))}catch{}}const Ce=ra()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:Ed(),pluginErrors:new Map,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(i=>i.id!==n)})),updatePluginState:(n,s)=>e(i=>({activePlugins:i.activePlugins.map(o=>o.id===n?{...o,state:s}:o)})),registerExtensionPoint:(n,s)=>e(i=>{const o=i.extensionPoints.get(n)??[],a=o.find(l=>l.id===s.id);if(a){if(a.pluginId!==s.pluginId)return console.warn(`[PluginHost] Extension point "${n}/${s.id}" is owned by plugin "${a.pluginId}"; registration from "${s.pluginId}" was rejected (cross-plugin overwrite).`),i;const l=new Map(i.extensionPoints);return l.set(n,o.map(d=>d.id===s.id?s:d)),{extensionPoints:l}}const c=new Map(i.extensionPoints);return c.set(n,[...o,s]),{extensionPoints:c}}),unregisterExtensionPoint:(n,s,i)=>e(o=>{const a=o.extensionPoints.get(n);if(!a)return o;const c=a.find(u=>u.id===s);if(!c)return o;if(i&&c.pluginId!==i)return console.warn(`[PluginHost] Plugin "${i}" cannot unregister extension point "${n}/${s}" owned by "${c.pluginId}".`),o;const l=a.filter(u=>u.id!==s),d=new Map(o.extensionPoints);return l.length===0?d.delete(n):d.set(n,l),{extensionPoints:d}}),unregisterPluginExtensionPoints:n=>e(s=>{const i=new Map(s.extensionPoints);for(const[o,a]of i){const c=a.filter(l=>l.pluginId!==n);c.length===0?i.delete(o):i.set(o,c)}return{extensionPoints:i}}),unregisterPluginRuntimeExtensionPoints:n=>e(s=>{const i=new Map(s.extensionPoints);let o=!1;for(const[a,c]of i){const l=c.filter(d=>d.pluginId!==n||d.origin==="manifest");l.length!==c.length&&(o=!0,l.length===0?i.delete(a):i.set(a,l))}return o?{extensionPoints:i}:s}),getExtensions:n=>[...t().extensionPoints.get(n)??[]].sort((i,o)=>(i.position??100)-(o.position??100)),setDashboardVisibility:(n,s)=>e(i=>{const o=new Map(i.dashboardVisibility);return o.set(n,s),ml(o),{dashboardVisibility:o}}),setPluginError:(n,s)=>e(i=>{const o=new Map(i.pluginErrors);return o.set(n,s),{pluginErrors:o}}),clearPluginError:n=>e(s=>{if(!s.pluginErrors.has(n))return s;const i=new Map(s.pluginErrors);return i.delete(n),{pluginErrors:i}}),setDashboardVisibilityBatch:n=>e(s=>{const i=new Map(s.dashboardVisibility);for(const[o,a]of n)i.set(o,a);return ml(i),{dashboardVisibility:i}})}));function Mx(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:image/")||e.startsWith("/")||e.startsWith("./")||/\.(svg|png|jpe?g|webp|gif|ico)(\?.*)?$/i.test(e)}function $x(e){return!(!e||e.length>8||/^[a-zA-Z0-9_-]+$/.test(e))}function Fx(e){if(!e)return null;const t=Cr;if(t[e])return t[e];const n=e.split(/[-_\s]+/).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("");return t[n]?t[n]:null}function fn({icon:e,size:t=18,className:n="shrink-0",fallback:s=Vr,alt:i=""}){const[o,a]=f.useState(!1);if(!e)return r.jsx(s,{size:t,className:n});if(typeof e=="function"||typeof e=="object"&&e!==null&&"$$typeof"in e){const c=e;return r.jsx(c,{size:t,className:n})}if(typeof e=="string"){const c=e.trim();if(!c)return r.jsx(s,{size:t,className:n});if(Mx(c))return o?r.jsx(s,{size:t,className:n}):r.jsx("img",{src:c,alt:i,style:{width:`${t}px`,height:`${t}px`},className:`object-contain rounded-xs ${n}`,onError:()=>a(!0),loading:"lazy"});if($x(c))return r.jsx("span",{className:`inline-flex items-center justify-center font-normal leading-none select-none ${n}`,style:{fontSize:`${Math.round(t*.95)}px`,width:`${t}px`,height:`${t}px`},"aria-hidden":!i,title:i,children:c});const l=Fx(c);if(l)return r.jsx(l,{size:t,className:n})}return r.jsx(s,{size:t,className:n})}const ca="zh",Et={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:"暂无学生",openInNewTab:"在新标签页打开"},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",openInNewTab:"Open in new tab"}};function da(e){return e?e.toLowerCase().startsWith("en")?"en":"zh":ca}const Pn=new Map;let ua="zh";function Bx(e,t){if(!e||!t||typeof t!="object")return;const n={};for(const[i,o]of Object.entries(t))if(o&&typeof o=="object"){const a=da(i);n[a]={...n[a]||{},...o}}const s=Pn.get(e)||{};Pn.set(e,{...s,...n,...Object.fromEntries(Object.entries(n).map(([i,o])=>[i,{...s[i]||{},...o}]))})}function Ux(e){Pn.delete(e)}function Vx(){return ua}function Yt(e,t){return!e||!t?e:e.replace(/\{([^{}]+)\}/g,(n,s)=>{const i=t[s.trim()];return i!=null?String(i):n})}function Td(e){if(!e)return"";let t=e.replace(/^%+|%+$/g,"").trim();t.includes(":")&&(t=t.split(":").slice(1).join(":"));const n=t.split(".").filter(Boolean);return(n.length>1?n.slice(-2).join(" "):n[0]||t).replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(/\s+/).filter(Boolean).map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")||e}function Ad(e,t,n,s){let i,o,a=s||ua;typeof t=="string"?(i=t,o=n):t&&typeof t=="object"&&(o=t,n&&typeof n=="object"&&"defaultValue"in n&&(i=n.defaultValue));const c=da(a),l=ca;if(e.includes(":")){const d=e.indexOf(":"),u=e.substring(0,d),m=e.substring(d+1),p=Pn.get(u);if(p){if(p[c]&&p[c][m]!==void 0)return Yt(p[c][m],o);if(p[l]&&p[l][m]!==void 0)return Yt(p[l][m],o)}}if(Et[c]?.[e]!==void 0)return Yt(Et[c][e],o);if(Et[l]?.[e]!==void 0)return Yt(Et[l][e],o);for(const[,d]of Pn){if(d[c]?.[e]!==void 0)return Yt(d[c][e],o);if(d[l]?.[e]!==void 0)return Yt(d[l][e],o)}return i!=null?Yt(i,o):Td(e)}function mn(e,t,n){if(!e)return"";const s=String(e).trim();if(/^%([\w.-]+)%$/.test(s)){const o=s.slice(1,-1),a=da(n||ua),c=ca;if(t){const l=Pn.get(t);if(l){if(l[a]?.[o]!==void 0)return l[a][o];if(l[c]?.[o]!==void 0)return l[c][o]}}return Et[a]?.[o]!==void 0?Et[a][o]:Et[c]?.[o]!==void 0?Et[c][o]:Td(o)}return s.includes(":")&&!s.includes(" ")&&!s.includes("/")?Ad(s,void 0,void 0,n):s}const fo=Et,Id=3,Wx=300*1e3,Es=new Map;function Hx(e){const t=Date.now(),n=Es.get(e);if(!n||t-n.lastAt>Wx)return Es.set(e,{count:1,lastAt:t,blown:!1}),{shouldBreak:!1,count:1};n.count+=1,n.lastAt=t;const s=n.count>=Id;return s&&(n.blown=!0),{shouldBreak:s,count:n.count}}function qx(e){Es.delete(e)}function di(e){return Es.get(e)?.blown??!1}function Us(e){Es.delete(e)}function Gx(e){if(typeof e!="string")return"";const t=e.split(/[\\/]/).pop()||"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n).toLowerCase()}const Qx=Object.freeze({".pdf":"application/pdf",".rtf":"application/rtf",".odt":"application/vnd.oasis.opendocument.text",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".txt":"text/plain",".md":"text/plain",".csv":"text/plain",".json":"text/plain",".xml":"text/plain",".html":"text/plain",".css":"text/plain",".py":"text/plain",".js":"text/plain",".mjs":"text/plain",".cjs":"text/plain",".ts":"text/plain",".tsx":"text/plain",".jsx":"text/plain",".java":"text/plain",".c":"text/plain",".h":"text/plain",".cpp":"text/plain",".cs":"text/plain",".go":"text/plain",".rs":"text/plain",".rb":"text/plain",".php":"text/plain",".sql":"text/plain",".ino":"text/plain",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".heic":"image/heic",".zip":"application/zip"}),Jx=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".heic"]),Kx=new Set([".txt",".md",".csv",".json",".xml",".html",".css",".py",".js",".mjs",".cjs",".ts",".tsx",".jsx",".java",".c",".h",".cpp",".cs",".go",".rs",".rb",".php",".sql",".ino"]),Yx=new Set(["application/pdf","text/plain","image/png","image/jpeg","image/gif","image/webp","image/bmp"]),SE=512*1024;function jE(e){const t=Gx(e?.name??""),n=Qx[t]??"application/octet-stream";return t===".pdf"?{kind:"pdf",extension:t,contentType:n,inlineSafe:!0,asText:!1}:Jx.has(t)?{kind:"image",extension:t,contentType:n,inlineSafe:Yx.has(n),asText:!1}:Kx.has(t)?{kind:"text",extension:t,contentType:"text/plain",inlineSafe:!0,asText:!0}:{kind:"unsupported",extension:t,contentType:n,inlineSafe:!1,asText:!1}}function Zx(e,t){if(!Array.isArray(e))return!1;const n=(t||"").toLowerCase(),s=e.filter(i=>typeof i=="string").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return s.includes("*")?!0:n?s.some(i=>(i.startsWith(".")?i:`.${i}`)===n):!1}class Xx{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 eb=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function Pd(e,t){const n=t+".";return e.startsWith(n)||eb.test(e)?e:n+e}const mo="api:write",po="api:admin",go="grades:write",xo="agent:tool",bo="ai:invoke",ps="task:register",tb="student-data:read",nb="student-data:write",sb={ASSIGNMENT_MANAGE:"assignment:manage",ASSIGNMENT_READ:"assignment:read",ASSIGNMENT_REVIEW:"assignment:review",ASSIGNMENT_SUBMIT:"assignment:submit",ASSIGNMENT_WRITE:"assignment:write",LESSON_DELETE:"lesson:delete",LESSON_READ:"lesson:read",LESSON_WRITE:"lesson:write",MANAGEMENT_READ:"management:read",MANAGEMENT_WRITE:"management:write",PLUGIN_READ:"plugin:read",PLUGIN_WRITE:"plugin:write",PROCESS_READ:"process:read",PROCESS_WRITE:"process:write",STUDENT_WRITE:"student:write",VFS_READ:"vfs:read",VFS_WRITE:"vfs:write",WHITEBOARD_READ:"whiteboard:read",WHITEBOARD_WRITE:"whiteboard:write",CLASS_READ:"class:read",CLASS_WRITE:"class:write",STUDENT_READ:"student:read",API_WRITE:mo,API_ADMIN:po,GRADES_WRITE:go,AGENT_TOOL:xo,AI_INVOKE:bo,TASK_REGISTER:ps,STUDENT_DATA_READ:tb,STUDENT_DATA_WRITE:nb,SEGMENT_GATE_EVAL:"segment:gate_eval"},rb=Object.freeze(Array.from(new Set(Object.values(sb))));new Set(rb);const ib=Object.freeze(["/api/plugins","/api/users","/api/auth","/api/ai-providers","/api/agent","/api/grade-sync","/api/site-settings","/api/approvals"]),ob=Object.freeze(["/gdpr-delete"]),ab=/^\/api\/[^/]+\/[^/]+$/;function lb(e){if(typeof e!="string"||e.length===0)return"";const t=e.split("?")[0]??"";return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function cb(e){return!Array.isArray(e)||e.length===0?"":lb(e[0])}function Zt(e,t){return e.some(n=>typeof n=="string"&&(n===t||n.startsWith(`${t}:`)))}function db(e){return e==="get"||e.startsWith("get")}function ub(e){const{token:t,method:n,args:s,tokens:i}=e,o=e.caps??[];if(i.frontendApi&&t===i.frontendApi){if(db(n)||n==="request"&&!Array.isArray(s))return null;const a=cb(s),c=ib.some(u=>a===u||a.startsWith(`${u}/`)),l=ob.some(u=>a.endsWith(u)),d=n==="del"&&ab.test(a);return c||l||d?Zt(o,po)?null:`${l?`不可逆操作 '${a}'`:d?`实体级删除 '${a}'`:`写入高危路径 '${a||"<未提供路径>"}'`} 需要 manifest 声明 '${po}' 能力`:Zt(o,mo)?null:`写操作(${n})需要 manifest 声明 '${mo}' 能力(普通只读调用请用 get)`}if(i.socketService&&t===i.socketService)return n==="disconnect"||n==="destroy"?`插件无权调用 ${n}()——断开课堂实时通道会中断正在进行的教学`:null;if(i.semesterGradeService&&t===i.semesterGradeService)return n.startsWith("save")||n.startsWith("write")||n.startsWith("set")?Zt(o,go)?null:`写入学期成绩需要 manifest 声明 '${go}' 能力('grades' 或 'grades:read' 不足以解锁写入)`:null;if(i.processService&&t===i.processService)return n==="registerHandler"||n==="registerInterval"?Zt(o,ps)?null:`注册后台任务(${n})需要 manifest 声明 '${ps}' 能力`:n==="restore"?Zt(o,ps)?null:`恢复后台任务(restore)会重放全部插件的 running 进程,需要 manifest 声明 '${ps}' 能力`:null;if(i.aiService&&t===i.aiService)return n==="generateText"||n==="chat"||n==="complete"?Zt(o,bo)?null:`调用 AI 生成(${n})需要 manifest 声明 '${bo}' 能力`:null;if(i.actionRegistry&&t===i.actionRegistry){if(n==="register"){const c=(Array.isArray(s)?s[0]:void 0)?.exposeToAgent;if(c===void 0||c!==!1)return Zt(o,xo)?null:`注册对外暴露的 action 需要 manifest 声明 '${xo}' 能力(如不希望进入 AI Agent 工具列表,请设置 exposeToAgent: false)`}return null}return i.storageService&&t===i.storageService||i.uiService&&t===i.uiService,null}const gs="@openlearn/frontend:IFrontendAPI",yo="@openlearn/frontend:ISocketService",lr="@openlearn/frontend:IUIService",cr="@openlearn/frontend:IStorageService",zd="@openlearn/frontend:ISemesterGradeService",hb="@openlearn/frontend:IHostActionDispatcher";var Le=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(Le||{});const fb=Object.freeze({frontendApi:gs,socketService:yo,uiService:lr,storageService:cr,semesterGradeService:zd});function mb(e,t,n,s=[]){return ub({token:e,method:t,args:n,caps:s,tokens:fb})}const xs="ol-plugin-frame",Vs="ol-plugin-view",pb="allow-scripts",gb="/plugin-sandbox/frame";function pl(e){return!!e&&typeof e=="object"&&e.channel===xs}function xb(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const bb=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,yb=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,wb={};function gl(e,t){return(wb.jsx?yb:bb).test(e)}const vb=/[ \t\n\f\r]/g;function Sb(e){return typeof e=="object"?e.type==="text"?xl(e.value):!1:xl(e)}function xl(e){return e.replace(vb,"")===""}class Ls{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}Ls.prototype.normal={};Ls.prototype.property={};Ls.prototype.space=void 0;function Ld(e,t){const n={},s={};for(const i of e)Object.assign(n,i.property),Object.assign(s,i.normal);return new Ls(n,s,t)}function wo(e){return e.toLowerCase()}class st{constructor(t,n){this.attribute=n,this.property=t}}st.prototype.attribute="";st.prototype.booleanish=!1;st.prototype.boolean=!1;st.prototype.commaOrSpaceSeparated=!1;st.prototype.commaSeparated=!1;st.prototype.defined=!1;st.prototype.mustUseProperty=!1;st.prototype.number=!1;st.prototype.overloadedBoolean=!1;st.prototype.property="";st.prototype.spaceSeparated=!1;st.prototype.space=void 0;let jb=0;const me=on(),Ue=on(),vo=on(),J=on(),Pe=on(),nn=on(),it=on();function on(){return 2**++jb}const So=Object.freeze(Object.defineProperty({__proto__:null,boolean:me,booleanish:Ue,commaOrSpaceSeparated:it,commaSeparated:nn,number:J,overloadedBoolean:vo,spaceSeparated:Pe},Symbol.toStringTag,{value:"Module"})),ui=Object.keys(So);class ha extends st{constructor(t,n,s,i){let o=-1;if(super(t,n),bl(this,"space",i),typeof s=="number")for(;++o<ui.length;){const a=ui[o];bl(this,ui[o],(s&So[a])===So[a])}}}ha.prototype.defined=!0;function bl(e,t,n){n&&(e[t]=n)}function Ln(e){const t={},n={};for(const[s,i]of Object.entries(e.properties)){const o=new ha(s,e.transform(e.attributes||{},s),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(o.mustUseProperty=!0),t[s]=o,n[wo(s)]=s,n[wo(o.attribute)]=s}return new Ls(t,n,e.space)}const Rd=Ln({properties:{ariaActiveDescendant:null,ariaAtomic:Ue,ariaAutoComplete:null,ariaBusy:Ue,ariaChecked:Ue,ariaColCount:J,ariaColIndex:J,ariaColSpan:J,ariaControls:Pe,ariaCurrent:null,ariaDescribedBy:Pe,ariaDetails:null,ariaDisabled:Ue,ariaDropEffect:Pe,ariaErrorMessage:null,ariaExpanded:Ue,ariaFlowTo:Pe,ariaGrabbed:Ue,ariaHasPopup:null,ariaHidden:Ue,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Pe,ariaLevel:J,ariaLive:null,ariaModal:Ue,ariaMultiLine:Ue,ariaMultiSelectable:Ue,ariaOrientation:null,ariaOwns:Pe,ariaPlaceholder:null,ariaPosInSet:J,ariaPressed:Ue,ariaReadOnly:Ue,ariaRelevant:null,ariaRequired:Ue,ariaRoleDescription:Pe,ariaRowCount:J,ariaRowIndex:J,ariaRowSpan:J,ariaSelected:Ue,ariaSetSize:J,ariaSort:null,ariaValueMax:J,ariaValueMin:J,ariaValueNow:J,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function _d(e,t){return t in e?e[t]:t}function Od(e,t){return _d(e,t.toLowerCase())}const kb=Ln({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:nn,acceptCharset:Pe,accessKey:Pe,action:null,allow:null,allowFullScreen:me,allowPaymentRequest:me,allowUserMedia:me,alpha:me,alt:null,as:null,async:me,autoCapitalize:null,autoComplete:Pe,autoFocus:me,autoPlay:me,blocking:Pe,capture:null,charSet:null,checked:me,cite:null,className:Pe,closedBy:null,colorSpace:null,cols:J,colSpan:J,command:null,commandFor:null,content:null,contentEditable:Ue,controls:me,controlsList:Pe,coords:J|nn,crossOrigin:null,data:null,dateTime:null,decoding:null,default:me,defer:me,dir:null,dirName:null,disabled:me,download:vo,draggable:Ue,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:me,formTarget:null,headers:Pe,height:J,hidden:vo,high:J,href:null,hrefLang:null,htmlFor:Pe,httpEquiv:Pe,id:null,imageSizes:null,imageSrcSet:null,inert:me,inputMode:null,integrity:null,is:null,isMap:me,itemId:null,itemProp:Pe,itemRef:Pe,itemScope:me,itemType:Pe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:me,low:J,manifest:null,max:null,maxLength:J,media:null,method:null,min:null,minLength:J,multiple:me,muted:me,name:null,nonce:null,noModule:me,noValidate:me,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:me,optimum:J,pattern:null,ping:Pe,placeholder:null,playsInline:me,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:me,referrerPolicy:null,rel:Pe,required:me,reversed:me,rows:J,rowSpan:J,sandbox:Pe,scope:null,scoped:me,seamless:me,selected:me,shadowRootClonable:me,shadowRootCustomElementRegistry:me,shadowRootDelegatesFocus:me,shadowRootMode:null,shadowRootSerializable:me,shape:null,size:J,sizes:null,slot:null,span:J,spellCheck:Ue,src:null,srcDoc:null,srcLang:null,srcSet:null,start:J,step:null,style:null,tabIndex:J,target:null,title:null,translate:null,type:null,typeMustMatch:me,useMap:null,value:Ue,width:J,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Pe,axis:null,background:null,bgColor:null,border:J,borderColor:null,bottomMargin:J,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:me,declare:me,event:null,face:null,frame:null,frameBorder:null,hSpace:J,leftMargin:J,link:null,longDesc:null,lowSrc:null,marginHeight:J,marginWidth:J,noResize:me,noHref:me,noShade:me,noWrap:me,object:null,profile:null,prompt:null,rev:null,rightMargin:J,rules:null,scheme:null,scrolling:Ue,standby:null,summary:null,text:null,topMargin:J,valueType:null,version:null,vAlign:null,vLink:null,vSpace:J,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:me,disablePictureInPicture:me,disableRemotePlayback:me,exportParts:nn,part:Pe,prefix:null,property:null,results:J,security:null,unselectable:null},space:"html",transform:Od}),Nb=Ln({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:it,accentHeight:J,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:J,amplitude:J,arabicForm:null,ascent:J,attributeName:null,attributeType:null,azimuth:J,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:J,by:null,calcMode:null,capHeight:J,className:Pe,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:J,diffuseConstant:J,direction:null,display:null,dur:null,divisor:J,dominantBaseline:null,download:me,dx:null,dy:null,edgeMode:null,editable:null,elevation:J,enableBackground:null,end:null,event:null,exponent:J,externalResourcesRequired:null,fill:null,fillOpacity:J,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:nn,g2:nn,glyphName:nn,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:J,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:J,horizOriginX:J,horizOriginY:J,id:null,ideographic:J,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:J,k:J,k1:J,k2:J,k3:J,k4:J,kernelMatrix:it,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:J,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:J,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:J,overlineThickness:J,paintOrder:null,panose1:null,path:null,pathLength:J,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Pe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:J,pointsAtY:J,pointsAtZ:J,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:it,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:it,rev:it,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:it,requiredFeatures:it,requiredFonts:it,requiredFormats:it,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:J,specularExponent:J,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:J,strikethroughThickness:J,string:null,stroke:null,strokeDashArray:it,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:J,strokeOpacity:J,strokeWidth:null,style:null,surfaceScale:J,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:it,tabIndex:J,tableValues:null,target:null,targetX:J,targetY:J,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:it,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:J,underlineThickness:J,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:J,values:null,vAlphabetic:J,vMathematical:J,vectorEffect:null,vHanging:J,vIdeographic:J,version:null,vertAdvY:J,vertOriginX:J,vertOriginY:J,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:J,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:_d}),Dd=Ln({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()}}),Md=Ln({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Od}),$d=Ln({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Cb={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"},Eb=/[A-Z]/g,yl=/-[a-z]/g,Tb=/^data[-\w.:]+$/i;function Ab(e,t){const n=wo(t);let s=t,i=st;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Tb.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(yl,Pb);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!yl.test(o)){let a=o.replace(Eb,Ib);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=ha}return new i(s,t)}function Ib(e){return"-"+e.toLowerCase()}function Pb(e){return e.charAt(1).toUpperCase()}const zb=Ld([Rd,kb,Dd,Md,$d],"html"),fa=Ld([Rd,Nb,Dd,Md,$d],"svg");function Lb(e){return e.join(" ").trim()}var pn={},hi,wl;function Rb(){if(wl)return hi;wl=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,c=/^\s+|\s+$/g,l=`
3
+ `,d="/",u="*",m="",p="comment",h="declaration";function g(x,b){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];b=b||{};var v=1,S=1;function T(F){var P=F.match(t);P&&(v+=P.length);var $=F.lastIndexOf(l);S=~$?F.length-$:S+F.length}function k(){var F={line:v,column:S};return function(P){return P.position=new w(F),R(),P}}function w(F){this.start=F,this.end={line:v,column:S},this.source=b.source}w.prototype.content=x;function I(F){var P=new Error(b.source+":"+v+":"+S+": "+F);if(P.reason=F,P.filename=b.source,P.line=v,P.column=S,P.source=x,!b.silent)throw P}function _(F){var P=F.exec(x);if(P){var $=P[0];return T($),x=x.slice($.length),P}}function R(){_(n)}function L(F){var P;for(F=F||[];P=E();)P!==!1&&F.push(P);return F}function E(){var F=k();if(!(d!=x.charAt(0)||u!=x.charAt(1))){for(var P=2;m!=x.charAt(P)&&(u!=x.charAt(P)||d!=x.charAt(P+1));)++P;if(P+=2,m===x.charAt(P-1))return I("End of comment missing");var $=x.slice(2,P-2);return S+=2,T($),x=x.slice(P),S+=2,F({type:p,comment:$})}}function A(){var F=k(),P=_(s);if(P){if(E(),!_(i))return I("property missing ':'");var $=_(o),V=F({type:h,property:y(P[0].replace(e,m)),value:$?y($[0].replace(e,m)):m});return _(a),V}}function D(){var F=[];L(F);for(var P;P=A();)P!==!1&&(F.push(P),L(F));return F}return R(),D()}function y(x){return x?x.replace(c,m):m}return hi=g,hi}var vl;function _b(){if(vl)return pn;vl=1;var e=pn&&pn.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pn,"__esModule",{value:!0}),pn.default=n;const t=e(Rb());function n(s,i){let o=null;if(!s||typeof s!="string")return o;const a=(0,t.default)(s),c=typeof i=="function";return a.forEach(l=>{if(l.type!=="declaration")return;const{property:d,value:u}=l;c?i(d,u,l):u&&(o=o||{},o[d]=u)}),o}return pn}var as={},Sl;function Ob(){if(Sl)return as;Sl=1,Object.defineProperty(as,"__esModule",{value:!0}),as.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,o=function(d){return!d||n.test(d)||e.test(d)},a=function(d,u){return u.toUpperCase()},c=function(d,u){return"".concat(u,"-")},l=function(d,u){return u===void 0&&(u={}),o(d)?d:(d=d.toLowerCase(),u.reactCompat?d=d.replace(i,c):d=d.replace(s,c),d.replace(t,a))};return as.camelCase=l,as}var ls,jl;function Db(){if(jl)return ls;jl=1;var e=ls&&ls.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(_b()),n=Ob();function s(i,o){var a={};return!i||typeof i!="string"||(0,t.default)(i,function(c,l){c&&l&&(a[(0,n.camelCase)(c,o)]=l)}),a}return s.default=s,ls=s,ls}var Mb=Db();const $b=Xc(Mb),Fd=Bd("end"),ma=Bd("start");function Bd(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 Fb(e){const t=ma(e),n=Fd(e);if(t&&n)return{start:t,end:n}}function ws(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?kl(e.position):"start"in e||"end"in e?kl(e):"line"in e||"column"in e?jo(e):""}function jo(e){return Nl(e&&e.line)+":"+Nl(e&&e.column)}function kl(e){return jo(e&&e.start)+"-"+jo(e&&e.end)}function Nl(e){return e&&typeof e=="number"?e:1}class Ye extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let i="",o={},a=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?i=t:!o.cause&&t&&(a=!0,i=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const l=s.indexOf(":");l===-1?o.ruleId=s:(o.source=s.slice(0,l),o.ruleId=s.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){const l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=c?c.line:void 0,this.name=ws(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ye.prototype.file="";Ye.prototype.name="";Ye.prototype.reason="";Ye.prototype.message="";Ye.prototype.stack="";Ye.prototype.column=void 0;Ye.prototype.line=void 0;Ye.prototype.ancestors=void 0;Ye.prototype.cause=void 0;Ye.prototype.fatal=void 0;Ye.prototype.place=void 0;Ye.prototype.ruleId=void 0;Ye.prototype.source=void 0;const pa={}.hasOwnProperty,Bb=new Map,Ub=/[A-Z]/g,Vb=new Set(["table","tbody","thead","tfoot","tr"]),Wb=new Set(["td","th"]),Ud="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Hb(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=Xb(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=Zb(n,t.jsx,t.jsxs)}const i={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"?fa:zb,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=Vd(i,e,void 0);return o&&typeof o!="string"?o:i.create(e,i.Fragment,{children:o||void 0},void 0)}function Vd(e,t,n){if(t.type==="element")return qb(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Gb(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Jb(e,t,n);if(t.type==="mdxjsEsm")return Qb(e,t);if(t.type==="root")return Kb(e,t,n);if(t.type==="text")return Yb(e,t)}function qb(e,t,n){const s=e.schema;let i=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(i=fa,e.schema=i),e.ancestors.push(t);const o=Hd(e,t.tagName,!1),a=e0(e,t);let c=xa(e,t);return Vb.has(t.tagName)&&(c=c.filter(function(l){return typeof l=="string"?!Sb(l):!0})),Wd(e,a,o,t),ga(a,c),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function Gb(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)}Ts(e,t.position)}function Qb(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Ts(e,t.position)}function Jb(e,t,n){const s=e.schema;let i=s;t.name==="svg"&&s.space==="html"&&(i=fa,e.schema=i),e.ancestors.push(t);const o=t.name===null?e.Fragment:Hd(e,t.name,!0),a=t0(e,t),c=xa(e,t);return Wd(e,a,o,t),ga(a,c),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function Kb(e,t,n){const s={};return ga(s,xa(e,t)),e.create(t,e.Fragment,s,n)}function Yb(e,t){return t.value}function Wd(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function ga(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Zb(e,t,n){return s;function s(i,o,a,c){const d=Array.isArray(a.children)?n:t;return c?d(o,a,c):d(o,a)}}function Xb(e,t){return n;function n(s,i,o,a){const c=Array.isArray(o.children),l=ma(s);return t(i,o,a,c,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function e0(e,t){const n={};let s,i;for(i in t.properties)if(i!=="children"&&pa.call(t.properties,i)){const o=n0(e,i,t.properties[i]);if(o){const[a,c]=o;e.tableCellAlignToStyle&&a==="align"&&typeof c=="string"&&Wb.has(t.tagName)?s=c:n[a]=c}}if(s){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function t0(e,t){const n={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const a=o.expression;a.type;const c=a.properties[0];c.type,Object.assign(n,e.evaluater.evaluateExpression(c.argument))}else Ts(e,t.position);else{const i=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const c=s.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Ts(e,t.position);else o=s.value===null?!0:s.value;n[i]=o}return n}function xa(e,t){const n=[];let s=-1;const i=e.passKeys?new Map:Bb;for(;++s<t.children.length;){const o=t.children[s];let a;if(e.passKeys){const l=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(l){const d=i.get(l)||0;a=l+"-"+d,i.set(l,d+1)}}const c=Vd(e,o,a);c!==void 0&&n.push(c)}return n}function n0(e,t,n){const s=Ab(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?xb(n):Lb(n)),s.property==="style"){let i=typeof n=="object"?n:s0(e,String(n));return e.stylePropertyNameCase==="css"&&(i=r0(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&s.space?Cb[s.property]||s.property:s.attribute,n]}}function s0(e,t){try{return $b(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,i=new Ye("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=Ud+"#cannot-parse-style-attribute",i}}function Hd(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let o=-1,a;for(;++o<i.length;){const c=gl(i[o])?{type:"Identifier",name:i[o]}:{type:"Literal",value:i[o]};a=a?{type:"MemberExpression",object:a,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}s=a}else s=gl(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const i=s.value;return pa.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(s);Ts(e)}function Ts(e,t){const n=new Ye("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=Ud+"#cannot-handle-mdx-estrees-without-createevaluater",n}function r0(e){const t={};let n;for(n in e)pa.call(e,n)&&(t[i0(n)]=e[n]);return t}function i0(e){let t=e.replace(Ub,o0);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function o0(e){return"-"+e.toLowerCase()}const fi={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"]},a0={};function l0(e,t){const n=a0,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return qd(e,s,i)}function qd(e,t,n){if(c0(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 Cl(e.children,t,n)}return Array.isArray(e)?Cl(e,t,n):""}function Cl(e,t,n){const s=[];let i=-1;for(;++i<e.length;)s[i]=qd(e[i],t,n);return s.join("")}function c0(e){return!!(e&&typeof e=="object")}const El=document.createElement("i");function ba(e){const t="&"+e+";";El.innerHTML=t;const n=El.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function vt(e,t,n,s){const i=e.length;let o=0,a;if(t<0?t=-t>i?0:i+t:t=t>i?i: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);o<s.length;)a=s.slice(o,o+1e4),a.unshift(t,0),e.splice(...a),o+=1e4,t+=1e4}function dt(e,t){return e.length>0?(vt(e,e.length,0,t),e):t}const Tl={}.hasOwnProperty;function d0(e){const t={};let n=-1;for(;++n<e.length;)u0(t,e[n]);return t}function u0(e,t){let n;for(n in t){const i=(Tl.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let a;if(o)for(a in o){Tl.call(i,a)||(i[a]=[]);const c=o[a];h0(i[a],Array.isArray(c)?c:c?[c]:[])}}}function h0(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);vt(e,0,0,s)}function Gd(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 kn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const yt=Wt(/[A-Za-z]/),at=Wt(/[\dA-Za-z]/),f0=Wt(/[#-'*+\--9=?A-Z^-~]/);function ko(e){return e!==null&&(e<32||e===127)}const No=Wt(/\d/),m0=Wt(/[\dA-Fa-f]/),p0=Wt(/[!-/:-@[-`{-~]/);function de(e){return e!==null&&e<-2}function nt(e){return e!==null&&(e<0||e===32)}function Ee(e){return e===-2||e===-1||e===32}const g0=Wt(/\p{P}|\p{S}/u),x0=Wt(/\s/);function Wt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Rn(e){const t=[];let n=-1,s=0,i=0;for(;++n<e.length;){const o=e.charCodeAt(n);let a="";if(o===37&&at(e.charCodeAt(n+1))&&at(e.charCodeAt(n+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(a=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(n+1);o<56320&&c>56319&&c<57344?(a=String.fromCharCode(o,c),i=1):a="�"}else a=String.fromCharCode(o);a&&(t.push(e.slice(s,n),encodeURIComponent(a)),s=n+i+1,a=""),i&&(n+=i,i=0)}return t.join("")+e.slice(s)}function ze(e,t,n,s){const i=s?s-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(l){return Ee(l)?(e.enter(n),c(l)):t(l)}function c(l){return Ee(l)&&o++<i?(e.consume(l),c):(e.exit(n),t(l))}}const b0={tokenize:y0};function y0(e){const t=e.attempt(this.parser.constructs.contentInitial,s,i);let n;return t;function s(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),ze(e,t,"linePrefix")}function i(c){return e.enter("paragraph"),o(c)}function o(c){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,a(c)}function a(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return de(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),a)}}const w0={tokenize:v0},Al={tokenize:S0};function v0(e){const t=this,n=[];let s=0,i,o,a;return c;function c(S){if(s<n.length){const T=n[s];return t.containerState=T[1],e.attempt(T[0].continuation,l,d)(S)}return d(S)}function l(S){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();const T=t.events.length;let k=T,w;for(;k--;)if(t.events[k][0]==="exit"&&t.events[k][1].type==="chunkFlow"){w=t.events[k][1].end;break}b(s);let I=T;for(;I<t.events.length;)t.events[I][1].end={...w},I++;return vt(t.events,k+1,0,t.events.slice(T)),t.events.length=I,d(S)}return c(S)}function d(S){if(s===n.length){if(!i)return p(S);if(i.currentConstruct&&i.currentConstruct.concrete)return g(S);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Al,u,m)(S)}function u(S){return i&&v(),b(s),p(S)}function m(S){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,g(S)}function p(S){return t.containerState={},e.attempt(Al,h,g)(S)}function h(S){return s++,n.push([t.currentConstruct,t.containerState]),p(S)}function g(S){if(S===null){i&&v(),b(0),e.consume(S);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),y(S)}function y(S){if(S===null){x(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return de(S)?(e.consume(S),x(e.exit("chunkFlow")),s=0,t.interrupt=void 0,c):(e.consume(S),y)}function x(S,T){const k=t.sliceStream(S);if(T&&k.push(null),S.previous=o,o&&(o.next=S),o=S,i.defineSkip(S.start),i.write(k),t.parser.lazy[S.start.line]){let w=i.events.length;for(;w--;)if(i.events[w][1].start.offset<a&&(!i.events[w][1].end||i.events[w][1].end.offset>a))return;const I=t.events.length;let _=I,R,L;for(;_--;)if(t.events[_][0]==="exit"&&t.events[_][1].type==="chunkFlow"){if(R){L=t.events[_][1].end;break}R=!0}for(b(s),w=I;w<t.events.length;)t.events[w][1].end={...L},w++;vt(t.events,_+1,0,t.events.slice(I)),t.events.length=w}}function b(S){let T=n.length;for(;T-- >S;){const k=n[T];t.containerState=k[1],k[0].exit.call(t,e)}n.length=S}function v(){i.write([null]),o=void 0,i=void 0,t.containerState._closeFlow=void 0}}function S0(e,t,n){return ze(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Il(e){if(e===null||nt(e)||x0(e))return 1;if(g0(e))return 2}function ya(e,t,n){const s=[];let i=-1;for(;++i<e.length;){const o=e[i].resolveAll;o&&!s.includes(o)&&(t=o(t,n),s.push(o))}return t}const Co={name:"attention",resolveAll:j0,tokenize:k0};function j0(e,t){let n=-1,s,i,o,a,c,l,d,u;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;l=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 m={...e[s][1].end},p={...e[n][1].start};Pl(m,-l),Pl(p,l),a={type:l>1?"strongSequence":"emphasisSequence",start:m,end:{...e[s][1].end}},c={type:l>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},o={type:l>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...a.start},end:{...c.end}},e[s][1].end={...a.start},e[n][1].start={...c.end},d=[],e[s][1].end.offset-e[s][1].start.offset&&(d=dt(d,[["enter",e[s][1],t],["exit",e[s][1],t]])),d=dt(d,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",o,t]]),d=dt(d,ya(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),d=dt(d,[["exit",o,t],["enter",c,t],["exit",c,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,d=dt(d,[["enter",e[n][1],t],["exit",e[n][1],t]])):u=0,vt(e,s-1,n-s+3,d),n=s+d.length-u-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function k0(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,i=Il(s);let o;return a;function a(l){return o=l,e.enter("attentionSequence"),c(l)}function c(l){if(l===o)return e.consume(l),c;const d=e.exit("attentionSequence"),u=Il(l),m=!u||u===2&&i||n.includes(l),p=!i||i===2&&u||n.includes(s);return d._open=!!(o===42?m:m&&(i||!p)),d._close=!!(o===42?p:p&&(u||!m)),t(l)}}function Pl(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const N0={name:"autolink",tokenize:C0};function C0(e,t,n){let s=0;return i;function i(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(h){return yt(h)?(e.consume(h),a):h===64?n(h):d(h)}function a(h){return h===43||h===45||h===46||at(h)?(s=1,c(h)):d(h)}function c(h){return h===58?(e.consume(h),s=0,l):(h===43||h===45||h===46||at(h))&&s++<32?(e.consume(h),c):(s=0,d(h))}function l(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||ko(h)?n(h):(e.consume(h),l)}function d(h){return h===64?(e.consume(h),u):f0(h)?(e.consume(h),d):n(h)}function u(h){return at(h)?m(h):n(h)}function m(h){return h===46?(e.consume(h),s=0,u):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):p(h)}function p(h){if((h===45||at(h))&&s++<63){const g=h===45?p:m;return e.consume(h),g}return n(h)}}const Qr={partial:!0,tokenize:E0};function E0(e,t,n){return s;function s(o){return Ee(o)?ze(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||de(o)?t(o):n(o)}}const Qd={continuation:{tokenize:A0},exit:I0,name:"blockQuote",tokenize:T0};function T0(e,t,n){const s=this;return i;function i(a){if(a===62){const c=s.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),o}return n(a)}function o(a){return Ee(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function A0(e,t,n){const s=this;return i;function i(a){return Ee(a)?ze(e,o,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):o(a)}function o(a){return e.attempt(Qd,t,n)(a)}}function I0(e){e.exit("blockQuote")}const Jd={name:"characterEscape",tokenize:P0};function P0(e,t,n){return s;function s(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),i}function i(o){return p0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const Kd={name:"characterReference",tokenize:z0};function z0(e,t,n){const s=this;let i=0,o,a;return c;function c(m){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),l}function l(m){return m===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(m),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,a=at,u(m))}function d(m){return m===88||m===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(m),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,a=m0,u):(e.enter("characterReferenceValue"),o=7,a=No,u(m))}function u(m){if(m===59&&i){const p=e.exit("characterReferenceValue");return a===at&&!ba(s.sliceSerialize(p))?n(m):(e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(m)&&i++<o?(e.consume(m),u):n(m)}}const zl={partial:!0,tokenize:R0},Ll={concrete:!0,name:"codeFenced",tokenize:L0};function L0(e,t,n){const s=this,i={partial:!0,tokenize:k};let o=0,a=0,c;return l;function l(w){return d(w)}function d(w){const I=s.events[s.events.length-1];return o=I&&I[1].type==="linePrefix"?I[2].sliceSerialize(I[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),u(w)}function u(w){return w===c?(a++,e.consume(w),u):a<3?n(w):(e.exit("codeFencedFenceSequence"),Ee(w)?ze(e,m,"whitespace")(w):m(w))}function m(w){return w===null||de(w)?(e.exit("codeFencedFence"),s.interrupt?t(w):e.check(zl,y,T)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(w))}function p(w){return w===null||de(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),m(w)):Ee(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ze(e,h,"whitespace")(w)):w===96&&w===c?n(w):(e.consume(w),p)}function h(w){return w===null||de(w)?m(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||de(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),m(w)):w===96&&w===c?n(w):(e.consume(w),g)}function y(w){return e.attempt(i,T,x)(w)}function x(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&Ee(w)?ze(e,v,"linePrefix",o+1)(w):v(w)}function v(w){return w===null||de(w)?e.check(zl,y,T)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||de(w)?(e.exit("codeFlowValue"),v(w)):(e.consume(w),S)}function T(w){return e.exit("codeFenced"),t(w)}function k(w,I,_){let R=0;return L;function L(P){return w.enter("lineEnding"),w.consume(P),w.exit("lineEnding"),E}function E(P){return w.enter("codeFencedFence"),Ee(P)?ze(w,A,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):A(P)}function A(P){return P===c?(w.enter("codeFencedFenceSequence"),D(P)):_(P)}function D(P){return P===c?(R++,w.consume(P),D):R>=a?(w.exit("codeFencedFenceSequence"),Ee(P)?ze(w,F,"whitespace")(P):F(P)):_(P)}function F(P){return P===null||de(P)?(w.exit("codeFencedFence"),I(P)):_(P)}}}function R0(e,t,n){const s=this;return i;function i(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o)}function o(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}const mi={name:"codeIndented",tokenize:O0},_0={partial:!0,tokenize:D0};function O0(e,t,n){const s=this;return i;function i(d){return e.enter("codeIndented"),ze(e,o,"linePrefix",5)(d)}function o(d){const u=s.events[s.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(d):n(d)}function a(d){return d===null?l(d):de(d)?e.attempt(_0,a,l)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||de(d)?(e.exit("codeFlowValue"),a(d)):(e.consume(d),c)}function l(d){return e.exit("codeIndented"),t(d)}}function D0(e,t,n){const s=this;return i;function i(a){return s.parser.lazy[s.now().line]?n(a):de(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):ze(e,o,"linePrefix",5)(a)}function o(a){const c=s.events[s.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(a):de(a)?i(a):n(a)}}const M0={name:"codeText",previous:F0,resolve:$0,tokenize:B0};function $0(e){let t=e.length-4,n=3,s,i;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;)i===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(i=s):(s===t||e[s][1].type==="lineEnding")&&(e[i][1].type="codeTextData",s!==i+2&&(e[i][1].end=e[s-1][1].end,e.splice(i+2,s-i-2),t-=s-i-2,s=i+2),i=void 0);return e}function F0(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function B0(e,t,n){let s=0,i,o;return a;function a(m){return e.enter("codeText"),e.enter("codeTextSequence"),c(m)}function c(m){return m===96?(e.consume(m),s++,c):(e.exit("codeTextSequence"),l(m))}function l(m){return m===null?n(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),l):m===96?(o=e.enter("codeTextSequence"),i=0,u(m)):de(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),l):(e.enter("codeTextData"),d(m))}function d(m){return m===null||m===32||m===96||de(m)?(e.exit("codeTextData"),l(m)):(e.consume(m),d)}function u(m){return m===96?(e.consume(m),i++,u):i===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(m)):(o.type="codeTextData",d(m))}}class U0{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 i=n||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return s&&cs(this.left,s),o.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),cs(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),cs(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);cs(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);cs(this.left,n.reverse())}}}function cs(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 Yd(e){const t={};let n=-1,s,i,o,a,c,l,d;const u=new U0(e);for(;++n<u.length;){for(;n in t;)n=t[n];if(s=u.get(n),n&&s[1].type==="chunkFlow"&&u.get(n-1)[1].type==="listItemPrefix"&&(l=s[1]._tokenizer.events,o=0,o<l.length&&l[o][1].type==="lineEndingBlank"&&(o+=2),o<l.length&&l[o][1].type==="content"))for(;++o<l.length&&l[o][1].type!=="content";)l[o][1].type==="chunkText"&&(l[o][1]._isInFirstContentOfListItem=!0,o++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,V0(u,n)),n=t[n],d=!0);else if(s[1]._container){for(o=n,i=void 0;o--;)if(a=u.get(o),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),a[1].type="lineEnding",i=o);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;i&&(s[1].end={...u.get(i)[1].start},c=u.slice(i,n),c.unshift(s),u.splice(i,n-i+1,c))}}return vt(e,0,Number.POSITIVE_INFINITY,u.slice(0)),!d}function V0(e,t){const n=e.get(t)[1],s=e.get(t)[2];let i=t-1;const o=[];let a=n._tokenizer;a||(a=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const c=a.events,l=[],d={};let u,m,p=-1,h=n,g=0,y=0;const x=[y];for(;h;){for(;e.get(++i)[1]!==h;);o.push(i),h._tokenizer||(u=s.sliceStream(h),h.next||u.push(null),m&&a.defineSkip(h.start),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(u),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),m=h,h=h.next}for(h=n;++p<c.length;)c[p][0]==="exit"&&c[p-1][0]==="enter"&&c[p][1].type===c[p-1][1].type&&c[p][1].start.line!==c[p][1].end.line&&(y=p+1,x.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):x.pop(),p=x.length;p--;){const b=c.slice(x[p],x[p+1]),v=o.pop();l.push([v,v+b.length-1]),e.splice(v,2,b)}for(l.reverse(),p=-1;++p<l.length;)d[g+l[p][0]]=g+l[p][1],g+=l[p][1]-l[p][0]-1;return d}const W0={resolve:q0,tokenize:G0},H0={partial:!0,tokenize:Q0};function q0(e){return Yd(e),e}function G0(e,t){let n;return s;function s(c){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(c)}function i(c){return c===null?o(c):de(c)?e.check(H0,a,o)(c):(e.consume(c),i)}function o(c){return e.exit("chunkContent"),e.exit("content"),t(c)}function a(c){return e.consume(c),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function Q0(e,t,n){const s=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),ze(e,o,"linePrefix")}function o(a){if(a===null||de(a))return n(a);const c=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(a):e.interrupt(s.parser.constructs.flow,n,t)(a)}}function Zd(e,t,n,s,i,o,a,c,l){const d=l||Number.POSITIVE_INFINITY;let u=0;return m;function m(b){return b===60?(e.enter(s),e.enter(i),e.enter(o),e.consume(b),e.exit(o),p):b===null||b===32||b===41||ko(b)?n(b):(e.enter(s),e.enter(a),e.enter(c),e.enter("chunkString",{contentType:"string"}),y(b))}function p(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(i),e.exit(s),t):(e.enter(c),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(c),p(b)):b===null||b===60||de(b)?n(b):(e.consume(b),b===92?g:h)}function g(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function y(b){return!u&&(b===null||b===41||nt(b))?(e.exit("chunkString"),e.exit(c),e.exit(a),e.exit(s),t(b)):u<d&&b===40?(e.consume(b),u++,y):b===41?(e.consume(b),u--,y):b===null||b===32||b===40||ko(b)?n(b):(e.consume(b),b===92?x:y)}function x(b){return b===40||b===41||b===92?(e.consume(b),y):y(b)}}function Xd(e,t,n,s,i,o){const a=this;let c=0,l;return d;function d(h){return e.enter(s),e.enter(i),e.consume(h),e.exit(i),e.enter(o),u}function u(h){return c>999||h===null||h===91||h===93&&!l||h===94&&!c&&"_hiddenFootnoteSupport"in a.parser.constructs?n(h):h===93?(e.exit(o),e.enter(i),e.consume(h),e.exit(i),e.exit(s),t):de(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),m(h))}function m(h){return h===null||h===91||h===93||de(h)||c++>999?(e.exit("chunkString"),u(h)):(e.consume(h),l||(l=!Ee(h)),h===92?p:m)}function p(h){return h===91||h===92||h===93?(e.consume(h),c++,m):m(h)}}function eu(e,t,n,s,i,o){let a;return c;function c(p){return p===34||p===39||p===40?(e.enter(s),e.enter(i),e.consume(p),e.exit(i),a=p===40?41:p,l):n(p)}function l(p){return p===a?(e.enter(i),e.consume(p),e.exit(i),e.exit(s),t):(e.enter(o),d(p))}function d(p){return p===a?(e.exit(o),l(a)):p===null?n(p):de(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),ze(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(p))}function u(p){return p===a||p===null||de(p)?(e.exit("chunkString"),d(p)):(e.consume(p),p===92?m:u)}function m(p){return p===a||p===92?(e.consume(p),u):u(p)}}function vs(e,t){let n;return s;function s(i){return de(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,s):Ee(i)?ze(e,s,n?"linePrefix":"lineSuffix")(i):t(i)}}const J0={name:"definition",tokenize:Y0},K0={partial:!0,tokenize:Z0};function Y0(e,t,n){const s=this;let i;return o;function o(h){return e.enter("definition"),a(h)}function a(h){return Xd.call(s,e,c,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function c(h){return i=kn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):n(h)}function l(h){return nt(h)?vs(e,d)(h):d(h)}function d(h){return Zd(e,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function u(h){return e.attempt(K0,m,m)(h)}function m(h){return Ee(h)?ze(e,p,"whitespace")(h):p(h)}function p(h){return h===null||de(h)?(e.exit("definition"),s.parser.defined.push(i),t(h)):n(h)}}function Z0(e,t,n){return s;function s(c){return nt(c)?vs(e,i)(c):n(c)}function i(c){return eu(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Ee(c)?ze(e,a,"whitespace")(c):a(c)}function a(c){return c===null||de(c)?t(c):n(c)}}const X0={name:"hardBreakEscape",tokenize:ey};function ey(e,t,n){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),i}function i(o){return de(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const ty={name:"headingAtx",resolve:ny,tokenize:sy};function ny(e,t){let n=e.length-2,s=3,i,o;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&&(i={type:"atxHeadingText",start:e[s][1].start,end:e[n][1].end},o={type:"chunkText",start:e[s][1].start,end:e[n][1].end,contentType:"text"},vt(e,s,n-s+1,[["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t]])),e}function sy(e,t,n){let s=0;return i;function i(u){return e.enter("atxHeading"),o(u)}function o(u){return e.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&s++<6?(e.consume(u),a):u===null||nt(u)?(e.exit("atxHeadingSequence"),c(u)):n(u)}function c(u){return u===35?(e.enter("atxHeadingSequence"),l(u)):u===null||de(u)?(e.exit("atxHeading"),t(u)):Ee(u)?ze(e,c,"whitespace")(u):(e.enter("atxHeadingText"),d(u))}function l(u){return u===35?(e.consume(u),l):(e.exit("atxHeadingSequence"),c(u))}function d(u){return u===null||u===35||nt(u)?(e.exit("atxHeadingText"),c(u)):(e.consume(u),d)}}const ry=["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"],Rl=["pre","script","style","textarea"],iy={concrete:!0,name:"htmlFlow",resolveTo:ly,tokenize:cy},oy={partial:!0,tokenize:uy},ay={partial:!0,tokenize:dy};function ly(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 cy(e,t,n){const s=this;let i,o,a,c,l;return d;function d(C){return u(C)}function u(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),m}function m(C){return C===33?(e.consume(C),p):C===47?(e.consume(C),o=!0,y):C===63?(e.consume(C),i=3,s.interrupt?t:j):yt(C)?(e.consume(C),a=String.fromCharCode(C),x):n(C)}function p(C){return C===45?(e.consume(C),i=2,h):C===91?(e.consume(C),i=5,c=0,g):yt(C)?(e.consume(C),i=4,s.interrupt?t:j):n(C)}function h(C){return C===45?(e.consume(C),s.interrupt?t:j):n(C)}function g(C){const K="CDATA[";return C===K.charCodeAt(c++)?(e.consume(C),c===K.length?s.interrupt?t:A:g):n(C)}function y(C){return yt(C)?(e.consume(C),a=String.fromCharCode(C),x):n(C)}function x(C){if(C===null||C===47||C===62||nt(C)){const K=C===47,G=a.toLowerCase();return!K&&!o&&Rl.includes(G)?(i=1,s.interrupt?t(C):A(C)):ry.includes(a.toLowerCase())?(i=6,K?(e.consume(C),b):s.interrupt?t(C):A(C)):(i=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(C):o?v(C):S(C))}return C===45||at(C)?(e.consume(C),a+=String.fromCharCode(C),x):n(C)}function b(C){return C===62?(e.consume(C),s.interrupt?t:A):n(C)}function v(C){return Ee(C)?(e.consume(C),v):L(C)}function S(C){return C===47?(e.consume(C),L):C===58||C===95||yt(C)?(e.consume(C),T):Ee(C)?(e.consume(C),S):L(C)}function T(C){return C===45||C===46||C===58||C===95||at(C)?(e.consume(C),T):k(C)}function k(C){return C===61?(e.consume(C),w):Ee(C)?(e.consume(C),k):S(C)}function w(C){return C===null||C===60||C===61||C===62||C===96?n(C):C===34||C===39?(e.consume(C),l=C,I):Ee(C)?(e.consume(C),w):_(C)}function I(C){return C===l?(e.consume(C),l=null,R):C===null||de(C)?n(C):(e.consume(C),I)}function _(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||nt(C)?k(C):(e.consume(C),_)}function R(C){return C===47||C===62||Ee(C)?S(C):n(C)}function L(C){return C===62?(e.consume(C),E):n(C)}function E(C){return C===null||de(C)?A(C):Ee(C)?(e.consume(C),E):n(C)}function A(C){return C===45&&i===2?(e.consume(C),$):C===60&&i===1?(e.consume(C),V):C===62&&i===4?(e.consume(C),B):C===63&&i===3?(e.consume(C),j):C===93&&i===5?(e.consume(C),U):de(C)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(oy,q,D)(C)):C===null||de(C)?(e.exit("htmlFlowData"),D(C)):(e.consume(C),A)}function D(C){return e.check(ay,F,q)(C)}function F(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),P}function P(C){return C===null||de(C)?D(C):(e.enter("htmlFlowData"),A(C))}function $(C){return C===45?(e.consume(C),j):A(C)}function V(C){return C===47?(e.consume(C),a="",z):A(C)}function z(C){if(C===62){const K=a.toLowerCase();return Rl.includes(K)?(e.consume(C),B):A(C)}return yt(C)&&a.length<8?(e.consume(C),a+=String.fromCharCode(C),z):A(C)}function U(C){return C===93?(e.consume(C),j):A(C)}function j(C){return C===62?(e.consume(C),B):C===45&&i===2?(e.consume(C),j):A(C)}function B(C){return C===null||de(C)?(e.exit("htmlFlowData"),q(C)):(e.consume(C),B)}function q(C){return e.exit("htmlFlow"),t(C)}}function dy(e,t,n){const s=this;return i;function i(a){return de(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o):n(a)}function o(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}function uy(e,t,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qr,t,n)}}const hy={name:"htmlText",tokenize:fy};function fy(e,t,n){const s=this;let i,o,a;return c;function c(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),l}function l(j){return j===33?(e.consume(j),d):j===47?(e.consume(j),k):j===63?(e.consume(j),S):yt(j)?(e.consume(j),_):n(j)}function d(j){return j===45?(e.consume(j),u):j===91?(e.consume(j),o=0,g):yt(j)?(e.consume(j),v):n(j)}function u(j){return j===45?(e.consume(j),h):n(j)}function m(j){return j===null?n(j):j===45?(e.consume(j),p):de(j)?(a=m,V(j)):(e.consume(j),m)}function p(j){return j===45?(e.consume(j),h):m(j)}function h(j){return j===62?$(j):j===45?p(j):m(j)}function g(j){const B="CDATA[";return j===B.charCodeAt(o++)?(e.consume(j),o===B.length?y:g):n(j)}function y(j){return j===null?n(j):j===93?(e.consume(j),x):de(j)?(a=y,V(j)):(e.consume(j),y)}function x(j){return j===93?(e.consume(j),b):y(j)}function b(j){return j===62?$(j):j===93?(e.consume(j),b):y(j)}function v(j){return j===null||j===62?$(j):de(j)?(a=v,V(j)):(e.consume(j),v)}function S(j){return j===null?n(j):j===63?(e.consume(j),T):de(j)?(a=S,V(j)):(e.consume(j),S)}function T(j){return j===62?$(j):S(j)}function k(j){return yt(j)?(e.consume(j),w):n(j)}function w(j){return j===45||at(j)?(e.consume(j),w):I(j)}function I(j){return de(j)?(a=I,V(j)):Ee(j)?(e.consume(j),I):$(j)}function _(j){return j===45||at(j)?(e.consume(j),_):j===47||j===62||nt(j)?R(j):n(j)}function R(j){return j===47?(e.consume(j),$):j===58||j===95||yt(j)?(e.consume(j),L):de(j)?(a=R,V(j)):Ee(j)?(e.consume(j),R):$(j)}function L(j){return j===45||j===46||j===58||j===95||at(j)?(e.consume(j),L):E(j)}function E(j){return j===61?(e.consume(j),A):de(j)?(a=E,V(j)):Ee(j)?(e.consume(j),E):R(j)}function A(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),i=j,D):de(j)?(a=A,V(j)):Ee(j)?(e.consume(j),A):(e.consume(j),F)}function D(j){return j===i?(e.consume(j),i=void 0,P):j===null?n(j):de(j)?(a=D,V(j)):(e.consume(j),D)}function F(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||nt(j)?R(j):(e.consume(j),F)}function P(j){return j===47||j===62||nt(j)?R(j):n(j)}function $(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function V(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),z}function z(j){return Ee(j)?ze(e,U,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):U(j)}function U(j){return e.enter("htmlTextData"),a(j)}}const wa={name:"labelEnd",resolveAll:xy,resolveTo:by,tokenize:yy},my={tokenize:wy},py={tokenize:vy},gy={tokenize:Sy};function xy(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 i=s.type==="labelImage"?4:2;s.type="data",t+=i}}return e.length!==n.length&&vt(e,0,e.length,n),e}function by(e,t){let n=e.length,s=0,i,o,a,c;for(;n--;)if(i=e[n][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=n,i.type!=="labelLink")){s=2;break}}else i.type==="labelEnd"&&(a=n);const l={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[a][1].end}},u={type:"labelText",start:{...e[o+s+2][1].end},end:{...e[a-2][1].start}};return c=[["enter",l,t],["enter",d,t]],c=dt(c,e.slice(o+1,o+s+3)),c=dt(c,[["enter",u,t]]),c=dt(c,ya(t.parser.constructs.insideSpan.null,e.slice(o+s+4,a-3),t)),c=dt(c,[["exit",u,t],e[a-2],e[a-1],["exit",d,t]]),c=dt(c,e.slice(a+1)),c=dt(c,[["exit",l,t]]),vt(e,o,e.length,c),e}function yy(e,t,n){const s=this;let i=s.events.length,o,a;for(;i--;)if((s.events[i][1].type==="labelImage"||s.events[i][1].type==="labelLink")&&!s.events[i][1]._balanced){o=s.events[i][1];break}return c;function c(p){return o?o._inactive?m(p):(a=s.parser.defined.includes(kn(s.sliceSerialize({start:o.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(p),e.exit("labelMarker"),e.exit("labelEnd"),l):n(p)}function l(p){return p===40?e.attempt(my,u,a?u:m)(p):p===91?e.attempt(py,u,a?d:m)(p):a?u(p):m(p)}function d(p){return e.attempt(gy,u,m)(p)}function u(p){return t(p)}function m(p){return o._balanced=!0,n(p)}}function wy(e,t,n){return s;function s(m){return e.enter("resource"),e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),i}function i(m){return nt(m)?vs(e,o)(m):o(m)}function o(m){return m===41?u(m):Zd(e,a,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(m)}function a(m){return nt(m)?vs(e,l)(m):u(m)}function c(m){return n(m)}function l(m){return m===34||m===39||m===40?eu(e,d,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(m):u(m)}function d(m){return nt(m)?vs(e,u)(m):u(m)}function u(m){return m===41?(e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),e.exit("resource"),t):n(m)}}function vy(e,t,n){const s=this;return i;function i(c){return Xd.call(s,e,o,a,"reference","referenceMarker","referenceString")(c)}function o(c){return s.parser.defined.includes(kn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(c):n(c)}function a(c){return n(c)}}function Sy(e,t,n){return s;function s(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),i}function i(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),t):n(o)}}const jy={name:"labelStartImage",resolveAll:wa.resolveAll,tokenize:ky};function ky(e,t,n){const s=this;return i;function i(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),a):n(c)}function a(c){return c===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(c):t(c)}}const Ny={name:"labelStartLink",resolveAll:wa.resolveAll,tokenize:Cy};function Cy(e,t,n){const s=this;return i;function i(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),o}function o(a){return a===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(a):t(a)}}const pi={name:"lineEnding",tokenize:Ey};function Ey(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ze(e,t,"linePrefix")}}const dr={name:"thematicBreak",tokenize:Ty};function Ty(e,t,n){let s=0,i;return o;function o(d){return e.enter("thematicBreak"),a(d)}function a(d){return i=d,c(d)}function c(d){return d===i?(e.enter("thematicBreakSequence"),l(d)):s>=3&&(d===null||de(d))?(e.exit("thematicBreak"),t(d)):n(d)}function l(d){return d===i?(e.consume(d),s++,l):(e.exit("thematicBreakSequence"),Ee(d)?ze(e,c,"whitespace")(d):c(d))}}const tt={continuation:{tokenize:zy},exit:Ry,name:"list",tokenize:Py},Ay={partial:!0,tokenize:_y},Iy={partial:!0,tokenize:Ly};function Py(e,t,n){const s=this,i=s.events[s.events.length-1];let o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return c;function c(h){const g=s.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!s.containerState.marker||h===s.containerState.marker:No(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(dr,n,d)(h):d(h);if(!s.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return n(h)}function l(h){return No(h)&&++a<10?(e.consume(h),l):(!s.interrupt||a<2)&&(s.containerState.marker?h===s.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),d(h)):n(h)}function d(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||h,e.check(Qr,s.interrupt?n:u,e.attempt(Ay,p,m))}function u(h){return s.containerState.initialBlankLine=!0,o++,p(h)}function m(h){return Ee(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),p):n(h)}function p(h){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function zy(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Qr,i,o);function i(c){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,ze(e,t,"listItemIndent",s.containerState.size+1)(c)}function o(c){return s.containerState.furtherBlankLines||!Ee(c)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,a(c)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Iy,t,a)(c))}function a(c){return s.containerState._closeFlow=!0,s.interrupt=void 0,ze(e,e.attempt(tt,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function Ly(e,t,n){const s=this;return ze(e,i,"listItemIndent",s.containerState.size+1);function i(o){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(o):n(o)}}function Ry(e){e.exit(this.containerState.type)}function _y(e,t,n){const s=this;return ze(e,i,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){const a=s.events[s.events.length-1];return!Ee(o)&&a&&a[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const _l={name:"setextUnderline",resolveTo:Oy,tokenize:Dy};function Oy(e,t){let n=e.length,s,i,o;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){s=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!o&&e[n][1].type==="definition"&&(o=n);const a={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",o?(e.splice(i,0,["enter",a,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=a,e.push(["exit",a,t]),e}function Dy(e,t,n){const s=this;let i;return o;function o(d){let u=s.events.length,m;for(;u--;)if(s.events[u][1].type!=="lineEnding"&&s.events[u][1].type!=="linePrefix"&&s.events[u][1].type!=="content"){m=s.events[u][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||m)?(e.enter("setextHeadingLine"),i=d,a(d)):n(d)}function a(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===i?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Ee(d)?ze(e,l,"lineSuffix")(d):l(d))}function l(d){return d===null||de(d)?(e.exit("setextHeadingLine"),t(d)):n(d)}}const My={tokenize:$y};function $y(e){const t=this,n=e.attempt(Qr,s,e.attempt(this.parser.constructs.flowInitial,i,ze(e,e.attempt(this.parser.constructs.flow,i,e.attempt(W0,i)),"linePrefix")));return n;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Fy={resolveAll:nu()},By=tu("string"),Uy=tu("text");function tu(e){return{resolveAll:nu(e==="text"?Vy:void 0),tokenize:t};function t(n){const s=this,i=this.parser.constructs[e],o=n.attempt(i,a,c);return a;function a(u){return d(u)?o(u):c(u)}function c(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),l}function l(u){return d(u)?(n.exit("data"),o(u)):(n.consume(u),l)}function d(u){if(u===null)return!0;const m=i[u];let p=-1;if(m)for(;++p<m.length;){const h=m[p];if(!h.previous||h.previous.call(s,s.previous))return!0}return!1}}}function nu(e){return t;function t(n,s){let i=-1,o;for(;++i<=n.length;)o===void 0?n[i]&&n[i][1].type==="data"&&(o=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==o+2&&(n[o][1].end=n[i-1][1].end,n.splice(o+2,i-o-2),i=o+2),o=void 0);return e?e(n,s):n}}function Vy(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],i=t.sliceStream(s);let o=i.length,a=-1,c=0,l;for(;o--;){const d=i[o];if(typeof d=="string"){for(a=d.length;d.charCodeAt(a-1)===32;)c++,a--;if(a)break;a=-1}else if(d===-2)l=!0,c++;else if(d!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const d={type:n===e.length||l||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:s.start._bufferIndex+a,_index:s.start._index+o,line:s.end.line,column:s.end.column-c,offset:s.end.offset-c},end:{...s.end}};s.end={...d.start},s.start.offset===s.end.offset?Object.assign(s,d):(e.splice(n,0,["enter",d,t],["exit",d,t]),n+=2)}n++}return e}const Wy={42:tt,43:tt,45:tt,48:tt,49:tt,50:tt,51:tt,52:tt,53:tt,54:tt,55:tt,56:tt,57:tt,62:Qd},Hy={91:J0},qy={[-2]:mi,[-1]:mi,32:mi},Gy={35:ty,42:dr,45:[_l,dr],60:iy,61:_l,95:dr,96:Ll,126:Ll},Qy={38:Kd,92:Jd},Jy={[-5]:pi,[-4]:pi,[-3]:pi,33:jy,38:Kd,42:Co,60:[N0,hy],91:Ny,92:[X0,Jd],93:wa,95:Co,96:M0},Ky={null:[Co,Fy]},Yy={null:[42,95]},Zy={null:[]},Xy=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Yy,contentInitial:Hy,disable:Zy,document:Wy,flow:Gy,flowInitial:qy,insideSpan:Ky,string:Qy,text:Jy},Symbol.toStringTag,{value:"Module"}));function ew(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 i={},o=[];let a=[],c=[];const l={attempt:I(k),check:I(w),consume:v,enter:S,exit:T,interrupt:I(w,{interrupt:!0})},d={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:e,previous:null,sliceSerialize:p,sliceStream:h,write:m};let u=t.tokenize.call(d,l);return t.resolveAll&&o.push(t),d;function m(E){return a=dt(a,E),x(),a[a.length-1]!==null?[]:(_(t,0),d.events=ya(o,d.events,d),d.events)}function p(E,A){return nw(h(E),A)}function h(E){return tw(a,E)}function g(){const{_bufferIndex:E,_index:A,line:D,column:F,offset:P}=s;return{_bufferIndex:E,_index:A,line:D,column:F,offset:P}}function y(E){i[E.line]=E.column,L()}function x(){let E;for(;s._index<a.length;){const A=a[s._index];if(typeof A=="string")for(E=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===E&&s._bufferIndex<A.length;)b(A.charCodeAt(s._bufferIndex));else b(A)}}function b(E){u=u(E)}function v(E){de(E)?(s.line++,s.column=1,s.offset+=E===-3?2:1,L()):E!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===a[s._index].length&&(s._bufferIndex=-1,s._index++)),d.previous=E}function S(E,A){const D=A||{};return D.type=E,D.start=g(),d.events.push(["enter",D,d]),c.push(D),D}function T(E){const A=c.pop();return A.end=g(),d.events.push(["exit",A,d]),A}function k(E,A){_(E,A.from)}function w(E,A){A.restore()}function I(E,A){return D;function D(F,P,$){let V,z,U,j;return Array.isArray(F)?q(F):"tokenize"in F?q([F]):B(F);function B(Q){return ee;function ee(ue){const we=ue!==null&&Q[ue],X=ue!==null&&Q.null,pe=[...Array.isArray(we)?we:we?[we]:[],...Array.isArray(X)?X:X?[X]:[]];return q(pe)(ue)}}function q(Q){return V=Q,z=0,Q.length===0?$:C(Q[z])}function C(Q){return ee;function ee(ue){return j=R(),U=Q,Q.partial||(d.currentConstruct=Q),Q.name&&d.parser.constructs.disable.null.includes(Q.name)?G():Q.tokenize.call(A?Object.assign(Object.create(d),A):d,l,K,G)(ue)}}function K(Q){return E(U,j),P}function G(Q){return j.restore(),++z<V.length?C(V[z]):$}}}function _(E,A){E.resolveAll&&!o.includes(E)&&o.push(E),E.resolve&&vt(d.events,A,d.events.length-A,E.resolve(d.events.slice(A),d)),E.resolveTo&&(d.events=E.resolveTo(d.events,d))}function R(){const E=g(),A=d.previous,D=d.currentConstruct,F=d.events.length,P=Array.from(c);return{from:F,restore:$};function $(){s=E,d.previous=A,d.currentConstruct=D,d.events.length=F,c=P,L()}}function L(){s.line in i&&s.column<2&&(s.column=i[s.line],s.offset+=i[s.line]-1)}}function tw(e,t){const n=t.start._index,s=t.start._bufferIndex,i=t.end._index,o=t.end._bufferIndex;let a;if(n===i)a=[e[n].slice(s,o)];else{if(a=e.slice(n,i),s>-1){const c=a[0];typeof c=="string"?a[0]=c.slice(s):a.shift()}o>0&&a.push(e[i].slice(0,o))}return a}function nw(e,t){let n=-1;const s=[];let i;for(;++n<e.length;){const o=e[n];let a;if(typeof o=="string")a=o;else switch(o){case-5:{a="\r";break}case-4:{a=`
4
+ `;break}case-3:{a=`\r
5
+ `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&i)continue;a=" ";break}default:a=String.fromCharCode(o)}i=o===-2,s.push(a)}return s.join("")}function sw(e){const s={constructs:d0([Xy,...(e||{}).extensions||[]]),content:i(b0),defined:[],document:i(w0),flow:i(My),lazy:{},string:i(By),text:i(Uy)};return s;function i(o){return a;function a(c){return ew(s,o,c)}}}function rw(e){for(;!Yd(e););return e}const Ol=/[\0\t\n\r]/g;function iw(){let e=1,t="",n=!0,s;return i;function i(o,a,c){const l=[];let d,u,m,p,h;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),m=0,t="",n&&(o.charCodeAt(0)===65279&&m++,n=void 0);m<o.length;){if(Ol.lastIndex=m,d=Ol.exec(o),p=d&&d.index!==void 0?d.index:o.length,h=o.charCodeAt(p),!d){t=o.slice(m);break}if(h===10&&m===p&&s)l.push(-3),s=void 0;else switch(s&&(l.push(-5),s=void 0),m<p&&(l.push(o.slice(m,p)),e+=p-m),h){case 0:{l.push(65533),e++;break}case 9:{for(u=Math.ceil(e/4)*4,l.push(-2);e++<u;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:s=!0,e=1}m=p+1}return c&&(s&&l.push(-5),t&&l.push(t),l.push(null)),l}}const ow=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function aw(e){return e.replace(ow,lw)}function lw(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),o=i===120||i===88;return Gd(n.slice(o?2:1),o?16:10)}return ba(n)||e}const su={}.hasOwnProperty;function cw(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),dw(n)(rw(sw(n).document().write(iw()(e,t,!0))))}function dw(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(oe),autolinkProtocol:R,autolinkEmail:R,atxHeading:o(Y),blockQuote:o(X),characterEscape:R,characterReference:R,codeFenced:o(pe),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(pe,a),codeText:o(ke,a),codeTextData:R,data:R,codeFlowValue:R,definition:o(je),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(M),hardBreakEscape:o(te),hardBreakTrailing:o(te),htmlFlow:o(ne,a),htmlFlowData:R,htmlText:o(ne,a),htmlTextData:R,image:o(ie),label:a,link:o(oe),listItem:o(le),listItemValue:p,listOrdered:o(be,m),listUnordered:o(be),paragraph:o(Ne),reference:C,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Y),strong:o(Te),thematicBreak:o(se)},exit:{atxHeading:l(),atxHeadingSequence:k,autolink:l(),autolinkEmail:we,autolinkProtocol:ue,blockQuote:l(),characterEscapeValue:L,characterReferenceMarkerHexadecimal:G,characterReferenceMarkerNumeric:G,characterReferenceValue:Q,characterReference:ee,codeFenced:l(x),codeFencedFence:y,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:L,codeIndented:l(b),codeText:l(P),codeTextData:L,data:L,definition:l(),definitionDestinationString:T,definitionLabelString:v,definitionTitleString:S,emphasis:l(),hardBreakEscape:l(A),hardBreakTrailing:l(A),htmlFlow:l(D),htmlFlowData:L,htmlText:l(F),htmlTextData:L,image:l(V),label:U,labelText:z,lineEnding:E,link:l($),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:K,resourceDestinationString:j,resourceTitleString:B,resource:q,setextHeading:l(_),setextHeadingLineSequence:I,setextHeadingText:w,strong:l(),thematicBreak:l()}};ru(t,(e||{}).mdastExtensions||[]);const n={};return s;function s(N){let O={type:"root",children:[]};const W={stack:[O],tokenStack:[],config:t,enter:c,exit:d,buffer:a,resume:u,data:n},H=[];let Z=-1;for(;++Z<N.length;)if(N[Z][1].type==="listOrdered"||N[Z][1].type==="listUnordered")if(N[Z][0]==="enter")H.push(Z);else{const he=H.pop();Z=i(N,he,Z)}for(Z=-1;++Z<N.length;){const he=t[N[Z][0]];su.call(he,N[Z][1].type)&&he[N[Z][1].type].call(Object.assign({sliceSerialize:N[Z][2].sliceSerialize},W),N[Z][1])}if(W.tokenStack.length>0){const he=W.tokenStack[W.tokenStack.length-1];(he[1]||Dl).call(W,void 0,he[0])}for(O.position={start:_t(N.length>0?N[0][1].start:{line:1,column:1,offset:0}),end:_t(N.length>0?N[N.length-2][1].end:{line:1,column:1,offset:0})},Z=-1;++Z<t.transforms.length;)O=t.transforms[Z](O)||O;return O}function i(N,O,W){let H=O-1,Z=-1,he=!1,fe,xe,re,Be;for(;++H<=W;){const Ae=N[H];switch(Ae[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ae[0]==="enter"?Z++:Z--,Be=void 0;break}case"lineEndingBlank":{Ae[0]==="enter"&&(fe&&!Be&&!Z&&!re&&(re=H),Be=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Be=void 0}if(!Z&&Ae[0]==="enter"&&Ae[1].type==="listItemPrefix"||Z===-1&&Ae[0]==="exit"&&(Ae[1].type==="listUnordered"||Ae[1].type==="listOrdered")){if(fe){let Me=H;for(xe=void 0;Me--;){const Fe=N[Me];if(Fe[1].type==="lineEnding"||Fe[1].type==="lineEndingBlank"){if(Fe[0]==="exit")continue;xe&&(N[xe][1].type="lineEndingBlank",he=!0),Fe[1].type="lineEnding",xe=Me}else if(!(Fe[1].type==="linePrefix"||Fe[1].type==="blockQuotePrefix"||Fe[1].type==="blockQuotePrefixWhitespace"||Fe[1].type==="blockQuoteMarker"||Fe[1].type==="listItemIndent"))break}re&&(!xe||re<xe)&&(fe._spread=!0),fe.end=Object.assign({},xe?N[xe][1].start:Ae[1].end),N.splice(xe||H,0,["exit",fe,Ae[2]]),H++,W++}if(Ae[1].type==="listItemPrefix"){const Me={type:"listItem",_spread:!1,start:Object.assign({},Ae[1].start),end:void 0};fe=Me,N.splice(H,0,["enter",Me,Ae[2]]),H++,W++,re=void 0,Be=!0}}}return N[O][1]._spread=he,W}function o(N,O){return W;function W(H){c.call(this,N(H),H),O&&O.call(this,H)}}function a(){this.stack.push({type:"fragment",children:[]})}function c(N,O,W){this.stack[this.stack.length-1].children.push(N),this.stack.push(N),this.tokenStack.push([O,W||void 0]),N.position={start:_t(O.start),end:void 0}}function l(N){return O;function O(W){N&&N.call(this,W),d.call(this,W)}}function d(N,O){const W=this.stack.pop(),H=this.tokenStack.pop();if(H)H[0].type!==N.type&&(O?O.call(this,N,H[0]):(H[1]||Dl).call(this,N,H[0]));else throw new Error("Cannot close `"+N.type+"` ("+ws({start:N.start,end:N.end})+"): it’s not open");W.position.end=_t(N.end)}function u(){return l0(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function p(N){if(this.data.expectingFirstListItemValue){const O=this.stack[this.stack.length-2];O.start=Number.parseInt(this.sliceSerialize(N),10),this.data.expectingFirstListItemValue=void 0}}function h(){const N=this.resume(),O=this.stack[this.stack.length-1];O.lang=N}function g(){const N=this.resume(),O=this.stack[this.stack.length-1];O.meta=N}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const N=this.resume(),O=this.stack[this.stack.length-1];O.value=N.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const N=this.resume(),O=this.stack[this.stack.length-1];O.value=N.replace(/(\r?\n|\r)$/g,"")}function v(N){const O=this.resume(),W=this.stack[this.stack.length-1];W.label=O,W.identifier=kn(this.sliceSerialize(N)).toLowerCase()}function S(){const N=this.resume(),O=this.stack[this.stack.length-1];O.title=N}function T(){const N=this.resume(),O=this.stack[this.stack.length-1];O.url=N}function k(N){const O=this.stack[this.stack.length-1];if(!O.depth){const W=this.sliceSerialize(N).length;O.depth=W}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function I(N){const O=this.stack[this.stack.length-1];O.depth=this.sliceSerialize(N).codePointAt(0)===61?1:2}function _(){this.data.setextHeadingSlurpLineEnding=void 0}function R(N){const W=this.stack[this.stack.length-1].children;let H=W[W.length-1];(!H||H.type!=="text")&&(H=Je(),H.position={start:_t(N.start),end:void 0},W.push(H)),this.stack.push(H)}function L(N){const O=this.stack.pop();O.value+=this.sliceSerialize(N),O.position.end=_t(N.end)}function E(N){const O=this.stack[this.stack.length-1];if(this.data.atHardBreak){const W=O.children[O.children.length-1];W.position.end=_t(N.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(O.type)&&(R.call(this,N),L.call(this,N))}function A(){this.data.atHardBreak=!0}function D(){const N=this.resume(),O=this.stack[this.stack.length-1];O.value=N}function F(){const N=this.resume(),O=this.stack[this.stack.length-1];O.value=N}function P(){const N=this.resume(),O=this.stack[this.stack.length-1];O.value=N}function $(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=O,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function V(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=O,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function z(N){const O=this.sliceSerialize(N),W=this.stack[this.stack.length-2];W.label=aw(O),W.identifier=kn(O).toLowerCase()}function U(){const N=this.stack[this.stack.length-1],O=this.resume(),W=this.stack[this.stack.length-1];if(this.data.inReference=!0,W.type==="link"){const H=N.children;W.children=H}else W.alt=O}function j(){const N=this.resume(),O=this.stack[this.stack.length-1];O.url=N}function B(){const N=this.resume(),O=this.stack[this.stack.length-1];O.title=N}function q(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function K(N){const O=this.resume(),W=this.stack[this.stack.length-1];W.label=O,W.identifier=kn(this.sliceSerialize(N)).toLowerCase(),this.data.referenceType="full"}function G(N){this.data.characterReferenceType=N.type}function Q(N){const O=this.sliceSerialize(N),W=this.data.characterReferenceType;let H;W?(H=Gd(O,W==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):H=ba(O);const Z=this.stack[this.stack.length-1];Z.value+=H}function ee(N){const O=this.stack.pop();O.position.end=_t(N.end)}function ue(N){L.call(this,N);const O=this.stack[this.stack.length-1];O.url=this.sliceSerialize(N)}function we(N){L.call(this,N);const O=this.stack[this.stack.length-1];O.url="mailto:"+this.sliceSerialize(N)}function X(){return{type:"blockquote",children:[]}}function pe(){return{type:"code",lang:null,meta:null,value:""}}function ke(){return{type:"inlineCode",value:""}}function je(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function M(){return{type:"emphasis",children:[]}}function Y(){return{type:"heading",depth:0,children:[]}}function te(){return{type:"break"}}function ne(){return{type:"html",value:""}}function ie(){return{type:"image",title:null,url:"",alt:null}}function oe(){return{type:"link",title:null,url:"",children:[]}}function be(N){return{type:"list",ordered:N.type==="listOrdered",start:null,spread:N._spread,children:[]}}function le(N){return{type:"listItem",spread:N._spread,checked:null,children:[]}}function Ne(){return{type:"paragraph",children:[]}}function Te(){return{type:"strong",children:[]}}function Je(){return{type:"text",value:""}}function se(){return{type:"thematicBreak"}}}function _t(e){return{line:e.line,column:e.column,offset:e.offset}}function ru(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?ru(e,s):uw(e,s)}}function uw(e,t){let n;for(n in t)if(su.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 Dl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+ws({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+ws({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+ws({start:t.start,end:t.end})+") is still open")}function hw(e){const t=this;t.parser=n;function n(s){return cw(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function fw(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 mw(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
6
+ `}]}function pw(e,t){const n=t.value?t.value+`
7
+ `:"",s={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(s.className=["language-"+i[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function gw(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function xw(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function bw(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),i=Rn(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let a,c=e.footnoteCounts.get(s);c===void 0?(c=0,e.footnoteOrder.push(s),a=e.footnoteOrder.length):a=o+1,c+=1,e.footnoteCounts.set(s,c);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,l);const d={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,d),e.applyData(t,d)}function yw(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 ww(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function iu(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 i=e.all(t),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&a.type==="text"?a.value+=s:i.push({type:"text",value:s}),i}function vw(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return iu(e,t);const i={src:Rn(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(i.title=s.title);const o={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,o),e.applyData(t,o)}function Sw(e,t){const n={src:Rn(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 jw(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 kw(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return iu(e,t);const i={href:Rn(s.url||"")};s.title!==null&&s.title!==void 0&&(i.title=s.title);const o={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function Nw(e,t){const n={href:Rn(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 Cw(e,t,n){const s=e.all(t),i=n?Ew(n):ou(t),o={},a=[];if(typeof t.checked=="boolean"){const u=s[0];let m;u&&u.type==="element"&&u.tagName==="p"?m=u:(m={type:"element",tagName:"p",properties:{},children:[]},s.unshift(m)),m.children.length>0&&m.children.unshift({type:"text",value:" "}),m.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<s.length;){const u=s[c];(i||c!==0||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
8
+ `}),u.type==="element"&&u.tagName==="p"&&!i?a.push(...u.children):a.push(u)}const l=s[s.length-1];l&&(i||l.type!=="element"||l.tagName!=="p")&&a.push({type:"text",value:`
9
+ `});const d={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,d),e.applyData(t,d)}function Ew(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=ou(n[s])}return t}function ou(e){const t=e.spread;return t??e.children.length>1}function Tw(e,t){const n={},s=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i<s.length;){const a=s[i];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 o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(s,!0)};return e.patch(t,o),e.applyData(t,o)}function Aw(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Iw(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Pw(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function zw(e,t){const n=e.all(t),s=n.shift(),i=[];if(s){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([s],!0)};e.patch(t.children[0],a),i.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},c=ma(t.children[1]),l=Fd(t.children[t.children.length-1]);c&&l&&(a.position={start:c,end:l}),i.push(a)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function Lw(e,t,n){const s=n?n.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,c=a?a.length:t.children.length;let l=-1;const d=[];for(;++l<c;){const m=t.children[l],p={},h=a?a[l]:void 0;h&&(p.align=h);let g={type:"element",tagName:o,properties:p,children:[]};m&&(g.children=e.all(m),e.patch(m,g),g=e.applyData(m,g)),d.push(g)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(t,u),e.applyData(t,u)}function Rw(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Ml=9,$l=32;function _w(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),i=0;const o=[];for(;s;)o.push(Fl(t.slice(i,s.index),i>0,!0),s[0]),i=s.index+s[0].length,s=n.exec(t);return o.push(Fl(t.slice(i),i>0,!1)),o.join("")}function Fl(e,t,n){let s=0,i=e.length;if(t){let o=e.codePointAt(s);for(;o===Ml||o===$l;)s++,o=e.codePointAt(s)}if(n){let o=e.codePointAt(i-1);for(;o===Ml||o===$l;)i--,o=e.codePointAt(i-1)}return i>s?e.slice(s,i):""}function Ow(e,t){const n={type:"text",value:_w(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Dw(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Mw={blockquote:fw,break:mw,code:pw,delete:gw,emphasis:xw,footnoteReference:bw,heading:yw,html:ww,imageReference:vw,image:Sw,inlineCode:jw,linkReference:kw,link:Nw,listItem:Cw,list:Tw,paragraph:Aw,root:Iw,strong:Pw,table:zw,tableCell:Rw,tableRow:Lw,text:Ow,thematicBreak:Dw,toml:Ws,yaml:Ws,definition:Ws,footnoteDefinition:Ws};function Ws(){}const au=-1,Jr=0,Ss=1,Pr=2,va=3,Sa=4,ja=5,ka=6,lu=7,cu=8,$w=typeof self=="object"?self:globalThis,Bl=(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 $w[e](t)},Fw=(e,t)=>{const n=(i,o)=>(e.set(o,i),i),s=i=>{if(e.has(i))return e.get(i);const[o,a]=t[i];switch(o){case Jr:case au:return n(a,i);case Ss:{const c=n([],i);for(const l of a)c.push(s(l));return c}case Pr:{const c=n({},i);for(const[l,d]of a)c[s(l)]=s(d);return c}case va:return n(new Date(a),i);case Sa:{const{source:c,flags:l}=a;return n(new RegExp(c,l),i)}case ja:{const c=n(new Map,i);for(const[l,d]of a)c.set(s(l),s(d));return c}case ka:{const c=n(new Set,i);for(const l of a)c.add(s(l));return c}case lu:{const{name:c,message:l}=a;return n(Bl(c,l),i)}case cu:return n(BigInt(a),i);case"BigInt":return n(Object(BigInt(a)),i);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:c}=new Uint8Array(a);return n(new DataView(c),a)}}return n(Bl(o,a),i)};return s},Ul=e=>Fw(new Map,e)(0),gn="",{toString:Bw}={},{keys:Uw}=Object,ds=e=>{const t=typeof e;if(t!=="object"||!e)return[Jr,t];const n=Bw.call(e).slice(8,-1);switch(n){case"Array":return[Ss,gn];case"Object":return[Pr,gn];case"Date":return[va,gn];case"RegExp":return[Sa,gn];case"Map":return[ja,gn];case"Set":return[ka,gn];case"DataView":return[Ss,n]}return n.includes("Array")?[Ss,n]:n.includes("Error")?[lu,n]:[Pr,n]},Hs=([e,t])=>e===Jr&&(t==="function"||t==="symbol"),Vw=(e,t,n,s)=>{const i=(a,c)=>{const l=s.push(a)-1;return n.set(c,l),l},o=a=>{if(n.has(a))return n.get(a);let[c,l]=ds(a);switch(c){case Jr:{let u=a;switch(l){case"bigint":c=cu,u=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);u=null;break;case"undefined":return i([au],a)}return i([c,u],a)}case Ss:{if(l){let p=a;return l==="DataView"?p=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(p=new Uint8Array(a)),i([l,[...p]],a)}const u=[],m=i([c,u],a);for(const p of a)u.push(o(p));return m}case Pr:{if(l)switch(l){case"BigInt":return i([l,a.toString()],a);case"Boolean":case"Number":case"String":return i([l,a.valueOf()],a)}if(t&&"toJSON"in a)return o(a.toJSON());const u=[],m=i([c,u],a);for(const p of Uw(a))(e||!Hs(ds(a[p])))&&u.push([o(p),o(a[p])]);return m}case va:return i([c,a.toISOString()],a);case Sa:{const{source:u,flags:m}=a;return i([c,{source:u,flags:m}],a)}case ja:{const u=[],m=i([c,u],a);for(const[p,h]of a)(e||!(Hs(ds(p))||Hs(ds(h))))&&u.push([o(p),o(h)]);return m}case ka:{const u=[],m=i([c,u],a);for(const p of a)(e||!Hs(ds(p)))&&u.push(o(p));return m}}const{message:d}=a;return i([c,{name:l,message:d}],a)};return o},Vl=(e,{json:t,lossy:n}={})=>{const s=[];return Vw(!(t||n),!!t,new Map,s)(e),s},zr=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Ul(Vl(e,t)):structuredClone(e):(e,t)=>Ul(Vl(e,t));function Ww(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 Hw(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function qw(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Ww,s=e.options.footnoteBackLabel||Hw,i=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let l=-1;for(;++l<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[l]);if(!d)continue;const u=e.all(d),m=String(d.identifier).toUpperCase(),p=Rn(m.toLowerCase());let h=0;const g=[],y=e.footnoteCounts.get(m);for(;y!==void 0&&++h<=y;){g.length>0&&g.push({type:"text",value:" "});let v=typeof n=="string"?n:n(l,h);typeof v=="string"&&(v={type:"text",value:v}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+p+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(l,h),className:["data-footnote-backref"]},children:Array.isArray(v)?v:[v]})}const x=u[u.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const v=x.children[x.children.length-1];v&&v.type==="text"?v.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...g)}else u.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+p},children:e.wrap(u,!0)};e.patch(d,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...zr(a),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
10
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
11
+ `}]}}const du=(function(e){if(e==null)return Kw;if(typeof e=="function")return Kr(e);if(typeof e=="object")return Array.isArray(e)?Gw(e):Qw(e);if(typeof e=="string")return Jw(e);throw new Error("Expected function, string, or object as test")});function Gw(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=du(e[n]);return Kr(s);function s(...i){let o=-1;for(;++o<t.length;)if(t[o].apply(this,i))return!0;return!1}}function Qw(e){const t=e;return Kr(n);function n(s){const i=s;let o;for(o in e)if(i[o]!==t[o])return!1;return!0}}function Jw(e){return Kr(t);function t(n){return n&&n.type===e}}function Kr(e){return t;function t(n,s,i){return!!(Yw(n)&&e.call(this,n,typeof s=="number"?s:void 0,i||void 0))}}function Kw(){return!0}function Yw(e){return e!==null&&typeof e=="object"&&"type"in e}const uu=[],Zw=!0,Wl=!1,Xw="skip";function ev(e,t,n,s){let i;typeof t=="function"&&typeof n!="function"?(s=n,n=t):i=t;const o=du(i),a=s?-1:1;c(e,void 0,[])();function c(l,d,u){const m=l&&typeof l=="object"?l:{};if(typeof m.type=="string"){const h=typeof m.tagName=="string"?m.tagName:typeof m.name=="string"?m.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(l.type+(h?"<"+h+">":""))+")"})}return p;function p(){let h=uu,g,y,x;if((!t||o(l,d,u[u.length-1]||void 0))&&(h=tv(n(l,u)),h[0]===Wl))return h;if("children"in l&&l.children){const b=l;if(b.children&&h[0]!==Xw)for(y=(s?b.children.length:-1)+a,x=u.concat(b);y>-1&&y<b.children.length;){const v=b.children[y];if(g=c(v,y,x)(),g[0]===Wl)return g;y=typeof g[1]=="number"?g[1]:y+a}}return h}}}function tv(e){return Array.isArray(e)?e:typeof e=="number"?[Zw,e]:e==null?uu:[e]}function hu(e,t,n,s){let i,o,a;typeof t=="function"&&typeof n!="function"?(o=void 0,a=t,i=n):(o=t,a=n,i=s),ev(e,o,c,i);function c(l,d){const u=d[d.length-1],m=u?u.children.indexOf(l):void 0;return a(l,m,u)}}const Eo={}.hasOwnProperty,nv={};function sv(e,t){const n=t||nv,s=new Map,i=new Map,o=new Map,a={...Mw,...n.handlers},c={all:d,applyData:iv,definitionById:s,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:a,one:l,options:n,patch:rv,wrap:av};return hu(e,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){const m=u.type==="definition"?s:i,p=String(u.identifier).toUpperCase();m.has(p)||m.set(p,u)}}),c;function l(u,m){const p=u.type,h=c.handlers[p];if(Eo.call(c.handlers,p)&&h)return h(c,u,m);if(c.options.passThrough&&c.options.passThrough.includes(p)){if("children"in u){const{children:y,...x}=u,b=zr(x);return b.children=c.all(u),b}return zr(u)}return(c.options.unknownHandler||ov)(c,u,m)}function d(u){const m=[];if("children"in u){const p=u.children;let h=-1;for(;++h<p.length;){const g=c.one(p[h],u);if(g){if(h&&p[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Hl(g.value)),!Array.isArray(g)&&g.type==="element")){const y=g.children[0];y&&y.type==="text"&&(y.value=Hl(y.value))}Array.isArray(g)?m.push(...g):m.push(g)}}}return m}}function rv(e,t){e.position&&(t.position=Fb(e))}function iv(e,t){let n=t;if(e&&e.data){const s=e.data.hName,i=e.data.hChildren,o=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"&&o&&Object.assign(n.properties,zr(o)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function ov(e,t){const n=t.data||{},s="value"in t&&!(Eo.call(n,"hProperties")||Eo.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 av(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
12
+ `});++s<e.length;)s&&n.push({type:"text",value:`
13
+ `}),n.push(e[s]);return t&&e.length>0&&n.push({type:"text",value:`
14
+ `}),n}function Hl(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function ql(e,t){const n=sv(e,t),s=n.one(e,void 0),i=qw(n),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return i&&o.children.push({type:"text",value:`
15
+ `},i),o}function lv(e,t){return e&&"run"in e?async function(n,s){const i=ql(n,{file:s,...t});await e.run(i,s)}:function(n,s){return ql(n,{file:s,...e||t})}}function Gl(e){if(e)throw e}var gi,Ql;function cv(){if(Ql)return gi;Ql=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,i=function(d){return typeof Array.isArray=="function"?Array.isArray(d):t.call(d)==="[object Array]"},o=function(d){if(!d||t.call(d)!=="[object Object]")return!1;var u=e.call(d,"constructor"),m=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!u&&!m)return!1;var p;for(p in d);return typeof p>"u"||e.call(d,p)},a=function(d,u){n&&u.name==="__proto__"?n(d,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):d[u.name]=u.newValue},c=function(d,u){if(u==="__proto__")if(e.call(d,u)){if(s)return s(d,u).value}else return;return d[u]};return gi=function l(){var d,u,m,p,h,g,y=arguments[0],x=1,b=arguments.length,v=!1;for(typeof y=="boolean"&&(v=y,y=arguments[1]||{},x=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});x<b;++x)if(d=arguments[x],d!=null)for(u in d)m=c(y,u),p=c(d,u),y!==p&&(v&&p&&(o(p)||(h=i(p)))?(h?(h=!1,g=m&&i(m)?m:[]):g=m&&o(m)?m:{},a(y,{name:u,newValue:l(v,g,p)})):typeof p<"u"&&a(y,{name:u,newValue:p}));return y},gi}var dv=cv();const xi=Xc(dv);function To(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 uv(){const e=[],t={run:n,use:s};return t;function n(...i){let o=-1;const a=i.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);c(null,...i);function c(l,...d){const u=e[++o];let m=-1;if(l){a(l);return}for(;++m<i.length;)(d[m]===null||d[m]===void 0)&&(d[m]=i[m]);i=d,u?hv(u,c)(...d):a(null,...d)}}function s(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function hv(e,t){let n;return s;function s(...a){const c=e.length>a.length;let l;c&&a.push(i);try{l=e.apply(this,a)}catch(d){const u=d;if(c&&n)throw u;return i(u)}c||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(a,...c){n||(n=!0,t(a,...c))}function o(a){i(null,a)}}const bt={basename:fv,dirname:mv,extname:pv,join:gv,sep:"/"};function fv(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Rs(e);let n=0,s=-1,i=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(o){n=i+1;break}}else s<0&&(o=!0,s=i+1);return s<0?"":e.slice(n,s)}if(t===e)return"";let a=-1,c=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(o){n=i+1;break}}else a<0&&(o=!0,a=i+1),c>-1&&(e.codePointAt(i)===t.codePointAt(c--)?c<0&&(s=i):(c=-1,s=a));return n===s?s=a:s<0&&(s=e.length),e.slice(n,s)}function mv(e){if(Rs(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 pv(e){Rs(e);let t=e.length,n=-1,s=0,i=-1,o=0,a;for(;t--;){const c=e.codePointAt(t);if(c===47){if(a){s=t+1;break}continue}n<0&&(a=!0,n=t+1),c===46?i<0?i=t:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===s+1?"":e.slice(i,n)}function gv(...e){let t=-1,n;for(;++t<e.length;)Rs(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":xv(n)}function xv(e){Rs(e);const t=e.codePointAt(0)===47;let n=bv(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function bv(e,t){let n="",s=0,i=-1,o=0,a=-1,c,l;for(;++a<=e.length;){if(a<e.length)c=e.codePointAt(a);else{if(c===47)break;c=47}if(c===47){if(!(i===a-1||o===1))if(i!==a-1&&o===2){if(n.length<2||s!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",s=0):(n=n.slice(0,l),s=n.length-1-n.lastIndexOf("/")),i=a,o=0;continue}}else if(n.length>0){n="",s=0,i=a,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",s=2)}else n.length>0?n+="/"+e.slice(i+1,a):n=e.slice(i+1,a),s=a-i-1;i=a,o=0}else c===46&&o>-1?o++:o=-1}return n}function Rs(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const yv={cwd:wv};function wv(){return"/"}function Ao(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function vv(e){if(typeof e=="string")e=new URL(e);else if(!Ao(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 Sv(e)}function Sv(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 i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const bi=["history","path","basename","stem","extname","dirname"];class fu{constructor(t){let n;t?Ao(t)?n={path:t}:typeof t=="string"||jv(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":yv.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<bi.length;){const o=bi[s];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let i;for(i in n)bi.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?bt.basename(this.path):void 0}set basename(t){wi(t,"basename"),yi(t,"basename"),this.path=bt.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?bt.dirname(this.path):void 0}set dirname(t){Jl(this.basename,"dirname"),this.path=bt.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?bt.extname(this.path):void 0}set extname(t){if(yi(t,"extname"),Jl(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=bt.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Ao(t)&&(t=vv(t)),wi(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?bt.basename(this.path,this.extname):void 0}set stem(t){wi(t,"stem"),yi(t,"stem"),this.path=bt.join(this.dirname||"",t+(this.extname||""))}fail(t,n,s){const i=this.message(t,n,s);throw i.fatal=!0,i}info(t,n,s){const i=this.message(t,n,s);return i.fatal=void 0,i}message(t,n,s){const i=new Ye(t,n,s);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function yi(e,t){if(e&&e.includes(bt.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+bt.sep+"`")}function wi(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Jl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function jv(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const kv=(function(e){const s=this.constructor.prototype,i=s[e],o=function(){return i.apply(o,arguments)};return Object.setPrototypeOf(o,s),o}),Nv={}.hasOwnProperty;class Na extends kv{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=uv()}copy(){const t=new Na;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(xi(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(ji("data",this.frozen),this.namespace[t]=n,this):Nv.call(this.namespace,t)&&this.namespace[t]||void 0:t?(ji("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 i=n.call(t,...s);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=qs(t),s=this.parser||this.Parser;return vi("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),vi("process",this.parser||this.Parser),Si("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(o,a){const c=qs(t),l=s.parse(c);s.run(l,c,function(u,m,p){if(u||!m||!p)return d(u);const h=m,g=s.stringify(h,p);Tv(g)?p.value=g:p.result=g,d(u,p)});function d(u,m){u||!m?a(u):o?o(m):n(void 0,m)}}}processSync(t){let n=!1,s;return this.freeze(),vi("processSync",this.parser||this.Parser),Si("processSync",this.compiler||this.Compiler),this.process(t,i),Yl("processSync","process",n),s;function i(o,a){n=!0,Gl(o),s=a}}run(t,n,s){Kl(t),this.freeze();const i=this.transformers;return!s&&typeof n=="function"&&(s=n,n=void 0),s?o(void 0,s):new Promise(o);function o(a,c){const l=qs(n);i.run(t,l,d);function d(u,m,p){const h=m||t;u?c(u):a?a(h):s(void 0,h,p)}}}runSync(t,n){let s=!1,i;return this.run(t,n,o),Yl("runSync","run",s),i;function o(a,c){Gl(a),i=c,s=!0}}stringify(t,n){this.freeze();const s=qs(n),i=this.compiler||this.Compiler;return Si("stringify",i),Kl(t),i(t,s)}use(t,...n){const s=this.attachers,i=this.namespace;if(ji("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?c(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(d){if(typeof d=="function")l(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[u,...m]=d;l(u,m)}else a(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function a(d){if(!("plugins"in d)&&!("settings"in d))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");c(d.plugins),d.settings&&(i.settings=xi(!0,i.settings,d.settings))}function c(d){let u=-1;if(d!=null)if(Array.isArray(d))for(;++u<d.length;){const m=d[u];o(m)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function l(d,u){let m=-1,p=-1;for(;++m<s.length;)if(s[m][0]===d){p=m;break}if(p===-1)s.push([d,...u]);else if(u.length>0){let[h,...g]=u;const y=s[p][1];To(y)&&To(h)&&(h=xi(!0,y,h)),s[p]=[d,h,...g]}}}}const Cv=new Na().freeze();function vi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Si(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ji(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 Kl(e){if(!To(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Yl(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function qs(e){return Ev(e)?e:new fu(e)}function Ev(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Tv(e){return typeof e=="string"||Av(e)}function Av(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Iv="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Zl=[],Xl={allowDangerousHtml:!0},Pv=/^(https?|ircs?|mailto|xmpp)$/i,zv=[{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 Lv(e){const t=Rv(e),n=_v(e);return Ov(t.runSync(t.parse(n),n),e)}function Rv(e){const t=e.rehypePlugins||Zl,n=e.remarkPlugins||Zl,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Xl}:Xl;return Cv().use(hw).use(n).use(lv,s).use(t)}function _v(e){const t=e.children||"",n=new fu;return typeof t=="string"&&(n.value=t),n}function Ov(e,t){const n=t.allowedElements,s=t.allowElement,i=t.components,o=t.disallowedElements,a=t.skipHtml,c=t.unwrapDisallowed,l=t.urlTransform||Dv;for(const u of zv)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+Iv+u.id,void 0);return hu(e,d),Hb(e,{Fragment:r.Fragment,components:i,ignoreInvalidStyle:!0,jsx:r.jsx,jsxs:r.jsxs,passKeys:!0,passNode:!0});function d(u,m,p){if(u.type==="raw"&&p&&typeof m=="number")return a?p.children.splice(m,1):p.children[m]={type:"text",value:u.value},m;if(u.type==="element"){let h;for(h in fi)if(Object.hasOwn(fi,h)&&Object.hasOwn(u.properties,h)){const g=u.properties[h],y=fi[h];(y===null||y.includes(u.tagName))&&(u.properties[h]=l(String(g||""),h,u))}}if(u.type==="element"){let h=n?!n.includes(u.tagName):o?o.includes(u.tagName):!1;if(!h&&s&&typeof m=="number"&&(h=!s(u,m,p)),h&&p&&typeof m=="number")return c&&u.children?p.children.splice(m,1,...u.children):p.children.splice(m,1),m}}}function Dv(e){const t=e.indexOf(":"),n=e.indexOf("?"),s=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||s!==-1&&t>s||Pv.test(e.slice(0,t))?e:""}let Mv=0;function $v(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++Mv}`},i={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
16
+ <html><head>
17
+ <script>
18
+ window.__LMS_STUDENT__ = ${JSON.stringify(s)};
19
+ window.__LMS_COURSEWARE__ = ${JSON.stringify(i)};
20
+ (function() {
21
+ try {
22
+ // Override window.postMessage (self-targeting, always works)
23
+ var origPM = window.postMessage;
24
+ window.postMessage = function(msg, targetOrigin, transfer) {
25
+ var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
26
+ try { return origPM.call(this, msg, origin, transfer); }
27
+ catch(err) { if (err.name === 'SyntaxError') return origPM.call(this, msg, '*', transfer); throw err; }
28
+ };
29
+ // Shadow window.parent / window.top with Proxy to intercept .postMessage()
30
+ // Direct assignment (window.parent.postMessage = ...) silently fails on cross-origin WindowProxy
31
+ function proxyWin(realRef, propName) {
32
+ try {
33
+ var safePost = function(msg, targetOrigin, transfer) {
34
+ var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
35
+ try { return realRef.postMessage.call(realRef, msg, origin, transfer); }
36
+ catch(err) { if (err.name === 'SyntaxError') return realRef.postMessage.call(realRef, msg, '*', transfer); throw err; }
37
+ };
38
+ var px = new Proxy(realRef, {
39
+ get: function(t, p) {
40
+ if (p === 'postMessage') return safePost;
41
+ try { var v = t[p]; return typeof v === 'function' ? v.bind(t) : v; } catch(e) { return undefined; }
42
+ }
43
+ });
44
+ Object.defineProperty(window, propName, { get: function() { return px; }, configurable: true });
45
+ } catch(e) {}
46
+ }
47
+ if (window.parent && window.parent !== window) proxyWin(window.parent, 'parent');
48
+ try { if (window.top && window.top !== window) proxyWin(window.top, 'top'); } catch(e) {}
49
+ } catch(e) {}
50
+ })();
51
+ <\/script>
52
+ <script src="/bridge.js?cw=${encodeURIComponent(t||"")}"><\/script>
53
+ </head><body>
54
+ ${e||""}
55
+ </body></html>`}class Fv{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 i=s.resolve(t,n);if(i)return i}catch{}return null}}const ur=new Fv,Bv=4;let Gs=0;const Io=new Set;function ec(){return Gs>=Bv?null:(Gs+=1,()=>{Gs=Math.max(0,Gs-1);for(const e of Io)e()})}function Uv(e){return Io.add(e),()=>{Io.delete(e)}}function Vv(e,t){const[n,s]=f.useState(!e),[i,o]=f.useState(!1),a=f.useRef(null);return f.useEffect(()=>{if(!e||n)return;const c=t.current;if(!c)return;if(typeof IntersectionObserver>"u"){s(!0);return}const l=new IntersectionObserver(d=>{d.some(u=>u.isIntersecting)&&(s(!0),l.disconnect())},{rootMargin:"200px"});return l.observe(c),()=>l.disconnect()},[e,n,t]),f.useEffect(()=>{if(!n){a.current?.(),a.current=null,o(!1);return}const c=ec();if(c)a.current=c,o(!0);else{const l=Uv(()=>{const d=ec();d&&(l(),a.current=d,o(!0))});return()=>l()}},[n]),f.useEffect(()=>()=>{a.current?.()},[]),i}const Qe=[];for(let e=0;e<256;++e)Qe.push((e+256).toString(16).slice(1));function Wv(e,t=0){return(Qe[e[t+0]]+Qe[e[t+1]]+Qe[e[t+2]]+Qe[e[t+3]]+"-"+Qe[e[t+4]]+Qe[e[t+5]]+"-"+Qe[e[t+6]]+Qe[e[t+7]]+"-"+Qe[e[t+8]]+Qe[e[t+9]]+"-"+Qe[e[t+10]]+Qe[e[t+11]]+Qe[e[t+12]]+Qe[e[t+13]]+Qe[e[t+14]]+Qe[e[t+15]]).toLowerCase()}const Hv=new Uint8Array(16);function qv(){return crypto.getRandomValues(Hv)}const ki={};function Yr(e,t,n){let s;{const i=Date.now(),o=qv();Gv(ki,i,o),s=Qv(o,ki.msecs,ki.seq,t,n)}return t??Wv(s)}function Gv(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function Qv(e,t,n,s,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!s)s=new Uint8Array(16),i=0;else if(i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],s[i++]=t/1099511627776&255,s[i++]=t/4294967296&255,s[i++]=t/16777216&255,s[i++]=t/65536&255,s[i++]=t/256&255,s[i++]=t&255,s[i++]=112|n>>>28&15,s[i++]=n>>>20&255,s[i++]=128|n>>>14&63,s[i++]=n>>>6&255,s[i++]=n<<2&255|e[10]&3,s[i++]=e[11],s[i++]=e[12],s[i++]=e[13],s[i++]=e[14],s[i++]=e[15],s}function Ni(e){return e==="*"?{kind:"global",key:"*"}:e.length>2&&e.endsWith(".*")&&!e.slice(0,-2).includes("*")?{kind:"prefix",key:e.slice(0,-1)}:{kind:"exact",key:e}}class Jv{constructor(){this.handlers=new Map,this.prefixHandlers=new Map,this.globalHandlers=new Set,this.wildcardCount=0}subscribe(t,n){const{kind:s,key:i}=Ni(t);let o;if(s==="global")o=this.globalHandlers,this.wildcardCount++;else if(s==="prefix"){let c=this.prefixHandlers.get(i);c||(c=new Set,this.prefixHandlers.set(i,c)),o=c,this.wildcardCount++}else{let c=this.handlers.get(i);c||(c=new Set,this.handlers.set(i,c)),o=c}o.add(n);let a=!1;return()=>{a||(a=!0,o.delete(n),!(o.size>0)&&(s==="global"?this.wildcardCount--:s==="prefix"?(this.wildcardCount--,this.prefixHandlers.delete(i)):this.handlers.delete(i)))}}subscribePayload(t,n){const s=i=>n(i.payload,i);return this.subscribe(t,s)}once(t,n){const s=this.subscribe(t,i=>{s(),n(i)});return s}resolveHandlers(t){const n=this.handlers.get(t);if(this.wildcardCount===0)return n&&n.size>0?Array.from(n):[];let s=null;for(const[i,o]of this.prefixHandlers)if(t.startsWith(i)){if(!s&&(s=new Set,n))for(const a of n)s.add(a);for(const a of o)s.add(a)}if(this.globalHandlers.size>0){if(!s&&(s=new Set,n))for(const i of n)s.add(i);for(const i of this.globalHandlers)s.add(i)}return s?Array.from(s):n&&n.size>0?Array.from(n):[]}async publish(t){const n=this.resolveHandlers(t.type);if(n.length!==0)for(const s of n)try{const i=s(t);i instanceof Promise&&i.catch(o=>{console.error(`[FrontendEventBus] Async handler error on '${t.type}':`,o)})}catch(i){console.error(`[FrontendEventBus] Handler error on '${t.type}':`,i)}}async emit(t,n,s="frontend"){const i={id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`fe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:t,source:s,payload:n,timestamp:Date.now()};return this.publish(i)}listenerCount(t){if(t){const{kind:s,key:i}=Ni(t);return s==="global"?this.globalHandlers.size:s==="prefix"?this.prefixHandlers.get(i)?.size??0:this.handlers.get(i)?.size||0}let n=this.wildcardCount;for(const s of this.handlers.values())n+=s.size;return n}clear(t){if(t){const{kind:n,key:s}=Ni(t);if(n==="global")this.wildcardCount-=this.globalHandlers.size,this.globalHandlers.clear();else if(n==="prefix"){const i=this.prefixHandlers.get(s);i&&(this.wildcardCount-=i.size),this.prefixHandlers.delete(s)}else this.handlers.delete(s)}else this.handlers.clear(),this.prefixHandlers.clear(),this.globalHandlers.clear(),this.wildcardCount=0}}const rn=new Jv,Kv=[{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"}],hr={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":"#475569","--text-subtle":"#5a6b80","--primary-solid":"#4f46e5","--primary-ink":"#4f46e5","--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":"#94a3b8","--text-subtle":"#8698ad","--primary-solid":"#4f46e5","--primary-ink":"#818cf8","--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":"#2f5a44","--text-subtle":"#457057","--primary-solid":"#2d6a4f","--primary-ink":"#2d6a4f","--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":"#a5d6a7","--text-subtle":"#66bb6a","--primary-solid":"#2f7d32","--primary-ink":"#66bb6a","--color-primary":"#4caf50","--color-primary-hover":"#388e3c"}},Ci="openlearn_theme",us="openlearn_custom_themes",Lr={};function Ca(e){return Lr[e]?Lr[e]:e in hr?hr[e]:hr.light}function Ei(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function Yv(e,t){if(typeof document>"u")return;Lr[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 i=Object.entries(t).map(([o,a])=>` ${o}: ${a};`).join(`
56
+ `);s.textContent=`[data-theme="${e}"] {
57
+ ${i}
58
+ }`}function Zv(e){if(typeof document>"u")return;delete Lr[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function Ti(e){if(!(typeof window>"u"))try{rn.publish({id:Yr(),type:"theme.changed",source:"theme-store",payload:{theme:e,tokens:Ca(e)},timestamp:Date.now()})}catch{}}const _n=ra((e,t)=>({theme:"light",availableThemes:[...Kv],initTheme:()=>{if(typeof window>"u")return;try{const i=localStorage.getItem(us);if(i){const o=JSON.parse(i);Array.isArray(o)&&o.forEach(a=>{a&&a.spec&&a.spec.id&&t().registerTheme(a.spec,a.cssVariables)})}}catch{}const s=localStorage.getItem(Ci)||"light";Ei(s),e({theme:s}),Ti(s)},setTheme:n=>{Ei(n),typeof window<"u"&&localStorage.setItem(Ci,n),e({theme:n}),Ti(n)},registerTheme:(n,s)=>{s&&Yv(n.id,s),e(i=>({availableThemes:[...i.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{Zv(n),e(s=>{const i=s.availableThemes.filter(a=>a.id!==n),o=s.theme===n?"light":s.theme;return s.theme===n&&(Ei("light"),typeof window<"u"&&localStorage.setItem(Ci,"light"),Ti("light")),{availableThemes:i,theme:o}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const i=localStorage.getItem(us);let o=i?JSON.parse(i):[];Array.isArray(o)||(o=[]),o=o.filter(a=>a.spec.id!==n.id),o.push({spec:n,cssVariables:s}),localStorage.setItem(us,JSON.stringify(o))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(us);if(s){let i=JSON.parse(s);Array.isArray(i)&&(i=i.filter(o=>o.spec.id!==n),localStorage.setItem(us,JSON.stringify(i)))}}catch{}t().unregisterTheme(n)}})),Ai="openlearn_font_scale",bn=85,yn=140,Ii=5,fr=100,tc=[{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 Pi(e){if(typeof document>"u")return;const t=Math.min(yn,Math.max(bn,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 zi(e){if(!(typeof window>"u"))try{rn.publish({id:Yr(),type:"font-scale.changed",source:"font-size-store",payload:{scale:e},timestamp:Date.now()})}catch{}}const Sn=ra((e,t)=>({scale:fr,minScale:bn,maxScale:yn,step:Ii,initFontSize:()=>{if(typeof window>"u")return;let n=fr;try{const s=localStorage.getItem(Ai);if(s){const i=Number(s);!isNaN(i)&&i>=bn&&i<=yn&&(n=i)}}catch{}Pi(n),e({scale:n}),zi(n);try{window.addEventListener("storage",s=>{if(s.key===Ai&&s.newValue){const i=Number(s.newValue);!isNaN(i)&&i>=bn&&i<=yn&&(Pi(i),e({scale:i}),zi(i))}})}catch{}},setScale:n=>{const s=Math.min(yn,Math.max(bn,Math.round(n)));if(Pi(s),typeof window<"u")try{localStorage.setItem(Ai,String(s))}catch{}e({scale:s}),zi(s)},increaseScale:()=>{const n=t().scale,s=Math.min(yn,n+Ii);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max(bn,n-Ii);t().setScale(s)},resetScale:()=>{t().setScale(fr)}})),nc=new Map,Li=new Map;async function Xv(e){const t=nc.get(e);if(t)return t;const n=Li.get(e);if(n)return n;const s=(async()=>{try{const i=await fetch(`/api/courseware/attempts/${encodeURIComponent(e)}/adopt`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!i.ok)return i.status!==401&&console.warn(`[LMS Bridge] Attempt adopt failed: HTTP ${i.status}`),e;const o=await i.json();return typeof o?.attemptId=="string"&&o.attemptId?(nc.set(e,o.attemptId),o.attemptId):e}catch(i){return console.warn("[LMS Bridge] Attempt adopt request failed:",i),e}finally{Li.delete(e)}})();return Li.set(e,s),s}const Rr=new Set;function eS(e){return Rr.add(e),()=>{Rr.delete(e)}}function mu(e){if(!e)return null;for(const t of Rr)if(t.contentWindow===e)return t;if(typeof document<"u")try{return Array.from(document.querySelectorAll("iframe[data-lms-bridge]")).find(n=>n.contentWindow===e)||null}catch{return null}return null}function sc(e){return typeof document>"u"||!e?!1:mu(e)!==null}function Po(e){const t=e.length;let n=t+2;for(let s=0;s<t;s++){const i=e.charCodeAt(s);if(i===34||i===92)n+=1;else if(i<32)n+=i===8||i===9||i===10||i===12||i===13?1:5;else if(i>=55296&&i<=57343){const o=s+1<t?e.charCodeAt(s+1):0;i<=56319&&o>=56320&&o<=57343?s++:n+=5}}return n}const zo=-1,wn=-2,tS=4;function nS(e){if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:typeof e.toJSON!="function"}function Lo(e,t,n){if(e===null)return 4;const s=typeof e;if(s==="boolean")return e===!0?4:5;if(s==="number"){const l=e;return Number.isFinite(l)?String(l).length:4}if(s==="string")return Po(e);if(typeof e!="object")return 0;if(t>=tS||!nS(e))return zo;let i=2,o=!0;const a=l=>(i+=l,n.total+=l,n.total>n.limit),c=l=>(i+=l,n.total>n.limit?wn:null);if(Array.isArray(e)){for(let l=0;l<e.length;l++){if(!o&&a(1))return wn;o=!1;const d=e[l];if(d===void 0||typeof d=="function"||typeof d=="symbol"){if(a(4))return wn;continue}const u=Lo(d,t+1,n);if(u<0)return u;const m=c(u);if(m!==null)return m}return i}for(const l of Object.keys(e)){let d;try{d=e[l]}catch{return zo}if(d===void 0||typeof d=="function"||typeof d=="symbol")continue;if(!o&&a(1)||(o=!1,a(Po(l)+1)))return wn;const u=Lo(d,t+1,n);if(u<0)return u;const m=c(u);if(m!==null)return m}return i}function sS(e,t=512*1024){if(!e||typeof e=="number"||typeof e=="boolean")return!1;if(typeof e=="string")return Po(e)>t;const s=Lo(e,0,{total:0,limit:t});if(s===wn)return!0;if(s===zo)try{return JSON.stringify(e).length>t}catch{return!1}return s>t}async function rS(e){const t=e.data;if(!t||typeof t!="object")return;const n=typeof t.type=="string"?t.type:"";if(!(n.startsWith("LMS_")||n==="submit"||n==="finish"||n==="completed"||n==="saveProgress"||typeof t.attempt_id=="string"))return;if(sS(t,512*1024)){console.warn("[LMS Bridge] Dropped oversized postMessage (>512KB)");return}if(typeof window<"u"&&e.source&&e.source!==window&&!sc(e.source))return;let i=t.attempt_id;const o=t.payload||t;if(!i&&e.source)try{const l=mu(e.source);if(l&&l.contentWindow){const d=l.contentWindow;d.__LMS_STUDENT__?.attempt_id&&(i=d.__LMS_STUDENT__.attempt_id)}}catch{}if(!i||typeof i!="string")return;if(i=await Xv(i),n==="LMS_CONFIG"){Qs("courseware.config_reported",i,t.config??o);return}if(n==="LMS_GET_PROGRESS"){const l=t.requestId,d=e.source;if(l&&d&&typeof d.postMessage=="function"){if(d!==window&&!sc(d)){console.warn("[LMS Bridge Security] Dropping response to untrusted window");return}let u;try{u=(await(await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/progress`)).json()).progress??null}catch{u=null}const m=e.origin&&e.origin!=="null"?e.origin:"*";d.postMessage({type:"LMS_PROGRESS_RESPONSE",requestId:l,progress:u},m)}return}const a=n==="LMS_SUBMIT"||n==="LMS_FINISH"||n==="submit"||n==="finish"||n==="completed"||o&&typeof o=="object"&&(o.score!==void 0||o.grade!==void 0||o.result!==void 0||o.points!==void 0),c=n==="LMS_SAVE_PROGRESS"||n==="saveProgress";if(a){Qs("courseware.submitted",i,o);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:o?.score??o?.grade??o?.result??o?.points??void 0,comment:o?.comment??o?.feedback??o?.note??void 0,completion:o?.completion??1,status:"completed",extra:o})});if(!l.ok){const d=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${l.status}`,d)}}catch(l){console.error("[LMS Bridge] Failed to submit attempt data to backend:",l)}}else if(c){Qs("courseware.progress_saved",i,o);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:o?.score??o?.grade??o?.result??o?.points??void 0,comment:o?.comment??o?.feedback??void 0,completion:o?.completion??void 0,status:"inprogress",extra:o})});if(!l.ok){const d=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${l.status}`,d)}}catch(l){console.error("[LMS Bridge] Failed to save progress to backend:",l)}}else{Qs("courseware.event_logged",i,o);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:n||"log",payload:o})});if(!l.ok){const d=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${l.status}`,d)}}catch(l){console.error("[LMS Bridge] Failed to log event to backend:",l)}}}function Qs(e,t,n){rn.publish({id:Yr(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t})}function iS(e){f.useEffect(()=>{if(!e)return;const t=n=>{rS(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function pu(){const e=[],t=new Set;for(const n of Rr)n&&!t.has(n)&&(t.add(n),e.push(n));if(typeof document<"u")try{document.querySelectorAll("iframe[data-lms-bridge]").forEach(n=>{t.has(n)||(t.add(n),e.push(n))})}catch{}return e}function _r(e,t){try{let n;if(e.src&&typeof window<"u")try{const s=new URL(e.src,window.location.href);s.origin&&s.origin!=="null"&&!e.src.startsWith("blob:")&&!e.src.startsWith("data:")&&(n=s.origin)}catch{}e.contentWindow?.postMessage(t,n||"*")}catch{}}function gu(e,t={}){if(!(typeof document>"u"))try{pu().forEach(s=>{_r(s,{type:"LMS_HOST_COMMAND",event:"theme:changed",payload:{theme:e,tokens:t}}),_r(s,{type:"LMS_THEME_CHANGED",theme:e,tokens:t})})}catch{}}function xu(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));pu().forEach(s=>{_r(s,{type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}}),_r(s,{type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)})})}catch{}}let Ri=null,_i=null;typeof window<"u"&&(rn.subscribe("theme.changed",e=>{Ri&&clearTimeout(Ri),Ri=setTimeout(()=>{const t=e.payload;t&&typeof t.theme=="string"&&gu(t.theme,t.tokens??{})},50)}),rn.subscribe("font-scale.changed",e=>{_i&&clearTimeout(_i),_i=setTimeout(()=>{const t=e.payload;t&&typeof t.scale=="number"&&xu(t.scale)},50)}));let zn=null;const Ro=new Set;function bu(e){if(zn=e,!!e)for(const t of Ro)try{t(e)}catch(n){console.error("[socket-service] socket-ready listener error:",n)}}function Ea(e){if(Ro.add(e),zn)try{e(zn)}catch(t){console.error("[socket-service] socket listener error:",t)}return()=>{Ro.delete(e)}}function oS(){if(!zn)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return zn}function ct(){return zn}class aS{constructor(t){this.socket=t,bu(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 yu=200;function lS(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 cS{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??yu,this.persist=t.persist??!1}ingest(t,n){const s={id:Yr(),timestamp:Date.now(),...t};if(this.buffer.push(s),this.buffer.length>this.capacity&&this.buffer.shift(),this.dispatch(s),!n?.skipBusSync)try{const i=lS(s);rn.publish(i)}catch(i){typeof console<"u"&&console.warn("[WhiteboardEventSlot] frontendEventBus publish failed:",i)}return this.persist&&typeof indexedDB<"u"&&this.persistEvent(s),s}emit(t,n,s={}){return this.ingest({...s,type:t,source:s.source??"manual",payload:n})}subscribe(t,n,s={}){const i={filter:t,handler:n};if(this.subscriptions.push(i),t.types)for(const o of t.types)this.byType.has(o)||this.byType.set(o,new Set),this.byType.get(o).add(i);if(s.replay&&s.replay>0){const o=this.query(t,{limit:s.replay});queueMicrotask(()=>{for(const a of o)try{n(a)}catch(c){console.error("[WhiteboardEventSlot] replay handler error:",c)}})}return()=>{const o=this.subscriptions.indexOf(i);if(o>=0&&this.subscriptions.splice(o,1),t.types)for(const a of t.types)this.byType.get(a)?.delete(i)}}query(t={},n={}){const s=n.limit??this.capacity,i=n.since??0,o=[];for(let a=this.buffer.length-1;a>=0;a--){const c=this.buffer[a];if(c.timestamp<i||rc(c,t)&&(o.push(c),o.length>=s))break}return o}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 i of s)if(rc(t,i.filter))try{i.handler(t)}catch(o){console.error("[WhiteboardEventSlot] handler error:",o)}}async persistEvent(t){if(!(typeof indexedDB>"u"))try{const n=await dS(),s=n.transaction("events","readwrite");s.objectStore("events").put(t),await new Promise((o,a)=>{s.oncomplete=()=>o(),s.onerror=()=>a(s.error)}),n.close()}catch{}}}function rc(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 Js=null;function dS(){return Js||(Js=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)}),Js)}const Mt=new cS({capacity:yu,persist:!1});typeof window<"u"&&rn.subscribe("courseware.*",e=>{if(e.source==="whiteboard"||e.source?.startsWith("whiteboard."))return;const t=e.payload??{},n=t.data??t,s=typeof n=="object"&&n!==null?n:{},i=t.attemptId||(typeof s.attemptId=="string"?s.attemptId:void 0);Mt.ingest({source:"iframe.bridge",type:e.type,attemptId:i,coursewareUuid:typeof s.courseware_uuid=="string"?s.courseware_uuid:void 0,payload:{...s,attemptId:i},raw:n},{skipBusSync:!0})});function Xt(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 uS=new Set(["guest","teacher","teacher_preview"]);function hS(e){const t=e.filter(o=>typeof o.score=="number").slice().sort((o,a)=>a.score-o.score),n=new Map;let s=0,i=null;return t.forEach((o,a)=>{const c=o.score;(i===null||c<i)&&(s=a+1,i=c),n.set(o.attemptId,s)}),n}function fS(e,t){return e.slice().sort((n,s)=>{const i=t.get(n.attemptId)??Number.MAX_SAFE_INTEGER,o=t.get(s.attemptId)??Number.MAX_SAFE_INTEGER;return i!==o?i-o:(n.studentName||n.studentId).localeCompare(s.studentName||s.studentId,"zh-Hans-CN")})}function mS({data:e,lessonId:t,elementId:n,className:s,title:i,lazy:o=!0}){const a=De.useRef(null),c=De.useRef(null),l=Vv(o,a),{theme:d}=_n(),{scale:u}=Sn(),m=ae(B=>B.session),[p,h]=f.useState([]),[g,y]=f.useState(!1),[x,b]=f.useState(null),[v,S]=f.useState(null),T=ur.resolve(e,{lessonId:t}),k=!!e.code&&!e.coursewareUuid&&!e.resourceId&&!T,w=e.coursewareUuid??(k?v:null);f.useEffect(()=>{if(!k||!e.code){S(null);return}let B=!1;return fetch("/api/courseware/inline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e.code})}).then(q=>q.ok?q.json():Promise.reject(new Error(`HTTP ${q.status}`))).then(q=>{!B&&typeof q?.uuid=="string"&&q.uuid&&S(q.uuid)}).catch(()=>{}),()=>{B=!0}},[k,e.code]),f.useEffect(()=>{if(!w){b(null);return}let B=!1;return fetch(`/api/courseware/${encodeURIComponent(w)}/access-token`).then(q=>q.ok?q.json():Promise.reject(new Error(`HTTP ${q.status}`))).then(q=>{!B&&typeof q?.token=="string"&&q.token&&b(q.token)}).catch(()=>{}),()=>{B=!0}},[w]),f.useEffect(()=>{const B=e.coursewareUuid;if(!B)return;let q=!1;const C=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(B)}&pageSize=all`).then(ee=>ee.ok?ee.json():{data:[]}).then(ee=>{q||h(In(ee))}).catch(()=>{})};C();let K=null,G=null;const Q=()=>C();try{K=oS(),K.on("courseware-attempt-updated",Q)}catch{G=setInterval(C,5e3)}return()=>{q=!0,K&&K.off("courseware-attempt-updated",Q),G&&clearInterval(G)}},[e.coursewareUuid]);const I=()=>{gu(d,Ca(d)),xu(u)};f.useEffect(()=>{const B=n??e.title??void 0,q=e.coursewareUuid;if(!B&&!q||!l)return;const C=a.current?.querySelector("iframe");if(!C||!(C instanceof HTMLIFrameElement)||!C.contentWindow)return;const K=G=>{if(G.source!==C.contentWindow)return;const Q=G.data;if(!(!Q||typeof Q!="object"))if(Q.type==="LMS_SUBMIT"){const ee=Q.payload??{};Mt.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:B,coursewareUuid:q,attemptId:typeof Q.attempt_id=="string"?Q.attempt_id:void 0,payload:{score:Xt(ee.score??ee.grade),total:Xt(ee.total??ee.fullScore),completion:Xt(ee.completion??ee.progress),comment:typeof ee.comment=="string"?ee.comment:void 0},raw:Q})}else if(Q.type==="LMS_SAVE_PROGRESS"){const ee=Q.payload??{};Mt.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:B,coursewareUuid:q,attemptId:typeof Q.attempt_id=="string"?Q.attempt_id:void 0,payload:{score:Xt(ee.score),completion:Xt(ee.completion??ee.progress)},raw:Q})}else if(Q.type==="LMS_FINISH")Mt.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:B,coursewareUuid:q,attemptId:typeof Q.attempt_id=="string"?Q.attempt_id:void 0,payload:{},raw:Q});else if(Q.type==="courseware:score"||Q.type==="openlearn-cw-sdk:score"){const ee=Q.payload??Q;Mt.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:B,coursewareUuid:q,payload:{score:Xt(ee.score),total:Xt(ee.total),detail:ee.detail,source:typeof Q.source=="string"?Q.source:"openlearn-cw-sdk"},raw:Q})}else typeof Q.type=="string"&&Q.type.startsWith("LMS_")&&Mt.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:B,coursewareUuid:q,payload:{originalType:Q.type},raw:Q})};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)},[l,n,e.title,e.coursewareUuid,t]);const _=e.coursewareUuid?`/runtime/${e.coursewareUuid}/${x?`?ct=${encodeURIComponent(x)}`:""}`:e.resourceId?`/api/resources/${e.resourceId}/`:T??(v?`/runtime/${v}/${x?`?ct=${encodeURIComponent(x)}`:""}`:void 0);f.useEffect(()=>{if(!l)return;const B=c.current??a.current?.querySelector("iframe");if(B&&B instanceof HTMLIFrameElement)return eS(B)},[l,_]);const R=p.filter(B=>B.finished_at!==null&&B.finished_at!==void 0),L=R.filter(B=>B.score!==null&&B.score!==void 0),E=L.length>0?L.reduce((B,q)=>B+(q.score||0),0)/L.length:null,A=60,D=m?.role==="student"&&(m.studentId||m.userId)||null,F=hS(p),P=R.filter(B=>!uS.has(B.studentId)||B.studentId===D),$=fS(P,F),V=D?P.find(B=>B.studentId===D)??null:null,z=V?F.get(V.attemptId)??null:null,U=F.size,j=!!e.coursewareUuid&&p.length>0;return r.jsxs("div",{ref:a,className:(s??"w-full h-full")+" relative",children:[l?r.jsx("iframe",{ref:c,className:"w-full h-full border-none",src:_,srcDoc:_?void 0:$v(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads","data-lms-bridge":"true",referrerPolicy:"no-referrer",title:i??e.title??"Interactive Courseware",credentialless:"true",onLoad:I}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"}),j&&r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",onClick:()=>y(B=>!B),"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:g?"隐藏成绩":`查看成绩 (${$.length})`}),g&&r.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:[r.jsx("div",{className:"text-xs text-gray-400 mb-2 flex items-center justify-between",children:r.jsxs("span",{children:[$.length," 人已提交",E!==null&&` · 均分 ${E.toFixed(1)}`]})}),D&&r.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:V?`我的成绩 ${typeof V.score=="number"?V.score:"—"}${z!==null?` · 全班第 ${z}/${U} 名`:""}`:"我还没有提交"}),$.length===0?r.jsx("div",{className:"text-xs text-gray-400 text-center py-4",children:"暂无提交"}):r.jsx("div",{className:"space-y-1.5",children:$.map(B=>{const q=typeof B.score=="number"?B.score:null,C=typeof B.completion=="number"?Math.round(B.completion*100):null,K=F.get(B.attemptId),G=!!D&&B.studentId===D;return r.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${G?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${B.attemptId}`,children:[r.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:K??"-"}),r.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[B.studentName||B.studentId,G&&r.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),r.jsxs("span",{className:`font-mono font-bold ${q!==null&&q>=A?"text-green-600":"text-red-500"}`,children:[q!==null?q:"-",C!==null&&r.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[C,"%"]})]})]},B.attemptId)})})]})]})]})}const pS=["http:","https:"],gS=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,xS=/[\u0000-\u001f\u007f]/;function mr(e){if(typeof e!="string")return null;const t=e.trim();if(!t||xS.test(t)||t.startsWith("//")||t.startsWith("\\\\"))return null;if(gS.exec(t)){const s=t.slice(0,t.indexOf(":")+1).toLowerCase();if(!pS.includes(s))return null}return t}class bS{constructor(){this.renderers=new Map}register(t,n,s){this.renderers.set(t,{impl:n,pluginId:s})}registerHostBuiltin(t,n){this.renderers.set(t,{impl:n,hostBuiltin:!0})}get(t){return this.renderers.get(t)?.impl}getEffectiveRenderer(t){const n=this.renderers.get(t);if(n)return n.pluginId||n.hostBuiltin?n.impl:void 0}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 pr=new bS,kE=({type:e,title:t,data:n,containerSize:s,onClose:i,lessonId:o,elementId:a,dismissible:c=!0,readOnly:l=!1,renderContent:d})=>{De.useEffect(()=>{if(!c)return;const k=w=>{w.key==="Escape"&&i()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[i,c]);const u=c?i:()=>{},m=pr.getEffectiveRenderer(e),[p,h]=f.useState({width:window.innerWidth,height:window.innerHeight});f.useEffect(()=>{const k=()=>h({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const g=De.useRef(null),[y,x]=f.useState({width:0,height:0}),b=De.useRef(null),v=De.useCallback(()=>{const k=g.current;if(!k)return;const w=window.getComputedStyle(k),I=k.clientWidth-(parseFloat(w.paddingLeft)||0)-(parseFloat(w.paddingRight)||0),_=k.clientHeight-(parseFloat(w.paddingTop)||0)-(parseFloat(w.paddingBottom)||0);x({width:Math.max(0,I),height:Math.max(0,_)})},[]),S=De.useCallback(k=>{g.current=k,b.current?.disconnect(),b.current=null,k&&typeof ResizeObserver<"u"&&(b.current=new ResizeObserver(v),b.current.observe(k))},[v]);f.useLayoutEffect(()=>{v()},[v]);const T=r.jsx("div",{className:"fixed inset-0 z-[99999] bg-black/60 flex items-center justify-center",style:{pointerEvents:"auto"},children:r.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:[r.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:[r.jsx("span",{className:"truncate",children:t}),c?r.jsxs("button",{onClick:i,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:[r.jsx(io,{size:14})," 退出全屏"]}):r.jsx("span",{className:`px-2 py-1 rounded-md text-xs font-bold flex items-center gap-1 select-none ${l?"bg-amber-100 text-amber-800 border border-amber-300":"bg-indigo-100 text-indigo-600"}`,title:l?"教师已开启全班专注锁定,当前为只读演示视图":"由教师端控制,无法在本地退出",children:l?"🔒 全班专注锁定中 · 演示视图":r.jsxs(r.Fragment,{children:[r.jsx(io,{size:12})," 教师同步视图"]})})]}),(()=>{const k=e==="quiz"||e==="assignment";return r.jsxs("div",{ref:S,"data-testid":"fullscreen-content",className:"flex-1 overflow-auto p-6 relative",style:{pointerEvents:l&&!k?"none":"auto"},children:[m?r.jsx(m,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:o,elementId:a}):d?d(y):r.jsx(wS,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:o}),l&&!k&&r.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:w=>{w.stopPropagation(),w.preventDefault()},onPointerDown:w=>{w.stopPropagation(),w.preventDefault()}})]})})()]})});return Vp.createPortal(T,document.body)},yS=[{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 wS({data:e,lessonId:t}){const n=yS.find(c=>e[c.field]!==void 0&&e[c.field]!==null&&e[c.field]!=="");if(!n)return r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-gray-500",children:[r.jsx(Is,{size:48,className:"opacity-30"}),r.jsx("div",{className:"text-sm font-medium",children:"自动识别渲染"}),r.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:i,label:o,extra:a}=n;if(s==="markdown")return r.jsx("div",{className:"prose prose-sm max-w-none",children:r.jsx(Lv,{children:String(e.markdown)})});if(s==="code")return r.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 r.jsx("div",{className:"flex items-start h-full",children:r.jsx("div",{className:"text-lg whitespace-pre-wrap leading-relaxed",children:String(e.text)})});if(s==="question"){const c=Array.isArray(e.options)?e.options:[];return r.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[r.jsx("h3",{className:"text-xl font-bold text-gray-800",children:e.question}),r.jsx("div",{className:"flex flex-col gap-3",children:c.map((l,d)=>r.jsxs("div",{className:"px-5 py-4 text-left bg-gray-50 border-2 border-gray-200 rounded-xl text-base",children:[r.jsxs("span",{className:"font-bold text-indigo-600 mr-3",children:["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[d],"."]}),l]},d))})]})}if(s==="url"){const c=mr(e.url);return c?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-indigo-600 underline text-lg",children:String(e.url)})}):r.jsx("div",{className:"flex items-center justify-center h-full text-sm text-slate-400",children:String(e.url)})}return s==="src"?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx("img",{src:String(e.src),alt:"",className:"max-w-full max-h-full object-contain rounded-lg"})}):s==="coursewareUuid"?r.jsx(mS,{data:{coursewareUuid:String(e.coursewareUuid)},lessonId:t,className:"w-full h-full rounded-xl border"}):s==="equation"?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx("div",{className:"text-2xl font-mono text-gray-800 bg-gray-50 px-8 py-4 rounded-xl border",children:String(e.equation)})}):r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"text-4xl mb-2",children:i}),r.jsx("div",{className:"text-lg font-semibold text-gray-800",children:o}),r.jsx("pre",{className:"mt-4 text-xs text-gray-500 max-w-md overflow-auto",children:JSON.stringify(e,null,2)})]})})}class vS{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 Oi=new vS;class SS{constructor(){this.store=jt(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId,i={...t,editFields:Array.isArray(t.editFields)?t.editFields:[],pluginId:s};this.store.setState(o=>{const a=new Map(o.items);return a.set(t.type,{config:i,pluginId:s}),{items:a}})}unregister(t,n){this.store.setState(s=>{const i=s.items.get(t);if(!i||n&&i.pluginId!==n)return s;const o=new Map(s.items);return o.delete(t),{items:o}})}unregisterPlugin(t){this.store.setState(n=>{let s=!1;const i=new Map(n.items);for(const[o,a]of n.items)a.pluginId===t&&(i.delete(o),s=!0);return s?{items:i}: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 Nn=new SS;function NE(){return Ut(Nn.getStore(),ed(e=>Array.from(e.items.values()).map(t=>t.config)))}const Ta=[{id:"intro",labelZh:"准备环节",labelEn:"Intro",icon:qp},{id:"lecture",labelZh:"讲授新课",labelEn:"Lecture",icon:Wr},{id:"practice",labelZh:"互动练习",labelEn:"Practice",icon:Gp},{id:"quiz",labelZh:"随堂测试",labelEn:"Quiz",icon:Ko},{id:"summary",labelZh:"要点总结",labelEn:"Summary",icon:lt}],_s=jt(()=>({items:new Map}));function wu(e){if(e&&typeof e!="string")return e;if(typeof e=="string"&&e.trim()){const t=Cr;if(t[e])return t[e];const n=e.split(/[-_\s]+/).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("");if(t[n])return t[n]}return nd}function vu(e,t){const n=t||e.pluginId;_s.setState(s=>{const i=new Map(s.items);return i.set(e.id,{meta:{...e,icon:wu(e.icon),pluginId:n},pluginId:n}),{items:i}})}function jS(e,t){_s.setState(n=>{const s=n.items.get(e);if(!s||t&&s.pluginId!==t)return n;const i=new Map(n.items);return i.delete(e),{items:i}})}function kS(e){_s.setState(t=>{let n=!1;const s=new Map(t.items);for(const[i,o]of t.items)o.pluginId===e&&(s.delete(i),n=!0);return n?{items:s}:t})}function NS(){return[...Ta,...Array.from(_s.getState().items.values()).map(e=>e.meta)]}function CE(){return Ut(_s,ed(e=>[...Ta,...Array.from(e.items.values()).map(t=>t.meta)]))}const _o=[{name:"Blue",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100",solid:"bg-blue-500 text-white border-blue-500 shadow-md ring-2 ring-blue-200",rail:"bg-blue-400"},{name:"Indigo",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100",solid:"bg-indigo-500 text-white border-indigo-500 shadow-md ring-2 ring-indigo-200",rail:"bg-indigo-400"},{name:"Green",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100",solid:"bg-green-500 text-white border-green-500 shadow-md ring-2 ring-green-200",rail:"bg-green-400"},{name:"Purple",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100",solid:"bg-purple-500 text-white border-purple-500 shadow-md ring-2 ring-purple-200",rail:"bg-purple-400"},{name:"Amber",color:"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100",solid:"bg-amber-500 text-white border-amber-500 shadow-md ring-2 ring-amber-200",rail:"bg-amber-400"}],EE=_o[1].color;function TE(e){return NS().find(t=>t.id===e)||Ta[1]}function AE(e){return _o.find(t=>t.color===e)||_o[1]}class CS{constructor(){this.store=jt(()=>({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(i=>{const o=new Map(i.items);return o.set(s,{config:{...t,quizType:s},pluginId:n||t.quizType}),{items:o}})}unregister(t,n){const s=t.trim(),i=this.store.getState().items.get(s);i&&n&&i.pluginId!==n||this.store.setState(o=>{const a=new Map(o.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[i,o]of s)o.pluginId===t&&s.delete(i);return{items:s}})}list(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}clear(){this.store.setState(()=>({items:new Map}))}}const Di=new CS;class ES{constructor(){this.store=jt(()=>({items:new Map}))}register(t,n){if(!t?.type||typeof t.type!="string"||!t.type.trim())throw new Error("[AssessmentQuestionTypeUiRegistry] type is required");if(typeof t.Editor!="function")throw new Error(`[AssessmentQuestionTypeUiRegistry] ${t.type}: Editor must be a component`);const s=t.type.trim();if(this.store.getState().items.has(s))throw new Error(`[AssessmentQuestionTypeUiRegistry] duplicate question type: ${s}`);this.store.setState(i=>{const o=new Map(i.items);return o.set(s,{config:{...t,type:s},pluginId:n||s}),{items:o}})}unregister(t,n){const s=this.store.getState().items.get(t);return!s||n!==void 0&&s.pluginId!==n?!1:(this.store.setState(i=>{const o=new Map(i.items);return o.delete(t),{items:o}}),!0)}clearOwned(t){const n=this.store.getState(),s=[...n.items.entries()].filter(([,i])=>i.pluginId===t);return s.length===0?0:(this.store.setState(()=>{const i=new Map(n.items);for(const[o]of s)i.delete(o);return{items:i}}),s.length)}get(t){return this.store.getState().items.get(t)?.config}list(){return[...this.store.getState().items.values()].map(t=>t.config)}subscribe(t){return this.store.subscribe(t)}getSnapshot(){return this.list()}}const Ct=new ES,TS=new Set(["slate","blue","violet","amber","rose","emerald","cyan","pink","indigo"]);function AS(e,t){const n=String(e.type??e.id??"");if(!n)return;const s=String(e.labelZh??e.label??e.title??e.name??n),i=String(e.labelEn??s),o=String(e.color??"violet"),a=TS.has(o)?o:"violet",c=String(e.group??e.category??"custom"),l=e.defaultData&&typeof e.defaultData=="object"&&!Array.isArray(e.defaultData)?e.defaultData:{},d=Array.isArray(e.editFields)?e.editFields:[];Nn.register({type:n,labelZh:s,labelEn:i,descriptionZh:String(e.descriptionZh??e.description??""),descriptionEn:String(e.descriptionEn??e.description??""),color:a,group:c,defaultData:l,editFields:d,pluginId:t},t)}function IS(e,t){const n=typeof e.labelZh=="string"?e.labelZh:"",s=typeof e.labelEn=="string"?e.labelEn:"";if(!n||!s)return;const i=String(e.id??"");i&&vu({id:i,labelZh:n,labelEn:s,icon:wu(typeof e.icon=="string"?e.icon:null),pluginId:t},t)}const Or=()=>null;function Ks(e){if(e instanceof Error&&e.message){const t=e.message;return/Failed to fetch frontend\.js/i.test(t)?"前端资源加载失败(HTTP 错误)":/Activation timeout/i.test(t)?"插件激活超时(5 秒)":/Cannot read properties of undefined/i.test(t)?"插件依赖缺失:宿主未提供共享运行时(React 等)":/Invalid plugin|missing manifest|activate function/i.test(t)?"插件入口格式不合法":t.length>160?`${t.slice(0,160)}…`:t}return"未知错误"}function PS(e,t,n,s){if(s.classroomTools)for(const o of s.classroomTools)e.registerExtensionPoint("classroom.tool",{id:o.id,label:o.name,icon:o.icon,slotProps:o.commandType?{commandType:o.commandType}:void 0,component:Or,pluginId:t,origin:"manifest"});const i=s.contributes;if(i&&i.locales&&typeof i.locales=="object"&&Bx(t,i.locales),i){for(const[o,a]of Object.entries(i))if(Array.isArray(a)&&!(o==="classroom.tool"&&s.classroomTools))for(const c of a){if(!c||typeof c!="object")continue;const l=c,d=String(l.id??l.type??"");d&&(e.registerExtensionPoint(o,{id:d,label:String(l.title??l.label??l.name??d),icon:typeof l.icon=="string"?l.icon:void 0,view:typeof l.view=="string"?l.view:void 0,slotProps:l.commandType?{...l,commandType:Pd(String(l.commandType),n)}:l,component:Or,pluginId:t,origin:"manifest"}),o==="editor.palette_item"?AS(l,t):o==="editor.timeline_segment"&&IS(l,t))}}}const zS=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class LS{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.dispatcher=Nd,this.disposers=new Map,this.manifests=new Map,this.sandboxFrames=new Map,this.sandboxCleanups=new Map,this.moduleLoader=t?.moduleLoader??this.defaultModuleLoader}trackDisposer(t,n){const s=this.disposers.get(t)??[];return s.push(n),this.disposers.set(t,s),()=>{const i=this.disposers.get(t);if(!i)return;const o=i.indexOf(n);o>=0&&i.splice(o,1),n()}}getDispatcher(){return this.dispatcher}setDispatcher(t){this.dispatcher=t}setWorkerManager(t){this.workerManager=t}async initialize(t,n,s,i,o){o&&(this.dispatcher=o);const a=new Xx;await a.register(gs,t),await a.register(yo,n),await a.register(lr,s),await a.register(cr,i),await a.register(zd,new RS(t)),await a.register(hb,this.dispatcher),this.registry=a,this.initialized=!0,Ce.getState().initialize(a)}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:Le.INSTALLED,executionMode:"inline",icon:t.icon,capabilitiesProposed:Array.isArray(t.capabilitiesProposed)?[...t.capabilitiesProposed]:[]})}registerManifestContributions(t,n){PS(Ce.getState(),t,n.id,n)}destroySandboxFrame(t){const n=this.sandboxCleanups.get(t);n&&(this.sandboxCleanups.delete(t),n());const s=this.sandboxFrames.get(t);if(s){this.sandboxFrames.delete(t);try{s.contentWindow?.postMessage({channel:xs,type:"deactivate",id:t},"*")}catch{}s.remove()}}async mountSandboxFrame(t,n,s){if(typeof document>"u")throw new Error(`Cannot sandbox plugin "${t}" outside a browser document`);this.destroySandboxFrame(t);const i=document.createElement("iframe");i.setAttribute("sandbox",pb),i.setAttribute("src",gb),i.setAttribute("title",`plugin-sandbox-${t}`),i.style.display="none";let o=0;const a=()=>{o++,o>1&&(console.error(`[PluginSandbox] Plugin "${t}" attempted unauthorized navigation. Destroying sandbox.`),this.destroySandboxFrame(t),this.unregisterPluginResources(t),this.pluginModules.delete(t),Ce.getState().updatePluginState(t,Le.ERROR))};i.addEventListener("load",a),document.body.appendChild(i),this.sandboxFrames.set(t,i);const c=this.registry?await this.registry.resolve(gs):null,l=this.registry?await this.registry.resolve(cr):null,d=this.registry?await this.registry.resolve(lr):null,u=Array.isArray(n.capabilitiesProposed)?n.capabilitiesProposed:[],m=p=>{if(p.source!==i.contentWindow||!pl(p.data))return;const h=p.data;h.type!=="call"||!h.callId||!h.op||this.answerSandboxCall(i,h.callId,h.op,h.args??[],{pluginId:t,manifest:n,caps:u,frontendApi:c,storageService:l,uiService:d}).catch(g=>{i.contentWindow?.postMessage({channel:xs,type:"reply",callId:h.callId,ok:!1,error:g instanceof Error?g.message:String(g)},"*")})};window.addEventListener("message",m),this.sandboxCleanups.set(t,()=>{i.removeEventListener("load",a),window.removeEventListener("message",m)}),await new Promise((p,h)=>{let g=!1;const y=window.setTimeout(()=>{g||(window.removeEventListener("message",b),h(new Error("Activation timeout (5000ms)")))},5e3),x=v=>{g||(g=!0,window.clearTimeout(y),window.removeEventListener("message",b),v?h(v):p())},b=v=>{if(v.source!==i.contentWindow||!pl(v.data))return;const S=v.data;if(S.type==="ready"){i.contentWindow?.postMessage({channel:xs,type:"load",id:t,pluginId:t,manifest:n,source:s},"*");return}if(S.type==="activated"&&S.id===t){x();return}if(S.type==="activate-error"&&S.id===t){x(new Error(S.error||"sandbox activation failed"));return}};window.addEventListener("message",b)})}async answerSandboxCall(t,n,s,i,o){const a=(c,l,d)=>{t.contentWindow?.postMessage({channel:xs,type:"reply",callId:n,ok:c,value:l,error:d},"*")};try{let c;if(s==="api.get"||s==="api.post"||s==="api.del"){const l=s.slice(4),d=mb(gs,l,i,o.caps);if(d)throw new Error(d);if(!o.frontendApi)throw new Error("frontendApi is not available");l==="get"?c=await o.frontendApi.get(String(i[0]??"")):l==="post"?c=await o.frontendApi.post(String(i[0]??""),i[1]):c=await o.frontendApi.del(String(i[0]??""))}else if(s==="storage.get"||s==="storage.set"||s==="storage.delete"){if(!o.storageService)throw new Error("storageService is not available");const l=`${o.manifest.id}:${String(i[0]??"")}`;if(s==="storage.get")c=o.storageService.get(l);else if(s==="storage.set"){const d=i[1];o.storageService.set(l,typeof d=="string"?d:JSON.stringify(d??null)),c=!0}else o.storageService.delete(l),c=!0}else if(s==="command.invoke"){if(!o.frontendApi)throw new Error("frontendApi is not available");const l=String(i[0]??"");c=await o.frontendApi.post(`/api/plugins/${encodeURIComponent(o.pluginId)}/sandbox-command`,{type:l,payload:i[1]})}else if(s==="ui.register"){const l=String(i[0]??""),d=i[1]&&typeof i[1]=="object"?i[1]:{};Ce.getState().registerExtensionPoint(l,{...d,pluginId:o.pluginId,origin:"runtime"}),c=!0}else if(s==="ui.toast"){const l=String(i[0]??"");o.uiService?.showToast(l,l,"info"),c=!0}else if(s==="context.get"){const l=Se.getState();c={lessonId:l.selectedLesson,classId:l.liveClassSelectedClassId}}else throw new Error(`Unsupported sandbox bridge op "${s}"`);a(!0,c)}catch(c){a(!1,void 0,c instanceof Error?c.message:String(c))}}async activateRemotePlugin(t,n,s){const i=Ce.getState();if(!n||typeof n.id!="string"||!n.id)throw new Error(`Invalid remote plugin manifest for "${t}": missing manifest.id`);const o=i.activePlugins.find(c=>c.id===t);if(o&&(o.state===Le.ACTIVE||o.state===Le.ACTIVATING))return;if(i.updatePluginState(t,Le.ACTIVATING),this.manifests.set(t,n),this.registerManifestContributions(t,n),!(s?.hasFrontend??o?.hasFrontend??!0)){this.pluginModules.set(t,{manifest:n,activate:async()=>{},deactivate:async()=>{}}),i.updatePluginState(t,Le.ACTIVE),Us(t),i.clearPluginError(t);return}try{const c=`/plugins/${t}/frontend.js`,l=await fetch(c,{credentials:"same-origin"});if(!l.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${l.status}`);let d=await l.text();if(window.HostSharedDeps&&(d=OS(d)),o?.executionMode==="inline"){const m=new Blob([d],{type:"text/javascript"}),p=URL.createObjectURL(m);try{const h=await import(p),g=h.default??h,y=g.activate??h.activate,x=g.deactivate??h.deactivate;if(typeof y=="function"){const b=await this.buildContext(t,n);await Promise.race([y(b),new Promise((v,S)=>setTimeout(()=>S(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:y,deactivate:typeof x=="function"?x:void 0})}}finally{URL.revokeObjectURL(p)}}else await this.mountSandboxFrame(t,n,d),this.pluginModules.set(t,{manifest:n,activate:async()=>{},deactivate:async()=>{this.destroySandboxFrame(t)}});i.updatePluginState(t,Le.ACTIVE),Us(t),i.clearPluginError(t)}catch(c){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,c),i.updatePluginState(t,Le.ERROR),this.destroySandboxFrame(t),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),i.setPluginError(t,Ks(c)),c}}async activatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(i=>i.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,Le.ACTIVATING);try{const i=this.sourceCodes.get(t);if(!i)throw new Error(`No source code found for plugin: ${t}`);const o=await this.moduleLoader(i),a=o.default??o,c=a.manifest??o.manifest,l=a.activate??o.activate,d=a.deactivate??o.deactivate;if(!c||typeof l!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(c.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${c.id}"`);this.registerManifestContributions(t,c);const u=await this.buildContext(t,c);await Promise.race([l(u),new Promise((m,p)=>setTimeout(()=>p(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:c,activate:l,deactivate:typeof d=="function"?d:void 0}),n.updatePluginState(t,Le.ACTIVE),Us(t),n.clearPluginError(t),this.manifests.set(t,c)}catch(i){throw n.updatePluginState(t,Le.ERROR),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),n.setPluginError(t,Ks(i)),i}}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(),i=this.sourceCodes.get(t);if(!i)throw new Error(`No source code found for plugin: ${t}`);const o={id:t,name:n.name,version:n.version,capabilitiesProposed:Array.isArray(n.capabilitiesProposed)?[...n.capabilitiesProposed]:[]};s.updatePluginState(t,Le.ACTIVATING);try{let a;if(this.registry)try{a=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:c}=await this.workerManager.createWorker(t,o,i,zS,a);this.pluginModules.set(t,{manifest:o,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(t)}}),s.updatePluginState(t,Le.ACTIVE),s.clearPluginError(t)}catch(a){throw s.updatePluginState(t,Le.ERROR),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),s.setPluginError(t,Ks(a)),a}}async deactivatePlugin(t){const n=Ce.getState(),s=n.activePlugins.find(i=>i.id===t);if(!(!s||s.state!==Le.ACTIVE)){n.updatePluginState(t,Le.DEACTIVATING);try{const i=this.pluginModules.get(t);i?.deactivate&&await Promise.race([i.deactivate(),new Promise((o,a)=>setTimeout(()=>a(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(i){console.error(`[FrontendPluginHost] Deactivation error for "${t}":`,i)}finally{this.unregisterPluginResources(t),this.pluginModules.delete(t),n.updatePluginState(t,Le.INACTIVE)}}}async suspendPlugin(t){const n=Ce.getState();try{const s=this.pluginModules.get(t);s?.deactivate&&await Promise.race([s.deactivate(),new Promise((i,o)=>setTimeout(()=>o(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(s){console.error(`[FrontendPluginHost] Suspend error for "${t}":`,s)}finally{this.unregisterPluginResources(t,{preserveManifestContributions:!0,keepBreakerState:!0}),this.pluginModules.delete(t),n.updatePluginState(t,Le.ERROR),Ce.getState().pluginErrors.get(t)||n.setPluginError(t,"插件前端连续崩溃,已自动降级")}}async retryPlugin(t){const n=Ce.getState(),s=n.activePlugins.find(i=>i.id===t);if(!s)return!1;n.unregisterPluginRuntimeExtensionPoints(t),n.clearPluginError(t);try{const i=this.manifests.get(t);if(s.executionMode==="worker")await this.activatePlugin(t);else if(i)await this.activateRemotePlugin(t,i,{hasFrontend:s.hasFrontend});else if(s.executionMode==="inline")await this.activatePlugin(t);else throw new Error(`无法重试插件 "${t}":缺少 manifest 缓存`);return!0}catch(i){return console.error(`[FrontendPluginHost] Retry failed for plugin "${t}":`,i),n.setPluginError(t,Ks(i)),!1}}async uninstallPlugin(t){const n=Ce.getState();n.activePlugins.find(i=>i.id===t)?.state===Le.ACTIVE&&await this.deactivatePlugin(t);try{await fetch(`/api/plugins/${t}`,{method:"DELETE"})}catch(i){console.error(`[FrontendPluginHost] Failed to DELETE plugin "${t}" on server:`,i)}this.sourceCodes.delete(t),this.pluginModules.delete(t),this.manifests.delete(t),this.unregisterPluginResources(t),n.removePlugin(t),n.clearPluginError(t)}getExtensions(t){return Ce.getState().getExtensions(t)}unregisterPluginResources(t,n){const s=this.disposers.get(t);if(s){const i=s.splice(0);for(const o of i)try{o()}catch(a){console.error(`[FrontendPluginHost] Error releasing subscription for "${t}":`,a)}this.disposers.delete(t)}this.destroySandboxFrame(t),n?.preserveManifestContributions?Ce.getState().unregisterPluginRuntimeExtensionPoints(t):Ce.getState().unregisterPluginExtensionPoints(t),pr.unregisterPlugin(t),Oi.unregisterPlugin(t),ur.unregisterPlugin(t),Nn.unregisterPlugin(t),kS(t),Di.clearOwned(t),Ct.clearOwned(t),Ux(t),n?.keepBreakerState||Us(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(gs),i=await this.registry.resolve(yo),o=await this.registry.resolve(lr),a=await this.registry.resolve(cr),c=this.dispatcher.createScopedDispatcher?this.dispatcher.createScopedDispatcher(t):{dispatch:(l,d)=>this.dispatcher.dispatch(l,{sourcePluginId:t,...d}),registerHandler:(l,d)=>this.dispatcher.registerHandler(l,d),subscribe:(l,d)=>this.dispatcher.subscribe(l,d),use:l=>this.dispatcher.use(l)};return{services:{frontendApi:s,socketService:i,uiService:o,storageService:a},pluginId:t,manifest:n,dispatcher:c,ui:{registerExtensionPoint:(l,d)=>{Ce.getState().registerExtensionPoint(l,{...d,pluginId:t,origin:"runtime"})},unregisterExtensionPoint:(l,d)=>{Ce.getState().unregisterExtensionPoint(l,d,t)},registerFullscreenRenderer:(l,d)=>{pr.register(l,d,t)},unregisterFullscreenRenderer:l=>{pr.unregister(l,t)},registerPropertyEditor:(l,d)=>{Oi.register(l,d,t)},unregisterPropertyEditor:l=>{Oi.unregister(l,t)},registerCoursewareSource:l=>{ur.register(l,t)},unregisterCoursewareSource:l=>{ur.unregister(l,t)},registerPaletteItem:l=>{Nn.register(l,t)},unregisterPaletteItem:l=>{Nn.unregister(l,t)},registerSegmentType:l=>{vu(l,t)},unregisterSegmentType:l=>{jS(l,t)},registerAssignmentQuestionRenderer:l=>{Di.register(l,t)},unregisterAssignmentQuestionRenderer:l=>{Di.unregister(l,t)},registerAssessmentQuestionType:l=>{Ct.register(l,t)},unregisterAssessmentQuestionType:l=>{Ct.unregister(l,t)}},navigation:{getTeacherTab:()=>Se.getState().teacherTab,setTeacherTab:l=>Se.getState().setTeacherTab(l),setSelectedLesson:l=>Se.getState().setSelectedLesson(l),subscribeTeacherTab:l=>{let d=Se.getState().teacherTab;return this.trackDisposer(t,Se.subscribe(u=>{const m=u.teacherTab;m!==d&&(d=m,l(m))}))}},context:{get:()=>{const l=Se.getState();return{lessonId:l.selectedLesson,classId:l.liveClassSelectedClassId}},subscribe:l=>{const d=Se.getState();let u={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};return this.trackDisposer(t,Se.subscribe(m=>{const p={lessonId:m.selectedLesson,classId:m.liveClassSelectedClassId};(p.lessonId!==u.lessonId||p.classId!==u.classId)&&(u=p,l(p))}))}},i18n:{t:(l,d,u)=>{const m=l.includes(":")?l:`${t}:${l}`;return Ad(m,d,u)},getLanguage:()=>Vx()},invokeCommand:async(l,d)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=Pd(l,n.id),m=await s.post("/api/plugins/execute-command",{type:u,payload:d});if(m.success&&m.result!==void 0)return m.result;throw new Error(m.error||"Command execution failed")},registerPanel:l=>{const d=l.slot||"teacher.dashboard.widget";Ce.getState().registerExtensionPoint(d,{...l,pluginId:t,origin:"runtime"})},registerMenu:l=>{const d=l.slot||"teacher.panel";Ce.getState().registerExtensionPoint(d,{...l,pluginId:t,origin:"runtime"})},registerToolbarButton:l=>{Ce.getState().registerExtensionPoint("classroom.tool",{...l,pluginId:t,origin:"runtime"})}}}}class RS{constructor(t){this.frontendApi=t}async saveSemesterGrade(t,n,s){const i=await this.frontendApi.post("/api/grade-sync",{lessonId:t,studentId:n,grade:s});if(!i.success)throw new Error(i.error||"Failed to sync semester grade")}}const ic={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 oc(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 _S(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 i=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\{([\s\S]*)\}$/);if(i){const l=i[1],d=oc(i[2]);return n.push(`const ${l} = ${t}?.default ?? ${t};`),d&&n.push(`const { ${d} } = ${t};`),n.join(" ")}const o=e.match(/^\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(o)return`const ${o[1]} = ${t};`;const a=e.match(/^\{([\s\S]*)\}$/);if(a)return`const { ${oc(a[1])} } = ${t};`;const c=e.match(/^([a-zA-Z_$][\w$]*)$/);return c?`const ${c[1]} = ${t}?.default ?? ${t};`:null}function OS(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>ic[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,i)=>{const o=ic[i];if(!o)return n;const a=_S(s,o);return a||n}),t}function DS(e){if(typeof e!="string"||!e.trim())return null;const t=e.trim();return t.includes("://")||t.startsWith("//")||t.startsWith("\\")||t.includes("..")||/^(javascript|data|blob):/i.test(t)?null:t.replace(/^\/+/,"")}function ac({pluginId:e,view:t,label:n,slot:s,lessonId:i,classId:o,studentId:a,studentName:c,className:l,onResize:d,variant:u="panel",style:m,locked:p=!1}){const h=f.useRef(null),[g,y]=f.useState(!1),[x,b]=f.useState(null),v=ae(P=>P.lang),S=ae(P=>P.selectedLesson),T=ae(P=>P.liveClassSelectedClassId),k=_n(P=>P.theme),w=i!==void 0?i:S,I=o!==void 0?o:T,_=DS(t),R=f.useCallback(()=>{const P=h.current;!P||!P.contentWindow||P.contentWindow.postMessage({channel:Vs,type:"init",payload:{pluginId:e,slot:s,lessonId:w,classId:I,studentId:a??null,studentName:c??null,lang:v,theme:k}},"*")},[e,s,w,I,a,c,v,k]);if(f.useEffect(()=>{const P=async $=>{const V=h.current;if(!V||$.source!==V.contentWindow)return;const z=$.data;if(!(!z||z.channel!==Vs)){if(z.type==="ready"){y(!0),R();return}if(z.type==="resize"&&typeof z.height=="number"&&z.height>0){b(z.height),d?.(z.height);return}if(z.type==="call"&&z.callId&&z.op){const{callId:U,op:j,args:B=[]}=z,q=(C,K,G)=>{V.contentWindow?.postMessage({channel:Vs,type:"reply",callId:U,ok:C,value:K,error:G},"*")};try{if(j==="ui.toast"){const C=String(B[0]??""),K=B[1],G=K==="success"||K==="warning"||K==="error"?K:"info";Se.getState().addToast({id:Math.random().toString(16).slice(2),title:n||e,message:C,type:G}),q(!0,!0)}else if(j==="command.invoke"){const C=String(B[0]??""),K=B[1],G=await fetch(`/api/plugins/${encodeURIComponent(e)}/sandbox-command`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({type:C,payload:K})}),Q=await G.json();!G.ok||Q.success===!1?q(!1,void 0,Q.error||`Command failed with HTTP ${G.status}`):q(!0,Q.result)}else if(j==="api.get"||j==="api.post"||j==="api.del"){const C=String(B[0]??"").replace(/^\/+/,""),K=C.startsWith("api/plugins/")?`/${C}`:`/api/plugins/${encodeURIComponent(e)}/${C}`,Q=await fetch(K,{method:j==="api.get"?"GET":j==="api.post"?"POST":"DELETE",headers:j==="api.post"?{"Content-Type":"application/json"}:void 0,credentials:"include",body:j==="api.post"?JSON.stringify(B[1]):void 0});let ee;try{ee=await Q.json()}catch{ee=await Q.text()}if(Q.ok)q(!0,ee);else{const ue=typeof ee=="object"&&ee!==null&&"error"in ee?String(ee.error):`Request failed with HTTP ${Q.status}`;q(!1,void 0,ue)}}else if(j==="storage.get"){const C=`ol_pv_${e}_${String(B[0]??"")}`,K=localStorage.getItem(C);let G=K;try{G=JSON.parse(K??"")}catch{}q(!0,G??K)}else if(j==="storage.set"){const C=`ol_pv_${e}_${String(B[0]??"")}`,K=typeof B[1]=="string"?B[1]:JSON.stringify(B[1]??null);localStorage.setItem(C,K),q(!0,!0)}else if(j==="storage.delete"){const C=`ol_pv_${e}_${String(B[0]??"")}`;localStorage.removeItem(C),q(!0,!0)}else q(!1,void 0,`Unsupported op "${j}"`)}catch(C){const K=C instanceof Error?C.message:String(C);q(!1,void 0,K)}}}};return window.addEventListener("message",P),()=>{window.removeEventListener("message",P)}},[e,n,d,R]),f.useEffect(()=>{!g||!h.current?.contentWindow||h.current.contentWindow.postMessage({channel:Vs,type:"context-update",payload:{lessonId:w,classId:I,studentId:a??null,studentName:c??null,lang:v,theme:k}},"*")},[w,I,a,c,v,k,g]),!_)return r.jsxs("div",{className:"flex flex-col items-center justify-center p-6 text-center text-red-600 bg-red-50/50 rounded-xl border border-red-200 m-4",children:[r.jsx(Cs,{size:32,className:"mb-2 text-red-500"}),r.jsx("p",{className:"text-sm font-semibold",children:v==="zh"?"非法的插件视图路径":"Invalid Plugin View Path"}),r.jsx("p",{className:"text-xs text-red-400 mt-1 font-mono",children:t||"(empty)"})]});const L=`/plugins/${encodeURIComponent(e)}/${_}`,E=u==="floating",A=p&&E,D=E?`fixed bottom-6 left-6 z-40 flex w-[300px] max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl transition-transform duration-300 ease-out dark:border-slate-700 dark:bg-slate-900 ${l||""}`:`relative w-full h-full flex flex-col min-h-0 bg-white dark:bg-slate-900 ${l||""}`,F={...m||{},...E?{height:`${x??180}px`}:x?{minHeight:`${x}px`}:{},...A?{transform:"translateY(calc(100% + 1.5rem))"}:{}};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`${D}${A?" pointer-events-none":""}`,style:F,"data-plugin-view-variant":u,"data-plugin-view-locked":p?"true":void 0,"data-plugin-view-collapsed":A?"true":void 0,"aria-hidden":A?!0:void 0,children:[!g&&r.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center bg-slate-50/80 dark:bg-slate-900/80 backdrop-blur-2xs transition-opacity duration-200",children:[r.jsx(mt,{size:24,className:"animate-spin text-indigo-500 mb-2"}),r.jsx("span",{className:"text-xs font-medium text-slate-500",children:v==="zh"?"正在加载插件视图...":"Loading plugin view..."})]}),r.jsx("iframe",{ref:h,src:L,title:n||`${e} view`,sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",onLoad:()=>{y(!0),R()},inert:p?!0:void 0,className:`w-full flex-1 border-none transition-opacity duration-200 ${g?"opacity-100":"opacity-0"}${p?" pointer-events-none":""}`}),p&&!E&&r.jsx("div",{"data-testid":"plugin-view-lock-cover",className:"absolute inset-0 z-20 flex items-center justify-center bg-slate-900/15 backdrop-blur-[1px] cursor-not-allowed select-none",title:v==="zh"?"老师已开启全班专注锁定,当前为只读跟随":"Classroom focus lock is on — read-only follow mode",onClick:P=>{P.stopPropagation(),P.preventDefault()},onPointerDown:P=>{P.stopPropagation(),P.preventDefault()},children:r.jsxs("span",{className:"px-2 py-1 rounded-full bg-slate-900/70 text-white text-[10px] font-bold tracking-wide",children:["🔒 ",v==="zh"?"专注锁定中":"Focus locked"]})})]}),A&&r.jsxs("button",{type:"button","data-testid":"plugin-view-lock-collapsed","aria-expanded":!1,"aria-label":v==="zh"?`${n||e} 已收起:老师已开启全班专注锁定`:`${n||e} collapsed: classroom focus lock is on`,title:v==="zh"?"老师已开启全班专注锁定,互动浮层已收起":"Classroom focus lock is on — the floating panel is collapsed",className:"fixed bottom-6 left-6 z-40 flex items-center gap-1 rounded-full border border-slate-300 bg-white/95 px-2.5 py-1.5 text-slate-500 shadow-lg backdrop-blur-xs transition-colors hover:text-slate-700 dark:border-slate-600 dark:bg-slate-800/95 dark:text-slate-300",style:m,onClick:()=>Se.getState().addToast({id:Math.random().toString(16).slice(2),title:n||e,message:v==="zh"?"老师已开启全班专注锁定,互动浮层暂时收起,解锁后自动恢复。":"Classroom focus lock is on — the floating panel is collapsed and will return after unlock.",type:"info"}),children:[r.jsx(sd,{size:14}),r.jsx("span",{className:"text-[10px] font-bold",children:"🔒"})]})]})}const MS=new Set(["student.classroom.overlay"]);function Mi(e){return MS.has(e)?"floating":"panel"}function $i(e,t){Ce.getState().unregisterPluginRuntimeExtensionPoints(e),(t?.suspendPlugin?t.suspendPlugin(e):t?.deactivatePlugin(e))?.catch(i=>console.error(`[ExtensionBreaker] auto-deactivate "${e}" failed:`,i))}function Fi(){return r.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-2",children:[r.jsx(mt,{size:24,className:"text-gray-400 animate-spin"}),r.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}function xn({pluginId:e,message:t,lang:n="zh",compact:s=!1}){const i=Cd(),[o,a]=De.useState(!1),c=n==="zh",l=De.useCallback(()=>{!i||o||(a(!0),i.retryPlugin(e).catch(()=>!1).finally(()=>a(!1)))},[i,e,o]),d=c?"插件加载失败":"Plugin failed to load",u=c?"重试":"Retry";return r.jsxs("div",{role:"alert","data-testid":`plugin-error-state-${e}`,className:`flex flex-col items-center justify-center text-center ${s?"py-4 px-3":"py-10 px-6"}`,children:[r.jsx(Bt,{size:s?20:32,className:"text-amber-500 mb-2","aria-hidden":"true"}),r.jsx("p",{className:`font-semibold text-amber-800 ${s?"text-xs":"text-sm"}`,children:d}),r.jsx("p",{className:"text-xs text-muted mt-1 max-w-md break-words",children:t}),r.jsxs("button",{type:"button",onClick:l,disabled:o||!i,"data-testid":`plugin-retry-btn-${e}`,className:"mt-3 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-amber-700 text-white hover:bg-amber-800 disabled:opacity-60 disabled:cursor-not-allowed transition-colors",children:[o?r.jsx(mt,{size:13,className:"animate-spin","aria-hidden":"true"}):r.jsx(Hr,{size:13,"aria-hidden":"true"}),o?c?"重试中…":"Retrying…":u]})]})}class Bi 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:i}=Hx(n);if(console.error(`[ExtensionBreaker] Plugin "${n}" frontend crash #${i}/${Id}`+(s?" — 达到熔断阈值,自动停用":""),t?.message?.slice(0,120)),s)try{this.props.onBreakerTrip?.(n)}catch(o){console.error("[ExtensionBreaker] breaker trip callback failed:",o)}}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function Ui({pluginId:e,children:t}){return De.useEffect(()=>{e&&qx(e)}),r.jsx(r.Fragment,{children:t})}function Vi({ext:e,route:t,slotProps:n,slot:s}){const i=De.useRef(null),o=JSON.stringify(n||{});De.useEffect(()=>{i.current&&typeof e.render=="function"&&(i.current.innerHTML="",Promise.resolve(e.render(i.current,{route:t,...n})).catch(console.error))},[e,t,o]);const c=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return r.jsx("div",{ref:i,className:`w-full ${c}`})}const Ys=new WeakMap;function Wi(e){const t=e?.component;if(typeof t!="function")return()=>null;const n=Ys.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=De.lazy(t);return Ys.set(t,s),s}if(typeof t=="function"&&!t.prototype?.isReactComponent){let s=!1;const i=De,o=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE||i.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,a=o?.H??o?.ReactCurrentDispatcher?.current;try{o&&("H"in o&&(o.H=null),o.ReactCurrentDispatcher&&(o.ReactCurrentDispatcher.current=null));const c=t();c&&typeof c.then=="function"&&(s=!0)}catch{}finally{o&&("H"in o&&(o.H=a),o.ReactCurrentDispatcher&&(o.ReactCurrentDispatcher.current=a))}if(s){console.error(`[ExtensionPoint] Detected an UNMARKED lazy factory (function returned a Promise). React would suspend forever without throwing. Auto-wrapping with React.lazy; please set \`__isLazyFactory = true\` on the factory or register the component directly. Offending function: ${t.name||"(anonymous)"}`);const c=De.lazy(t);return Ys.set(t,c),c}}return Ys.set(t,t),t}function hs(e,t,n){if(n)return n;if(!e||typeof e.getDispatcher!="function")return;const s=e.getDispatcher();return typeof s?.createScopedDispatcher=="function"?s.createScopedDispatcher(t):s}function $e({slot:e,fallback:t,lang:n,route:s,slotProps:i,placement:o,locked:a=!1}){const c=De.useRef(new Set),l=Cd(),d=Ce(x=>x.activePlugins),u=Ce(x=>x.dashboardVisibility),m=Ce(x=>x.pluginErrors),p=ae(x=>x.selectedLesson),h=ae(x=>x.liveClassSelectedClassId);if(!l)return t??null;let g=l.getExtensions(e);if(o&&(g=g.filter(x=>(x.placement??"after")===o)),e==="assignment.file.preview"){const x=String(i?.fileExtension??"").toLowerCase();if(!x)return null;g=g.filter(b=>{const v=b.slotProps??{},S=Array.isArray(v.extensions)?v.extensions:[];if(Zx(S,x))return!0;const T=Array.isArray(v.mimeTypes)?v.mimeTypes.filter(w=>typeof w=="string").map(w=>w.toLowerCase()):[],k=String(i?.file?.mime??"").toLowerCase();return k!==""&&T.includes(k)})}if(g.length===0)return null;const y=(x,b,v)=>{const S=m.get(x.pluginId);if(S)return r.jsx(xn,{pluginId:x.pluginId,message:S});if(di(x.pluginId))return c.current.has(x.pluginId)||(c.current.add(x.pluginId),console.warn(`[ExtensionBreaker] Plugin "${x.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(xn,{pluginId:x.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"});const T=typeof x.component=="function"&&x.component!==Or,k=typeof x.render=="function",w=!!(x.slotProps?.view||x.view);if(!T&&!k&&!w)return null;const I={...x.slotProps,...b,dispatcher:hs(l,x.pluginId,i?.dispatcher)};return r.jsx(Bi,{pluginId:x.pluginId,onBreakerTrip:_=>$i(_,l),fallback:r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:v}),children:r.jsx(f.Suspense,{fallback:r.jsx(Fi,{}),children:r.jsx(Ui,{pluginId:x.pluginId,children:T?De.createElement(Wi(x),I):k?r.jsx(Vi,{ext:x,route:x.route||s,slotProps:I,slot:e}):r.jsx(ac,{pluginId:x.pluginId,view:String(x.slotProps?.view||x.view),label:x.label,slot:e,lessonId:p,classId:i?.classId||h,studentId:i?.studentId??null,studentName:i?.studentName??null,variant:Mi(e),locked:a})})})},`${x.pluginId}/${x.id}`)};if(e==="class.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:g.map((b,v)=>{const S=`plugin:${b.pluginId}/${b.id}`,T=i?.classActiveTab===S,k=b.title||b.label||b.id,w=mn(k,b.pluginId,x),I=d.find(R=>R.id===b.pluginId),_=b.icon||I?.icon;return r.jsxs("button",{onClick:R=>{R.stopPropagation(),i?.setClassActiveTab?.(S)},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 ${T?"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:w,children:[r.jsx(fn,{icon:_,size:12,className:"shrink-0",alt:w}),r.jsx("span",{children:w})]},`${b.pluginId}/${b.id}`)})})}if(e==="class.tab"&&i?.renderType==="panel"){const x=i?.classActiveTab,b=g.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return b?y(b,{classId:i?.classId,students:i?.students,lang:i?.lang},"扩展 Tab 加载失败"):null}if(e==="timetable.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:g.map((b,v)=>{const S=`plugin:${b.pluginId}/${b.id}`,T=i?.timetableActiveTab===S,k=b.title||b.label||b.id,w=mn(k,b.pluginId,x),I=d.find(R=>R.id===b.pluginId),_=b.icon||I?.icon;return r.jsxs("button",{onClick:R=>{R.stopPropagation(),i?.setTimetableActiveTab?.(S)},className:`px-3 py-1.5 rounded-lg text-xs font-semibold tracking-wide transition-all cursor-pointer flex items-center gap-1.5 ${T?"bg-white text-indigo-700 shadow-sm font-bold":"text-gray-500 hover:text-gray-800"}`,title:w,children:[r.jsx(fn,{icon:_,size:14,className:"shrink-0",alt:w}),r.jsx("span",{children:w})]},`${b.pluginId}/${b.id}`)})})}if(e==="timetable.tab"&&i?.renderType==="panel"){const x=i?.timetableActiveTab,b=g.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return b?y(b,{classes:i?.classes,lessons:i?.lessons,lang:i?.lang,onSchedulesUpdated:i?.onSchedulesUpdated,onClassesUpdated:i?.onClassesUpdated},"课表扩展 Tab 加载失败"):null}if(e==="ai_sidebar.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:g.map((b,v)=>{const S=`plugin:${b.pluginId}/${b.id}`,T=i?.activeTab===S,k=b.title||b.label||b.id,w=mn(k,b.pluginId,x),I=d.find(R=>R.id===b.pluginId),_=b.icon||I?.icon;return r.jsxs("button",{onClick:R=>{R.stopPropagation(),i?.setActiveTab?.(S)},className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 min-w-0 cursor-pointer ${T?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,title:w,children:[r.jsx(fn,{icon:_,size:14,className:"shrink-0",alt:w}),r.jsx("span",{className:"truncate",children:w})]},`${b.pluginId}/${b.id}`)})})}if(e==="ai_sidebar.tab"&&i?.renderType==="panel"){const x=i?.activeTab,b=g.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return b?y(b,{activeTab:i?.activeTab,lang:i?.lang},"扩展面板加载失败"):null}if(e==="admin.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:g.map((b,v)=>{const S=`plugin:${b.pluginId}/${b.id}`,T=i?.adminActiveTab===S,k=b.title||b.label||b.id,w=mn(k,b.pluginId,x),I=d.find(R=>R.id===b.pluginId),_=b.icon||I?.icon;return r.jsxs("button",{onClick:R=>{R.stopPropagation(),i?.setAdminActiveTab?.(S)},className:`px-3.5 py-1.5 text-xs font-bold rounded-lg flex items-center gap-1.5 transition-all cursor-pointer ${T?"bg-white text-indigo-700 shadow-xs":"text-gray-500 hover:text-gray-800"}`,title:w,children:[r.jsx(fn,{icon:_,size:14,className:"shrink-0",alt:w}),r.jsx("span",{children:w})]},`${b.pluginId}/${b.id}`)})})}if(e==="admin.tab"&&i?.renderType==="panel"){const x=i?.adminActiveTab,b=g.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return b?y(b,{currentUserId:i?.currentUserId,currentUserRole:i?.currentUserRole,lang:i?.lang,siteInfo:i?.siteInfo,aiProviders:i?.aiProviders},"管理后台扩展 Tab 加载失败"):null}if(e==="student.profile.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:g.map((b,v)=>{const S=`plugin:${b.pluginId}/${b.id}`,T=i?.studentActiveTab===S,k=b.title||b.label||b.id,w=mn(k,b.pluginId,x),I=d.find(R=>R.id===b.pluginId),_=b.icon||I?.icon;return r.jsxs("button",{onClick:R=>{R.stopPropagation(),i?.setStudentActiveTab?.(S)},className:`px-3 py-1.5 text-xs font-bold rounded-lg flex items-center gap-1.5 transition-all cursor-pointer ${T?"bg-surface text-primary-theme shadow-xs border border-theme/60":"text-muted hover:text-main"}`,title:w,children:[r.jsx(fn,{icon:_,size:14,className:"shrink-0",alt:w}),r.jsx("span",{children:w})]},`${b.pluginId}/${b.id}`)})})}if(e==="student.profile.tab"&&i?.renderType==="panel"){const x=i?.studentActiveTab,b=g.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return b?y(b,{student:i?.student,lessonId:i?.lessonId,classId:i?.classId,lang:i?.lang,progressHistory:i?.progressHistory},"学生画像扩展 Tab 加载失败"):null}if(e==="teacher.tab"&&i?.renderType==="button"){const x=[...g].sort((S,T)=>(S.position??100)-(T.position??100)),b=i?.lang??"zh",v=fo[b];return r.jsx(r.Fragment,{children:x.map(S=>{const T=`${S.pluginId}/${S.id}`,k=i?.teacherTab===T,w=S.title||S.label||S.id,I=mn(w,S.pluginId,b),_=d.find(D=>D.id===S.pluginId),R=S.icon||_?.icon,L=m.has(S.pluginId),E=b==="zh"?`在新标签页打开"${I}"`:`Open "${I}" in a new tab`,A=T.replace(/[^a-zA-Z0-9_-]/g,"_");return r.jsxs("div",{className:`group relative flex items-center rounded-xl transition-all duration-150 ${k?"bg-primary-theme-light text-primary-theme font-bold border border-primary-theme/25 shadow-3xs":"border border-transparent text-muted hover:bg-surface-secondary hover:text-main"} ${L?"ring-1 ring-amber-400/70":""} ${i?.mainNavCollapsed?"justify-center":""}`,title:I,children:[r.jsxs("button",{type:"button",onClick:()=>i?.setTeacherTab?.(T),id:`nav_btn_${A}`,className:`flex items-center gap-2.5 py-2 flex-1 min-w-0 text-sm font-medium focus:outline-none focus-visible:ring-1 focus-visible:ring-primary-theme/50 rounded-lg ${k?"font-bold":""} ${i?.mainNavCollapsed?"justify-center px-2":"pl-2.5 pr-8"}`,children:[r.jsx(fn,{icon:R,size:18,className:"shrink-0",alt:I}),r.jsx("span",{className:i?.mainNavCollapsed?"hidden":"block truncate",children:I})]}),!i?.mainNavCollapsed&&r.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),Ix(T)},id:`nav_btn_${A}_newtab`,"aria-label":E,title:v.openInNewTab,"data-testid":`nav_newtab_${A}`,className:"absolute right-1.5 p-1 rounded-md opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:bg-black/10 dark:hover:bg-white/15 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary-theme/50 transition-opacity text-current",children:r.jsx(rd,{size:12,className:"shrink-0"})})]},`${S.pluginId}/${S.id}`)})})}if(e==="whiteboard.renderer"){const x=i?.elementType;if(!x)return null;const b=g.find(k=>{const w=k;return w.targetType===x||k.id===x||k.route===x||`${k.pluginId}/${k.id}`===x||w.slotProps?.elementType===x||w.slotProps?.targetType===x});if(!b)return null;const v=m.get(b.pluginId);if(v)return r.jsx(xn,{pluginId:b.pluginId,message:v,compact:!0});if(di(b.pluginId))return c.current.has(b.pluginId)||(c.current.add(b.pluginId),console.warn(`[ExtensionBreaker] Plugin "${b.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(xn,{pluginId:b.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh",compact:!0});const S=typeof b.component=="function",T=typeof b.render=="function";return!S&&!T?null:r.jsx(Bi,{pluginId:b.pluginId,onBreakerTrip:k=>$i(k,l),fallback:t??r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-2 text-xs text-red-600 flex items-center justify-center",children:r.jsx("span",{children:n==="zh"?"自定义图元加载失败":"Custom object failed to load"})}),children:r.jsx(f.Suspense,{fallback:t??r.jsx(Fi,{}),children:r.jsx(Ui,{pluginId:b.pluginId,children:S?De.createElement(Wi(b),{...b.slotProps,...i,dispatcher:hs(l,b.pluginId,i?.dispatcher)}):r.jsx(Vi,{ext:b,route:b.route||s,slotProps:{...b.slotProps,...i,dispatcher:hs(l,b.pluginId,i?.dispatcher)},slot:e})})})},`${b.pluginId}/${b.id}`)}return r.jsx(r.Fragment,{children:g.map((x,b)=>{const v=typeof x.component=="function"&&x.component!==Or,S=typeof x.render=="function",T=!!(x.slotProps?.view||x.view);if(e==="teacher.dashboard.widget"&&u.get(x.pluginId)===!1||!v&&!S&&!T)return null;const k=m.get(x.pluginId);return k?r.jsx(xn,{pluginId:x.pluginId,message:k},`${x.pluginId}/${x.id}`):di(x.pluginId)?(c.current.has(x.pluginId)||(c.current.add(x.pluginId),console.warn(`[ExtensionBreaker] Plugin "${x.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(xn,{pluginId:x.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"},`${x.pluginId}/${x.id}`)):r.jsx(Bi,{pluginId:x.pluginId,onBreakerTrip:w=>$i(w,l),fallback:r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:r.jsx("p",{children:n==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:r.jsx(f.Suspense,{fallback:t??r.jsx(Fi,{}),children:r.jsx(Ui,{pluginId:x.pluginId,children:v?De.createElement(Wi(x),{route:x.route||s,lessonId:p,classId:h,dispatcher:hs(l,x.pluginId,i?.dispatcher),...x.slotProps,...i}):S?r.jsx(Vi,{ext:x,route:x.route||s,slotProps:{lessonId:p,classId:h,dispatcher:hs(l,x.pluginId,i?.dispatcher),...x.slotProps,...i},slot:e}):r.jsx(ac,{pluginId:x.pluginId,view:String(x.slotProps?.view||x.view),label:x.label,slot:e,lessonId:p,classId:i?.classId||h,studentId:i?.studentId??null,studentName:i?.studentName??null,variant:Mi(e),locked:a,style:Mi(e)==="floating"&&b>0?{left:`calc(1.5rem + ${b*316}px)`}:void 0})})})},`${x.pluginId}/${x.id}`)})})}const $S=({state:e,onToggleAnonymous:t,onOpenRubricModal:n,onToggleVoiceDanmaku:s,onAdvanceStage:i,onAddMinute:o,onTogglePauseTimer:a,isFullscreen:c,onToggleFullscreen:l,onClose:d})=>{const u=p=>{const h=Math.floor(Math.max(0,p)/60),g=Math.max(0,p)%60;return`${String(h).padStart(2,"0")}:${String(g).padStart(2,"0")}`},m=Math.round(e.completedReviews/Math.max(1,e.totalStudents)*100);return r.jsxs("div",{id:"peer-review-telemetry-header",className:"w-full bg-[#131b2e] border-b border-[#2d3449] px-6 py-3 flex flex-wrap items-center justify-between gap-4 select-none shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"px-2 py-0.5 rounded bg-[#171f33] text-[#908fa0] text-[10px] font-mono font-semibold tracking-wider",children:"STAGE 02.4"}),r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-[#c7c4d7]",children:[r.jsx("span",{children:"随堂巩固"}),r.jsx(En,{size:13,className:"text-[#908fa0]"}),r.jsx("span",{children:"收卷归档"}),r.jsx(En,{size:13,className:"text-[#908fa0]"}),r.jsxs("span",{className:"text-[#4edea3] font-medium flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#4edea3] animate-ping"}),"全班大屏协同互评阶段 ",e.isLocked&&"(已锁定全班终端)"]})]})]}),r.jsx("div",{className:"h-4 w-[1px] bg-[#2d3449] hidden md:block"}),r.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded bg-[#00a572]/20 text-[#4edea3] text-xs font-medium border border-[#00a572]/30",children:[r.jsx(id,{size:14,className:"text-[#4edea3]"}),r.jsxs("span",{children:["教室主大屏协同输出 ",e.isDualScreen?"(4K 双屏模式)":"(投影模式)"]})]})]}),r.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[r.jsxs("div",{className:"flex items-center gap-2 bg-[#060e20] px-3 py-1.5 rounded-xl border border-[#2d3449]/60",children:[r.jsx(Qp,{size:18,className:"text-[#ffb95f] animate-pulse"}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0] leading-none",children:"COUNTDOWN"}),o&&r.jsx("button",{type:"button",onClick:o,className:"text-[10px] text-[#ffb95f] hover:text-[#ffddb8] font-mono transition-colors",title:"加时 1 分钟",children:"+1m"})]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[r.jsxs("span",{className:"text-sm font-semibold font-mono text-[#dae2fd] leading-none",children:[u(e.timeRemainingSeconds),r.jsxs("span",{className:"text-[#908fa0] text-xs font-normal",children:[" / ",u(e.totalTimeSeconds)]})]}),a&&r.jsx("button",{type:"button",onClick:a,className:"text-[#c7c4d7] hover:text-white transition-colors",title:e.isPaused?"恢复倒计时":"暂停倒计时",children:e.isPaused?r.jsx(Yo,{size:12,className:"text-[#4edea3]"}):r.jsx(Jp,{size:12})})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsxs("div",{className:"relative w-8 h-8 flex items-center justify-center",children:[r.jsxs("svg",{className:"w-8 h-8 -rotate-90",viewBox:"0 0 36 36",children:[r.jsx("path",{className:"text-[#2d3449]",d:"M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831",fill:"none",stroke:"currentColor",strokeWidth:"3.5"}),r.jsx("path",{className:"text-[#4edea3] transition-all duration-500",d:"M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831",fill:"none",stroke:"currentColor",strokeDasharray:`${m}, 100`,strokeLinecap:"round",strokeWidth:"3.5"})]}),r.jsxs("span",{className:"absolute text-[9px] font-mono text-[#dae2fd] font-semibold",children:[m,"%"]})]}),r.jsxs("div",{className:"flex flex-col",children:[r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0] leading-none",children:"SUBMISSIONS"}),r.jsxs("span",{className:"text-xs font-medium text-[#dae2fd] mt-0.5",children:[e.completedReviews," / ",e.totalStudents," 人已评"]})]})]}),r.jsxs("div",{className:"hidden lg:flex items-center gap-2 bg-[#171f33] px-3 py-1.5 rounded-xl border border-[#2d3449]/60",children:[r.jsx(Kp,{size:16,className:"text-[#c0c1ff]"}),r.jsxs("div",{className:"flex flex-col",children:[r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0] leading-none",children:"PEER REACTIONS"}),r.jsxs("span",{className:"text-xs font-mono font-medium text-[#c0c1ff] mt-0.5",children:[e.totalLikes," 次点赞 · ",e.totalNominations," 份提名"]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{htmlFor:"toggle-anon",className:"flex items-center gap-2 cursor-pointer bg-[#171f33] px-2.5 py-1.5 rounded-xl hover:bg-[#222a3d] transition-colors border border-[#2d3449]/50",title:"开启后隐藏学生真实姓名",children:[r.jsx("input",{id:"toggle-anon",type:"checkbox",checked:e.isAnonymous,onChange:t,className:"sr-only peer"}),r.jsx("div",{className:"w-7 h-4 bg-[#2d3449] peer-checked:bg-[#4edea3] rounded-full relative transition-colors",children:r.jsx("div",{className:`w-3 h-3 bg-white rounded-full absolute top-0.5 left-0.5 transition-transform ${e.isAnonymous?"translate-x-3":""}`})}),r.jsx("span",{className:"text-xs text-[#c7c4d7] font-medium",children:"双盲匿名"})]}),r.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-[#171f33] hover:bg-[#222a3d] text-[#c7c4d7] hover:text-[#dae2fd] transition-colors text-xs font-medium border border-[#2d3449]/50",children:[r.jsx(Zo,{size:15,className:"text-[#ffb95f]"}),r.jsx("span",{children:"互评量规"})]}),r.jsxs("button",{type:"button",onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-xl transition-colors text-xs font-medium border ${e.showDanmaku?"bg-[#00a572]/20 border-[#00a572]/40 text-[#4edea3]":"bg-[#171f33] border-[#2d3449]/50 text-[#c7c4d7] hover:text-[#dae2fd]"}`,title:"开关大屏弹幕墙",children:[r.jsx(Yp,{size:15,className:"text-[#4edea3]"}),r.jsx("span",{children:"全员语音弹幕"})]}),r.jsxs("button",{type:"button",onClick:i,className:"flex items-center gap-2 px-3.5 py-1.5 rounded-xl bg-[#c0c1ff] text-[#1000a9] hover:bg-[#8083ff] hover:text-white transition-all shadow-sm text-xs font-semibold",children:[r.jsx(Xo,{size:15}),r.jsx("span",{children:"揭晓勋章榜"}),r.jsx("span",{className:"font-mono text-[10px] bg-[#1000a9]/15 px-1 py-0.5 rounded leading-none",children:"Enter"})]}),r.jsx($e,{slot:"peer_review.action"}),l&&r.jsx("button",{type:"button",onClick:l,className:"p-1.5 rounded-xl text-[#c7c4d7] hover:text-white hover:bg-[#222a3d] transition-colors ml-1",title:c?"退出全屏":"全屏展示",children:c?r.jsx(io,{size:16}):r.jsx(ea,{size:16})}),d&&r.jsx("button",{type:"button",onClick:d,className:"p-1.5 rounded-xl text-[#ffb4ab] hover:text-white hover:bg-[#93000a]/50 transition-colors ml-1",title:"关闭大屏互评",children:r.jsx(Re,{size:16})})]})]})},FS=({matchingItems:e,badges:t,isAnonymous:n=!1,onSelectMatchingItem:s})=>{const i=(o,a)=>!a||o.length<=1?o:`${o[0]}**`;return r.jsxs("div",{id:"peer-review-matrix-panel",className:"flex flex-col gap-4 w-full select-none",children:[r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"w-7 h-7 rounded-lg bg-[#c0c1ff]/15 flex items-center justify-center text-[#c0c1ff]",children:r.jsx(od,{size:16})}),r.jsx("h2",{className:"text-sm font-semibold text-[#dae2fd]",children:"智能交叉互评"})]}),r.jsx("span",{className:"px-2 py-0.5 rounded bg-[#8083ff]/20 text-[#c0c1ff] font-mono text-[10px] font-semibold",children:"1生评2份"})]}),r.jsx("p",{className:"text-xs text-[#c7c4d7] leading-relaxed",children:"分层对调机制:将满分逻辑范本与攻坚调试作业交叉分发,激发逆向审阅与自愈思考。"})]}),r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsx("span",{className:"text-[#908fa0] font-mono text-[10px] font-semibold",children:"PEER MATCHING REALTIME"}),r.jsxs("span",{className:"text-[#4edea3] font-mono text-[11px] flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#4edea3] animate-pulse"})," 实时同步中"]})]}),r.jsx("div",{className:"flex flex-col gap-2.5 max-h-[380px] overflow-y-auto pr-0.5",children:e.map(o=>{const a=i(o.reviewerName,n),c=i(o.targetStudentName,n);return r.jsxs("div",{onClick:()=>s?.(o),className:`p-3 rounded-lg border transition-all cursor-pointer ${o.status==="submitted"?"bg-[#222a3d] border-[#4edea3]/40 shadow-sm":"bg-[#171f33] border-[#2d3449]/60 hover:bg-[#222a3d] hover:border-[#464554]"}`,children:[r.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"font-mono text-[11px] text-[#ffb95f] font-semibold",children:o.code}),r.jsxs("span",{className:"text-xs text-[#dae2fd] font-semibold truncate max-w-[130px]",children:[a," ",o.reviewerGroup?`(${o.reviewerGroup})`:""]})]}),o.status==="submitted"&&r.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#00a572]/20 text-[#4edea3]",children:"已提交评语"}),o.status==="in_progress"&&r.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#ca8100]/20 text-[#ffb95f] animate-pulse",children:"正在推导 (2/3)"}),o.status==="completed"&&r.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#00a572]/20 text-[#4edea3] flex items-center gap-1",children:[r.jsx(lt,{size:10})," 已完成"]}),o.status==="improvement"&&r.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#c0c1ff]/20 text-[#c0c1ff]",children:"提出改进建议 💡"})]}),r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-[#c7c4d7] mb-1.5",children:[r.jsx(Nr,{size:12,className:"text-[#908fa0] shrink-0"}),r.jsxs("span",{className:"text-[#c0c1ff] font-medium truncate",children:[c," · ",o.targetWorkTitle]})]}),o.comment&&r.jsxs("div",{className:"bg-[#060e20] p-2 rounded text-xs text-[#c7c4d7] italic border border-[#2d3449]/40 mb-1.5 leading-relaxed",children:['"',o.comment,'"']}),o.progressPercent!==void 0&&o.status==="in_progress"&&r.jsx("div",{className:"w-full bg-[#2d3449] h-1 rounded-full mt-2 overflow-hidden",children:r.jsx("div",{className:"bg-[#ffb95f] h-full rounded-full transition-all duration-300",style:{width:`${o.progressPercent}%`}})}),o.stars!==void 0&&r.jsxs("div",{className:"flex items-center justify-between mt-1.5 pt-1.5 border-t border-[#2d3449]/50",children:[r.jsx("div",{className:"flex text-[#ffb95f]",children:Array.from({length:5}).map((l,d)=>r.jsx(Er,{size:13,className:d<o.stars?"text-[#ffb95f] fill-[#ffb95f]":"text-[#464554]"},d))}),r.jsxs("span",{className:"text-[10px] font-mono text-[#908fa0]",children:[o.score?.toFixed(1)||"5.0"," / ",o.maxScore||"5.0"]})]})]},o.id)})})]}),r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] font-mono font-semibold text-[#908fa0]",children:"LIVE PEER BADGE STREAM"}),r.jsx(ta,{size:14,className:"text-[#908fa0]"})]}),r.jsx("div",{className:"flex flex-col gap-2 overflow-hidden",children:t.map(o=>r.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-[#171f33] border border-[#2d3449]/50 text-xs text-[#dae2fd]",children:[r.jsx("span",{className:"text-sm shrink-0",children:o.emoji}),r.jsxs("div",{className:"truncate",children:[r.jsx("span",{className:"text-[#4edea3] font-medium",children:i(o.senderName,n)}),r.jsx("span",{className:"text-[#c7c4d7] mx-1",children:"为"}),r.jsx("span",{className:"text-[#c0c1ff] font-medium",children:i(o.receiverName,n)}),r.jsx("span",{className:"ml-1 px-1.5 py-0.5 bg-[#222a3d] rounded text-[10px] font-mono text-[#ffb95f]",children:o.badgeTitle})]})]},o.id))}),r.jsx($e,{slot:"peer_review.badge"})]})]})},BS=({workA:e,workB:t,annotations:n,isAnonymous:s=!1,onFullscreenCanvas:i,onSyncSandboxToClass:o,onAddAnnotation:a})=>{const[c,l]=f.useState("visual"),[d,u]=f.useState(!1),[m,p]=f.useState(""),[h,g]=f.useState(null);if(!e&&!t)return null;const y=(v,S)=>!S||v.length<=1?v:`${v[0]}**`,x=v=>{v.preventDefault(),m.trim()&&(a?.(m.trim()),p(""),u(!1))},b=v=>{const S=v.files?.filter(k=>k.isImage||/\.(jpe?g|png|gif|webp|svg)$/i.test(k.name||k.url||""))||[],T=v.files?.filter(k=>!S.includes(k))||[];return r.jsxs("div",{"data-testid":`work-preview-${v.slot}`,className:"w-full h-44 rounded-lg bg-[#060e20] flex flex-col justify-center relative overflow-hidden border border-[#2d3449]/60",children:[r.jsx($e,{slot:"peer_review.work.preview",slotProps:{work:v,slot:v.slot,isAnonymous:s}}),S.length>0?r.jsxs("div",{className:"w-full h-full p-2.5 flex items-center gap-2 overflow-x-auto",children:[S.map((k,w)=>r.jsxs("div",{onClick:()=>k.url&&g(k.url),className:"relative group h-full rounded-md overflow-hidden border border-[#2d3449] bg-[#131b2e] cursor-pointer shrink-0 aspect-4/3 flex items-center justify-center",title:`${k.name} (点击放大)`,children:[r.jsx("img",{src:k.url,alt:k.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}),r.jsxs("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 text-[11px] text-white font-medium",children:[r.jsx(Ps,{size:14}),r.jsx("span",{children:"放大"})]}),r.jsx("span",{className:"absolute bottom-1 left-1 right-1 px-1 py-0.5 rounded bg-black/60 text-[9px] text-[#dae2fd] truncate",children:k.name})]},w)),T.length>0&&r.jsx("div",{className:"h-full flex flex-col justify-center gap-1 shrink-0 pl-1",children:T.map((k,w)=>{const I=mr(k.url);return I?r.jsxs("a",{href:I,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449] text-[11px] text-[#c0c1ff] hover:text-white transition-colors",children:[r.jsx(ai,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:k.name}),r.jsx(rd,{size:11,className:"opacity-70"})]},w):r.jsxs("span",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-[#171f33] border border-[#2d3449] text-[11px] text-[#c0c1ff]",children:[r.jsx(ai,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:k.name})]},w)})})]}):T.length>0?r.jsxs("div",{className:"w-full h-full p-3 flex flex-col gap-2 overflow-y-auto",children:[r.jsxs("div",{className:"text-[11px] text-[#908fa0] flex items-center gap-1 mb-0.5",children:[r.jsx(ld,{size:13,className:"text-[#8083ff]"}),r.jsxs("span",{children:["提交附件 (",T.length," 个文件)"]})]}),T.map((k,w)=>r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg bg-[#131b2e] border border-[#2d3449] text-xs",children:[r.jsxs("div",{className:"flex items-center gap-2 truncate",children:[r.jsx(ai,{size:15,className:"text-[#8083ff] shrink-0"}),r.jsx("span",{className:"text-[#dae2fd] truncate font-medium",children:k.name}),typeof k.size=="number"&&r.jsxs("span",{className:"text-[10px] text-[#908fa0] shrink-0",children:["(",(k.size/1024).toFixed(1)," KB)"]})]}),k.url&&mr(k.url)&&r.jsxs("a",{href:mr(k.url),target:"_blank",rel:"noreferrer",download:k.name,className:"flex items-center gap-1 px-2 py-1 rounded bg-[#171f33] hover:bg-[#222a3d] text-[#c0c1ff] hover:text-white text-[11px] font-medium border border-[#2d3449] transition-colors shrink-0",children:[r.jsx(oo,{size:12}),r.jsx("span",{children:"下载"})]})]},w))]}):v.codeLines&&v.codeLines.length>0?r.jsx("pre",{className:"px-4 py-3 font-mono text-[11px] leading-5 text-[#dae2fd] overflow-y-auto max-h-full whitespace-pre-wrap break-words",children:v.codeLines.map((k,w)=>r.jsx("div",{className:k.isHighlight?"text-[#4edea3]":"",style:{paddingLeft:`${(k.indent||0)*12}px`},children:k.text},w))}):v.textContent?r.jsx("div",{className:"px-4 py-3 font-sans text-xs leading-5 text-[#dae2fd] overflow-y-auto max-h-full whitespace-pre-wrap break-words",children:v.textContent}):r.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 px-6 text-center",children:[r.jsx(eg,{size:28,className:"text-[#4a5570]"}),r.jsxs("span",{className:"text-[11px] text-[#908fa0] leading-relaxed",children:["该作品没有可展示的作答内容",r.jsx("br",{}),r.jsx("span",{className:"text-[10px] opacity-70",children:"(原始作答流水为空或为纯数值型)"})]})]}),v.workContent&&r.jsxs("span",{className:"absolute bottom-2 right-2 text-[10px] font-mono text-[#908fa0] bg-[#131b2e]/90 px-1.5 py-0.5 rounded border border-[#2d3449]/50",children:["真实作答 · ",v.workContent.eventCount," 条事件"]})]})};return r.jsxs("div",{id:"spotlight-dual-work-arena",className:"flex flex-col gap-4 w-full select-none",children:[r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-wrap items-center justify-between gap-3 shadow-md",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#8083ff]/20 flex items-center justify-center text-[#c0c1ff] border border-[#8083ff]/30",children:r.jsx(ad,{size:20})}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h1",{className:"text-base font-bold text-[#dae2fd]",children:"大屏焦点作品对比赏析"}),r.jsxs("span",{className:"px-2 py-0.5 rounded bg-[#ca8100]/20 text-[#ffb95f] font-mono text-[10px] font-semibold flex items-center gap-1 border border-[#ca8100]/30",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#ffb95f] animate-ping"}),"教师激光笔协同标记中"]})]}),r.jsxs("span",{className:"text-xs text-[#c7c4d7] mt-0.5",children:["标杆创新解法 (",e?y(e.studentName,s):"作品 A 待就绪",") ⟷ 经典逆风翻盘解法 (",t?y(t.studentName,s):"作品 B 待就绪",")"]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[o&&r.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#171f33] hover:bg-[#222a3d] text-[#c7c4d7] hover:text-white border border-[#2d3449]/60 transition-colors text-xs font-medium",title:"将对比沙箱推送到全班学生机",children:[r.jsx(Zp,{size:14,className:"text-[#4edea3]"}),r.jsx("span",{children:"同步沙箱至全班"})]}),i&&r.jsx("button",{type:"button",onClick:i,className:"p-2 rounded-lg bg-[#171f33] hover:bg-[#222a3d] text-[#c7c4d7] hover:text-white border border-[#2d3449]/60 transition-colors",title:"全屏沉浸投影",children:r.jsx(ea,{size:16})})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e?r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md relative",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-[#8083ff] text-white flex items-center justify-center font-bold text-xs shadow-sm",children:s?"A":e.studentInitial}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("span",{className:"text-sm font-semibold text-[#dae2fd]",children:[y(e.studentName,s)," (作品 A)"]}),e.sourceLabel&&r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium border ${e.source==="plugin"?"bg-[#8083ff]/15 text-[#c0c1ff] border-[#8083ff]/30":e.source==="assignment"?"bg-[#00a572]/15 text-[#4edea3] border-[#00a572]/30":"bg-[#ca8100]/15 text-[#ffb95f] border-[#ca8100]/30"}`,children:e.sourceLabel})]}),r.jsx("span",{className:"text-[11px] font-mono text-[#908fa0]",children:e.workSubtitle})]})]}),r.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded bg-[#ca8100]/20 text-[#ffb95f] border border-[#ca8100]/30",children:[r.jsx(Er,{size:13,className:"text-[#ffb95f] fill-[#ffb95f]"}),r.jsx("span",{className:"font-mono text-xs font-semibold",children:typeof e.rating=="number"?e.rating.toFixed(1):"—"}),r.jsxs("span",{className:"text-[10px] text-[#908fa0]",children:["(",e.reviewCount??0,"评)"]})]})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.badges?.map((v,S)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${v.colorClass}`,children:v.label},S))}),b(e),e.codeLines?.some(v=>v.comment)?r.jsxs("div",{className:"bg-[#060e20] rounded-lg p-3 font-mono text-[11px] leading-5 border border-[#2d3449]/60 overflow-x-auto text-[#dae2fd]",children:[r.jsxs("div",{className:"text-[#908fa0] mb-1",children:["# ",e.codeTitle??""]}),e.codeLines.filter(v=>v.comment).map((v,S)=>r.jsx("div",{className:v.isHighlight?"bg-[#8083ff]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#908fa0]",children:v.comment})},S))]}):null]}):r.jsxs("div",{"data-testid":"work-slot-a-placeholder",className:"bg-[#131b2e]/60 rounded-xl p-6 flex flex-col items-center justify-center gap-2 border border-dashed border-[#2d3449] min-h-[280px] text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-[#8083ff]/10 text-[#8083ff] flex items-center justify-center font-bold text-sm",children:"A"}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"待选作品 A"}),r.jsx("span",{className:"text-[11px] text-[#908fa0]",children:"请在上方全班作品池中点击「设为焦点 A」进行对比"})]}),t?r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md relative",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-[#00a572] text-white flex items-center justify-center font-bold text-xs shadow-sm",children:s?"B":t.studentInitial}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("span",{className:"text-sm font-semibold text-[#dae2fd]",children:[y(t.studentName,s)," (作品 B)"]}),t.sourceLabel&&r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium border ${t.source==="plugin"?"bg-[#8083ff]/15 text-[#c0c1ff] border-[#8083ff]/30":t.source==="assignment"?"bg-[#00a572]/15 text-[#4edea3] border-[#00a572]/30":"bg-[#ca8100]/15 text-[#ffb95f] border-[#ca8100]/30"}`,children:t.sourceLabel})]}),r.jsx("span",{className:"text-[11px] font-mono text-[#908fa0]",children:t.workSubtitle})]})]}),r.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded bg-[#ca8100]/20 text-[#ffb95f] border border-[#ca8100]/30",children:[r.jsx(Er,{size:13,className:"text-[#ffb95f] fill-[#ffb95f]"}),r.jsx("span",{className:"font-mono text-xs font-semibold",children:typeof t.rating=="number"?t.rating.toFixed(1):"—"}),r.jsxs("span",{className:"text-[10px] text-[#908fa0]",children:["(",t.reviewCount??0,"评)"]})]})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.badges?.map((v,S)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${v.colorClass}`,children:v.label},S))}),b(t),t.codeLines?.some(v=>v.comment)?r.jsxs("div",{className:"bg-[#060e20] rounded-lg p-3 font-mono text-[11px] leading-5 border border-[#2d3449]/60 overflow-x-auto text-[#dae2fd]",children:[r.jsxs("div",{className:"text-[#908fa0] mb-1",children:["# ",t.codeTitle??""]}),t.codeLines.filter(v=>v.comment).map((v,S)=>r.jsx("div",{className:v.isSuccess?"bg-[#00a572]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#4edea3] text-[10px]",children:v.comment})},S))]}):null]}):r.jsxs("div",{"data-testid":"work-slot-b-placeholder",className:"bg-[#131b2e]/60 rounded-xl p-6 flex flex-col items-center justify-center gap-2 border border-dashed border-[#2d3449] min-h-[280px] text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-[#00a572]/10 text-[#00a572] flex items-center justify-center font-bold text-sm",children:"B"}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"待选作品 B"}),r.jsx("span",{className:"text-[11px] text-[#908fa0]",children:"请在上方全班作品池中点击「设为焦点 B」进行并排对比"})]})]}),r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xp,{size:16,className:"text-[#ffb95f]"}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"协同板书标注与点评审阅"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-[10px] font-mono text-[#908fa0]",children:[n.length," 条实时批注挂载"]}),a&&r.jsx("button",{type:"button",onClick:()=>u(!d),className:"text-[11px] text-[#c0c1ff] hover:text-white font-medium transition-colors",children:d?"取消批注":"+ 追加教师批注"})]})]}),d&&r.jsxs("form",{onSubmit:x,className:"flex gap-2",children:[r.jsx("input",{type:"text",value:m,onChange:v=>p(v.target.value),placeholder:"输入大屏协同批注要点...",className:"flex-1 px-3 py-1.5 rounded-lg bg-[#060e20] border border-[#2d3449] text-xs text-[#dae2fd] placeholder-[#908fa0] focus:outline-none focus:border-[#8083ff]"}),r.jsx("button",{type:"submit",className:"px-3 py-1.5 rounded-lg bg-[#c0c1ff] text-[#1000a9] font-semibold text-xs hover:bg-[#8083ff] hover:text-white transition-colors",children:"发送批注"})]}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(v=>r.jsxs("div",{className:"bg-[#171f33] p-3 rounded-lg flex flex-col gap-1.5 relative overflow-hidden border border-[#2d3449]/50",children:[r.jsx("div",{className:"w-1 absolute left-0 top-0 bottom-0",style:{backgroundColor:v.borderColor}}),r.jsxs("div",{className:"flex items-center justify-between pl-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold ${v.authorType==="teacher"?"bg-[#8083ff] text-white":"bg-[#00a572] text-white"}`,children:v.authorRole}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:y(v.authorName,s)})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0]",children:v.timeAgo})]}),r.jsx("p",{className:"text-xs text-[#dae2fd] pl-2 leading-relaxed",children:v.content})]},v.id))})]}),r.jsx($e,{slot:"peer_review.showcase.widget",slotProps:{workA:e,workB:t,annotations:n,isAnonymous:s}}),h&&r.jsx("div",{className:"fixed inset-0 z-[10000] bg-black/80 backdrop-blur-xs flex items-center justify-center p-4",onClick:()=>g(null),children:r.jsxs("div",{className:"relative max-w-4xl max-h-[90vh] bg-[#131b2e] rounded-xl overflow-hidden border border-[#2d3449] shadow-2xl p-2",onClick:v=>v.stopPropagation(),children:[r.jsx("button",{type:"button",onClick:()=>g(null),className:"absolute top-3 right-3 p-1.5 rounded-lg bg-[#060e20]/80 hover:bg-[#060e20] text-white transition-colors",children:r.jsx(Re,{size:18})}),r.jsx("img",{src:h,alt:"Work preview",className:"max-w-full max-h-[85vh] object-contain rounded-lg"})]})})]})},US=({dimensions:e,averagePercentage:t,reactions:n,onReactionClick:s,syncedStudentsCount:i})=>r.jsxs("div",{id:"peer-review-rubric-stats",className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-4 border border-[#2d3449]/60 shadow-md select-none w-full",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"全班三维量规综合达标率"}),r.jsxs("span",{className:"text-[11px] font-mono text-[#4edea3] font-semibold",children:["AVERAGE: ",typeof t=="number"?`${t.toFixed(1)}%`:"—"]})]}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:e.map(o=>r.jsxs("div",{className:"bg-[#171f33] p-2.5 rounded-lg flex flex-col gap-1.5 border border-[#2d3449]/50",children:[r.jsxs("div",{className:"flex justify-between text-xs",children:[r.jsx("span",{className:"text-[#908fa0] truncate",children:o.label}),r.jsxs("span",{className:`font-mono font-medium ${o.colorClass}`,children:[o.percentage,"%"]})]}),r.jsx("div",{className:"w-full bg-[#2d3449] h-1.5 rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${o.barColorClass}`,style:{width:`${o.percentage}%`}})})]},o.id))}),r.jsx($e,{slot:"peer_review.rubric.dimension"}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-1 border-t border-[#2d3449]/40",children:[r.jsx("div",{className:"flex items-center gap-2",children:n.map(o=>r.jsxs("button",{type:"button",onClick:()=>s?.(o.id),className:"flex items-center gap-1.5 px-3 py-1 rounded-full bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449]/60 transition-all text-xs text-[#dae2fd] active:scale-95 group",children:[r.jsx("span",{children:o.emoji}),r.jsx("span",{className:"font-medium group-hover:text-white",children:o.label}),r.jsxs("span",{className:`font-mono font-semibold ${o.colorClass}`,children:["+",o.count]})]},o.id))}),r.jsxs("span",{className:"text-[10px] font-mono text-[#908fa0] flex items-center gap-1",children:[r.jsx(ao,{size:13,className:"text-[#4edea3]"}),typeof i=="number"?`${i}台学生端已同步点赞动画`:"学生端同步状态未知"]})]})]}),VS=({podiumStudents:e,isAnonymous:t=!1,onAwardPeerReviewPoints:n,onArchiveTopWorks:s,onCallStudentMic:i,onInviteScreenShare:o,onAdvanceToStage3:a})=>{const c=(l,d)=>!d||l.length<=1?l:`${l[0]}**`;return r.jsxs("div",{id:"peer-review-leaderboard-panel",className:"flex flex-col gap-4 w-full select-none",children:[r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-3 shadow-md",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(tg,{size:18,className:"text-[#ffb95f]"}),r.jsx("h2",{className:"text-sm font-semibold text-[#dae2fd]",children:"互评推荐先锋榜"})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0] font-semibold",children:"TOP NOMINATED"})]}),r.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(l=>r.jsxs("div",{className:`p-3 rounded-lg border transition-all ${l.rank===1?"bg-[#222a3d] border-[#ffb95f]/40 shadow-sm":"bg-[#171f33] border-[#2d3449]/50 hover:bg-[#222a3d]"} flex flex-col gap-1.5`,children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`w-5 h-5 rounded-full font-mono text-[11px] font-bold flex items-center justify-center ${l.rankBadgeClass}`,children:l.rank}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:c(l.name,t)})]}),r.jsxs("span",{className:"font-mono text-xs font-semibold text-[#ffb95f]",children:[l.votes," 票推荐"]})]}),r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsx("span",{className:"text-[#c7c4d7] truncate max-w-[140px]",children:l.workTitle}),r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${l.tagBadgeClass}`,children:l.honorTitle})]})]},l.rank))})]}),r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-3 shadow-md",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"随堂微勋章即时分发箱"}),r.jsx(Xo,{size:15,className:"text-[#4edea3]"})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("button",{type:"button",onClick:n,className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449]/50 text-[#dae2fd] transition-colors text-xs text-left",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(wt,{size:14,className:"text-[#ffb95f]"}),r.jsx("span",{children:"为全员互评认真学生 +2 积分"})]}),r.jsx("span",{className:"font-mono text-[10px] text-[#4edea3] font-semibold bg-[#00a572]/20 px-1.5 py-0.5 rounded",children:"一键发放"})]}),r.jsxs("button",{type:"button",onClick:s,className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449]/50 text-[#dae2fd] transition-colors text-xs text-left",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(Is,{size:14,className:"text-[#c0c1ff]"}),r.jsx("span",{children:"TOP 2 优秀代码入库数字馆"})]}),r.jsx("span",{className:"font-mono text-[10px] text-[#c0c1ff] font-semibold bg-[#8083ff]/20 px-1.5 py-0.5 rounded",children:"入库归档"})]})]})]}),r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-col gap-3 shadow-md",children:[r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0] font-semibold",children:"TEACHER BROADCAST & STAGE TRANSITION"}),r.jsx("div",{className:"flex flex-col gap-2",children:(()=>{const l=e[0]?.name,d=e[1]?.name??l;return r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",disabled:!l,onClick:()=>l&&i(l),className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449]/50 text-[#dae2fd] transition-colors text-xs text-left disabled:opacity-40 disabled:cursor-not-allowed",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(lo,{size:14,className:"text-[#c0c1ff]"}),r.jsx("span",{children:l?`连麦作者 ${c(l,t)} (分享思路)`:"暂无提名,无法连麦"})]}),r.jsx("span",{className:"text-[#908fa0] text-[10px] font-mono",children:"连线"})]}),r.jsxs("button",{type:"button",disabled:!d,onClick:()=>d&&o(d),className:"w-full flex items-center justify-between px-3 py-2 rounded-lg bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449]/50 text-[#dae2fd] transition-colors text-xs text-left disabled:opacity-40 disabled:cursor-not-allowed",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(id,{size:14,className:"text-[#4edea3]"}),r.jsx("span",{children:d?`邀请 ${c(d,t)} 投屏分享`:"暂无提名,无法投屏"})]}),r.jsx("span",{className:"text-[#908fa0] text-[10px] font-mono",children:"邀请"})]})]})})()}),r.jsx($e,{slot:"peer_review.action"}),r.jsxs("div",{className:"pt-2",children:[r.jsxs("button",{type:"button",onClick:a,className:"w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl bg-[#c0c1ff] text-[#1000a9] hover:bg-[#8083ff] hover:text-white transition-all shadow-md group font-semibold text-xs text-center",children:[r.jsx("span",{children:"结束互评,公布全堂总积分榜与学情报告"}),r.jsx(Nr,{size:14,className:"group-hover:translate-x-1 transition-transform"})]}),r.jsx("div",{className:"text-center mt-2",children:r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0]",children:"HOTKEY: PRESS ENTER TO ADVANCE TO STAGE 03"})})]})]})]})},WS=({isVisible:e,danmakuList:t,onSendDanmaku:n,isAnonymous:s=!1})=>{const[i,o]=f.useState(""),[a,c]=f.useState(!1);if(!e)return null;const l=u=>{u.preventDefault(),i.trim()&&(n?.(i.trim(),"text"),o(""))},d=()=>{n?.("语音弹幕 · 点赞神仙算法!","voice")};return r.jsxs("div",{id:"peer-review-danmaku-overlay",className:"absolute inset-0 pointer-events-none overflow-hidden z-20",children:[t.map(u=>r.jsx("div",{className:"absolute whitespace-nowrap animate-danmaku-slide pointer-events-auto",style:{top:`${u.topPercent??Math.floor(Math.random()*60)+15}%`,right:"-100%"},children:r.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 rounded-full bg-[#131b2e]/85 backdrop-blur-md border border-[#2d3449] shadow-lg text-xs text-[#dae2fd]",children:[u.type==="voice"?r.jsxs("span",{className:"flex items-center gap-1 text-[#4edea3] font-mono text-[11px]",children:[r.jsx(lo,{size:12,className:"animate-pulse"}),r.jsxs("span",{children:[u.voiceDuration||3,"s"]})]}):r.jsx("span",{className:"text-sm",children:"💬"}),r.jsxs("span",{className:"text-[#c0c1ff] font-medium",children:[s&&u.sender.length>1?`${u.sender[0]}**`:u.sender,":"]}),r.jsx("span",{className:u.color||"text-white",children:u.text})]})},u.id)),r.jsx("div",{className:"absolute bottom-4 right-4 pointer-events-auto flex items-center gap-2",children:a?r.jsxs("form",{onSubmit:l,className:"flex items-center gap-1.5 bg-[#131b2e]/95 backdrop-blur-md border border-[#2d3449] p-1.5 rounded-full shadow-xl",children:[r.jsx("input",{type:"text",value:i,onChange:u=>o(u.target.value),placeholder:"发送大屏实时弹幕...",className:"bg-transparent px-3 py-1 text-xs text-white placeholder-[#908fa0] focus:outline-none w-48"}),r.jsx("button",{type:"submit",className:"p-1.5 rounded-full bg-[#c0c1ff] text-[#1000a9] hover:bg-white transition-colors",title:"发送",children:r.jsx(ng,{size:13})}),r.jsx("button",{type:"button",onClick:d,className:"p-1.5 rounded-full bg-[#171f33] hover:bg-[#222a3d] text-[#4edea3] transition-colors",title:"发送语音弹幕",children:r.jsx(lo,{size:13})}),r.jsx("button",{type:"button",onClick:()=>c(!1),className:"px-2 text-xs text-[#908fa0] hover:text-white",children:"收起"})]}):r.jsxs("button",{type:"button",onClick:()=>c(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#131b2e]/90 hover:bg-[#222a3d] backdrop-blur-md border border-[#2d3449] text-xs text-[#c7c4d7] hover:text-white shadow-lg transition-colors cursor-pointer",children:[r.jsx(cd,{size:13,className:"text-[#c0c1ff]"}),r.jsx("span",{children:"发弹幕"})]})})]})},HS=({isOpen:e,onClose:t})=>e?r.jsx("div",{id:"peer-review-rubric-modal",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 select-none",children:r.jsxs("div",{className:"bg-[#131b2e] border border-[#2d3449] rounded-2xl w-full max-w-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[r.jsxs("div",{className:"px-6 py-4 bg-[#171f33] border-b border-[#2d3449] flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-8 h-8 rounded-xl bg-[#ca8100]/20 text-[#ffb95f] flex items-center justify-center border border-[#ca8100]/30",children:r.jsx(Zo,{size:18})}),r.jsxs("div",{children:[r.jsx("h2",{className:"text-sm font-bold text-[#dae2fd]",children:"随堂交叉互评量规细则"}),r.jsx("p",{className:"text-[11px] text-[#908fa0]",children:"三维评价基准 · 激励互助逆向思考"})]})]}),r.jsx("button",{type:"button",onClick:t,className:"p-1.5 rounded-lg text-[#908fa0] hover:text-white hover:bg-[#222a3d] transition-colors",children:r.jsx(Re,{size:18})})]}),r.jsxs("div",{className:"p-6 flex flex-col gap-4 overflow-y-auto",children:[r.jsxs("div",{className:"bg-[#171f33] rounded-xl p-4 border border-[#2d3449]/60 flex flex-col gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-6 h-6 rounded-lg bg-[#8083ff]/20 text-[#c0c1ff] font-mono text-xs font-bold flex items-center justify-center",children:"1"}),r.jsx("span",{className:"text-sm font-semibold text-[#dae2fd]",children:"算法逻辑正确性 (40% 权重)"})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#4edea3] bg-[#00a572]/20 px-2 py-0.5 rounded",children:"全班达标率 98%"})]}),r.jsxs("ul",{className:"text-xs text-[#c7c4d7] space-y-1.5 pl-8 list-disc",children:[r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"5.0分(优秀):"}),"算法逻辑自适应,无死循环或边界越界,自适应笔触与角度动态计算完全闭合。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"4.0分(良好):"}),"核心功能正常,少数极端情况存在未自增或微小卡顿。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"3.0分(需改进):"}),"存在语法报错或死循环,需在互评中指明行号与修复要点。"]})]})]}),r.jsxs("div",{className:"bg-[#171f33] rounded-xl p-4 border border-[#2d3449]/60 flex flex-col gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-6 h-6 rounded-lg bg-[#00a572]/20 text-[#4edea3] font-mono text-xs font-bold flex items-center justify-center",children:"2"}),r.jsx("span",{className:"text-sm font-semibold text-[#dae2fd]",children:"代码规范与缩进 (30% 权重)"})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#4edea3] bg-[#00a572]/20 px-2 py-0.5 rounded",children:"全班达标率 96%"})]}),r.jsxs("ul",{className:"text-xs text-[#c7c4d7] space-y-1.5 pl-8 list-disc",children:[r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"5.0分(优秀):"}),"遵循 PEP8 规范,严格对齐 4 空格缩进,变量语义化规范清晰,关键算子附有说明注释。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"4.0分(良好):"}),"缩进基本统一,可读性良好。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"3.0分(需改进):"}),"Tab 与空格混用,循环体代码未有效缩进。"]})]})]}),r.jsxs("div",{className:"bg-[#171f33] rounded-xl p-4 border border-[#2d3449]/60 flex flex-col gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-6 h-6 rounded-lg bg-[#ca8100]/20 text-[#ffb95f] font-mono text-xs font-bold flex items-center justify-center",children:"3"}),r.jsx("span",{className:"text-sm font-semibold text-[#dae2fd]",children:"创意美感与拓展 (30% 权重)"})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#ffb95f] bg-[#ca8100]/20 px-2 py-0.5 rounded",children:"全班达标率 92%"})]}),r.jsxs("ul",{className:"text-xs text-[#c7c4d7] space-y-1.5 pl-8 list-disc",children:[r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"5.0分(优秀):"}),"巧妙运用数学模运算(`i % 3`)或外角定理,呈现层次丰富的动态发散图形。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"4.0分(良好):"}),"图形规则美观,配色和谐。"]}),r.jsxs("li",{children:[r.jsx("strong",{className:"text-white",children:"3.0分(需改进):"}),"单色基础图形,未探索步长或角度变化。"]})]})]}),r.jsx($e,{slot:"peer_review.rubric.dimension"})]}),r.jsx("div",{className:"px-6 py-3 bg-[#171f33] border-t border-[#2d3449] flex justify-end",children:r.jsx("button",{type:"button",onClick:t,className:"px-4 py-1.5 rounded-xl bg-[#c0c1ff] text-[#1000a9] font-semibold text-xs hover:bg-white transition-colors",children:"我已知晓"})})]})}):null;function qS(e){if(!Array.isArray(e)||e.length===0)return null;let t=0,n=0;for(const s of e){const i=s,o=Number(i.score??i.percentage??i.value);if(!Number.isFinite(o))continue;const a=Number(i.weight??0);!Number.isFinite(a)||a<=0||(t+=o*a,n+=a)}return n<=0?null:Math.round(t/n*10)/10}const GS=({isOpen:e,onClose:t,onAdvanceToStage3:n,lessonTitle:s="",addToast:i,workA:o,workB:a,showcaseWorks:c=[],onSelectSpotlightWork:l,reviewProgress:d,countdownSeconds:u,onAutoAssign:m,autoAssigning:p=!1,matchingItems:h,badges:g,annotations:y,rubricDimensions:x,reactions:b,podiumStudents:v,danmaku:S,syncedStudentsCount:T,teacherName:k,stageLabel:w})=>{const[I,_]=f.useState({stage:w||"",isLocked:!0,isDualScreen:!0,isAnonymous:!0,timeRemainingSeconds:u??0,totalTimeSeconds:u??0,isPaused:!1,completedReviews:d?.completed??0,totalStudents:d?.total??0,totalLikes:0,totalNominations:0,showVoiceDanmaku:!0,showDanmaku:!0}),[R,L]=f.useState(!1),[E,A]=f.useState(!1),[D,F]=f.useState(!1),[P,$]=f.useState(h??[]),[V,z]=f.useState(g??[]),[U,j]=f.useState(o??null),[B,q]=f.useState(a??null),[C,K]=f.useState(y??[]),[G,Q]=f.useState(x??[]),[ee,ue]=f.useState(b??[]),[we,X]=f.useState(v??[]),[pe,ke]=f.useState(S??[]);f.useEffect(()=>{o!==void 0&&j(o??null)},[o]),f.useEffect(()=>{a!==void 0&&q(a??null)},[a]),f.useEffect(()=>{h&&$(h)},[h]),f.useEffect(()=>{g&&z(g)},[g]),f.useEffect(()=>{y&&K(y)},[y]),f.useEffect(()=>{x&&Q(x)},[x]),f.useEffect(()=>{b&&ue(b)},[b]),f.useEffect(()=>{v&&X(v)},[v]),f.useEffect(()=>{S&&ke(S)},[S]),f.useEffect(()=>{if(!e||I.isPaused)return;const N=setInterval(()=>{_(O=>O.timeRemainingSeconds<=1?{...O,timeRemainingSeconds:0,isPaused:!0}:{...O,timeRemainingSeconds:O.timeRemainingSeconds-1})},1e3);return()=>clearInterval(N)},[e,I.isPaused]);const je=f.useCallback(N=>{e&&(N.key==="Enter"?(N.preventDefault(),se()):N.key==="Escape"?(N.preventDefault(),t()):N.code==="Space"&&N.target===document.body&&(N.preventDefault(),te()))},[e,t]);if(f.useEffect(()=>(window.addEventListener("keydown",je),()=>window.removeEventListener("keydown",je)),[je]),!e)return null;const M=()=>{_(N=>({...N,isAnonymous:!N.isAnonymous})),i?.("互评模式已切换",I.isAnonymous?"已恢复显示真实学生姓名":"已开启双盲匿名评价模式","info")},Y=()=>{_(N=>({...N,timeRemainingSeconds:N.timeRemainingSeconds+60,totalTimeSeconds:N.totalTimeSeconds+60})),i?.("互评加时","倒计时已增加 1 分钟","success")},te=()=>{_(N=>({...N,isPaused:!N.isPaused}))},ne=()=>{document.fullscreenElement?document.exitFullscreen&&(document.exitFullscreen().catch(()=>{}),L(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),L(!0))},ie=N=>{ue(O=>O.map(W=>W.id===N?{...W,count:W.count+1}:W)),_(O=>({...O,totalLikes:O.totalLikes+1}))},oe=N=>{const O={id:`ann-${Date.now()}`,authorType:"teacher",authorRole:"主讲教师",authorName:k||"教师",timeAgo:"刚刚",content:N,borderColor:"#8083ff"};K(W=>[O,...W]),i?.("批注已挂载","协同板书批注已同步至大屏","success")},be=(N,O="text")=>{const W={id:`d-${Date.now()}`,sender:k||"教师",text:N,type:O,voiceDuration:void 0,color:"text-[#4edea3]"};ke(H=>[...H,W])},le=()=>{i?.("功能尚未接入","批量积分发放通道建设中,本次未写入任何积分。","warning")},Ne=()=>{i?.("功能尚未接入","作品归档通道建设中,本次未做任何存储。","warning")},Te=N=>{i?.("功能尚未接入",`向 ${N} 发起连麦的信令通道建设中。`,"warning")},Je=N=>{i?.("功能尚未接入",`向 ${N} 的投屏邀请通道建设中。`,"warning")},se=()=>{i?.("互评阶段已结束","正在推进至 Stage 03 结课巡查与全堂总积分榜...","success"),n&&n(),t()};return r.jsxs("div",{id:"peer-review-showcase-modal",className:"fixed inset-0 z-[9999] bg-[#0b1326] text-[#dae2fd] flex flex-col select-none overflow-hidden font-sans",children:[r.jsx($S,{state:I,onToggleAnonymous:M,onOpenRubricModal:()=>A(!0),onToggleVoiceDanmaku:()=>_(N=>({...N,showDanmaku:!N.showDanmaku})),onAdvanceStage:se,onAddMinute:Y,onTogglePauseTimer:te,isFullscreen:R,onToggleFullscreen:ne,onClose:t}),r.jsxs("main",{className:"relative flex-1 overflow-y-auto w-full px-6 py-5",children:[!U&&!B&&c.length===0&&P.length===0&&we.length===0&&r.jsxs("div",{className:"mb-4 rounded-xl border border-[#2d3449] bg-[#0b1326] px-4 py-2.5 flex items-center gap-3 text-[11px] text-[#908fa0]",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),r.jsx("span",{className:"flex-1",children:"本节暂无可展示的互评数据(需至少 2 份学生提交作品)。点击右侧按钮按「1 生评 2 份」自动分配。"}),m&&r.jsx("button",{type:"button",disabled:p,onClick:()=>void m(),className:"px-3 py-1 rounded-lg bg-[#8083ff] text-white text-[11px] font-bold hover:bg-[#9497ff] transition-colors disabled:opacity-50 shrink-0",children:p?"分配中…":"一键分配互评"})]}),c&&c.length>0&&r.jsxs("div",{className:"mb-4 rounded-xl border border-[#2d3449] bg-[#131b2e] p-3 flex flex-col gap-2 shadow-md",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-[#4edea3] animate-pulse"}),r.jsxs("span",{className:"text-xs font-bold text-[#dae2fd]",children:["本节提交作品池(跨来源已聚合 ",c.length," 份作品)"]}),r.jsx("span",{className:"text-[10px] text-[#908fa0]",children:"包含课件作答、课堂作业与插件提交,点击可设为大屏焦点 A / B"})]}),r.jsx("button",{type:"button",onClick:()=>F(!D),className:"px-2.5 py-1 rounded-lg bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449] text-[11px] text-[#c0c1ff] hover:text-white font-medium transition-colors cursor-pointer",children:D?"收起作品池 ▲":`展开作品池 (${c.length}) ▼`})]}),D&&r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2.5 pt-2 border-t border-[#2d3449]/60 max-h-60 overflow-y-auto",children:c.map(N=>{const O=U?.id===N.workId,W=B?.id===N.workId,H=I.isAnonymous&&N.studentName.length>1?`${N.studentName[0]}**`:N.studentName;return r.jsxs("div",{className:`p-2.5 rounded-lg border text-xs flex flex-col gap-1.5 transition-all ${O?"bg-[#8083ff]/15 border-[#8083ff]":W?"bg-[#00a572]/15 border-[#00a572]":"bg-[#171f33] border-[#2d3449]/80 hover:border-[#8083ff]/40"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-1",children:[r.jsx("span",{className:"font-semibold text-[#dae2fd] truncate",children:H}),r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-medium border ${N.source==="plugin"?"bg-[#8083ff]/20 text-[#c0c1ff] border-[#8083ff]/30":N.source==="assignment"?"bg-[#00a572]/20 text-[#4edea3] border-[#00a572]/30":"bg-[#ca8100]/20 text-[#ffb95f] border-[#ca8100]/30"}`,children:N.sourceLabel})]}),r.jsx("div",{className:"text-[11px] text-[#908fa0] truncate",title:N.title,children:N.title}),N.files&&N.files.length>0&&r.jsxs("div",{className:"text-[10px] text-[#8083ff] truncate",children:["📎 ",N.files.length," 个附件 (",N.files.map(Z=>Z.name).join(", "),")"]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-auto pt-1",children:[r.jsx("button",{type:"button",onClick:()=>l?.("A",N.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${O?"bg-[#8083ff] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#8083ff]/40 text-[#dae2fd]"}`,children:O?"焦点 A ★":"设为焦点 A"}),r.jsx("button",{type:"button",onClick:()=>l?.("B",N.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${W?"bg-[#00a572] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#00a572]/40 text-[#dae2fd]"}`,children:W?"焦点 B ★":"设为焦点 B"})]})]},N.workId)})})]}),r.jsx(WS,{isVisible:I.showDanmaku,danmakuList:pe,onSendDanmaku:be,isAnonymous:I.isAnonymous}),r.jsxs("div",{className:"grid grid-cols-12 gap-5 items-start",children:[r.jsx("div",{className:"col-span-12 lg:col-span-3",children:r.jsx(FS,{matchingItems:P,badges:V,isAnonymous:I.isAnonymous,onSelectMatchingItem:N=>{i?.(`查看互评明细 ${N.code}`,`${N.reviewerName} 正在审阅 ${N.targetStudentName} 的作业`,"info")}})}),r.jsxs("div",{className:"col-span-12 lg:col-span-6 flex flex-col gap-4",children:[!U&&!B&&r.jsxs("div",{className:"rounded-xl border border-dashed border-[#2d3449] bg-[#0b1326] p-6 text-center",children:[r.jsx("p",{className:"text-xs font-bold text-[#dae2fd]",children:"暂无提交作品可供对比"}),r.jsx("p",{className:"text-[10px] text-[#908fa0] mt-1",children:"学生提交课件作业后,此处将自动展示两份真实作品的并排对比。"})]}),U||B?r.jsx(BS,{workA:U,workB:B,annotations:C,isAnonymous:I.isAnonymous,onFullscreenCanvas:ne,onSyncSandboxToClass:()=>{i?.("沙箱广播已生效",`对比范本已同步至全班 ${I.totalStudents||0} 台学生机控制台`,"success")},onAddAnnotation:oe}):null,r.jsx(US,{dimensions:G,averagePercentage:qS(G),reactions:ee,onReactionClick:ie,syncedStudentsCount:T})]}),r.jsx("div",{className:"col-span-12 lg:col-span-3",children:r.jsx(VS,{podiumStudents:we,isAnonymous:I.isAnonymous,onAwardPeerReviewPoints:le,onArchiveTopWorks:Ne,onCallStudentMic:Te,onInviteScreenShare:Je,onAdvanceToStage3:se})})]})]}),r.jsx(HS,{isOpen:E,onClose:()=>A(!1)})]})},gr={stage:"IN_CLASS_TEACHING",checkinCode:null,activePoll:null,activeBuzzer:null,pacing:{TOO_FAST:0,CONFUSED:0,CLEAR:0},classId:null,sessionId:null,stageStartedAt:null,attendance:{online:0,onlineInClass:0,expected:0,attended:0},feed:[],courseware:{attempts:0,participants:0,completed:0,avgCompletion:0},exitTicketSubmitted:0},QS=["classroom:stage_changed","classroom:quick_poll_started","classroom:quick_poll_updated","classroom:quick_poll_closed","classroom:buzzer_ready","classroom:buzzer_winner","classroom:buzzer_reset","classroom:pacing_updated","classroom:countdown_updated","classroom:exit_ticket_submitted","classroom:feed_appended","classroom:pulse_check_requested","classroom:checkin_submitted"],JS=4e3;function KS(e,t={}){const{enabled:n=!0,reconcileMs:s=JS}=t,[i,o]=f.useState(gr),[a,c]=f.useState("polling"),[l,d]=f.useState(null),u=f.useRef(0),m=f.useRef(!0);f.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);const p=f.useCallback(async()=>{if(!e)return;const h=++u.current;try{const g=await fetch(`/api/classroom/stage/${encodeURIComponent(e)}/data`);if(!g.ok)throw new Error(`stage data HTTP ${g.status}`);const y=await g.json();if(!m.current||h!==u.current)return;o({...gr,...y,pacing:{...gr.pacing,...y.pacing||{}}}),d(Date.now()),c(x=>x==="reconnecting"?"live":x==="error"?"polling":x)}catch(g){if(!m.current)return;c(y=>y==="live"?"reconnecting":y),console.warn("[StageDisplay] sync failed:",g)}},[e]);return f.useEffect(()=>{if(!n||!e)return;p();const h=setInterval(()=>void p(),s);return()=>clearInterval(h)},[n,e,s,p]),f.useEffect(()=>{if(!n||!e)return;let h=null;const g=()=>{h||(h=setTimeout(()=>{h=null,p()},120))};let y=null;const x=Ea(b=>{y?.(),b.emit("join-room",e);const v=QS.map(w=>{const I=_=>{const R=_?.lessonId;R&&R!==e||g()};return b.on(w,I),[w,I]}),S=()=>{c("live"),p()},T=()=>c("reconnecting"),k=()=>c("reconnecting");b.on("connect",S),b.on("disconnect",T),b.on("connect_error",k),b.connected&&c("live"),y=()=>{for(const[w,I]of v)b.off(w,I);b.off("connect",S),b.off("disconnect",T),b.off("connect_error",k)}});return()=>{x(),y?.(),h&&clearTimeout(h)}},[n,e,p]),{data:i,health:a,lastSyncedAt:l,refresh:p}}const YS={PRE_CLASS_READY:{zh:"课前就绪 · 准备上课",en:"Pre-Class Preparation"},IN_CLASS_TEACHING:{zh:"课中授课 · 互动探索",en:"Interactive Teaching"},WRAP_UP_EXIT_TICKET:{zh:"总结提升 · 结课通票",en:"Wrap-Up & Exit Ticket"},ARCHIVED_REPORT:{zh:"下课归档 · 学情简报",en:"Archived Report"}};function Aa(e,t="zh"){const n=YS[e];return n?t==="zh"?n.zh:n.en:e}let lc=0;function Dt(e){return lc+=1,`${e}-${Date.now().toString(36)}-${lc}`}function ZS(e,t,n={}){const{lang:s="zh",isFirstFrame:i=!1}=n,o=s==="zh",a=[];if(!e||i)return a;if(e.stage!==t.stage){const h=Aa(t.stage,s),g=t.stage==="ARCHIVED_REPORT",y=t.stage==="WRAP_UP_EXIT_TICKET";let x;y?x=o?"请提醒学生在设备上完成 60 秒结课通票":"Remind students to complete the 60s exit ticket":g&&(x=o?"本课节已归档,大屏将展示学情简报":"Lesson archived; the stage will show the learning report");let b="info",v="🎓";y?(b="accent",v="🎫"):g&&(b="warning",v="📦"),a.push({id:Dt("stage"),tone:b,icon:v,title:o?`课堂环节已切换:${h}`:`Stage changed: ${h}`,detail:x,dedupeKey:`stage:${t.stage}`})}const c=e.activePoll?.id??null,l=t.activePoll?.id??null;if(l&&l!==c)a.push({id:Dt("poll-start"),tone:"accent",icon:"⚡",title:o?"课堂极速投票已开始":"Quick poll started",detail:t.activePoll?.title?String(t.activePoll.title):void 0,dedupeKey:`poll-start:${l}`});else if(c&&!l){const h=e.activePoll?.totalVotes??0;a.push({id:Dt("poll-end"),tone:"info",icon:"📊",title:o?"课堂投票已结束":"Quick poll closed",detail:o?`本轮共 ${h} 人作答`:`${h} responded in this round`,dedupeKey:`poll-end:${c}`})}const d=e.activeBuzzer?.id??null,u=t.activeBuzzer?.id??null,m=e.activeBuzzer?.status??null,p=t.activeBuzzer?.status??null;if(u&&u!==d)a.push({id:Dt("buzz-start"),tone:"accent",icon:"🔔",title:o?"抢答已开始":"Buzz-in started",detail:t.activeBuzzer?.title?String(t.activeBuzzer.title):void 0,dedupeKey:`buzz-start:${u}`});else if(u&&u===d&&p==="LOCKED"&&m!=="LOCKED"){const h=t.activeBuzzer?.winnerName,g=t.activeBuzzer?.responseTimeMs;a.push({id:Dt("buzz-winner"),tone:"success",icon:"🏆",title:o?"抢答已产生赢家":"Buzz-in winner decided",detail:h?o?`${h}${g?` · 响应用时 ${g} 毫秒`:""}`:`${h}${g?` · ${g} ms`:""}`:void 0,dedupeKey:`buzz-winner:${u}`})}else u&&u===d&&p==="READY"&&m==="LOCKED"&&a.push({id:Dt("buzz-reset"),tone:"info",icon:"♻️",title:o?"抢答已重置,可以开始新一轮":"Buzzer reset — ready for a new round",dedupeKey:`buzz-reset:${u}`});return a}function XS(e,t,n="zh"){const s=n==="zh";return e===t?null:e==="reconnecting"?{id:Dt("conn"),tone:"warning",icon:"📡",title:s?"实时连接已断开,正在重连":"Live connection lost, reconnecting…",detail:s?"大屏内容可能不是最新,将以低频轮询兜底":"Falling back to low-frequency polling",dedupeKey:"conn:reconnecting"}:e==="live"&&t==="reconnecting"?{id:Dt("conn"),tone:"success",icon:"✅",title:s?"实时连接已恢复":"Live connection restored",dedupeKey:"conn:live"}:null}const cc={info:{ring:"border-sky-500/50 bg-sky-500/10 text-sky-200",icon:dd},success:{ring:"border-emerald-500/50 bg-emerald-500/10 text-emerald-200",icon:lt},warning:{ring:"border-amber-500/50 bg-amber-500/10 text-amber-200",icon:Bt},accent:{ring:"border-indigo-500/50 bg-indigo-500/10 text-indigo-200",icon:wt}},ej=6e3,dc=8e3;function tj({notices:e,onDismiss:t,lang:n="zh"}){const s=e.slice(-4),i=f.useRef(new Map);return f.useEffect(()=>{for(const a of s){if(i.current.has(a.id))continue;const c=setTimeout(()=>{i.current.delete(a.id),t(a.id)},ej);i.current.set(a.id,c)}const o=new Set(s.map(a=>a.id));for(const[a,c]of i.current)o.has(a)||(clearTimeout(c),i.current.delete(a))},[s,t]),f.useEffect(()=>()=>{for(const o of i.current.values())clearTimeout(o);i.current.clear()},[]),s.length===0?null:r.jsx("div",{"aria-live":"polite","data-testid":"stage-notice-stack",className:"fixed top-24 right-8 z-[10000] flex flex-col gap-2.5 w-[360px] pointer-events-none",children:s.map(o=>{const a=cc[o.tone]??cc.info,c=a.icon;return r.jsxs("div",{"data-testid":"stage-notice","data-dedupe-key":o.dedupeKey,className:`pointer-events-auto flex items-start gap-3 px-4 py-3 rounded-2xl border backdrop-blur-md shadow-2xl animate-slide-up ${a.ring}`,children:[r.jsx("span",{className:"text-xl leading-none shrink-0 mt-0.5","aria-hidden":"true",children:o.icon}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(c,{size:14,className:"shrink-0"}),r.jsx("span",{className:"text-sm font-bold truncate",children:o.title})]}),o.detail&&r.jsx("p",{className:"text-xs opacity-80 mt-1 line-clamp-2",children:o.detail})]}),r.jsx("button",{onClick:()=>t(o.id),"aria-label":n==="zh"?"关闭提示":"Dismiss",className:"shrink-0 p-1 rounded-lg opacity-60 hover:opacity-100 hover:bg-white/10 transition-colors cursor-pointer",children:r.jsx(Re,{size:14})})]},o.id)})})}function nj(e="zh"){const[t,n]=f.useState([]),s=f.useRef(new Map),i=f.useCallback(c=>{if(c.length===0)return;const l=Date.now();n(d=>{let u=d;for(const m of c){const p=s.current.get(m.dedupeKey);if(!(p&&l-p<dc)){s.current.set(m.dedupeKey,l);for(const[h,g]of s.current)l-g>dc&&s.current.delete(h);u=[...u,m]}}return u.length>40?u.slice(u.length-40):u})},[]),o=f.useCallback(c=>{n(l=>l.filter(d=>d.id!==c))},[]),a=f.useCallback(()=>n([]),[]);return{notices:t,push:i,dismiss:o,clear:a}}function sj({health:e,lastSyncedAt:t,lang:n="zh"}){const s=n==="zh",o={live:{label:s?"实时连接":"Live",cls:"text-emerald-300 border-emerald-500/40 bg-emerald-500/10",dot:"bg-emerald-400 animate-pulse",Icon:ao},reconnecting:{label:s?"重连中":"Reconnecting",cls:"text-amber-300 border-amber-500/40 bg-amber-500/10",dot:"bg-amber-400 animate-ping",Icon:rl},polling:{label:s?"轮询同步":"Polling",cls:"text-sky-300 border-sky-500/40 bg-sky-500/10",dot:"bg-sky-400",Icon:ao},error:{label:s?"连接异常":"Error",cls:"text-rose-300 border-rose-500/40 bg-rose-500/10",dot:"bg-rose-400",Icon:rl}}[e],a=o.Icon,c=t?new Date(t).toLocaleTimeString():"--:--:--";return r.jsxs("div",{"data-testid":"stage-connection-badge","data-health":e,className:`flex items-center gap-2 px-3 py-2 rounded-xl border font-semibold text-xs ${o.cls}`,title:s?`最近同步:${c}`:`Last sync: ${c}`,children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${o.dot}`}),r.jsx(a,{size:13}),r.jsx("span",{children:o.label}),r.jsx("span",{className:"font-mono opacity-70",children:c})]})}function rj(){if(typeof document>"u")return!1;const e=document.documentElement;return!!(e.requestFullscreen||e.webkitRequestFullscreen)}function Zs(){return typeof document>"u"?!1:!!(document.fullscreenElement||document.webkitFullscreenElement)}function ij(){const[e,t]=f.useState(!1),[n,s]=f.useState(!1),i=f.useRef(!1);f.useEffect(()=>{if(typeof document>"u")return;const l=()=>{const d=Zs();s(d),d||(i.current=!1,t(!1))};return document.addEventListener("fullscreenchange",l),document.addEventListener("webkitfullscreenchange",l),()=>{document.removeEventListener("fullscreenchange",l),document.removeEventListener("webkitfullscreenchange",l)}},[]),f.useEffect(()=>{if(typeof window>"u")return;const l=d=>{d.key==="Escape"&&(Zs()||i.current&&(i.current=!1,t(!1)))};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[]);const o=f.useCallback(async()=>{if(t(!0),!rj()){i.current=!0;return}try{const l=document.documentElement;await(l.requestFullscreen?.()??l.webkitRequestFullscreen?.()),s(!0)}catch(l){i.current=!0,console.warn("[ViewportFullscreen] native fullscreen rejected, falling back to viewport fill:",l)}},[]),a=f.useCallback(async()=>{if(i.current=!1,t(!1),s(!1),Zs())try{await document.exitFullscreen?.()}catch(l){console.warn("[ViewportFullscreen] exit failed:",l)}},[]),c=f.useCallback(()=>{Zs()||i.current?a():o()},[o,a]);return{isFullscreen:e,nativeActive:n,toggle:c,exit:a}}function Tt(e){return typeof e=="number"&&Number.isFinite(e)?String(e):"—"}function js(e,t){return!t||t<=0?"—":`${Math.round(e/t*100)}%`}function oj({attendance:e,zh:t=!0}){const n=e?.onlineInClass??0,s=e?.expected??0,i=e?.attended??0,o=js(n,s),a=s>0;return r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-6 shadow-xl flex flex-col gap-4",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-slate-800/80 pb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white font-bold text-base",children:[r.jsx(Jo,{size:18,className:"text-blue-400"}),r.jsx("span",{children:t?"课堂出勤":"Attendance"})]}),r.jsxs("span",{"data-testid":"stage-attendance-online",className:"flex items-center gap-1.5 text-xs font-semibold text-emerald-300",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),t?"实时在线":"Online"," ",Tt(n)]})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsx("div",{className:"text-2xl font-black font-mono text-white",children:Tt(n)}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"本班在线":"Online"})]}),r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsx("div",{className:"text-2xl font-black font-mono text-white",children:Tt(i)}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"已到课":"Attended"})]}),r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsx("div",{className:"text-2xl font-black font-mono text-white",children:Tt(s)}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"应到":"Expected"})]})]}),a?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400",children:[r.jsx("span",{children:t?"实到率":"Attendance rate"}),r.jsx("span",{className:"font-mono font-bold text-white",children:js(i,s)})]}),r.jsx("div",{className:"h-3 w-full bg-slate-800 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-blue-500 rounded-full transition-all duration-500",style:{width:js(i,s)}})}),r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400",children:[r.jsx("span",{children:t?"当前在线率":"Live online rate"}),r.jsx("span",{className:"font-mono font-bold text-emerald-300",children:o})]})]}):r.jsx("p",{className:"text-[11px] text-slate-400 leading-relaxed",children:t?"本课节未绑定班级名单,暂无应到/实到口径(避免用 0% 误导为「无人到课」)。":"No class roster bound to this lesson; expected/attended is unavailable."})]})}function aj({stats:e,zh:t=!0}){const n=e?.attempts??0,s=e?.participants??0,i=e?.completed??0,o=e?.avgCompletion??0,a=n>0;return r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-6 shadow-xl flex flex-col gap-4",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-slate-800/80 pb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white font-bold text-base",children:[r.jsx(sg,{size:18,className:"text-amber-400"}),r.jsx("span",{children:t?"互动课件参与":"Courseware Activity"})]}),a&&r.jsxs("span",{className:"text-xs text-slate-400 font-mono",children:[n," ",t?"次作答":"attempts"]})]}),a?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsx("div",{className:"text-2xl font-black font-mono text-white",children:Tt(s)}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"参与人数":"Students"})]}),r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsx("div",{className:"text-2xl font-black font-mono text-white",children:Tt(i)}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"已完成":"Completed"})]}),r.jsxs("div",{className:"bg-slate-800/50 rounded-2xl border border-slate-700/50 py-3",children:[r.jsxs("div",{className:"text-2xl font-black font-mono text-white",children:[Tt(o),"%"]}),r.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:t?"平均完成度":"Avg done"})]})]}),r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400",children:[r.jsx("span",{children:t?"完成率":"Completion rate"}),r.jsx("span",{className:"font-mono font-bold text-white",children:js(i,n)})]}),r.jsx("div",{className:"h-3 w-full bg-slate-800 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-amber-500 rounded-full transition-all duration-500",style:{width:js(i,n)}})})]}):r.jsxs("p",{className:"text-[11px] text-slate-400 leading-relaxed flex items-center gap-2",children:[r.jsx(Zo,{size:14,className:"shrink-0"}),t?"还没有学生打开互动课件。展示口径为平台累计(含往期课节),作答数据将在学生开始操作后实时出现。":"No courseware activity yet."]})]})}const lj={quiz_answered:"✅",checkin:"🙋",achievement:"🏅",assignment_submitted:"📄",assignment_graded:"🖊️",progress:"📈",courseware_submitted:"🖥️",answer:"💡",success:"🎉",info:"ℹ️"};function cj({feed:e,zh:t=!0}){const n=e??[];return r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-6 shadow-xl flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-slate-800/80 pb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white font-bold text-base",children:[r.jsx(ta,{size:18,className:"text-blue-400"}),r.jsx("span",{children:t?"课堂动态":"Live Feed"})]}),r.jsxs("span",{className:"text-xs text-slate-400 font-mono",children:[n.length," ",t?"条":"items"]})]}),n.length>0?r.jsx("ul",{className:"flex flex-col gap-1.5 max-h-64 overflow-y-auto no-scrollbar",children:n.map(s=>r.jsxs("li",{className:"flex items-start gap-2 text-xs text-slate-300 px-2 py-1.5 rounded-lg hover:bg-slate-800/50 transition-colors",children:[r.jsx("span",{"aria-hidden":"true",className:"shrink-0",children:lj[s.type]??"•"}),r.jsxs("span",{className:"flex-1 leading-relaxed break-words",children:[s.actorName?r.jsx("span",{className:"font-bold text-white",children:s.actorName}):null,r.jsx("span",{className:"ml-1",children:s.message})]}),s.at>0&&r.jsx("span",{className:"shrink-0 font-mono text-[10px] text-slate-400",children:new Date(s.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},s.id))}):r.jsxs("p",{className:"text-[11px] text-slate-400 leading-relaxed flex items-center gap-2",children:[r.jsx(ud,{size:14,className:"shrink-0"}),t?"课堂动态会在学生答题、签到、提交课件时实时出现在这里。":"Live events will appear here."]})]})}function dj({submitted:e,expected:t,zh:n=!0}){const s=e??0,i=t??0;return r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(rg,{size:13,className:"text-indigo-400"}),n?"结课通票已提交":"Exit tickets submitted"]}),r.jsxs("span",{className:"font-mono font-bold text-white",children:[Tt(s),i>0?` / ${Tt(i)}`:""]})]})}function uj({lessonId:e,lessonTitle:t="互动课堂",data:n,lang:s="zh",health:i,lastSyncedAt:o,showCloseButton:a=!0,onClose:c,peerReview:l,syncedStudentsCount:d,peerReviewOpen:u,onOpenPeerReview:m,onClosePeerReview:p}){const{isFullscreen:h,toggle:g}=ij(),[y,x]=f.useState(""),[b,v]=f.useState(!1),S=u??b,T=I=>{u===void 0&&v(I),I?m?.():p?.()};f.useEffect(()=>{const I=()=>{x(new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}))};I();const _=setInterval(I,1e3);return()=>clearInterval(_)},[]);const k=n.pacing??gr.pacing,w=(k.TOO_FAST||0)+(k.CONFUSED||0)+(k.CLEAR||0);return r.jsxs("div",{id:"stage-display-modal",className:"fixed inset-0 z-[9999] bg-slate-950 text-slate-100 flex flex-col select-none overflow-hidden",children:[r.jsxs("header",{className:"h-20 px-8 bg-slate-900/80 border-b border-slate-800 flex items-center justify-between backdrop-blur-md",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 bg-blue-500/10 border border-blue-500/30 rounded-full text-blue-400 font-semibold text-sm",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-blue-400 animate-ping"}),r.jsx("span",{children:s==="zh"?"大屏教学展台":"Stage Display"})]}),r.jsx("h1",{className:"text-2xl font-bold tracking-tight text-white line-clamp-1",children:t}),r.jsx("span",{className:"px-3 py-1 bg-slate-800 text-slate-300 text-xs font-mono rounded-md border border-slate-700",children:Aa(n.stage,s)})]}),r.jsxs("div",{className:"flex items-center gap-6",children:[i&&r.jsx(sj,{health:i,lastSyncedAt:o??null,lang:s}),r.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-slate-800/60 rounded-xl border border-slate-700/60 font-mono text-xl font-bold text-slate-200",children:[r.jsx(zs,{size:20,className:"text-blue-400"}),r.jsx("span",{children:y})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($e,{slot:"stage.display.action",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s,onToggleFullscreen:g,onOpenPeerReview:()=>T(!0)}}),r.jsxs("button",{id:"stage-peer-review-toggle",type:"button",onClick:()=>T(!0),className:"flex items-center gap-1.5 px-3 py-2 bg-teal-500/20 hover:bg-teal-500/30 text-teal-300 rounded-xl transition-colors border border-teal-500/40 text-xs font-semibold cursor-pointer",title:"进入全班大屏作业互评与协同赏析模式 (Stitch 21e2dac1)",children:[r.jsx(ad,{size:15}),r.jsx("span",{children:"作业互评赏析"})]}),r.jsx("button",{id:"stage-fullscreen-toggle",onClick:g,className:"p-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl transition-colors border border-slate-700 cursor-pointer",title:h?"退出全屏":"全屏展示",children:h?r.jsx(ig,{size:20}):r.jsx(og,{size:20})}),a&&r.jsx("button",{id:"stage-close-button",onClick:c,className:"p-3 bg-rose-900/40 hover:bg-rose-900/70 text-rose-300 rounded-xl transition-colors border border-rose-800/50 cursor-pointer",title:"关闭展台",children:r.jsx(Re,{size:20})})]})]})]}),r.jsx("div",{className:"max-h-12 overflow-hidden shrink-0",children:r.jsx($e,{slot:"classroom.stage.display.ticker",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,lang:s}})}),r.jsxs("main",{className:"flex-1 p-8 grid grid-cols-12 gap-8 overflow-y-auto",children:[r.jsxs("section",{className:"col-span-8 flex flex-col gap-6",children:[n.stage==="PRE_CLASS_READY"&&r.jsxs("div",{className:"flex-1 bg-gradient-to-br from-slate-900 to-slate-800 rounded-3xl border border-slate-800 p-10 flex flex-col justify-center items-center text-center shadow-2xl",children:[r.jsx("div",{className:"p-4 bg-blue-500/10 rounded-3xl border border-blue-500/20 text-blue-400 mb-6",children:r.jsx(ud,{size:48,className:"animate-pulse"})}),r.jsx("h2",{className:"text-3xl font-extrabold text-white mb-2",children:s==="zh"?"即将开始上课,请同学们准备":"Class Starting Soon"}),r.jsx("p",{className:"text-slate-400 text-lg mb-8 max-w-md",children:s==="zh"?"请打开平板或电脑进入课堂,输入口令加入":"Please join the interactive session using your device"}),n.checkinCode&&r.jsxs("div",{className:"px-10 py-6 bg-slate-800/90 rounded-2xl border border-blue-500/40 shadow-inner flex flex-col items-center",children:[r.jsx("span",{className:"text-xs uppercase tracking-widest text-slate-400 font-bold mb-2",children:s==="zh"?"课堂入课口令":"Class Code"}),r.jsx("span",{className:"text-6xl font-mono font-black tracking-wider text-blue-400",children:n.checkinCode})]})]}),n.activePoll&&r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-8 shadow-xl flex flex-col gap-6",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-slate-800/80 pb-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"p-2.5 bg-amber-500/10 text-amber-400 rounded-xl border border-amber-500/20",children:r.jsx(wt,{size:24})}),r.jsxs("div",{children:[r.jsx("span",{className:"text-xs font-bold text-amber-400 uppercase tracking-wide",children:s==="zh"?"课堂极速互动":"Quick Activity"}),r.jsx("h3",{className:"text-xl font-bold text-white",children:n.activePoll.title})]})]}),r.jsxs("div",{className:"text-right",children:[r.jsx("span",{className:"text-3xl font-black text-amber-400 font-mono",children:n.activePoll.totalVotes||0}),r.jsx("span",{className:"text-xs text-slate-400 block",children:s==="zh"?"人已作答":"Responded"})]})]}),r.jsx("div",{className:"grid grid-cols-2 gap-4 my-2",children:(Array.isArray(n.activePoll.options)&&n.activePoll.options.length>0?n.activePoll.options:[]).map(I=>{const _=n.activePoll.distribution?.[I]||0,R=Math.round(_/(n.activePoll.totalVotes||1)*100);return r.jsxs("div",{className:"p-5 bg-slate-800/50 rounded-2xl border border-slate-700/50 flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-10 h-10 rounded-xl bg-blue-600 text-white font-bold text-lg flex items-center justify-center shadow-md",children:I}),r.jsxs("span",{className:"font-semibold text-slate-200 text-lg",children:["选项 ",I]})]}),r.jsxs("span",{className:"font-mono font-bold text-xl text-blue-400",children:[R,"% (",_,")"]})]}),r.jsx("div",{className:"h-4 w-full bg-slate-700/40 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-indigo-500 transition-all duration-500 rounded-full",style:{width:`${R}%`}})})]},I)})})]}),n.activeBuzzer&&r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-8 shadow-xl flex flex-col items-center text-center justify-center",children:[r.jsx("div",{className:"p-4 bg-rose-500/10 rounded-2xl border border-rose-500/20 text-rose-400 mb-4",children:r.jsx(na,{size:36,className:"animate-bounce"})}),r.jsx("h3",{className:"text-2xl font-bold text-white mb-2",children:n.activeBuzzer.title}),n.activeBuzzer.status==="READY"?r.jsxs("div",{className:"my-6 py-6 px-12 bg-rose-950/30 border border-rose-500/30 rounded-2xl",children:[r.jsx("span",{className:"text-4xl font-extrabold text-rose-400 animate-pulse block",children:s==="zh"?"⚡ 全班抢答中...":"⚡ Buzzing in progress..."}),r.jsx("span",{className:"text-sm text-slate-400 mt-2 block",children:s==="zh"?"请按手中的抢答按钮!":"Press your buzzer now!"})]}):r.jsxs("div",{className:"my-6 py-6 px-12 bg-emerald-950/30 border border-emerald-500/40 rounded-2xl flex flex-col items-center",children:[r.jsx(Xo,{size:48,className:"text-amber-400 mb-2"}),r.jsx("span",{className:"text-sm text-emerald-400 font-bold tracking-wide uppercase",children:s==="zh"?"🎉 抢答成功!":"🎉 First to Buzz!"}),r.jsx("span",{className:"text-5xl font-black text-white my-2 font-mono",children:n.activeBuzzer.winnerName||"同学"}),n.activeBuzzer.responseTimeMs&&r.jsx("span",{className:"text-sm font-mono text-emerald-300",children:s==="zh"?`响应用时:${n.activeBuzzer.responseTimeMs} 毫秒`:`Reaction time: ${n.activeBuzzer.responseTimeMs} ms`})]})]}),n.stage==="WRAP_UP_EXIT_TICKET"&&r.jsxs("div",{className:"bg-gradient-to-br from-indigo-950/40 to-slate-900 rounded-3xl border border-indigo-800/40 p-8 shadow-xl flex flex-col items-center text-center",children:[r.jsx(ag,{size:48,className:"text-indigo-400 mb-4"}),r.jsx("h3",{className:"text-3xl font-extrabold text-white mb-2",children:s==="zh"?"60 秒结课通票 (Exit Ticket)":"60s Exit Ticket"}),r.jsx("p",{className:"text-slate-300 text-lg max-w-lg mb-6",children:s==="zh"?"请同学们打开设备完成本次课堂评估:选星级、写下今天最困惑的一个知识点。":"Please complete your 60-second summary ticket on your device."})]}),!n.activePoll&&!n.activeBuzzer&&n.stage!=="PRE_CLASS_READY"&&n.stage!=="WRAP_UP_EXIT_TICKET"&&r.jsxs("div",{className:"flex-1 min-h-[220px] bg-gradient-to-br from-slate-900 to-slate-800 rounded-3xl border border-slate-800 p-10 flex flex-col justify-center items-center text-center",children:[r.jsx("div",{className:"p-4 bg-slate-800/60 rounded-3xl border border-slate-700/50 text-slate-400 mb-5",children:r.jsx(Wr,{size:40})}),r.jsx("h3",{className:"text-2xl font-extrabold text-white mb-2",children:s==="zh"?"等待课堂互动":"Waiting for classroom activity"}),r.jsx("p",{className:"text-slate-400 text-base max-w-lg",children:s==="zh"?"当前没有进行中的投票或抢答。教师发起互动后,这里会立刻展示实时结果;右侧的出勤、课件参与与课堂动态为实时数据。":"No poll or buzz-in is running. Real-time results will appear here; attendance and activity metrics are live on the right."})]}),r.jsx($e,{slot:"stage.display.card",slotProps:{lessonId:e,stage:n.stage}})]}),r.jsxs("aside",{className:"col-span-4 flex flex-col gap-6",children:[r.jsx(oj,{attendance:n.attendance,zh:s==="zh"}),r.jsx(aj,{stats:n.courseware,zh:s==="zh"}),n.stage==="WRAP_UP_EXIT_TICKET"&&r.jsx("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-5 shadow-xl",children:r.jsx(dj,{submitted:n.exitTicketSubmitted,expected:n.attendance?.expected,zh:s==="zh"})}),r.jsx(cj,{feed:n.feed,zh:s==="zh"}),r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-6 shadow-xl flex flex-col gap-4",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-slate-800/80 pb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white font-bold text-base",children:[r.jsx(lg,{size:18,className:"text-blue-400"}),r.jsx("span",{children:s==="zh"?"学习节奏晴雨表":"Pacing Barometer"})]}),r.jsxs("span",{className:"text-xs text-slate-400 font-mono",children:[w," ",s==="zh"?"次反馈":"signals"]})]}),r.jsxs("div",{className:"flex flex-col gap-3 my-1",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsxs("span",{className:"flex items-center gap-2 text-emerald-300 font-medium",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-emerald-400"}),s==="zh"?"听懂了 / 节奏合适":"Clear & Smooth"]}),r.jsx("span",{className:"font-mono font-bold text-white",children:k.CLEAR||0})]}),r.jsx("div",{className:"h-3 w-full bg-slate-800 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-emerald-500 rounded-full transition-all duration-500",style:{width:`${w>0?(k.CLEAR||0)/w*100:0}%`}})}),r.jsxs("div",{className:"flex items-center justify-between text-sm pt-2",children:[r.jsxs("span",{className:"flex items-center gap-2 text-amber-300 font-medium",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-amber-400"}),s==="zh"?"有些困惑 / 需点拨":"Confused"]}),r.jsx("span",{className:"font-mono font-bold text-white",children:k.CONFUSED||0})]}),r.jsx("div",{className:"h-3 w-full bg-slate-800 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-amber-500 rounded-full transition-all duration-500",style:{width:`${w>0?(k.CONFUSED||0)/w*100:0}%`}})}),r.jsxs("div",{className:"flex items-center justify-between text-sm pt-2",children:[r.jsxs("span",{className:"flex items-center gap-2 text-rose-300 font-medium",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-rose-400"}),s==="zh"?"讲太快了 / 跟不上":"Too Fast"]}),r.jsx("span",{className:"font-mono font-bold text-white",children:k.TOO_FAST||0})]}),r.jsx("div",{className:"h-3 w-full bg-slate-800 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full bg-rose-500 rounded-full transition-all duration-500",style:{width:`${w>0?(k.TOO_FAST||0)/w*100:0}%`}})})]}),r.jsx("p",{className:"text-xs text-slate-400 text-center mt-2",children:s==="zh"?"提示:此数据来自学生端匿名点击,自动脱敏保护学生自尊。":"Aggregated anonymized signals from student devices."})]})]})]}),S&&r.jsx(GS,{isOpen:S,onClose:()=>T(!1),lessonTitle:t,syncedStudentsCount:d,...l??{}}),r.jsx("div",{className:"absolute inset-0 pointer-events-none z-30 overflow-hidden",children:r.jsx($e,{slot:"stage.display.overlay",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s}})})]})}const hj=/\b(function|const|let|var|class|def|import|return|if|for|while|print|console)\b|[{};]\s*$/;function fj(e){const t=Array.isArray(e)?e.filter(Boolean):[];if(t.length===0)return{kind:"empty",lines:[],eventCount:0};const n=t.filter(u=>{const m=String(u?.eventType??u?.event_type??"").toLowerCase();return m.includes("submit")||m.includes("finish")||m.includes("complete")}),s=n.length>0?n:t,i=s[s.length-1],o=i?.payload??i?.payloadJson??i?.data??{},a=pj(o,["code","source","src","program","html","content","answer"]);if(a&&(hj.test(a)||a.includes(`
59
+ `)||a.length>120))return{kind:"code",lines:a.split(`
60
+ `).slice(0,14).map(u=>({text:u.slice(0,160),indent:Math.floor((u.match(/^\s*/)?.[0].length??0)/2),isHighlight:/correct|answer|正确|对|错|✓|✗/i.test(u)})),eventCount:t.length};const c=Object.entries(o).filter(([,u])=>typeof u!="object"||u===null),l=c.filter(([u])=>!mj.has(u.toLowerCase()));if(l.length>=3)return{kind:"structured",lines:l.slice(0,10).map(([u,m])=>({text:`${u}: ${gj(m)}`,indent:0})),eventCount:t.length};if(a)return{kind:"text",lines:a.split(`
61
+ `).slice(0,12).map(u=>({text:u.slice(0,200),indent:0})),eventCount:t.length};const d=c.filter(([,u])=>typeof u=="number");return d.length>0?{kind:"numeric",lines:d.slice(0,6).map(([u,m])=>({text:`${u}: ${m}`,indent:0})),eventCount:t.length}:{kind:"empty",lines:[],eventCount:t.length}}const mj=new Set(["type","score","comment","completion","timestamp","t","watch","attemptsd","eventtype","payload"]);function pj(e,t){for(const n of t){const s=e?.[n];if(typeof s=="string"&&s.trim())return s}return null}function gj(e){return e==null?"—":Array.isArray(e)?e.map(t=>String(t)).join("、"):typeof e=="object"?JSON.stringify(e):String(e)}const xj={code:"代码",text:"文本作答",structured:"结构化答案",numeric:"数值结果",empty:"无内容"},uc={workA:null,workB:null,matchingItems:[],badges:[],podiumStudents:[],danmaku:[],reactions:[],rubricDimensions:[],reviewProgress:{completed:0,total:0},fromServer:!1};function hc(e,t,n){if(!e)return null;const s=e.studentName||"学生",i=n[e.workId]||(e.codeSnippet||e.textContent?{kind:e.codeSnippet?"code":"text",lines:(e.codeSnippet||e.textContent||"").split(`
62
+ `).slice(0,16).map(a=>({text:a.slice(0,160),indent:0})),eventCount:1}:null),o=i?.lines?.length?i.lines:e.codeSnippet?e.codeSnippet.split(`
63
+ `).slice(0,16).map(a=>({text:a,indent:0})):void 0;return{id:e.workId,slot:t,studentName:s,studentInitial:s.slice(0,1),workTitle:e.title||`${s} · ${e.sourceLabel}`,workSubtitle:`${e.sourceLabel}${typeof e.score=="number"?` · 得分 ${e.score}`:""}`,source:e.source,sourceLabel:e.sourceLabel,textContent:e.textContent,files:e.files,submittedAt:e.submittedAt,badges:[],workContent:i??null,codeTitle:e.title?`${e.sourceLabel} · ${e.title}`:void 0,codeLines:o}}function bj({lessonId:e,enabled:t,attempts:n,studentCount:s,addToast:i,lang:o="zh"}){const[a,c]=f.useState([]),[l,d]=f.useState(null),[u,m]=f.useState([]),[p,h]=f.useState(null),[g,y]=f.useState(null),[x,b]=f.useState(!1),v=f.useCallback((R,L)=>{R==="A"?h(L):y(L)},[]);f.useEffect(()=>{if(!e){c([]);return}let R=!0;const L=async()=>{try{const A=await fetch(`/api/classroom/sessions/${e}/top-performers?limit=50`);if(!A.ok||!R)return;const D=await A.json(),F=Array.isArray(D?.topPerformers)?D.topPerformers:[];if(!R)return;c(F.map(P=>({studentId:String(P.studentId??""),studentName:String(P.studentName??""),cumulativeScore:Number(P.cumulativeScore)||0,accuracy:Number(P.accuracy)||0})))}catch{}};L();const E=setInterval(()=>void L(),2e4);return()=>{R=!1,clearInterval(E)}},[e]);const[S,T]=f.useState({}),k=f.useCallback(async R=>{if(R)try{const L=await fetch(`/api/courseware/attempts/${encodeURIComponent(R)}/raw`);if(!L.ok)return;const E=await L.json(),A=Array.isArray(E?.events)?E.events:Array.isArray(E)?E:[];if(A.length===0)return;T(D=>({...D,[R]:fj(A)}))}catch{}},[]);f.useEffect(()=>{const R=[...n].filter(L=>L?.studentId&&L.studentId!=="teacher"&&L.studentId!=="guest").sort((L,E)=>(Number(E.score)||0)-(Number(L.score)||0)).slice(0,2);for(const L of R)L.attemptId&&!S[L.attemptId]&&k(String(L.attemptId))},[n,S,k]);const w=f.useCallback(async()=>{if(!e){d(null),m([]);return}try{const[R,L]=await Promise.all([fetch(`/api/classroom/sessions/${e}/peer-review`),fetch(`/api/classroom/sessions/${e}/showcase-works`)]);if(R.ok){const E=await R.json();d(E),Array.isArray(E?.showcaseWorks)&&E.showcaseWorks.length>0&&m(E.showcaseWorks)}if(L.ok){const E=await L.json();Array.isArray(E?.works)&&E.works.length>0&&m(E.works)}}catch{}},[e]);f.useEffect(()=>{if(!t)return;w();const R=setInterval(()=>void w(),5e3);return()=>clearInterval(R)},[t,w]);const I=f.useCallback(async()=>{if(e){b(!0);try{const R=await fetch(`/api/classroom/sessions/${e}/peer-review/auto-assign`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({perStudent:2})}),L=await R.json().catch(()=>null);if(!R.ok){i?.(o==="zh"?"分配失败":"Assign failed",L?.error??`HTTP ${R.status}`,"error");return}i?.(o==="zh"?"✅ 互评已分配":"✅ Peer reviews assigned",o==="zh"?`${L.works} 份作品 · 生成 ${L.tasks} 条任务(口径:${L.scope==="lesson"?"本课节作品池":"本班全部"})`:`${L.tasks} tasks created`,"success"),await w()}finally{b(!1)}}},[e,i,o,w]);return{data:f.useMemo(()=>{const R=n.filter(P=>P?.studentId&&P.studentId!=="teacher"&&P.studentId!=="guest"),L=[...R].sort((P,$)=>(Number($.score)||0)-(Number(P.score)||0)),E=(P,$)=>{if(!P)return null;const V=String(P.studentName||P.studentId),z=typeof P.score=="number"?P.score:null,U=String(P.attemptId??`work-${$}`),j=S[U];return{id:U,slot:$,studentName:V,studentInitial:V.slice(0,1),workTitle:`${V} · ${P.coursewareName??"课件作品"}`,workSubtitle:z===null?P.status==="completed"?"已完成提交":"作答中":`得分 ${z}${typeof P.completion=="number"?` · 完成度 ${Math.round(P.completion*100)}%`:""}`,source:"courseware",sourceLabel:"课件作答",badges:[],workContent:j??null,codeTitle:j?`真实作答内容(${xj[j.kind]})`:void 0,codeLines:j?.lines.length?j.lines:void 0}};let A=null,D=null;if(u.length>0){const P=u.find(V=>V.workId===p)||u[0],$=u.find(V=>V.workId===g)||u.find(V=>V.workId!==P?.workId)||u[1];A=hc(P,"A",S),D=hc($,"B",S)}else A=E(L[0],"A"),D=E(L[1],"B");const F=l?.podiumStudents?.length>0?l.podiumStudents:a.slice(0,3).map((P,$)=>({rank:$+1,name:P.studentName,votes:P.cumulativeScore,workTitle:`${P.accuracy}% 正确率`,honorTitle:$===0?"本节最高分":"优秀表现",rankBadgeClass:$===0?"bg-[#ffb95f] text-[#2a1700]":"bg-[#171f33] text-[#908fa0]",tagBadgeClass:"bg-[#ca8100]/20 text-[#ffb95f]"}));return l?.matchingItems?.length||l?.podiumStudents?.length?{...uc,workA:A,workB:D,matchingItems:l.matchingItems??[],badges:l.badges??[],podiumStudents:F,danmaku:l.danmaku??[],reactions:l.reactions??[],rubricDimensions:l.dimensions??[],reviewProgress:l.progress??{completed:0,total:0},fromServer:!0}:{...uc,workA:A,workB:D,podiumStudents:F,reviewProgress:{completed:R.filter(P=>P.status==="completed").length,total:s}}},[l,n,a,s,S,u,p,g]),topPerformers:a,showcaseWorks:u,selectedWorkAId:p,selectedWorkBId:g,setSpotlightWork:v,autoAssigning:x,autoAssign:I,refresh:w}}function yj({lessonId:e,lessonTitle:t="互动课堂",lang:n="zh"}){const{data:s,health:i,lastSyncedAt:o}=KS(e),{notices:a,push:c,dismiss:l}=nj(n),[d,u]=f.useState(!1),[m,p]=f.useState([]),[h,g]=f.useState("");f.useEffect(()=>{if(!d||!e)return;let T=!1;return(async()=>{try{const k=await fetch("/api/courseware/attempts?pageSize=all");k.ok&&!T&&p(In(await k.json()))}catch{}})(),()=>{T=!0}},[d,e]),f.useEffect(()=>{let T=!1;return(async()=>{try{const k=await fetch("/api/auth/session");if(k.ok&&!T){const w=await k.json();g(String(w?.session?.name??w?.session?.username??""))}}catch{}})(),()=>{T=!0}},[]);const y=bj({lessonId:e,enabled:d,attempts:m,studentCount:s.attendance?.expected??0,lang:n}),x=f.useMemo(()=>({workA:y.data.workA,workB:y.data.workB,matchingItems:y.data.matchingItems,badges:y.data.badges,podiumStudents:y.data.podiumStudents,danmaku:y.data.danmaku,reactions:y.data.reactions,rubricDimensions:y.data.rubricDimensions,reviewProgress:y.data.reviewProgress,onAutoAssign:y.autoAssign,autoAssigning:y.autoAssigning,syncedStudentsCount:s.attendance?.onlineInClass,teacherName:h,stageLabel:Aa(s.stage,n)}),[y,s.attendance,h,s.stage,n]),b=f.useRef(null),v=f.useRef(!0),S=f.useRef(i);return f.useEffect(()=>{if(v.current){v.current=!1,b.current=s;return}const T=b.current;b.current=s,T&&c(ZS(T,s,{lang:n,isFirstFrame:!1}))},[s,n,c]),f.useEffect(()=>{const T=XS(i,S.current,n);S.current=i,T&&c([T])},[i,n,c]),e?r.jsxs(r.Fragment,{children:[r.jsx(uj,{lessonId:e,lessonTitle:t,data:s,lang:n,health:i,lastSyncedAt:o,peerReviewOpen:d,onOpenPeerReview:()=>u(!0),onClosePeerReview:()=>u(!1),peerReview:x,showCloseButton:!1}),r.jsx(tj,{notices:a,onDismiss:l,lang:n})]}):r.jsxs("div",{className:"fixed inset-0 z-[9999] bg-slate-950 text-slate-100 flex flex-col items-center justify-center gap-3",children:[r.jsx("div",{className:"text-5xl",children:"📺"}),r.jsx("h1",{className:"text-2xl font-extrabold",children:n==="zh"?"大屏展台 · 等待课节":"Stage Display · Waiting for lesson"}),r.jsx("p",{className:"text-slate-400 text-sm max-w-md text-center px-6",children:n==="zh"?"请在教师端「在线课堂」中选择要授课的课节,这里会自动接入对应课堂的实时数据。":"Select a lesson in the teacher console; the stage will connect to it automatically."})]})}function wj(e){const t=kt(),n=e.session!==void 0?e.session:t?.session,s=e.activeRole??t?.activeRole??"teacher",i=e.setActiveRole??t?.setActiveRole??(()=>{}),o=e.isStudentLiveMode??t?.isStudentLiveMode??!1,a=e.isStudentPreviewMode??t?.isStudentPreviewMode??!1,c=e.lang??t?.lang??"zh",l=e.students??t?.students??[],d=e.activeStudentId!==void 0?e.activeStudentId:t?.activeStudentId??null;return n?.role==="teacher"&&s==="student"&&!o?r.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:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.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:[r.jsx(Ps,{size:12}),c==="zh"?a?"学生视角预览":"学生模拟模式":a?"Student Preview":"Student View Mode"]}),r.jsx("span",{children:c==="zh"?`您当前正在以学生身份(${l.find(u=>u.id===d)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${l.find(u=>u.id===d)?.name||"None"}).`})]}),r.jsxs("button",{type:"button",onClick:()=>{if(a){window.close();return}i("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:[a?r.jsx(Re,{size:13}):r.jsx(Ur,{size:13}),c==="zh"?a?"关闭此预览标签页":"退出模拟并返回教师端":a?"Close Preview Tab":"Exit Student View"]})]}):null}function vj({userId:e,lang:t,onOpenProfile:n}){const s=`edu_os_default_pwd_hint_dismissed_${e||"unknown"}`,[i,o]=f.useState(()=>{try{return localStorage.getItem(s)==="1"}catch{return!1}});if(i)return null;const a=()=>{o(!0);try{localStorage.setItem(s,"1")}catch{}},c=t==="zh";return r.jsxs("div",{id:"student_default_password_banner",role:"status",className:"flex items-center gap-2 px-4 py-1.5 text-xs bg-amber-50 dark:bg-amber-950/40 text-amber-800 dark:text-amber-200 border-b border-amber-200 dark:border-amber-900/50",children:[r.jsx(Br,{size:13,className:"shrink-0","aria-hidden":"true"}),r.jsx("span",{className:"flex-1",children:c?"你当前仍在使用初始默认密码,建议尽快修改以保护账号安全。":"You are still using the initial default password. Please change it soon to protect your account."}),r.jsx("button",{type:"button",onClick:n,className:"shrink-0 px-2 py-0.5 rounded-md font-semibold bg-amber-100 dark:bg-amber-900/60 hover:bg-amber-200 dark:hover:bg-amber-900 text-amber-900 dark:text-amber-100 border border-amber-300 dark:border-amber-800 transition-colors",children:c?"去修改":"Change now"}),r.jsx("button",{type:"button",onClick:a,"aria-label":c?"关闭提示":"Dismiss hint",className:"shrink-0 p-1 rounded-md hover:bg-amber-100 dark:hover:bg-amber-900/60 transition-colors",children:r.jsx(Re,{size:13,"aria-hidden":"true"})})]})}const fs="openlearn_timetable_ocr_task",Hi="openlearn_timetable_ocr_draft";function fc(e){try{const t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Xs(e,t,n=[]){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{if(n.length>0&&t&&typeof t=="object")try{const s={...t};for(const i of n)s[i]=null;sessionStorage.setItem(e,JSON.stringify(s))}catch{}}}function mc(e){try{sessionStorage.removeItem(e)}catch{}}const Sj=jt((e,t)=>({timetableOcrTask:fc(fs),timetableOcrDraft:fc(Hi),isAnyTaskRunning:!1,startTimetableOcr:async({imageBase64:n,lang:s,providerId:i,fileName:o})=>{const a=`task_ocr_${Date.now()}`,c={id:a,type:"timetable_ocr",title:s==="zh"?"课表图片 AI 识别":"Timetable Image AI Recognition",status:"running",startedAt:Date.now(),meta:{fileName:o}};e({timetableOcrTask:c,isAnyTaskRunning:!0}),Xs(fs,c),Ve.getState().addToast({id:`toast_start_${a}`,title:s==="zh"?"⏳ 课表识别已在后台启动":"⏳ Timetable OCR Running in Background",message:s==="zh"?"大模型正在后台分析提取课表内容,您可以继续进行其他操作,识别完成后将通过通知提醒您。":"AI is analyzing your timetable image in the background. You can navigate freely; you will be notified upon completion.",type:"info"});try{const l=await fetch("/api/timetable/ocr",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({imageBase64:n,lang:s,providerId:i||void 0})}),d=await l.json();if(!l.ok||!d.success)throw new Error(d.error||(s==="zh"?"识别请求失败":"OCR recognition failed"));const u=Array.isArray(d.entries)?d.entries:[],m={...c,status:"completed",completedAt:Date.now(),result:{entries:u,providerUsed:d.providerUsed}};e({timetableOcrTask:m,isAnyTaskRunning:!1}),Xs(fs,m),Ve.getState().addToast({id:`toast_done_${a}`,title:s==="zh"?"🎉 AI 课表识别完成":"🎉 Timetable OCR Completed",message:s==="zh"?`已成功从图片中解析出 ${u.length} 节课程,点击前往核对并导入。`:`Successfully parsed ${u.length} timetable entries. Click to review and import.`,type:"success",action:{label:s==="zh"?"查看并导入课表":"View Timetable",onClick:()=>{Se.getState().setTeacherTab("timetable"),Ve.getState().setPendingTimetableSubTab("ocr_import")}}})}catch(l){console.error("[AsyncTask] Timetable OCR failed:",l);const d={...c,status:"failed",completedAt:Date.now(),error:l?.message||(s==="zh"?"未知识别错误":"Unknown OCR error")};e({timetableOcrTask:d,isAnyTaskRunning:!1}),Xs(fs,d),Ve.getState().addToast({id:`toast_fail_${a}`,title:s==="zh"?"AI 课表识别失败":"Timetable OCR Failed",message:l?.message||(s==="zh"?"请检查图片是否清晰可见,或前往「系统管理 -> AI 提供商管理」检查模型连通性。":"Please check the image quality or AI provider settings."),type:"error"})}},setTimetableOcrDraft:n=>{const s={imagePreview:null,imageBase64:null,fileName:"",providerId:"",entries:[],selected:[],...t().timetableOcrDraft||{},...n,updatedAt:Date.now()};e({timetableOcrDraft:s}),Xs(Hi,s,["imagePreview","imageBase64"])},clearTimetableOcrTask:()=>{e({timetableOcrTask:null,isAnyTaskRunning:!1,timetableOcrDraft:null}),mc(fs),mc(Hi)}})),jj=e=>Ut(Sj,e);function kj({session:e,lang:t,onLogout:n,onProfile:s}){const[i,o]=f.useState(!1),a=f.useRef(null);f.useEffect(()=>{if(!i)return;const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[i]);const c=(l,d)=>t==="zh"?l:d;return r.jsxs("div",{className:"relative",ref:a,children:[r.jsxs("button",{type:"button",onClick:()=>o(l=>!l),"aria-haspopup":"menu","aria-expanded":i,title:e.name,className:"flex items-center gap-1 rounded-full p-1 hover:bg-gray-100 transition-colors cursor-pointer",children:[r.jsx("span",{className:"w-9 h-9 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:e.avatar?r.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):r.jsx(sn,{size:20})}),r.jsx(Tn,{size:14,className:`text-gray-400 transition-transform duration-200 ${i?"rotate-180":""}`})]}),i&&r.jsxs("div",{role:"menu",className:"absolute right-0 mt-2 w-52 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden py-1",children:[r.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[r.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:e.name,children:e.name}),r.jsx("p",{className:"text-xs text-gray-400 truncate",children:e.username})]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{o(!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:[r.jsx(sn,{size:16,className:"text-gray-400"}),c("个人资料","Profile")]}),r.jsx($e,{slot:"nav.user_menu",slotProps:{session:e,lang:t,closeMenu:()=>o(!1)}}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{o(!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:[r.jsx(Ur,{size:16}),c("注销登录","Sign Out")]})]})]})}const Nj=[{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"}}],pc={...hr.light};function Cj({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:i,deleteCustomTheme:o}=_n(),a=f.useId(),[c,l]=f.useState("custom-mytheme"),[d,u]=f.useState("我的专属主题"),[m,p]=f.useState("自定义教学调色板配置"),[h,g]=f.useState({...pc}),[y,x]=f.useState("none"),[b,v]=f.useState(""),[S,T]=f.useState(!1),[k,w]=f.useState(null);if(!e)return null;const I=s.filter(z=>z.category==="custom"),_=z=>{w(z),setTimeout(()=>w(null),3e3)},R=z=>{l(z.id),u(z.label),p(z.description),g({...z.tokens}),_(`已载入预设: ${z.label}`)},L=z=>{l(z.id),u(z.label),p(z.description);const U=Ca(z.id);U&&Object.keys(U).length>0&&g({...U}),_(`已载入自定义主题: ${z.label}`)},E=(z,U)=>{g(j=>({...j,[z]:U}))},A=()=>{const z=c.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!z){alert("请输入有效的主题标识 (ID)");return}const U={id:z,label:d.trim()||"未命名主题",description:m.trim()||"自定义主题",previewBg:h["--bg-app"]||"#ffffff",previewPrimary:h["--color-primary"]||"#4f46e5",category:"custom"};i(U,h),_(`主题「${U.label}」已保存并成功激活!`)},D=()=>{v(JSON.stringify({version:"1.0",id:c,label:d,description:m,tokens:h},null,2)),x("export")},F=()=>{v(""),x("import")},P=()=>{try{const z=JSON.parse(b);if(!z.tokens||typeof z.tokens!="object")throw new Error("缺少合法的 tokens 字段");z.id&&l(z.id),z.label&&u(z.label),z.description&&p(z.description),g(U=>({...U,...z.tokens})),x("none"),_("主题配置导入成功!")}catch(z){alert(`导入失败: ${z.message||"JSON 格式解析错误"}`)}},$=()=>{navigator.clipboard.writeText(b),T(!0),setTimeout(()=>T(!1),2e3)},V=[{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 r.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:r.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:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme shrink-0 bg-surface",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-primary-theme/10 rounded-xl text-primary-theme",children:r.jsx(co,{size:22})}),r.jsxs("div",{children:[r.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-main",children:[n==="zh"?"主题可视化设计器":"Theme Visual Designer",r.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"})]}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{onClick: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",title:"导入 JSON",children:[r.jsx(il,{size:14}),n==="zh"?"导入配置":"Import"]}),r.jsxs("button",{onClick:D,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:[r.jsx(oo,{size:14}),n==="zh"?"导出配置":"Export"]}),r.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:r.jsx(Re,{size:18})})]})]}),k&&r.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:[r.jsx(ot,{size:14}),k]}),r.jsxs("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden",children:[r.jsxs("div",{className:"w-full md:w-1/2 border-r border-theme overflow-y-auto p-6 space-y-6",children:[r.jsxs("section",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[r.jsx(wt,{size:14,className:"text-amber-500"}),n==="zh"?"创意预设配色":"Creative Presets"]}),r.jsx("span",{className:"text-xs text-muted",children:"一键填入调色板"})]}),r.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Nj.map(z=>r.jsxs("button",{onClick:()=>R(z),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:[r.jsxs("div",{className:"flex items-center justify-between w-full",children:[r.jsxs("div",{className:"font-semibold text-xs text-main flex items-center gap-2",children:[r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/10 shrink-0",style:{backgroundColor:z.tokens["--color-primary"]}}),z.label]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:z.tokens["--bg-app"]}}),r.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:z.tokens["--bg-surface"]}})]})]}),r.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:z.description})]},z.id))})]}),r.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[r.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[r.jsx(cg,{size:14,className:"text-primary-theme"}),n==="zh"?"主题基础信息":"Theme Metadata"]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:`${a}-themeId`,className:"block text-xs font-medium text-muted mb-1",children:"主题标识 (ID)"}),r.jsx("input",{id:`${a}-themeId`,type:"text",value:c,onChange:z=>l(z.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"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:`${a}-label`,className:"block text-xs font-medium text-muted mb-1",children:"主题名称"}),r.jsx("input",{id:`${a}-label`,type:"text",value:d,onChange:z=>u(z.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"})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:`${a}-description`,className:"block text-xs font-medium text-muted mb-1",children:"主题描述"}),r.jsx("input",{id:`${a}-description`,type:"text",value:m,onChange:z=>p(z.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"})]})]}),r.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[r.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[r.jsx(co,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),r.jsx("div",{className:"space-y-2.5",children:V.map(z=>{const U=h[z.key]||"#000000";return r.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme hover:bg-surface-secondary/40 transition-colors",children:[r.jsxs("div",{className:"flex-1 min-w-0 pr-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs font-medium text-main",children:z.labelZh}),r.jsx("span",{className:"text-xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:z.key})]}),r.jsx("p",{className:"text-xs text-muted mt-0.5",children:z.desc})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[r.jsx("div",{className:"relative flex items-center",children:r.jsx("input",{type:"color",value:U.startsWith("#")&&U.length===7?U:"#4f46e5",onChange:j=>E(z.key,j.target.value),className:"w-8 h-8 rounded-lg cursor-pointer border border-theme p-0.5 bg-surface",title:"打开系统拾色器"})}),r.jsx("input",{type:"text",value:U,onChange:j=>E(z.key,j.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"})]})]},z.key)})})]}),I.length>0&&r.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[r.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[r.jsx(nd,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),r.jsx("div",{className:"space-y-2",children:I.map(z=>r.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme bg-surface-secondary/30",children:[r.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[r.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 shrink-0",style:{backgroundColor:z.previewPrimary}}),r.jsxs("div",{className:"truncate",children:[r.jsx("div",{className:"text-xs font-semibold text-main truncate",children:z.label}),r.jsx("div",{className:"text-xs text-muted truncate",children:z.description})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[r.jsx("button",{onClick:()=>L(z),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:"编辑"}),r.jsx("button",{onClick:()=>{confirm(`确定删除自定义主题「${z.label}」吗?`)&&(o(z.id),_(`已删除主题「${z.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:r.jsx(qr,{size:13})})]})]},z.id))})]})]}),r.jsxs("div",{className:"w-full md:w-1/2 flex flex-col p-6 bg-surface-secondary/30 overflow-y-auto",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-muted",children:[r.jsx(Ps,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),r.jsxs("span",{className:"text-xs text-muted font-mono",children:["当前预览: ",d," (",c,")"]})]}),r.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:[r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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"}),r.jsx("span",{className:"font-bold text-xs",style:{color:h["--text-main"]},children:"OpenLearn V2"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.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"}),r.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"})]})]}),r.jsxs("div",{className:"p-4 space-y-4 flex-1 overflow-y-auto",children:[r.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:[r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{children:[r.jsx("h4",{className:"font-bold text-sm",style:{color:h["--text-main"]},children:"高中物理实验探究:机械能守恒定律"}),r.jsx("p",{className:"text-xs mt-1",style:{color:h["--text-muted"]},children:"DIS 光电门传感器毫秒级数据回传与曲线拟合分析"})]}),r.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:"进行中"})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[r.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[r.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"光电门测速 (v)"}),r.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"2.43 m/s"})]}),r.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[r.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"动能增量 (ΔEk)"}),r.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--color-primary"]},children:"0.589 J"})]}),r.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[r.jsx("div",{className:"text-xs",style:{color:h["--text-muted"]},children:"误差率 (Err)"}),r.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"0.84 %"})]})]}),r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.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:"开始数据采集"}),r.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:"重置实验"}),r.jsx("button",{className:"px-2 py-1.5 rounded-lg text-xs transition-colors cursor-pointer",style:{color:h["--text-muted"]},children:"查看教案"})]})]}),r.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:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-xs font-semibold",style:{color:h["--text-main"]},children:"互动白板区域 (Whiteboard Canvas)"}),r.jsx("span",{className:"text-xs font-mono",style:{color:h["--text-muted"]},children:"60 FPS"})]}),r.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:[r.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:r.jsx(Is,{size:20})}),r.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"})]})]})]})]})]})]}),r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-theme shrink-0 bg-surface",children:[r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("button",{onClick:()=>{g({...pc}),_("已重置为系统默认调色板")},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:[r.jsx(hd,{size:14}),n==="zh"?"重置默认":"Reset Defaults"]})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.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"}),r.jsxs("button",{onClick:A,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:[r.jsx(dg,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),y!=="none"&&r.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:r.jsxs("div",{className:"bg-surface border border-theme rounded-2xl p-5 w-full max-w-lg shadow-2xl space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h3",{className:"font-bold text-sm text-main flex items-center gap-2",children:y==="export"?r.jsxs(r.Fragment,{children:[r.jsx(oo,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):r.jsxs(r.Fragment,{children:[r.jsx(il,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),r.jsx("button",{onClick:()=>x("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:r.jsx(Re,{size:16})})]}),r.jsx("div",{children:r.jsx("textarea",{value:b,readOnly:y==="export",onChange:z=>v(z.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"})}),r.jsx("div",{className:"flex items-center justify-end gap-2",children:y==="export"?r.jsx(r.Fragment,{children:r.jsxs("button",{onClick:$,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?r.jsx(ot,{size:14}):r.jsx(jn,{size:14}),S?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>x("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"}),r.jsx("button",{onClick:P,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 Ej({lang:e="zh"}){const[t,n]=f.useState(!1),[s,i]=f.useState(!1),o=f.useRef(null),{theme:a,availableThemes:c,setTheme:l}=_n();f.useEffect(()=>{function u(m){o.current&&!o.current.contains(m.target)&&n(!1)}return t&&document.addEventListener("mousedown",u),()=>{document.removeEventListener("mousedown",u)}},[t]);const d=u=>{switch(u){case"dark":return r.jsx(hg,{size:16,className:"text-indigo-400"});case"eyecare":return r.jsx(Ps,{size:16,className:"text-emerald-500"});case"chalkboard":return r.jsx(co,{size:16,className:"text-green-400"});case"light":default:return r.jsx(ug,{size:16,className:"text-amber-500"})}};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"relative",ref:o,children:[r.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:d(a)}),t&&r.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:[r.jsxs("div",{className:"px-3 py-2 border-b border-theme-subtle mb-1",children:[r.jsx("div",{className:"text-xs font-semibold text-main uppercase tracking-wider",children:e==="zh"?"界面主题模式":"Interface Theme"}),r.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"针对不同教学采光与场景优化":"Optimized for diverse lighting"})]}),r.jsx("div",{className:"space-y-1",children:c.map(u=>{const m=a===u.id;return r.jsxs("button",{onClick:()=>{l(u.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 ${m?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.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:u.previewPrimary}}),r.jsxs("div",{children:[r.jsx("div",{className:"font-medium text-main leading-none",children:u.label}),r.jsx("div",{className:"text-xs text-muted mt-1 leading-tight opacity-80",children:u.description})]})]}),m&&r.jsx(ot,{size:14,className:"text-primary-theme shrink-0"})]},u.id)})}),r.jsx("div",{className:"pt-2 mt-1 border-t border-theme-subtle",children:r.jsxs("button",{onClick:()=>{n(!1),i(!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:[r.jsx(wt,{size:14}),r.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),r.jsx(Cj,{isOpen:s,onClose:()=>i(!1),lang:e})]})}function Su({lang:e="zh"}){const[t,n]=f.useState(!1),s=f.useRef(null),{scale:i,minScale:o,maxScale:a,setScale:c,increaseScale:l,decreaseScale:d,resetScale:u}=Sn();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 m=tc.find(h=>h.scale===i),p=i===fr;return r.jsxs("div",{className:"relative",ref:s,children:[r.jsxs("button",{type:"button",onClick:()=>n(!t),title:e==="zh"?`界面字体缩放: ${i}%(点击调节)`:`Interface Font Scaling: ${i}% (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 ${p?"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:[r.jsx(fg,{size:16}),!p&&r.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:[i,"%"]})]}),t&&r.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:[r.jsxs("div",{className:"px-1 pb-2 border-b border-theme-subtle mb-2.5 flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-semibold text-main",children:e==="zh"?"界面字号大小":"Interface Font Size"}),r.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"全局等比缩放排版与文字":"Proportionally scale typography"})]}),!p&&r.jsxs("button",{type:"button",onClick:u,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:[r.jsx(hd,{size:11}),r.jsx("span",{children:e==="zh"?"重置":"Reset"})]})]}),r.jsxs("div",{className:"bg-surface-secondary/70 rounded-lg p-2 flex items-center justify-between mb-3 border border-theme-subtle",children:[r.jsx("button",{type:"button",onClick:d,disabled:i<=o,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:r.jsx(mg,{size:14})}),r.jsxs("div",{className:"text-center",children:[r.jsxs("div",{className:"text-sm font-black text-main leading-tight",children:[i,"%"]}),r.jsx("div",{className:"text-xs text-muted",children:m?e==="zh"?m.labelZh.split(" ")[0]:m.labelEn.split(" ")[0]:e==="zh"?"自定义比例":"Custom"})]}),r.jsx("button",{type:"button",onClick:l,disabled:i>=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:r.jsx(Gr,{size:14})})]}),r.jsxs("div",{className:"space-y-1 mb-3",children:[r.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wider px-1",children:e==="zh"?"常用档位":"Presets"}),r.jsx("div",{className:"grid grid-cols-1 gap-1",children:tc.map(h=>{const g=i===h.scale;return r.jsxs("button",{type:"button",onClick:()=>c(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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-60"}),r.jsx("span",{children:e==="zh"?h.labelZh:h.labelEn})]}),g&&r.jsx(ot,{size:13,className:"text-primary-theme shrink-0"})]},h.scale)})})]}),r.jsxs("div",{className:"p-2.5 rounded-lg border border-theme-subtle bg-surface-secondary/40 mb-2",children:[r.jsxs("div",{className:"text-xs text-muted mb-1 flex items-center justify-between",children:[r.jsx("span",{children:e==="zh"?"实时效果预览":"Live Preview"}),r.jsxs("span",{children:[i,"%"]})]}),r.jsx("p",{className:"text-xs text-main font-medium leading-relaxed",children:e==="zh"?"让每一个文字都清晰舒适,智能赋能教学。":"Clear and comfortable typography empowers modern teaching."})]}),r.jsx("div",{className:"text-xs text-muted/80 text-center px-1",children:e==="zh"?"快捷键:Ctrl + Alt + 加号/减号":"Shortcut: Ctrl + Alt + +/-"})]})]})}function Tj(e){const t=kt(),n=e.lang??t?.lang??"zh",s=e.activeStudentId!==void 0?e.activeStudentId:t?.activeStudentId??null,i=e.students??t?.students??[],o=e.selectedLesson!==void 0?e.selectedLesson:t?.selectedLesson??null,a=e.lessons??t?.lessons??[],c=e.isStudentLocked??t?.isNavigationLocked??t?.isStudentLocked??!1,l=e.isFollowingTeacher??t?.isFollowingTeacher??!1,d=e.setIsFollowingTeacher??t?.setIsFollowingTeacher??(()=>{}),u=e.notifyLockedNavigation??t?.notifyLockedNavigation??(()=>{});return r.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:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.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:"🎓"}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h1",{className:"text-sm font-black text-main tracking-wide",children:n==="zh"?"互动课堂 · 学生端":"Interactive Classroom · Student Client"}),r.jsxs("span",{className:"flex items-center gap-1 text-xs font-bold text-emerald-700 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full",children:[r.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"}),n==="zh"?"已与教师中控台实时联动":"Synced with Teacher"]})]}),r.jsxs("div",{className:"text-xs text-muted flex items-center gap-2",children:[r.jsx("span",{children:s?`学生: ${i.find(m=>m.id===s)?.name||s}`:"学生端"}),r.jsx("span",{children:"•"}),r.jsx("span",{children:o?`课节: ${a.find(m=>m.id===o)?.title||o}`:"等待教师推流课节..."})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:()=>{if(c){u();return}d(!l)},disabled:c,className:`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 shadow-2xs ${c?"cursor-not-allowed":"cursor-pointer"} ${l?"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"} ${c?"opacity-70":""}`,title:c?n==="zh"?"全班专注锁定中,已强制跟随教师步调":"Class focus is locked; following the teacher is enforced":n==="zh"?"开启后,教师端切换课节/环节/Tab时,学生端将自动同步跟随":"Follow teacher navigation",children:[r.jsx(Hr,{size:12,className:l?"animate-spin":""}),r.jsx("span",{children:n==="zh"?`跟随教师步调: ${l?"开":"关"}`:`Follow Teacher: ${l?"ON":"OFF"}`})]}),r.jsx(Su,{lang:n}),r.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:n==="zh"?"切换全屏":"Toggle Fullscreen",children:r.jsx(ea,{size:14})}),r.jsx("button",{type:"button",onClick:()=>window.close(),className:"px-2.5 py-1.5 text-xs font-bold text-rose-700 dark:text-rose-400 hover:text-rose-800 bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 rounded-lg transition-colors cursor-pointer",title:n==="zh"?"关闭学生端Tab":"Close Tab",children:n==="zh"?"关闭Tab":"Close Tab"})]})]})}function Aj(e){const t=kt(),n=e.activeRole??t?.activeRole??"teacher",s=e.studentPreviewTab??t?.isStudentPreviewMode??!1,i=e.lang??t?.lang??"zh",o=e.teacherTab??t?.teacherTab??"live_class",a=e.studentViewStatus??t?.studentViewStatus??"dashboard",c=e.session!==void 0?e.session:t?.session,l=e.activeStudentId!==void 0?e.activeStudentId:t?.activeStudentId??null,d=e.students??t?.students??[],u=e.studentDashboardData??t?.studentDashboardData??null,m=e.isNotificationsOpen??t?.isNotificationsOpen??!1,p=e.studentNotifications??t?.studentNotifications??[],h=e.unreadNotifications??t?.unreadNotifications??[],g=e.readNotifications??t?.readNotifications??new Set;e.selectedNotificationForModal!==void 0?e.selectedNotificationForModal:t?.selectedNotificationForModal;const y=e.dbConnected??t?.dbConnected??!1,x=e.dbStatus??t?.dbStatus??"normal",b=e.siteInfo??t?.siteInfo,v=e.setActiveStudentId??t?.setActiveStudentId??(()=>{}),S=e.setReadNotifications??t?.setReadNotifications??(()=>{}),T=e.setIsSystemResourceLibraryOpen??t?.setIsSystemResourceLibraryOpen??(()=>{}),k=e.setProfileOpen??t?.setProfileOpen??(()=>{}),w=e.setTeacherTab??t?.setTeacherTab??(()=>{}),I=e.setStudentViewStatus??t?.setStudentViewStatus??(()=>{}),_=e.setIsNotificationsOpen??t?.setIsNotificationsOpen??(()=>{}),R=e.setSelectedNotificationForModal??t?.setSelectedNotificationForModal??(()=>{}),L=e.handleLogout??t?.handleLogout??t?.onLogout??(()=>{}),E=e.toggleLanguage??t?.toggleLanguage??(()=>{}),A=e.setActiveRole??t?.setActiveRole??(()=>{}),D=e.isStudentLocked??t?.isNavigationLocked??t?.isStudentLocked??!1,F=e.onBlockedNavigate??t?.notifyLockedNavigation,P=jj(U=>U.timetableOcrTask);if(t?.isStudentLiveMode)return r.jsx(Tj,{});const $=n==="student"&&D,V=()=>{if($){F?.();return}n==="teacher"?w("live_class"):n==="student"&&I("dashboard")},z=()=>{if($){F?.();return}n==="teacher"?w("dashboard"):n==="student"&&I("dashboard")};return r.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:[r.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[r.jsxs("button",{onClick:V,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:$?i==="zh"?"全班专注锁定中,无法返回首页":"Class focus locked — cannot return to home":i==="zh"?"返回首页":"Back to Home",children:[b.logoUrl?r.jsx("img",{src:b.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):r.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-tr from-indigo-600 to-indigo-700 flex items-center justify-center text-white font-black text-sm shadow-xs shrink-0",children:"OL"}),r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:b.siteName||"OpenLearn Next"}),r.jsxs("span",{className:"text-xs font-medium text-subtle tracking-tight",children:["v","0.7.12"]}),b.slogan&&r.jsx("span",{className:"hidden md:inline text-xs text-subtle font-normal truncate max-w-[200px]",children:b.slogan})]})]}),r.jsx($e,{slot:"header.status_pill",slotProps:{dbConnected:y,dbStatus:x,lang:i}}),P?.status==="running"&&r.jsxs("div",{className:"hidden md:flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-violet-50 text-violet-700 text-xs font-semibold border border-violet-200 animate-pulse select-none",title:i==="zh"?"大模型正在后台分析提取课表内容...":"AI is processing timetable in background...",children:[r.jsx(mt,{size:13,className:"animate-spin text-violet-600"}),r.jsx("span",{children:i==="zh"?"后台识别课表中...":"Timetable OCR Running..."})]}),P?.status==="completed"&&o!=="timetable"&&r.jsxs("button",{type:"button",onClick:()=>{w("timetable"),Ve.getState().setPendingTimetableSubTab("ocr_import")},className:"hidden md:flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-50 text-emerald-700 hover:bg-emerald-100 text-xs font-bold border border-emerald-200 transition-colors shadow-2xs cursor-pointer select-none",title:i==="zh"?"点击前往课表管理查看识别结果":"Click to view timetable result",children:[r.jsx(lt,{size:13,className:"text-emerald-600"}),r.jsx("span",{children:i==="zh"?`课表识别已完成 (${P.result?.entries.length||0}节) · 查看`:`Timetable Ready (${P.result?.entries.length||0})`})]}),r.jsx($e,{slot:"header.async_task.item",slotProps:{lang:i,activeRole:n,teacherTab:o,setTeacherTab:w}}),r.jsxs("button",{onClick:z,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer ${n==="teacher"&&o==="dashboard"||n==="student"&&a==="dashboard"?"bg-indigo-50 text-indigo-700":"text-slate-600 hover:text-indigo-600 hover:bg-slate-100"} ${$?"opacity-50":""}`,children:[$?r.jsx(ro,{size:16}):r.jsx(fd,{size:16}),i==="zh"?"系统总览":"Dashboard"]}),n==="student"&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),r.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[r.jsx(md,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),n==="student"&&c?.role==="teacher"&&r.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:[r.jsxs("span",{className:"text-xs font-semibold text-amber-800 flex items-center gap-1",children:[r.jsx(Ps,{size:13,className:"text-amber-600"}),i==="zh"?"模拟学生:":"View as:"]}),r.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:l||"",onChange:U=>v(U.target.value),children:[r.jsxs("option",{value:"",children:["-- ",i==="zh"?"选择学生":"Select Student"," --"]}),d.map(U=>r.jsx("option",{value:U.id,children:U.name},U.id))]}),r.jsxs("button",{type:"button",onClick:()=>{if(s){window.close();return}A?.("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:i==="zh"?s?"关闭此学生视角预览标签页":"退出模拟学生并返回教师端工作台":s?"Close this student preview tab":"Exit student view and return to teacher workspace",children:[s?r.jsx(Re,{size:12}):r.jsx(Ur,{size:12}),i==="zh"?s?"关闭预览":"返回教师端":s?"Close Tab":"Exit Student View"]})]})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[n==="student"&&l&&u&&r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>_(!m),"aria-label":i==="zh"?`通知${h.length>0?`(${h.length} 条未读)`:""}`:`Notifications${h.length>0?` (${h.length} unread)`:""}`,"aria-expanded":m,className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[r.jsx(na,{size:20,"aria-hidden":"true"}),h.length>0&&r.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})]}),m&&r.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden",children:[r.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[r.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),h.length>0&&r.jsx("button",{onClick:async()=>{if(l){try{const U=p.filter(j=>!g.has(j.id)).map(j=>fetch(`/api/students/${l}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:j.id})}));await Promise.all(U)}catch(U){console.error(U)}S(U=>{const j=new Set(U);return p.forEach(B=>j.add(B.id)),j})}},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),r.jsx("div",{className:"max-h-96 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):r.jsx("div",{className:"divide-y divide-gray-100",children:p.map(U=>{const j=!g.has(U.id);return r.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${j?"bg-indigo-50/30":""}`,onClick:()=>{j&&(l&&fetch(`/api/students/${l}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:U.id})}).catch(console.error),S(q=>new Set(q).add(U.id)));const B=u?.assignments?.find(q=>q.id===U.relatedId);R({...U,assignment:B}),_(!1)},children:r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"mt-0.5",children:U.type==="new_assignment"?r.jsx(An,{size:16,className:"text-indigo-500"}):r.jsx(lt,{size:16,className:"text-green-500"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:`text-sm ${j?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:U.title}),r.jsx("div",{className:`text-xs mt-0.5 ${j?"text-gray-600":"text-gray-500"}`,children:U.message})]}),j&&r.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},U.id)})})})]})]}),r.jsx("div",{id:"app-header-plugin-actions",className:"flex items-center gap-2 empty:hidden",children:r.jsx($e,{slot:"header.action",lang:i,fallback:r.jsx(r.Fragment,{}),slotProps:{session:c,currentRole:n,lang:i}})}),r.jsxs("button",{onClick:()=>T(!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:[r.jsx(Tr,{size:14,className:"text-emerald-500 animate-pulse"}),i==="zh"?"系统资源库":"System Resource Library"]}),r.jsx("button",{onClick:E,title:i==="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:r.jsx(Tr,{size:16})}),r.jsx(Su,{lang:i}),r.jsx(Ej,{lang:i}),n!=="student"&&(()=>{const U=x==="error"||!y?{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:i==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:x==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:i==="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:i==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return r.jsxs("div",{id:"db-connection-status-badge",className:`w-8 h-8 rounded-lg border flex items-center justify-center relative select-none shrink-0 cursor-pointer transition-colors shadow-3xs ${U.bg}`,title:U.label,children:[r.jsx(pg,{size:15}),r.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[r.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${U.ping}`}),r.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${U.dot}`})]})]})})(),r.jsx(kj,{session:c,lang:i,onLogout:L,onProfile:()=>k(!0)})]})]})}function Ij(){const[e,t]=f.useState(()=>typeof navigator>"u"?!0:navigator.onLine);return f.useEffect(()=>{const n=()=>t(!0),s=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",s),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",s)}},[]),e}function Pj(){const e=kt(),t=Ij(),n=e?.lang??"zh",s=e?.activeRole??"teacher",i=e?.session;return r.jsx("footer",{id:"app-statusbar",role:"status",className:"h-7 shrink-0 border-t border-theme bg-surface text-muted text-xs flex items-center justify-end gap-3 px-4 empty:hidden",children:r.jsx($e,{slot:"statusbar.item",lang:n,fallback:r.jsx(r.Fragment,{}),slotProps:{session:i,currentRole:s,lang:n,isOnline:t}})})}function zj({lang:e,aiProviders:t,onAIProvidersChanged:n,currentUserId:s,currentUserRole:i}){const[o,a]=f.useState(!1),[c,l]=f.useState(null),[d,u]=f.useState(""),[m,p]=f.useState(""),[h,g]=f.useState(""),[y,x]=f.useState(""),[b,v]=f.useState(!1),[S,T]=f.useState(!1),k=()=>{l(null),u(""),p(""),g(""),x(""),v(!1),a(!0)},w=L=>{l(L),u(L.name),p(L.api_url),g(L.api_key||""),x(L.model_name),v(!!L.is_shared),a(!0)},I=async L=>{if(L.preventDefault(),!d.trim()||!m.trim()||!y.trim()){alert(e==="zh"?"名称、API URL 和模型名称不可为空":"Name, API URL and Model Name are required.");return}try{T(!0);const E=!!c,A=E?`/api/ai-providers/${c.id}`:"/api/ai-providers",D=E?"PUT":"POST",F={name:d.trim(),api_url:m.trim(),api_key:h,model_name:y.trim()};i==="administrator"&&(F.is_shared=b?1:0);const P=await fetch(A,{method:D,headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(P.ok)a(!1),l(null),n();else{const $=await P.json().catch(()=>({}));alert($.error||"Server error")}}catch(E){const A=E instanceof Error?E.message:String(E);alert(A||"Error")}finally{T(!1)}},_=async(L,E)=>{if(confirm(e==="zh"?`确认要删除 AI 提供商 [${E}] 吗?`:`Confirm deleting AI Provider [${E}]?`))try{(await fetch(`/api/ai-providers/${L}`,{method:"DELETE"})).ok?n():alert("Delete failed")}catch(A){const D=A instanceof Error?A.message:String(A);alert(D||"Error")}},R=async L=>{try{const E=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:L.id,api_url:L.api_url,api_key:L.api_key,model_name:L.model_name})});if(E.ok)alert(e==="zh"?`[${L.name}] 连接测试成功!`:`[${L.name}] Connection test successful!`);else{const A=await E.json().catch(()=>({}));alert(e==="zh"?`测试失败: ${A.error||"未知错误"}`:`Test failed: ${A.error||"Unknown error"}`)}}catch(E){const A=E instanceof Error?E.message:String(E);alert(e==="zh"?`网络异常: ${A}`:`Network error: ${A}`)}};return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 animate-fade-in text-gray-800",children:r.jsxs("div",{className:"bg-white border border-gray-200 rounded-xl shadow-3xs overflow-hidden",children:[r.jsxs("div",{className:"p-4 sm:p-5 border-b border-gray-100 flex items-center justify-between bg-gray-50/60",children:[r.jsxs("div",{children:[r.jsxs("h3",{className:"font-bold text-gray-800 flex items-center gap-2 text-sm sm:text-base",children:[r.jsx(pd,{className:"text-indigo-600",size:18}),e==="zh"?"OpenAI 兼容 / 自定义模型 AI 提供商列表":"AI Providers List (OpenAI-Compatible)"]}),r.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:e==="zh"?"支持 OpenAI 兼容 API。私有模型仅您个人可用,平台共享模型供全校教师共用。":"OpenAI-compatible APIs. Private models are exclusive to your account; shared models are available to all teachers."})]}),r.jsxs("button",{onClick:k,className:"flex items-center gap-1.5 px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg shadow-sm transition-all text-xs cursor-pointer",children:[r.jsx(Gr,{size:14}),e==="zh"?"添加 AI 提供商":"Add AI Provider"]})]}),r.jsx("div",{className:"p-4 sm:p-5",children:t.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-400 text-center",children:[r.jsx(Vr,{size:40,className:"mb-3 opacity-30 text-indigo-500"}),r.jsx("span",{className:"font-semibold text-sm",children:e==="zh"?"暂未配置任何 AI 提供商":"No AI Providers Registered"}),r.jsx("p",{className:"text-xs text-gray-400 mt-1 max-w-xs",children:e==="zh"?"点击右上角按钮新建。":"Click the button above to add one."})]}):r.jsx("div",{className:"overflow-x-auto border border-gray-100 rounded-xl",children:r.jsxs("table",{className:"w-full text-left border-collapse min-w-[700px]",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"bg-slate-50/70 border-b border-gray-100 text-gray-500 font-bold text-xs uppercase tracking-wider",children:[r.jsx("th",{className:"py-3.5 px-4",children:e==="zh"?"名称":"Name"}),r.jsx("th",{className:"py-3.5 px-4",children:e==="zh"?"类型 / 范围":"Scope"}),r.jsx("th",{className:"py-3.5 px-4",children:e==="zh"?"API 端点 URL":"API Endpoint URL"}),r.jsx("th",{className:"py-3.5 px-4",children:e==="zh"?"模型代号":"Model Identifier"}),r.jsx("th",{className:"py-3.5 px-4",children:e==="zh"?"密钥状态":"API Key"}),r.jsx("th",{className:"py-3.5 px-4 text-center",children:e==="zh"?"操作":"Actions"})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 text-xs text-gray-700",children:t.map(L=>{const E=!!L.is_shared,A=E?i==="administrator":!L.owner_id||!s||L.owner_id===s;return r.jsxs("tr",{className:"hover:bg-slate-50/50 transition-colors",children:[r.jsx("td",{className:"py-4 px-4",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${E?"bg-purple-500":"bg-indigo-500"}`}),r.jsx("span",{className:"font-extrabold text-gray-800 text-sm",children:L.name})]})}),r.jsx("td",{className:"py-4 px-4 whitespace-nowrap",children:E?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold bg-purple-50 text-purple-700 border border-purple-200",children:[r.jsx(ol,{size:12}),e==="zh"?"平台共享":"Platform Shared"]}):r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200",children:[r.jsx(sn,{size:12}),e==="zh"?"个人私有":"Private"]})}),r.jsx("td",{className:"py-4 px-4 font-mono text-gray-550 truncate max-w-[220px]",children:L.api_url}),r.jsx("td",{className:"py-4 px-4",children:r.jsx("span",{className:"bg-slate-100 text-slate-800 font-bold px-2 py-1 rounded font-mono text-xs border border-slate-200",children:L.model_name})}),r.jsx("td",{className:"py-4 px-4",children:L.api_key?r.jsxs("span",{className:"text-emerald-600 font-bold flex items-center gap-1 font-mono",children:[r.jsx(ot,{size:12})," Key Saved"]}):r.jsx("span",{className:"text-amber-500/90 font-mono italic",children:"Not Set"})}),r.jsx("td",{className:"py-4 px-4 text-center",children:r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsxs("button",{onClick:()=>R(L),className:"px-2.5 py-1 text-xs font-semibold rounded-lg border transition-all cursor-pointer flex items-center gap-1.5 shadow-3xs bg-emerald-50 border-emerald-200 text-emerald-700 hover:bg-emerald-100",title:e==="zh"?"测试连通性":"Test Connection",children:[r.jsx(Tr,{size:11}),r.jsx("span",{children:e==="zh"?"测试":"Test"})]}),r.jsx("button",{onClick:()=>w(L),disabled:!A,className:`px-2.5 py-1 rounded-lg border font-semibold transition-all shadow-3xs ${A?"text-indigo-700 hover:bg-indigo-100 border-indigo-200 bg-indigo-50 cursor-pointer":"text-gray-400 border-gray-200 bg-gray-50 opacity-50 cursor-not-allowed"}`,title:A?e==="zh"?"编辑配置":"Edit":e==="zh"?"平台共享配置仅管理员可修改":"Shared provider can only be modified by administrator",children:e==="zh"?"编辑":"Edit"}),r.jsx("button",{onClick:()=>_(L.id,L.name),disabled:!A,className:`px-2.5 py-1 rounded-lg border font-semibold transition-all shadow-3xs ${A?"text-rose-600 hover:bg-rose-100 border-rose-200 bg-rose-50 cursor-pointer":"text-gray-400 border-gray-200 bg-gray-50 opacity-50 cursor-not-allowed"}`,title:A?e==="zh"?"删除":"Delete":e==="zh"?"平台共享配置仅管理员可修改":"Shared provider can only be modified by administrator",children:e==="zh"?"删除":"Delete"})]})})]},L.id)})})]})})})]})}),o&&r.jsx("div",{className:"fixed inset-0 bg-gray-900/40 backdrop-blur-xs flex items-center justify-center p-4 z-[60] overflow-y-auto",children:r.jsxs("div",{className:"bg-white rounded-2xl shadow-xl border border-gray-200/60 w-full max-w-md overflow-hidden text-gray-800 text-left",children:[r.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-gray-100 bg-slate-50/70",children:[r.jsxs("h3",{className:"font-extrabold text-sm sm:text-base text-gray-800 flex items-center gap-2",children:[r.jsx(gg,{className:"text-indigo-600",size:18}),c?e==="zh"?"编辑 AI 提供商配置":"Edit AI Provider":e==="zh"?"添加全新 AI 提供商":"Add New AI Provider"]}),r.jsx("button",{onClick:()=>{a(!1),l(null)},className:"p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition-colors cursor-pointer",children:r.jsx(Re,{size:16})})]}),r.jsxs("form",{onSubmit:I,className:"p-5 space-y-4 text-left",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5 text-left",children:e==="zh"?"服务商名称 *":"Provider Name *"}),r.jsx("input",{type:"text",required:!0,placeholder:"e.g. Deepseek, Minimax",value:d,onChange:L=>u(L.target.value),className:"w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all font-semibold"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5 text-left",children:e==="zh"?"API 端点 URL *":"API Endpoint URL *"}),r.jsx("input",{type:"url",required:!0,placeholder:"https://api.deepseek.com/v1",value:m,onChange:L=>p(L.target.value),className:"w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all font-mono"}),r.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:e==="zh"?"符合 OpenAI 规范的标准 API 统一基准 URL。":"OpenAI-compatible base URL (e.g. /v1)."})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5 text-left",children:e==="zh"?"模型代号 *":"Model Identifier *"}),r.jsx("input",{type:"text",required:!0,placeholder:"e.g. deepseek-chat",value:y,onChange:L=>x(L.target.value),className:"w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all font-mono"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5 text-left",children:e==="zh"?"API Key (可选)":"API Key (Optional)"}),r.jsx("input",{type:"password",placeholder:e==="zh"?"不修改请留空":"Leave empty to keep existing",value:h,onChange:L=>g(L.target.value),className:"w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all font-mono"})]}),i==="administrator"&&r.jsx("div",{className:"pt-2 border-t border-gray-100",children:r.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:b,onChange:L=>v(L.target.checked),className:"mt-0.5 w-4 h-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500 cursor-pointer"}),r.jsxs("div",{children:[r.jsxs("span",{className:"text-xs font-bold text-gray-800 flex items-center gap-1.5",children:[r.jsx(ol,{size:14,className:"text-purple-600"}),e==="zh"?"设为平台共享模型 (全校教师可用)":"Set as Platform Shared (All teachers)"]}),r.jsx("span",{className:"text-xs text-gray-400 mt-0.5 block leading-relaxed",children:e==="zh"?"勾选后,所有教师可直接在侧栏与课表中使用该模型,但无法查看或篡改您的 API Key。不勾选则仅为您个人私有。":"If enabled, all teachers can use this model without seeing your API key. Otherwise it remains private."})]})]})}),r.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4 border-t border-gray-100",children:[r.jsx("button",{type:"button",onClick:()=>{a(!1),l(null)},className:"px-4 py-2 text-xs font-bold text-gray-500 bg-slate-100 hover:bg-slate-200 rounded-lg cursor-pointer transition-colors",children:e==="zh"?"取消":"Cancel"}),r.jsxs("button",{type:"submit",disabled:S,className:"px-4 py-2 text-xs font-bold text-white bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded-lg shadow-sm transition-all cursor-pointer flex items-center gap-1.5",children:[S?r.jsx(mt,{size:13,className:"animate-spin"}):r.jsx(ot,{size:14}),r.jsx("span",{children:S?e==="zh"?"保存中...":"Saving...":e==="zh"?"保存至数据库":"Save Connection"})]})]})]})]})})]})}function Lj({open:e,session:t,lang:n,onClose:s,onSaved:i,onAvatar:o}){const[a,c]=f.useState("profile"),[l,d]=f.useState(t.name),[u,m]=f.useState(!1),[p,h]=f.useState(null),g=kt(),[y,x]=f.useState([]),b=f.useCallback(async()=>{try{const M=await fetch("/api/ai-providers");if(M.ok){const Y=await M.json();x(Array.isArray(Y)?Y:[])}}catch{}},[]);f.useEffect(()=>{e&&a==="ai_providers"&&b()},[e,a,b]);const v=g?.aiProviders&&g.aiProviders.length>0?g.aiProviders:y,S=()=>{g?.onAIProvidersChanged&&g.onAIProvidersChanged(),b()},T=t.userId||t.id,k=t.subRole==="administrator"?"administrator":t.role,w=f.useRef(null),[I,_]=f.useState(!1),[R,L]=f.useState(null),[E,A]=f.useState(!1),[D,F]=f.useState(""),[P,$]=f.useState(""),[V,z]=f.useState(""),[U,j]=f.useState(!1),[B,q]=f.useState(null),[C,K]=f.useState(!1);if(!e)return null;const G=(M,Y)=>n==="zh"?M:Y,Q=t.role==="teacher"?t.subRole==="administrator"?G("管理员","Administrator"):G("教师","Teacher"):G("学生","Student"),ee=l.trim(),ue=ee.length>0&&ee!==t.name,we=async()=>{if(!(!ue||u)){m(!0),h(null);try{const M=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ee})}),Y=await M.json();if(!M.ok){h(Y.error||(n==="zh"?"保存失败":"Save failed"));return}i(Y.name??ee)}catch{h(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{m(!1)}}},X=D.length>0&&P.length>=8&&/[a-zA-Z]/.test(P)&&/[0-9]/.test(P)&&P===V,pe=async()=>{if(!(!X||U)){j(!0),q(null);try{const M=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:D,newPassword:P})}),Y=await M.json();if(!M.ok){q(Y.error||(n==="zh"?"修改失败":"Change failed"));return}K(!0),F(""),$(""),z(""),A(!1)}catch{q(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{j(!1)}}},ke=async M=>{const Y=M.target.files?.[0];if(M.target.value="",!!Y){_(!0),L(null);try{const te=await new Promise((oe,be)=>{const le=new FileReader;le.onload=()=>oe(le.result),le.onerror=()=>be(le.error),le.readAsDataURL(Y)}),ne=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:Y.name,base64Data:te})}),ie=await ne.json();if(!ne.ok){L(ie.error||(n==="zh"?"上传失败":"Upload failed"));return}o?.(ie.avatar)}catch{L(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{_(!1)}}},je=async()=>{_(!0),L(null);try{const M=await fetch("/api/auth/avatar",{method:"DELETE"}),Y=await M.json().catch(()=>({}));if(!M.ok){L(Y.error||(n==="zh"?"移除失败":"Remove failed"));return}o?.(null)}catch{L(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{_(!1)}};return r.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:s,children:r.jsxs("div",{className:`bg-white rounded-2xl shadow-xl w-full transition-all duration-150 overflow-hidden flex flex-col ${a==="ai_providers"?"max-w-4xl max-h-[88vh]":"max-w-md"}`,onClick:M=>M.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5 border-b border-gray-100 bg-slate-50/50 shrink-0",children:[t.role!=="student"?r.jsxs("div",{className:"flex items-center gap-1.5 bg-gray-200/70 p-1 rounded-xl",children:[r.jsxs("button",{type:"button",onClick:()=>c("profile"),className:`px-3 py-1.5 text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${a==="profile"?"bg-white text-indigo-700 shadow-3xs":"text-gray-600 hover:text-gray-900"}`,children:[r.jsx(sn,{size:13}),G("个人资料","Profile")]}),r.jsxs("button",{type:"button",onClick:()=>c("ai_providers"),className:`px-3 py-1.5 text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${a==="ai_providers"?"bg-white text-indigo-700 shadow-3xs":"text-gray-600 hover:text-gray-900"}`,children:[r.jsx(pd,{size:13}),G("AI 模型设置","AI Providers")]})]}):r.jsx("h3",{className:"font-semibold text-gray-800",children:G("个人资料","Profile")}),r.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer p-1 rounded-full hover:bg-gray-100 transition-colors",children:r.jsx(Re,{size:18})})]}),a==="ai_providers"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(zj,{lang:n==="zh"?"zh":"en",aiProviders:v,onAIProvidersChanged:S,currentUserId:T,currentUserRole:k})}):r.jsxs("div",{className:"p-5 space-y-5 overflow-y-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:t.avatar?r.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):r.jsx(sn,{size:28})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:t.name}),r.jsx("p",{className:"text-xs text-gray-400",children:Q}),r.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:()=>w.current?.click(),disabled:I,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:I?G("上传中…","Uploading…"):t.avatar?G("更换头像","Change avatar"):G("上传头像","Upload avatar")}),t.avatar&&r.jsx("button",{type:"button",onClick:je,disabled:I,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:G("移除","Remove")})]}),r.jsx("input",{ref:w,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:ke})]})]}),R&&r.jsx("p",{className:"text-xs text-rose-500",children:R}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:G("显示名称","Display Name")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{value:l,onChange:M=>d(M.target.value),maxLength:50,className:"flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("button",{onClick:we,disabled:!ue||u,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:u?G("保存中…","Saving…"):G("保存","Save")})]}),p&&r.jsx("p",{className:"text-xs text-rose-500 mt-1",children:p})]}),r.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[r.jsx(Br,{size:16,className:"text-gray-400"}),G("修改密码","Change Password")]}),!E&&!C&&r.jsx("button",{onClick:()=>{A(!0),q(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:G("修改","Edit")})]}),C&&r.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[r.jsx(lt,{size:16}),G("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),E&&r.jsxs("div",{className:"mt-3 space-y-3",children:[r.jsx("input",{type:"password",value:D,onChange:M=>F(M.target.value),placeholder:G("当前密码","Current password"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("input",{type:"password",value:P,onChange:M=>$(M.target.value),placeholder:G("新密码(≥8 位,含字母和数字)","New password (≥8 chars, letters + numbers)"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("input",{type:"password",value:V,onChange:M=>z(M.target.value),placeholder:G("确认新密码","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"}),B&&r.jsx("p",{className:"text-xs text-rose-500",children:B}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx("button",{onClick:()=>{A(!1),F(""),$(""),z(""),q(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:G("取消","Cancel")}),r.jsx("button",{onClick:pe,disabled:!X||U,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:U?G("提交中…","Submitting…"):G("提交","Submit")})]})]})]}),r.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-gray-400",children:G("用户名(登录账号)","Username (login)")}),r.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:t.username,children:t.username||"-"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-gray-400",children:G("角色","Role")}),r.jsx("span",{className:"text-sm font-medium text-gray-700",children:Q})]})]})]})]})})}const Rj=f.lazy(()=>He(()=>import("./student-workspace-C4UgD58C.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.StudentWorkspace}))),ju="studentShell",ku="workspace";function Nu(e){try{const t=e??(typeof window<"u"?window.location.search:"");return new URLSearchParams(t).get(ju)===ku}catch{return!1}}function gc(){const e=kt(),t=e?.session??null,n=e?.activeStudentId||t?.studentId||t?.userId||"";if(!t||!n)return r.jsx("div",{className:"flex-1 flex items-center justify-center p-8 text-sm text-subtle",children:r.jsx("span",{children:"学生身份未就绪,无法打开 Student Workspace 预览。"})});const s=e?.lang==="en"?"en":"zh";return r.jsxs("div",{"data-testid":"student-workspace-preview",className:"flex-1 min-h-0 flex flex-col",children:[r.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold bg-amber-50 text-amber-800 border-b border-amber-200",children:"Student Workspace 预览壳(C 组迁移中,功能不等价于现有学生端)"}),r.jsx(f.Suspense,{fallback:r.jsxs("div",{className:"flex-1 flex items-center justify-center gap-2 text-subtle",children:[r.jsx(mt,{className:"w-5 h-5 animate-spin"}),r.jsx("span",{className:"text-sm",children:"正在加载预览壳…"})]}),children:r.jsx(Rj,{student:{id:n,name:t.name??""},lessonId:e?.selectedLesson??void 0,lang:s})})]})}const _j=Object.freeze(Object.defineProperty({__proto__:null,STUDENT_WORKSPACE_PREVIEW_QUERY:ju,STUDENT_WORKSPACE_PREVIEW_VALUE:ku,StudentWorkspacePreview:gc,default:gc,isStudentWorkspacePreviewEnabled:Nu},Symbol.toStringTag,{value:"Module"})),Oj=f.lazy(()=>He(()=>import("./StudentView-Bi9kgSrN.js").then(e=>e.S),__vite__mapDeps([9,1,2,6,8])).then(e=>({default:e.StudentView}))),Dj=f.lazy(()=>He(()=>import("./TeacherView-C5JmoKHk.js"),__vite__mapDeps([10,1,2,6,8])).then(e=>({default:e.TeacherView}))),Mj=f.lazy(()=>He(()=>Promise.resolve().then(()=>_j),void 0).then(e=>({default:e.StudentWorkspacePreview})));function $j(e){const{activeRole:t}=e,n=t==="student"&&Nu();return r.jsx(f.Suspense,{fallback:r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-subtle gap-3",children:[r.jsx(mt,{className:"w-8 h-8 animate-spin text-indigo-500"}),r.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?n?r.jsx(Mj,{}):r.jsx(Oj,{}):r.jsx(Dj,{})})}const Fj=(e,t,n)=>e.replace(/\{\{\s*([\w-]+)\s*\}\}/g,(s,i)=>{const o=n[i];return o!==void 0&&o!==""?o:t?.find(c=>c.name===i)?.default??`{{${i}}}`});function Bj({setInput:e,currentInput:t,lang:n="zh"}){const s=Ce(g=>g.extensionPoints),[i,o]=f.useState(!1),[a,c]=f.useState(null),[l,d]=f.useState({}),u=f.useMemo(()=>s.get("ai.prompt.template")??[],[s]),m=n==="zh",p=u.find(g=>g.id===a);if(u.length===0)return null;const h=(g,y)=>{const x=g.slotProps?.prompt??"",b=Fj(x,g.slotProps?.parameters,y);e(t?`${t.trimEnd()}
64
+
65
+ ${b}`:b),o(!1),c(null),d({})};return r.jsxs("div",{className:"relative shrink-0",children:[r.jsx("button",{type:"button",onClick:()=>o(!i),disabled:a!==null&&!!p,className:`p-1 px-1.5 rounded-full transition-colors cursor-pointer ${i?"text-indigo-600 bg-indigo-50":"text-gray-500 hover:text-indigo-600 hover:bg-gray-100"}`,title:m?"插件提示词模板":"Plugin prompt templates",children:r.jsx(xg,{size:14})}),i&&r.jsxs("div",{className:"absolute bottom-full mb-2 left-0 w-80 max-h-72 overflow-y-auto bg-white border border-gray-200 rounded-xl shadow-xl z-40 text-xs",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-gray-100 sticky top-0 bg-white",children:[r.jsx("span",{className:"font-semibold text-gray-700",children:m?"插件提示词模板":"Prompt templates"}),r.jsx("button",{type:"button",onClick:()=>{o(!1),c(null)},className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:r.jsx(Re,{size:12})})]}),p?r.jsxs("div",{className:"p-3 space-y-2",children:[r.jsx("div",{className:"font-medium text-gray-800",children:p.slotProps?.title||p.id}),(p.slotProps?.parameters??[]).map(g=>r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"text-[11px] text-gray-500",children:g.label||g.name}),r.jsx("input",{value:l[g.name]??"",onChange:y=>d(x=>({...x,[g.name]:y.target.value})),className:"mt-0.5 w-full border border-gray-200 rounded-lg px-2 py-1 text-xs focus:outline-none focus:ring-2 focus:ring-indigo-100 focus:border-indigo-300",placeholder:g.default||g.name})]},g.name)),r.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[r.jsx("button",{type:"button",onClick:()=>h(p,l),className:"flex-1 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-semibold transition-colors cursor-pointer",children:m?"插入到输入框":"Insert"}),r.jsx("button",{type:"button",onClick:()=>c(null),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 border border-gray-200 rounded-lg transition-colors cursor-pointer",children:m?"返回":"Back"})]})]}):r.jsx("div",{className:"py-1",children:u.map(g=>{const y=g.slotProps?.title||g.id,x=g.slotProps?.description;return r.jsxs("button",{type:"button",onClick:()=>{const b=g.slotProps?.parameters??[];if(b.length>0){const v={};for(const S of b)S.default&&(v[S.name]=S.default);d(v),c(g.id)}else h(g,{})},className:"w-full text-left px-3 py-2 hover:bg-indigo-50 transition-colors cursor-pointer",children:[r.jsx("div",{className:"font-medium text-gray-800",children:y}),x&&r.jsx("div",{className:"text-[11px] text-gray-500 mt-0.5 line-clamp-2",children:x})]},g.id)})})]})]})}function Uj(e={}){const t=kt(),n=e.showRightSidebar??t?.showRightSidebar??!1,s=e.setShowRightSidebar??t?.setShowRightSidebar??(()=>{}),i=e.rightSidebarTab??t?.rightSidebarTab??"agent",o=e.setRightSidebarTab??t?.setRightSidebarTab??(()=>{}),a=e.effectiveAgentProviderId??t?.effectiveAgentProviderId??"";e.agentProviderId??t?.agentProviderId;const c=e.setAgentProviderId??t?.setAgentProviderId??(()=>{}),l=e.personaId??t?.personaId??"",d=e.setPersonaId??t?.setPersonaId??(()=>{}),u=e.aiProviders??t?.aiProviders??[],m=e.selectedAgentProvider!==void 0?e.selectedAgentProvider:t?.selectedAgentProvider??null,p=e.chatLog??t?.chatLog??[],h=e.loading??t?.loading??!1,g=e.input??t?.input??"",y=e.setInput??t?.setInput??(()=>{}),x=e.handleSend??t?.handleSend??(async()=>{}),b=e.chatAttachments??t?.chatAttachments??[],v=e.setChatAttachments??t?.setChatAttachments??(()=>{}),S=e.handleChatFileChange??t?.handleChatFileChange??(()=>{}),T=e.handleChatDrop??t?.handleChatDrop??(()=>{}),k=e.onClearAgentMemory??t?.handleClearAgentMemory??(()=>{}),w=e.events??t?.events??[],I=e.lang??t?.lang??"zh",_=e.t??t?.t??{},R=f.useRef(null);f.useEffect(()=>{R.current?.scrollIntoView({behavior:"smooth"})},[p]);const[L,E]=f.useState([]);return f.useEffect(()=>{!n||L.length>0||fetch("/api/agent/personas").then(A=>A.ok?A.json():null).then(A=>{A?.success&&Array.isArray(A.personas)&&E(A.personas)}).catch(()=>{})},[n]),r.jsx("div",{className:`transition-all duration-300 bg-white border-l border-gray-200 flex flex-col shadow-xl relative z-30 shrink-0 ${n?"w-96":"w-12 items-center cursor-pointer hover:bg-gray-50"}`,children:n?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[r.jsxs("button",{onClick:()=>o("agent"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${i==="agent"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[r.jsx(li,{size:14})," Agent"]}),r.jsxs("button",{onClick:()=>o("shell"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${i==="shell"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[r.jsx(or,{size:14})," Shell"]}),r.jsx($e,{slot:"ai_sidebar.tab",slotProps:{renderType:"button",activeTab:i,setActiveTab:o,lang:I}}),r.jsx("button",{onClick:()=>s(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:r.jsx(bg,{size:14})})]}),i==="agent"?r.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[r.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:r.jsx(li,{size:16})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:_.agentTitle}),r.jsx("p",{className:"text-xs text-gray-500",children:_.agentSubtitle}),r.jsxs("button",{onClick:k,title:I==="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:["🧹 ",I==="zh"?"清除记忆":"Clear memory"]})]})]}),r.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[r.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-gray-400",children:I==="zh"?"AI 提供商":"AI Provider"}),r.jsxs("div",{className:"relative w-full",children:[u.length===0?r.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:r.jsx("option",{value:"",children:I==="zh"?"未配置 AI 提供商":"No AI Provider"})}):r.jsx("select",{value:a,onChange:A=>c(A.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:u.map(A=>{const D=A.is_shared?I==="zh"?"· 平台共享":"· Shared":I==="zh"?"· 私有":"· Private";return r.jsxs("option",{value:A.id,children:[A.name," (",D.trim(),")"]},A.id)})}),r.jsx(Tn,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),r.jsx("div",{className:"text-xs text-gray-400 truncate w-full text-right",title:m?.model_name||"",children:m?`${m.model_name}`:I==="zh"?"未配置提供商":"No Provider"})]})]})}),d&&L.length>0&&r.jsx("div",{className:"mx-4 mb-3",children:r.jsxs("select",{value:l||"",onChange:A=>d(A.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 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:[r.jsx("option",{value:"",children:I==="zh"?"🤖 助教角色:默认":"🤖 Persona: Default"}),L.filter(A=>A.id!=="plain_assistant").map(A=>r.jsxs("option",{value:A.id,children:[A.icon||"🎯"," ",I==="zh"?A.nameZh:A.nameEn]},A.id))]})}),u.length===0&&r.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:[r.jsx(Bt,{size:15,className:"shrink-0 text-amber-600 mt-0.5"}),r.jsxs("div",{className:"flex-1 leading-relaxed",children:[r.jsx("span",{className:"font-semibold",children:I==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),r.jsx("p",{className:"mt-0.5 text-amber-700",children:I==="zh"?"请前往「系统管理 -> AI 提供商管理」添加大模型服务(如 DeepSeek、Qwen、OpenAI 等)。":'Please configure an AI provider in "System Management -> AI Provider Management" to use the AI assistant.'})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[p.map((A,D)=>r.jsx("div",{className:`flex flex-col ${A.role==="user"?"items-end":"items-start"}`,children:r.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${A.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:A.content})},D)),h&&r.jsx("div",{className:"flex items-start",children:r.jsxs("div",{className:"px-4 py-2.5 rounded-2xl max-w-[85%] text-xs bg-gray-100 text-gray-500 rounded-bl-none flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),r.jsx("div",{ref:R})]}),r.jsxs("form",{onSubmit:x,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:A=>A.preventDefault(),onDrop:T,children:[b.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:b.map((A,D)=>r.jsxs("div",{className:"flex items-center gap-1 bg-indigo-50 border border-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full text-xs",children:[r.jsx(ld,{size:10,className:"shrink-0"}),r.jsx("span",{className:"truncate max-w-[100px]",title:A.name,children:A.name}),r.jsx("button",{type:"button",onClick:()=>v(F=>F.filter((P,$)=>$!==D)),className:"hover:bg-indigo-200 rounded-full p-0.5 cursor-pointer ml-0.5 transition-colors text-indigo-400 hover:text-indigo-600",children:r.jsx(Re,{size:10})})]},D))}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("label",{className:"p-1 px-1.5 text-gray-500 hover:text-indigo-600 rounded-full hover:bg-gray-100 cursor-pointer transition-colors shrink-0",children:[r.jsx(yg,{size:14}),r.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:S,accept:".csv,.txt,.json,.md"})]}),r.jsx(Bj,{setInput:y,currentInput:g,lang:I}),r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"text",value:g,disabled:u.length===0,onChange:A=>y(A.target.value),placeholder:u.length===0?I==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":_.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"}),r.jsx("button",{type:"submit",disabled:h||!g.trim()||u.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:r.jsx(cd,{size:10})})]})]})]})]}):i==="shell"?r.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:[r.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:r.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[r.jsx(or,{size:14}),r.jsx("span",{className:"text-xs",children:_.eventStream})]})}),r.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:w.length===0?r.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):w.map((A,D)=>r.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[r.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[r.jsxs("span",{className:"text-gray-500 shrink-0 text-xs",children:["[",new Date(A.timestamp).toLocaleTimeString(),"]"]}),r.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:A.source,children:A.source})]}),r.jsx("div",{className:"text-green-300 font-bold",children:A.type}),r.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:A.payload})]},D))})]}):r.jsx("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-4",children:r.jsx($e,{slot:"ai_sidebar.tab",slotProps:{renderType:"panel",activeTab:i,lang:I}})})]}):r.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-subtle w-full",onClick:()=>s(!0),children:[r.jsx(li,{size:18,className:"mb-6 hover:text-indigo-500"}),r.jsx(or,{size:18,className:"hover:text-indigo-500"}),r.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:r.jsx("div",{className:"uppercase tracking-widest text-xs rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const Vj=f.lazy(()=>He(()=>import("./ImportModal-Ct0I5cAL.js"),__vite__mapDeps([11,1,2,6])).then(e=>({default:e.ImportModal}))),Wj=f.lazy(()=>He(()=>import("./CourseWizardModal-BAkW5VJX.js"),__vite__mapDeps([12,1,2,6,8])).then(e=>({default:e.CourseWizardModal}))),Hj=f.lazy(()=>He(()=>import("./ImportLessonsModal-CQlq4b81.js"),__vite__mapDeps([13,1,2,6,8])).then(e=>({default:e.ImportLessonsModal}))),qj=f.lazy(()=>He(()=>import("./QuizGeneratorModal-CNY8ISjR.js"),__vite__mapDeps([14,1,2,6,8])).then(e=>({default:e.QuizGeneratorModal}))),Gj=f.lazy(()=>He(()=>import("./ProcessLogsModal-D97xLgnL.js"),__vite__mapDeps([15,1,2,6])).then(e=>({default:e.ProcessLogsModal}))),Qj=f.lazy(()=>He(()=>import("./CloudDriveModal-C8UAn3MO.js"),__vite__mapDeps([16,1,2,17,6,8])).then(e=>({default:e.CloudDriveModal}))),Jj=f.lazy(()=>He(()=>import("./SystemResourceLibraryModal-DDALKrJC.js"),__vite__mapDeps([18,1,2,16,17,6,8])).then(e=>({default:e.SystemResourceLibraryModal}))),Kj=f.lazy(()=>He(()=>import("./BatchPickerModal-QALdhrX6.js"),__vite__mapDeps([19,1,2,6,8])).then(e=>({default:e.BatchPickerModal}))),Yj=f.lazy(()=>He(()=>import("./ExportWeightModal-D2Y13384.js"),__vite__mapDeps([20,1,2,6,8])).then(e=>({default:e.ExportWeightModal}))),Zj=f.lazy(()=>He(()=>import("./NotificationDetailModal-BF_-pn0c.js"),__vite__mapDeps([21,1,2,6,8])).then(e=>({default:e.NotificationDetailModal}))),Xj=f.lazy(()=>He(()=>import("./HelpTour-DBq2otcV.js"),__vite__mapDeps([22,1,2,6])).then(e=>({default:e.HelpTour}))),ek=f.lazy(()=>He(()=>import("./CoursewareHubPanel-BkjcusjZ.js"),__vite__mapDeps([23,1,2,6])).then(e=>({default:e.CoursewareHubPanel})));function tk(e={}){const t=kt(),{lang:n=t?.lang??"zh",t:s=t?.t??{},showImportModal:i=t?.showImportModal??!1,setShowImportModal:o=t?.setShowImportModal??(()=>{}),handleImportFile:a=t?.handleImportFile??(()=>{}),importError:c=t?.importError??null,importSuccess:l=t?.importSuccess??null,isImporting:d=t?.isImporting??!1,downloadCSVTemplate:u=t?.downloadCSVTemplate??(()=>{}),addToast:m=t?.addToast??(()=>{}),isImportLessonsOpen:p=t?.isImportLessonsOpen??!1,setIsImportLessonsOpen:h=t?.setIsImportLessonsOpen??(()=>{}),importStatus:g=t?.importStatus??"idle",setIsDraggingImport:y=t?.setIsDraggingImport??(()=>{}),handleCSVFileChange:x=t?.handleCSVFileChange??(()=>{}),handleImportFileChange:b=t?.handleImportFileChange??(()=>{}),downloadCsvTemplate:v=t?.downloadCsvTemplate??(()=>{}),downloadCourseTemplate:S=t?.downloadCourseTemplate??(()=>{}),packagePreview:T=t?.packagePreview??null,handlePackageImportSubmit:k=t?.handlePackageImportSubmit??(()=>{}),packageDuplicate:w=t?.packageDuplicate??null,handlePackageDuplicateDismiss:I=t?.handlePackageDuplicateDismiss??(()=>{}),isDraggingImport:_=t?.isDraggingImport??!1,previewImportData:R=t?.previewImportData??[],setPreviewImportData:L=t?.setPreviewImportData??(()=>{}),setImportStatus:E=t?.setImportStatus??(()=>{}),importProgress:A=t?.importProgress??0,importProgressTotal:D=t?.importProgressTotal??0,importErrorMsg:F=t?.importErrorMsg??"",setImportErrorMsg:P=t?.setImportErrorMsg??(()=>{}),handleCSVImportSubmit:$=t?.handleCSVImportSubmit??(()=>{}),lessons:V=t?.lessons??[],fetchClassDashboard:z=t?.fetchClassDashboard??(()=>{}),currentVfsParent:U=t?.currentVfsParent??null,setCurrentVfsParent:j=t?.setCurrentVfsParent??(()=>{}),vfsNodes:B=t?.vfsNodes??[],showProcessLogs:q=t?.showProcessLogs??null,setShowProcessLogs:C=t?.setShowProcessLogs??(()=>{}),processLogsContent:K=t?.processLogsContent??"",isCloudDriveOpen:G=t?.isCloudDriveOpen??!1,setIsCloudDriveOpen:Q=t?.setIsCloudDriveOpen??(()=>{}),cloudDrivePreviewNode:ee=t?.cloudDrivePreviewNode??null,setCloudDrivePreviewNode:ue=t?.setCloudDrivePreviewNode??(()=>{}),isSystemResourceLibraryOpen:we=t?.isSystemResourceLibraryOpen??!1,setIsSystemResourceLibraryOpen:X=t?.setIsSystemResourceLibraryOpen??(()=>{}),systemResourceTab:pe=t?.systemResourceTab??"system",setSystemResourceTab:ke=t?.setSystemResourceTab??(()=>{}),selectedLibraryResourceId:je=t?.selectedLibraryResourceId??null,setSelectedLibraryResourceId:M=t?.setSelectedLibraryResourceId??(()=>{}),loadingLibraryResources:Y=t?.loadingLibraryResources??!1,libraryResources:te=t?.libraryResources??[],fetchLibraryResources:ne=t?.fetchLibraryResources??(()=>{}),classes:ie=t?.classes??[],expandedClassId:oe=t?.expandedClassId??null,isExportWeightModalOpen:be=t?.isExportWeightModalOpen??!1,setIsExportWeightModalOpen:le=t?.setIsExportWeightModalOpen??(()=>{}),quizzesWeight:Ne=t?.quizzesWeight??40,setQuizzesWeight:Te=t?.setQuizzesWeight??(()=>{}),assignmentsWeight:Je=t?.assignmentsWeight??60,setAssignmentsWeight:se=t?.setAssignmentsWeight??(()=>{}),handleQuizzesWeightChange:N=t?.handleQuizzesWeightChange??(()=>{}),handleAssignmentsWeightChange:O=t?.handleAssignmentsWeightChange??(()=>{}),customCategoryOverrides:W=t?.customCategoryOverrides??{},setCustomCategoryOverrides:H=t?.setCustomCategoryOverrides??(()=>{}),classDashboardMap:Z=t?.classDashboardMap??{},exportClassId:he=t?.exportClassId??"",exportClassName:fe=t?.exportClassName??"",csvPreviewData:xe=t?.csvPreviewData??null,handleExportGrades:re=t?.handleExportGrades??(()=>{}),setSelectedAssignment:Be=t?.setSelectedAssignment??(()=>{}),setStudentViewStatus:Ae=t?.setStudentViewStatus??(()=>{}),setQuizStudentAnswers:Me=t?.setQuizStudentAnswers??(()=>{}),setSubAssignmentTab:Fe=t?.setSubAssignmentTab??(()=>{}),isTourOpen:At=t?.isTourOpen??!1,setIsTourOpen:et=t?.setIsTourOpen??(()=>{}),handleSeedSuccess:Nt=t?.handleSeedSuccess??(()=>{}),setTeacherTab:Ht=t?.setTeacherTab??(()=>{}),showCoursewareHub:Dn=t?.showCoursewareHub??!1,setShowCoursewareHub:qt=t?.setShowCoursewareHub??(()=>{})}=e,_e=e.courseWizard??t,an=_e?.isCourseWizardOpen??e.isCourseWizardOpen??!1,Mn=_e?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),$n=_e?.wizardStep??e.wizardStep??1,Fn=_e?.setWizardStep??e.setWizardStep??(()=>{}),ln=_e?.wizardIsSubmitting??e.wizardIsSubmitting??!1,Bn=_e?.wizardCourseTitle??e.wizardCourseTitle??"",cn=_e?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),Un=_e?.wizardCourseDescription??e.wizardCourseDescription??"",Vn=_e?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Wn=_e?.wizardCourseCategory??e.wizardCourseCategory??"",It=_e?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),dn=_e?.wizardCourseTimeline??e.wizardCourseTimeline??[],Gt=_e?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),Hn=_e?.wizardCourseContent??e.wizardCourseContent??"",qn=_e?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),Pt=_e?.wizardIsGeneratingOutline??e.wizardIsGeneratingOutline??!1,un=_e?.handleGenerateOutline??e.handleGenerateOutline??(async()=>{}),hn=_e?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),Oe=e.quizGenerator??t,Gn=Oe?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,Qn=Oe?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),Jn=Oe?.quizGenMode??e.quizGenMode??"scan_lesson",Kn=Oe?.setQuizGenMode??e.setQuizGenMode??(()=>{}),Yn=Oe?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",Zn=Oe?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),Xn=Oe?.quizGenTopic??e.quizGenTopic??"",es=Oe?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),ts=Oe?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,ns=Oe?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),ss=Oe?.suggestedObjectives??e.suggestedObjectives??[],rs=Oe?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),is=Oe?.suggestedQuestions??e.suggestedQuestions??[],ye=Oe?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),Ke=Oe?.quizGenTimeLimit??e.quizGenTimeLimit??0,Qt=Oe?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),ge=Oe?.savingQuiz??e.savingQuiz??!1,qe=Oe?.setSavingQuiz??e.setSavingQuiz??(()=>{}),Ze=Oe?.quizGeneratorClassId??e.quizGeneratorClassId??null,Xe=e.classBatch??t,pt=Xe?.batchPicker??e.batchPicker??null,rt=Xe?.setBatchPicker??e.setBatchPicker??(()=>{}),zt=Xe?.batchPickerLesson??e.batchPickerLesson??"",Jt=Xe?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),Ds=Xe?.batchPickerDate??e.batchPickerDate??"",ni=Xe?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),Ms=Xe?.batchPickerTargetClass??e.batchPickerTargetClass??"",si=Xe?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),ri=Xe?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),$s=e.studentNotificationsHook??t,ii=$s?.selectedNotificationForModal??e.selectedNotificationForModal??null,oi=$s?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return r.jsxs(f.Suspense,{fallback:null,children:[r.jsx(Vj,{show:i,onClose:()=>o(!1),lang:n,handleImportFile:a,importError:c,importSuccess:l,isImporting:d,downloadCSVTemplate:u}),r.jsx(Wj,{isCourseWizardOpen:an,setIsCourseWizardOpen:Mn,lang:n,wizardStep:$n,setWizardStep:Fn,wizardIsSubmitting:ln,wizardCourseTitle:Bn,setWizardCourseTitle:cn,wizardCourseDescription:Un,setWizardCourseDescription:Vn,wizardCourseCategory:Wn,setWizardCourseCategory:It,wizardCourseTimeline:dn,setWizardCourseTimeline:Gt,wizardCourseContent:Hn,setWizardCourseContent:qn,addToast:m,wizardIsGeneratingOutline:Pt,handleGenerateOutline:un,handleDeployWizardCourse:hn}),r.jsx(Hj,{isImportLessonsOpen:p,setIsImportLessonsOpen:h,lang:n,importStatus:g,setIsDraggingImport:y,handleCSVFileChange:x,handleImportFileChange:b,downloadCsvTemplate:v,downloadCourseTemplate:S,packagePreview:T,handlePackageImportSubmit:k,packageDuplicate:w,handlePackageDuplicateDismiss:I,isDraggingImport:_,previewImportData:R,setPreviewImportData:L,setImportStatus:E,importProgress:A,importProgressTotal:D,importErrorMsg:F,setImportErrorMsg:P,handleCSVImportSubmit:$}),r.jsx(qj,{isQuizGeneratorOpen:Gn,setIsQuizGeneratorOpen:Qn,lessons:V,quizGenMode:Jn,setQuizGenMode:Kn,quizGenSelectedLessonId:Yn,setQuizGenSelectedLessonId:Zn,quizGenTopic:Xn,setQuizGenTopic:es,isGeneratingSuggestions:ts,setIsGeneratingSuggestions:ns,suggestedObjectives:ss,setSuggestedObjectives:rs,suggestedQuestions:is,setSuggestedQuestions:ye,quizGenTimeLimit:Ke,setQuizGenTimeLimit:Qt,savingQuiz:ge,setSavingQuiz:qe,quizGeneratorClassId:Ze,fetchClassDashboard:z}),r.jsx(Gj,{showProcessLogs:q,setShowProcessLogs:C,processLogsContent:K,t:s}),r.jsx(Qj,{isOpen:G,onClose:()=>Q(!1),vfsNodes:B,currentVfsParent:U,setCurrentVfsParent:j,cloudDrivePreviewNode:ee,setCloudDrivePreviewNode:ue}),r.jsx(Jj,{isSystemResourceLibraryOpen:we,setIsSystemResourceLibraryOpen:X,lang:n,systemResourceTab:pe,setSystemResourceTab:ke,selectedLibraryResourceId:je,setSelectedLibraryResourceId:M,vfsNodes:B,currentVfsParent:U,setCurrentVfsParent:j,cloudDrivePreviewNode:ee,setCloudDrivePreviewNode:ue,loadingLibraryResources:Y,libraryResources:te,fetchLibraryResources:ne}),r.jsx(Kj,{batchPicker:pt,setBatchPicker:rt,batchPickerLesson:zt,setBatchPickerLesson:Ge=>Jt(typeof Ge=="function"?Ge(zt):Ge),batchPickerDate:Ds,setBatchPickerDate:Ge=>ni(typeof Ge=="function"?Ge(Ds):Ge),batchPickerTargetClass:Ms,setBatchPickerTargetClass:Ge=>si(typeof Ge=="function"?Ge(Ms):Ge),lessons:V,classes:ie,expandedClassId:oe,confirmBatchPicker:ri,lang:n}),r.jsx(Yj,{isExportWeightModalOpen:be,setIsExportWeightModalOpen:le,lang:n,quizzesWeight:Ne,setQuizzesWeight:Te,assignmentsWeight:Je,setAssignmentsWeight:se,handleQuizzesWeightChange:N,handleAssignmentsWeightChange:O,customCategoryOverrides:W,setCustomCategoryOverrides:H,classDashboardMap:Z,exportClassId:he,exportClassName:fe,csvPreviewData:xe,handleExportGrades:re}),r.jsx(Zj,{notification:ii,onClose:()=>oi(null),lang:n,onOpenWorkspace:Ge=>{Be(Ge),Ae("assignment"),Me({}),Fe("quiz")}}),r.jsx(Xj,{isOpen:At,onClose:()=>et(!1),lang:n,onSeedSuccess:Nt,onJumpTab:Ge=>Ht(Ge)}),Dn&&r.jsx(ek,{onClose:()=>qt(!1),lang:n})]})}const nk="openlearn_live_classroom_sync";class Cu{constructor(t=nk,n,s){this.channel=null,this.isDestroyed=!1,this.messageListeners=[],this.lessonId=null,this.classId=null,this.socketBoundTo=null,this.offSocketReady=null,this.handleRemoteSync=i=>{this.isDestroyed||!i?.message||this.lessonId&&i.lessonId&&i.lessonId!==this.lessonId||this.emitToListeners(i.message)},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)}),this.offSocketReady=Ea(()=>this.ensureSocketBound())}ensureSocketBound(){if(this.isDestroyed)return;const t=ct();!t||t===this.socketBoundTo||(this.unbindSocket(),t.on("classroom:sync_message",this.handleRemoteSync),this.socketBoundTo=t)}unbindSocket(){this.socketBoundTo&&(this.socketBoundTo.off("classroom:sync_message",this.handleRemoteSync),this.socketBoundTo=null)}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.ensureSocketBound(),this.messageListeners.push(t),()=>{this.messageListeners=this.messageListeners.filter(n=>n!==t)}}postMessage(t){if(this.isDestroyed)return;if(this.ensureSocketBound(),this.channel)try{this.channel.postMessage(t)}catch(s){console.warn("[ClassroomSyncChannel] Failed to post message to BroadcastChannel:",s)}const n=ct();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)}}broadcastChangeLesson(t){this.lessonId=t,this.postMessage({type:"TEACHER_CHANGE_LESSON",payload:{lessonId:t,classId:this.classId}});const n=ct();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=ct();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=ct();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=ct();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}});const s=ct();s&&s.emit("teacher-pick-student",{studentId:t,studentName:n,lessonId:this.lessonId,classId:this.classId})}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=ct();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 i=ct();i&&s&&i.emit("teacher-broadcast-fullscreen",{elementId:t,lessonId:s,classId:this.classId})}acknowledgePick(t){this.postMessage({type:"STUDENT_ACKNOWLEDGE_PICK",payload:{studentId:t}});const n=ct();n&&n.emit("student-acknowledge-pick",{studentId:t,lessonId:this.lessonId})}sendHeartbeat(t){this.postMessage({type:"STUDENT_HEARTBEAT",payload:{studentId:t,timestamp:Date.now()}})}destroy(){this.isDestroyed=!0,this.messageListeners=[],this.offSocketReady?.(),this.offSocketReady=null,this.unbindSocket(),this.channel&&(this.channel.close(),this.channel=null)}}async function sk(e){const t=await fetch(`/api/students/${e}/read_notifications`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function rk(e,t){await fetch(`/api/students/${e}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:t})})}async function ik(e,t){await fetch(`/api/students/${e}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function ok(e,t){const n=await fetch(`/api/classes/${e}/lessons/${t}/progress`);return n.ok?{ok:!0,data:await n.json()}:{ok:!1}}async function ak(e){const t=await fetch(`/api/students/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}function lk(e,t,n=typeof window<"u"?window:null){const s=f.useRef(t);s.current=t,f.useEffect(()=>{if(!n)return;const i=o=>{const a=o;s.current?.(a.detail,a)};return n.addEventListener(e,i),()=>{n.removeEventListener(e,i)}},[e,n])}function ck(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return;const t=new e,n=t.currentTime,s=t.createOscillator(),i=t.createGain();s.type="sine",s.frequency.setValueAtTime(587.33,n),s.frequency.exponentialRampToValueAtTime(880,n+.3),i.gain.setValueAtTime(.25,n),i.gain.exponentialRampToValueAtTime(.001,n+.8),s.connect(i),i.connect(t.destination),s.start(n),s.stop(n+.8)}catch{}}function dk({lessonId:e,lang:t="zh",syncChannel:n}){const[s,i]=f.useState(null),[o,a]=f.useState(!1),[c,l]=f.useState(!0),[d,u]=f.useState(!1),m=f.useRef(s);m.current=s,f.useEffect(()=>{if(!e)return;let v=null,S;try{v=n||new Cu,S=v.onMessage(I=>{I.type==="TEACHER_BROADCAST_COUNTDOWN"?i(I.payload):I.type==="TEACHER_SYNC_TIMER"&&i(_=>_?{..._,timeRemaining:I.payload.timeRemaining,isRunning:I.payload.isRunning,endsAt:I.payload.isRunning?Date.now()+I.payload.timeRemaining*1e3:null}:{lessonId:e,totalDuration:Math.max(300,I.payload.timeRemaining),timeRemaining:I.payload.timeRemaining,isRunning:I.payload.isRunning,isPaused:!1,label:t==="zh"?"⏱️ 课堂限时任务":"⏱️ Timed Task",endsAt:I.payload.isRunning?Date.now()+I.payload.timeRemaining*1e3:null,updatedAt:Date.now()})})}catch{}(async()=>{try{const I=await fetch(`/api/classroom/sessions/${e}/countdown`);if(I.ok){const _=await I.json();_.success&&_.countdown&&i(_.countdown)}}catch{}})();let k=null;const w=Ea(I=>{const _=R=>{!R||R.lessonId&&R.lessonId!==e||i(R)};k?.(),I.on("classroom:countdown_updated",_),k=()=>I.off("classroom:countdown_updated",_)});return()=>{S?.(),w(),k?.(),!n&&typeof v?.destroy=="function"&&v.destroy()}},[e,t]),lk("openlearn:countdown:updated",v=>{v&&i(v)});const p=f.useRef(null);if(f.useEffect(()=>{!s?.isRunning||!s.endsAt||p.current!==s.endsAt&&(p.current=s.endsAt,u(!1))},[s?.isRunning,s?.endsAt]),f.useEffect(()=>{if(!s||!s.isRunning||!s.endsAt)return;const v=setInterval(()=>{const S=m.current;if(!S||!S.isRunning||!S.endsAt)return;const T=Date.now(),k=Math.max(0,Math.round((S.endsAt-T)/1e3));if(k!==S.timeRemaining){const w={...S,timeRemaining:k,updatedAt:T};k<=0&&(w.isRunning=!1,w.isPaused=!1,w.endsAt=null,c&&!d&&(ck(),u(!0))),i(w);try{window.dispatchEvent(new CustomEvent("openlearn:student:countdown_tick",{detail:{timeRemaining:k,totalDuration:S.totalDuration,label:S.label}}))}catch{}}},500);return()=>clearInterval(v)},[s?.isRunning,s?.endsAt,c,d]),!s||s.timeRemaining===0&&!s.isRunning&&!d)return null;const h=v=>{const S=Math.floor(v/60),T=v%60,k=w=>w.toString().padStart(2,"0");return`${k(S)}:${k(T)}`},g=s.totalDuration>0?Math.min(100,Math.max(0,s.timeRemaining/s.totalDuration*100)):0,y=s.timeRemaining>0&&s.timeRemaining<=60,x=s.timeRemaining>60&&s.timeRemaining<=180,b=s.timeRemaining===0;return r.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 ${o?"w-auto":"w-72 sm:w-80"}`,children:r.jsxs("div",{className:`bg-surface/95 backdrop-blur-md border rounded-2xl shadow-2xl p-3 flex flex-col gap-2 transition-all ${y?"border-rose-500/80 shadow-rose-500/20":x?"border-amber-500/80 shadow-amber-500/20":b?"border-emerald-500/80 shadow-emerald-500/20":"border-theme shadow-primary-theme/10"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[r.jsx("span",{className:`p-1 rounded-lg text-white shrink-0 ${y?"bg-rose-500 animate-pulse":x?"bg-amber-500":b?"bg-emerald-500":"bg-primary-theme"}`,children:r.jsx(zs,{size:12,className:s.isRunning?"animate-spin":"",style:{animationDuration:"6s"}})}),r.jsx("span",{className:"text-xs font-bold text-main truncate",children:s.label||(t==="zh"?"课堂任务":"Task")})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{type:"button",onClick:()=>l(!c),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:c?"提示音已开启":"提示音已静音",children:c?r.jsx(wg,{size:12}):r.jsx(vg,{size:12})}),r.jsx("button",{type:"button",onClick:()=>a(!o),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:o?"展开":"收起",children:o?r.jsx(Tn,{size:12}):r.jsx(sd,{size:12})})]})]}),!o&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between px-1",children:[r.jsx("span",{id:"student-countdown-digits",className:`text-2xl font-black font-mono tracking-widest ${y?"text-rose-500 animate-pulse":x?"text-amber-500":b?"text-emerald-500":"text-primary-theme"}`,children:h(s.timeRemaining)}),r.jsx("span",{className:"text-[11px] font-semibold text-muted",children:b?t==="zh"?"🎉 时间已截止!":"Time is up!":s.isPaused?t==="zh"?"⏸️ 老师已暂停计时":"Paused":t==="zh"?"与全班同步中":"Synced"})]}),r.jsx("div",{className:"w-full h-1.5 bg-surface-secondary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full transition-all duration-500 ${y?"bg-rose-500":x?"bg-amber-500":b?"bg-emerald-500":"bg-primary-theme"}`,style:{width:`${g}%`}})}),r.jsx($e,{slot:"student.classroom.countdown",slotProps:{countdown:s,lang:t}})]})]})})}const uk=({isOpen:e,onClose:t,lessonId:n,studentName:s="我",lang:i="zh",coreQuestion:o,challengeQuestion:a,onSubmitSuccess:c})=>{const[l,d]=f.useState(null),[u,m]=f.useState(!1),[p,h]=f.useState(null),g=!!o,y=g&&!!a,[x,b]=f.useState(null),[v,S]=f.useState(5),[T,k]=f.useState(""),[w,I]=f.useState(""),[_,R]=f.useState(!1),[L,E]=f.useState(!1),A=()=>{if(!l||!o)return;const P=l===o.correctOption;h(P),m(!0)},D=async()=>{if(_)return;R(!0);const P=g?p?x?"challenge_done":"passed":"remediation":null;try{n&&await fetch(`/api/classroom/sessions/${n}/exit-ticket`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rating:v,puzzledConcept:T.trim(),feedback:w.trim(),...g?{coreAnswer:l,isCorrect:p,tierLevel:P,challengeAnswer:x}:{}})}),E(!0),c?.()}catch{E(!0),c?.()}finally{R(!1)}},F=()=>{c?.(),t()};return e?r.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:r.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:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/80 pb-3 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 text-indigo-500 font-extrabold text-base",children:[r.jsx(lt,{size:20}),r.jsx("span",{children:i==="zh"?"60 秒自适应结课通票 (Adaptive Exit Ticket)":"60s Adaptive Exit Ticket"})]}),r.jsx("button",{onClick:F,className:"text-muted hover:text-main rounded-lg p-1 cursor-pointer","aria-label":"Close",children:r.jsx(Re,{size:18})})]}),L?r.jsxs("div",{className:"py-8 flex flex-col items-center justify-center text-center gap-3",children:[r.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:r.jsx(lt,{size:32})}),r.jsx("h3",{className:"text-base font-black text-main",children:i==="zh"?"结课通票提交成功!":"Exit Ticket Submitted!"}),r.jsx("p",{className:"text-xs text-muted max-w-xs",children:i==="zh"?"你的学情反馈与梯级作答已实时同步至教师大屏与个人课后学情卡。":"Feedback synced to classroom dashboard."}),r.jsx("button",{onClick:F,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:i==="zh"?"完成":"Done"})]}):r.jsxs("div",{className:"flex flex-col gap-4 text-xs",children:[o&&r.jsxs("div",{className:"bg-surface-secondary/70 p-4 rounded-2xl border border-border/60 flex flex-col gap-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"font-extrabold text-main flex items-center gap-1.5 text-xs",children:[r.jsx("span",{className:"px-2 py-0.5 rounded bg-indigo-500 text-white font-mono text-[10px]",children:"必做诊断"}),r.jsx("span",{children:"1. 核心概念过关题"})]}),u&&r.jsx("span",{className:`text-2xs font-bold px-2 py-0.5 rounded-full ${p?"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:p?"✓ 概念通关":"需巩固"})]}),r.jsx("p",{className:"text-main font-semibold leading-relaxed",children:o.question}),r.jsx("div",{className:"space-y-1.5",children:o.options.map(P=>r.jsxs("button",{type:"button",disabled:u,onClick:()=>d(P.key),className:`w-full p-2.5 rounded-xl border text-left flex items-start gap-2.5 transition-all cursor-pointer ${l===P.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"} ${u?"cursor-default opacity-90":""}`,children:[r.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:P.key}),r.jsx("span",{className:"text-2xs leading-relaxed",children:P.text})]},P.key))}),!u&&r.jsxs("button",{type:"button",disabled:!l,onClick:A,className:`mt-1 py-1.5 px-3 rounded-xl font-bold text-2xs transition-colors flex items-center justify-center gap-1 ${l?"bg-indigo-600 hover:bg-indigo-700 text-white cursor-pointer shadow-xs":"bg-surface-secondary text-muted cursor-not-allowed"}`,children:[r.jsx("span",{children:"确认本题答案"}),r.jsx(En,{size:12})]}),u&&p&&y&&a&&r.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:[r.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs",children:[r.jsx(wt,{size:14,className:"text-emerald-600 dark:text-emerald-400"}),r.jsx("span",{children:"太棒了!已解锁【Lv.2 进阶探究挑战题】(冲刺思维勋章)"})]}),r.jsx("p",{className:"text-2xs font-semibold text-main",children:a.prompt}),r.jsx("div",{className:"grid grid-cols-1 gap-1",children:a.options.map(P=>r.jsxs("button",{type:"button",onClick:()=>b(P.key),className:`p-2 rounded-lg border text-left text-2xs transition-colors ${x===P.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:[r.jsxs("span",{className:"font-mono font-bold mr-1.5",children:[P.key,"."]}),r.jsx("span",{children:P.text})]},P.key))})]}),u&&!p&&r.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:[r.jsxs("div",{className:"flex items-center gap-1.5 font-bold text-2xs text-amber-600 dark:text-amber-400",children:[r.jsx(Is,{size:14}),r.jsx("span",{children:"核心概念支架提示卡"})]}),r.jsx("p",{className:"text-2xs leading-relaxed",children:o.scaffoldHint}),r.jsxs("p",{className:"text-3xs text-muted",children:["解析:",o.explanation]})]})]}),r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx("label",{className:"text-2xs font-bold text-main",children:i==="zh"?"2. 今日课堂综合掌握感评估":"Rate Today Lesson"}),r.jsxs("div",{className:"flex items-center gap-2",children:[[1,2,3,4,5].map(P=>r.jsx("button",{type:"button",onClick:()=>S(P),"aria-label":`${P} 星`,"aria-pressed":P===v,className:"p-0.5 text-xl transition-transform hover:scale-125 cursor-pointer",children:r.jsx(Er,{size:20,className:P<=v?"text-amber-400 fill-amber-400":"text-slate-300"})},P)),r.jsxs("span",{className:"text-2xs font-bold text-amber-700 dark:text-amber-400 font-mono ml-1",children:[v,".0 星"]})]})]}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsx("label",{className:"text-2xs font-bold text-main",children:i==="zh"?"3. 今天最困惑或没完全搞懂的知识点/卡点是什么?":"Most Confused Concept"}),r.jsx("input",{type:"text",value:T,onChange:P=>k(P.target.value),placeholder:i==="zh"?"用几个关键词概括本节课的卡点...":"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"})]}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsx("label",{className:"text-2xs font-bold text-main",children:i==="zh"?"4. 给老师的一句小建议 (选填)":"Feedback (Optional)"}),r.jsx("input",{type:"text",value:w,onChange:P=>I(P.target.value),placeholder:i==="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"})]}),r.jsx("button",{type:"button",disabled:_,onClick:D,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:r.jsx("span",{children:_?i==="zh"?"正在提交...":"Submitting...":i==="zh"?"提交自适应结课通票":"Submit Exit Ticket"})})]})]})}):null};class Oo extends Error{constructor(t,n){super(n),this.name="ApiError",this.status=t}}async function Ie(e,t={}){const n=await fetch(e,{credentials:"same-origin",...t,headers:{...t.body?{"Content-Type":"application/json"}:{},...t.headers??{}}}),s=await n.text();let i=null;try{i=s?JSON.parse(s):null}catch{i=null}if(!n.ok)throw new Oo(n.status,i?.error||`HTTP ${n.status}`);return i}const $t={listQuestionTypes:()=>Ie("/api/assessment-question-types"),list:(e={})=>{const t=new URLSearchParams;e.kind&&t.set("kind",e.kind),e.status&&t.set("status",e.status);const n=t.toString();return Ie(`/api/assessments${n?`?${n}`:""}`)},get:e=>Ie(`/api/assessments/${encodeURIComponent(e)}`),create:e=>Ie("/api/assessments",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>Ie(`/api/assessments/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)}),remove:e=>Ie(`/api/assessments/${encodeURIComponent(e)}`,{method:"DELETE"}),replaceItems:(e,t)=>Ie(`/api/assessments/${encodeURIComponent(e)}/items`,{method:"PUT",body:JSON.stringify({items:t})}),listBank:e=>Ie(`/api/question-bank${e?`?type=${encodeURIComponent(e)}`:""}`),createBankItem:e=>Ie("/api/question-bank",{method:"POST",body:JSON.stringify(e)}),removeBankItem:e=>Ie(`/api/question-bank/${encodeURIComponent(e)}`,{method:"DELETE"}),getAssignments:e=>Ie(`/api/assessments/${encodeURIComponent(e)}/assignments`),getTeacherView:e=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/teacher-view`),publish:(e,t)=>Ie(`/api/assessments/${encodeURIComponent(e)}/publish`,{method:"POST",body:JSON.stringify(t)}),closeAssignment:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/close`,{method:"POST"}),releaseScores:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/release`,{method:"POST"}),syncGradebook:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/sync-gradebook`,{method:"POST"}),getAssignmentProgress:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/progress`),listAttempts:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`),stats:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/stats`),gradeAnswer:(e,t,n)=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/grade`,{method:"PUT",body:JSON.stringify(n)}),aiSuggestGrade:(e,t)=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/ai-suggest`,{method:"POST"}),regrade:e=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/regrade`,{method:"POST"}),exportCsvUrl:e=>`/api/assessment-assignments/${encodeURIComponent(e)}/export?format=csv`,startClassroomAssessment:(e,t)=>Ie(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment`,{method:"POST",body:JSON.stringify(t)}),getClassroomAssessmentProgress:(e,t)=>Ie(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment-progress${t?`?assignmentId=${encodeURIComponent(t)}`:""}`),myAssessments:()=>Ie("/api/me/assessments"),startAttempt:e=>Ie(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`,{method:"POST"}),reportProctor:(e,t)=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/proctor`,{method:"PUT",body:JSON.stringify(t)}),saveAnswer:(e,t,n)=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({answer:n})}),submitAttempt:e=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/submit`,{method:"POST"}),attemptResult:e=>Ie(`/api/assessment-attempts/${encodeURIComponent(e)}/result`)},As="w-full px-2.5 py-1.5 border border-theme rounded-lg text-xs bg-surface text-main focus:outline-none focus:ring-1 focus:ring-indigo-500";function hk(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function Dr({htmlFor:e,children:t}){return r.jsx("label",{htmlFor:e,className:"block text-xs font-semibold text-muted mb-1",children:t})}function Eu({config:e,answerKey:t,onChange:n,lang:s,disabled:i,multiple:o,idPrefix:a}){const c=hk(e),l=o?Array.isArray(t?.indexes)?t.indexes.map(Number).filter(p=>Number.isInteger(p)):[]:typeof t?.index=="number"?[t.index]:[],d=p=>n({config:{...e,options:p},answerKey:t}),u=(p,h)=>{if(o){const g=h?[...new Set([...l,p])].sort((y,x)=>y-x):l.filter(y=>y!==p);n({config:e,answerKey:g.length>0?{indexes:g}:null})}else n({config:e,answerKey:{index:p}})},m=p=>String.fromCharCode(65+p);return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("fieldset",{className:"space-y-1.5",children:[r.jsx("legend",{className:"text-xs font-semibold text-muted mb-1",children:s==="zh"?"选项与正确答案":"Options & correct answer"}),c.map((p,h)=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:o?"checkbox":"radio",id:`${a}-opt-${h}`,name:`${a}-answer`,checked:l.includes(h),disabled:i,onChange:g=>u(h,g.target.checked),"aria-label":`${s==="zh"?"把选项":"Mark option"} ${m(h)} ${s==="zh"?"标为正确答案":"as correct"}`,className:"shrink-0 accent-indigo-600"}),r.jsx("label",{htmlFor:`${a}-opt-${h}`,className:"sr-only",children:s==="zh"?`选项 ${m(h)}`:`Option ${m(h)}`}),r.jsx("span",{className:"text-xs font-bold text-muted w-4 shrink-0",children:m(h)}),r.jsx("input",{type:"text",value:p,disabled:i,"aria-label":s==="zh"?`选项 ${m(h)} 内容`:`Option ${m(h)} text`,onChange:g=>{const y=[...c];y[h]=g.target.value,d(y)},className:As}),r.jsx("button",{type:"button",disabled:i||c.length<=2,onClick:()=>{const g=c.filter((y,x)=>x!==h);d(g),n({config:{...e,options:g},answerKey:null})},"aria-label":s==="zh"?`删除选项 ${m(h)}`:`Delete option ${m(h)}`,className:"p-1 rounded-md text-muted hover:text-rose-500 hover:bg-rose-500/10 disabled:opacity-40 cursor-pointer shrink-0",children:r.jsx(qr,{size:13})})]},h))]}),r.jsxs("button",{type:"button",disabled:i,onClick:()=>d([...c,s==="zh"?`选项 ${m(c.length)}`:`Option ${m(c.length)}`]),className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-theme text-xs font-semibold text-main hover:bg-surface-secondary cursor-pointer",children:[r.jsx(Gr,{size:12}),s==="zh"?"添加选项":"Add option"]}),l.length===0&&r.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:s==="zh"?"未设置正确答案:该题交卷后进入人工批改。":"No correct answer set: this item will need manual grading."})]})}const fk=e=>r.jsx(Eu,{...e,multiple:!1,idPrefix:`sc-${e.lang}`}),mk=e=>r.jsx(Eu,{...e,multiple:!0,idPrefix:`mc-${e.lang}`}),pk=({config:e,answerKey:t,onChange:n,lang:s,disabled:i})=>{const o=t?.value;return r.jsxs("fieldset",{className:"space-y-2",children:[r.jsx("legend",{className:"text-xs font-semibold text-muted mb-1",children:s==="zh"?"正确答案":"Correct answer"}),r.jsx("div",{className:"flex items-center gap-4",children:[{value:!0,label:String(e.trueLabel??(s==="zh"?"正确":"True"))},{value:!1,label:String(e.falseLabel??(s==="zh"?"错误":"False"))}].map(a=>r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-main",children:[r.jsx("input",{type:"radio",name:`tf-${s}`,checked:o===a.value,disabled:i,onChange:()=>n({config:e,answerKey:{value:a.value}}),className:"accent-indigo-600"}),a.label]},String(a.value)))}),o===void 0&&r.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:s==="zh"?"未设置正确答案:该题交卷后进入人工批改。":"No correct answer set."})]})};function gk(e){const t=e.blanks;return Array.isArray(t)?t:[]}function xk(e,t){const n=e?.blanks,s=[];for(let i=0;i<t;i++){const o=Array.isArray(n)?n[i]:void 0;s.push(Array.isArray(o)?o.join(" | "):"")}return s}const bk=({config:e,answerKey:t,onChange:n,lang:s,disabled:i})=>{const o=gk(e),a=xk(t,o.length),c=(l,d)=>{const u=d.map(h=>h.split("|").map(g=>g.trim()).filter(Boolean)),m=u.some(h=>h.length>0),p=l.map((h,g)=>u[g]??[]);n({config:{...e,blanks:l},answerKey:m&&p.every(h=>h.length>0)?{blanks:p}:null})};return r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-muted",children:s==="zh"?"每个空一行;可接受答案用 | 分隔(任一命中即得分)。数值空按数值比较。":"One blank per row; separate accepted answers with |. Numeric blanks compare by value."}),o.map((l,d)=>r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_1fr_auto] gap-2 items-center",children:[r.jsxs("div",{children:[r.jsx(Dr,{htmlFor:`fb-accepted-${l.id}`,children:s==="zh"?`第 ${d+1} 空的可接受答案`:`Accepted answers for blank ${d+1}`}),r.jsx("input",{id:`fb-accepted-${l.id}`,type:"text",value:a[d]??"",disabled:i,onChange:u=>{const m=[...a];m[d]=u.target.value,c(o,m)},placeholder:s==="zh"?"光合作用 | photosynthesis":"photosynthesis",className:As})]}),r.jsxs("div",{children:[r.jsx(Dr,{htmlFor:`fb-type-${l.id}`,children:s==="zh"?"作答类型":"Answer type"}),r.jsxs("select",{id:`fb-type-${l.id}`,value:l.inputType??"text",disabled:i,onChange:u=>{const m=o.map((p,h)=>h===d?{...p,inputType:u.target.value}:p);c(m,a)},className:As,children:[r.jsx("option",{value:"text",children:s==="zh"?"文本":"Text"}),r.jsx("option",{value:"numeric",children:s==="zh"?"数值":"Numeric"})]})]}),r.jsx("button",{type:"button",disabled:i||o.length<=1,onClick:()=>{const u=o.filter((m,p)=>p!==d);c(u,a.filter((m,p)=>p!==d))},"aria-label":s==="zh"?`删除第 ${d+1} 空`:`Delete blank ${d+1}`,className:"p-1 mt-4 rounded-md text-muted hover:text-rose-500 hover:bg-rose-500/10 disabled:opacity-40 cursor-pointer justify-self-start",children:r.jsx(qr,{size:13})})]},l.id)),r.jsxs("button",{type:"button",disabled:i,onClick:()=>{const l=`b${o.length+1}-${Date.now().toString(36)}`;c([...o,{id:l,inputType:"text"}],[...a,""])},className:"inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-theme text-xs font-semibold text-main hover:bg-surface-secondary cursor-pointer",children:[r.jsx(Gr,{size:12}),s==="zh"?"添加空位":"Add blank"]}),!t&&r.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:s==="zh"?"每个空都填了可接受答案后才会启用自动判分。":"Fill every blank to enable auto-grading."})]})},yk=({config:e,onChange:t,lang:n,disabled:s})=>r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{children:[r.jsx(Dr,{htmlFor:"sa-placeholder",children:n==="zh"?"作答占位提示":"Placeholder"}),r.jsx("input",{id:"sa-placeholder",type:"text",value:String(e.placeholder??""),disabled:s,onChange:i=>t({config:{...e,placeholder:i.target.value},answerKey:null}),className:As})]}),r.jsxs("div",{children:[r.jsx(Dr,{htmlFor:"sa-maxlength",children:n==="zh"?"最多字数":"Max length"}),r.jsx("input",{id:"sa-maxlength",type:"number",min:1,value:Number(e.maxLength??2e3),disabled:s,onChange:i=>t({config:{...e,maxLength:Number(i.target.value)||2e3},answerKey:null}),className:As})]}),r.jsx("p",{className:"col-span-2 text-xs text-muted",children:n==="zh"?"简答题不自动判分,交卷后进入人工批改队列。":"Short answers are always graded manually."})]}),Ia="w-full px-3 py-2 border border-theme rounded-xl text-sm bg-surface text-main focus:outline-none focus:ring-2 focus:ring-indigo-500";function wk(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function vk(e){return String.fromCharCode(65+e)}const Tu=({config:e,value:t,onChange:n,lang:s,readOnly:i,multiple:o,name:a})=>{const c=wk(e),l=typeof t=="number"?t:null,d=Array.isArray(t)?t.map(Number).filter(u=>Number.isInteger(u)):[];return r.jsxs("fieldset",{className:"space-y-2",children:[r.jsx("legend",{className:"sr-only",children:o?s==="zh"?"可多选":"Select all that apply":s==="zh"?"单选":"Pick one"}),c.map((u,m)=>{const p=o?d.includes(m):l===m;return r.jsxs("label",{className:`flex items-start gap-2.5 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${p?"border-indigo-400 bg-indigo-50 text-main dark:bg-indigo-950/40":"border-theme bg-surface text-main hover:border-indigo-300"} ${i?"cursor-default":""}`,children:[r.jsx("input",{type:o?"checkbox":"radio",name:a,checked:p,disabled:i,onChange:h=>{if(!i)if(o){const g=h.target.checked?[...new Set([...d,m])].sort((y,x)=>y-x):d.filter(y=>y!==m);n(g)}else n(m)},className:"mt-0.5 accent-indigo-600 shrink-0"}),r.jsxs("span",{className:"text-sm leading-snug",children:[r.jsxs("span",{className:"font-bold text-muted mr-1.5",children:[vk(m),"."]}),u]})]},m)}),r.jsx("p",{className:"text-2xs text-muted",children:o?s==="zh"?"可多选:全对得满分,少选按命中比例给分,错选不得分。":"Select all: full marks for all correct, partial credit for fewer, zero for wrong picks.":s==="zh"?"单选题":"Single choice"})]})},Sk=e=>r.jsx(Tu,{...e,multiple:!1,name:"answer-single"}),jk=e=>r.jsx(Tu,{...e,multiple:!0,name:"answer-multi"}),kk=({config:e,value:t,onChange:n,lang:s,readOnly:i})=>{const o=[{v:!0,label:String(e.trueLabel??(s==="zh"?"正确":"True"))},{v:!1,label:String(e.falseLabel??(s==="zh"?"错误":"False"))}];return r.jsxs("fieldset",{className:"flex flex-wrap gap-2",children:[r.jsx("legend",{className:"sr-only",children:s==="zh"?"判断":"True or false"}),o.map(a=>r.jsxs("label",{className:`inline-flex items-center gap-2 px-4 py-2 rounded-xl border text-sm cursor-pointer ${t===a.v?"border-indigo-400 bg-indigo-50 text-main dark:bg-indigo-950/40":"border-theme bg-surface text-main hover:border-indigo-300"}`,children:[r.jsx("input",{type:"radio",name:"answer-tf",checked:t===a.v,disabled:i,onChange:()=>!i&&n(a.v),className:"accent-indigo-600"}),a.label]},String(a.v)))]})},Nk=({config:e,value:t,onChange:n,lang:s,readOnly:i})=>{const o=Array.isArray(e.blanks)?e.blanks:[],a=Array.isArray(t)?t:o.map(()=>"");return r.jsx("div",{className:"space-y-2",children:o.map((c,l)=>r.jsxs("div",{children:[r.jsx("label",{htmlFor:`blank-${c.id}`,className:"block text-2xs font-semibold text-muted mb-1",children:s==="zh"?`第 ${l+1} 空`:`Blank ${l+1}`}),r.jsx("input",{id:`blank-${c.id}`,type:c.inputType==="numeric"?"number":"text",value:String(a[l]??""),disabled:i,placeholder:c.placeholder,onChange:d=>{const u=o.map((m,p)=>p===l?d.target.value:String(a[p]??""));n(u)},className:Ia})]},c.id))})},Ck=({config:e,value:t,onChange:n,lang:s,readOnly:i})=>{const o=typeof e.maxLength=="number"?e.maxLength:2e3,a=typeof t=="string"?t:"";return r.jsxs("div",{children:[r.jsx("label",{htmlFor:"short-answer",className:"sr-only",children:s==="zh"?"作答内容":"Your answer"}),r.jsx("textarea",{id:"short-answer",rows:6,value:a,maxLength:o,disabled:i,placeholder:String(e.placeholder??(s==="zh"?"请输入你的作答":"Type your answer")),onChange:c=>n(c.target.value),className:`${Ia} resize-y`}),r.jsxs("p",{className:"text-2xs text-muted mt-1 text-right",children:[a.length,"/",o]})]})},Ek=({value:e,onChange:t,lang:n,readOnly:s})=>{const[i,o]=De.useState(()=>{try{return e==null?"":JSON.stringify(e)}catch{return""}});return r.jsxs("div",{children:[r.jsx("label",{htmlFor:"fallback-answer",className:"block text-2xs font-semibold text-muted mb-1",children:n==="zh"?"作答(JSON)":"Answer (JSON)"}),r.jsx("textarea",{id:"fallback-answer",rows:4,value:i,disabled:s,onChange:a=>{o(a.target.value);try{t(a.target.value.trim()?JSON.parse(a.target.value):null)}catch{t(a.target.value)}},className:`${Ia} resize-y font-mono`})]})},xc=["选项 A","选项 B","选项 C","选项 D"];let bc=!1;function Tk(){bc||(bc=!0,Ct.register({type:"single_choice",label:{zh:"单选题",en:"Single choice"},category:"objective",supports:["quiz","exam","survey"],Editor:fk,Answer:Sk,createDefaultConfig:()=>({options:[...xc]}),createDefaultAnswerKey:()=>({index:0})}),Ct.register({type:"multiple_choice",label:{zh:"多选题",en:"Multiple choice"},category:"objective",supports:["quiz","exam","survey"],Editor:mk,Answer:jk,createDefaultConfig:()=>({options:[...xc]}),createDefaultAnswerKey:()=>({indexes:[0]})}),Ct.register({type:"true_false",label:{zh:"判断题",en:"True / false"},category:"objective",supports:["quiz","exam","survey"],Editor:pk,Answer:kk,createDefaultConfig:()=>({trueLabel:"正确",falseLabel:"错误"}),createDefaultAnswerKey:()=>({value:!0})}),Ct.register({type:"fill_blank",label:{zh:"填空题",en:"Fill in the blank"},category:"objective",supports:["quiz","exam","survey"],Editor:bk,Answer:Nk,createDefaultConfig:()=>({blanks:[{id:"b1",inputType:"text"}]}),createDefaultAnswerKey:()=>null}),Ct.register({type:"short_answer",label:{zh:"简答/论述",en:"Short answer"},category:"subjective",supports:["quiz","exam","survey"],Editor:yk,Answer:Ck,createDefaultConfig:()=>({placeholder:"请输入你的作答",maxLength:2e3}),createDefaultAnswerKey:()=>null}))}Tk();const Ak=1500;function Ik(e){if(e===null)return"—";const t=Math.max(0,e),n=Math.floor(t/60),s=t%60;return n>=60?`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}:${String(s).padStart(2,"0")}`:`${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function yc(e){return e==null||e===""?"(未作答)":Array.isArray(e)?e.length===0?"(未作答)":e.map(t=>String(t)).join(" | "):typeof e=="object"?JSON.stringify(e):String(e)}function Pk({lang:e,onExit:t}){const n=e==="zh",[s,i]=f.useState({mode:"list"}),[o,a]=f.useState(null),[c,l]=f.useState(!1),[d,u]=f.useState(null),m=f.useCallback(async()=>{l(!0),u(null);try{const y=await $t.myAssessments();a(y.items)}catch(y){u(y instanceof Oo?y.message:String(y?.message??y))}finally{l(!1)}},[]);f.useEffect(()=>{s.mode==="list"&&m()},[s.mode,m]);const p=async y=>{u(null),l(!0);try{if(y.completed&&y.attempt){const x=await $t.attemptResult(y.attempt.id);i({mode:"result",result:x})}else{const x=await $t.startAttempt(y.assignmentId);i({mode:"answering",payload:x,answers:{...x.answers}})}}catch(x){u(x instanceof Oo?x.message:String(x?.message??x))}finally{l(!1)}};if(s.mode==="answering")return r.jsx(Pa,{lang:e,payload:s.payload,initialAnswers:s.answers,onSubmitted:y=>i({mode:"result",result:y}),onExit:()=>i({mode:"list"})});if(s.mode==="result")return r.jsx(za,{lang:e,result:s.result,onBack:()=>{i({mode:"list"}),m()}});const h=(o??[]).filter(y=>!y.completed),g=(o??[]).filter(y=>y.completed);return r.jsxs("div",{className:"flex-1 flex flex-col min-h-0 bg-surface border border-theme rounded-2xl shadow-xl overflow-hidden",children:[r.jsxs("div",{className:"px-5 py-4 border-b border-theme bg-surface-secondary/70 flex flex-wrap items-center gap-3 shrink-0",children:[t&&r.jsx("button",{type:"button",onClick:t,className:"p-1.5 rounded-lg border border-theme bg-surface text-muted hover:text-main cursor-pointer","aria-label":n?"返回学习看板":"Back to dashboard",children:r.jsx(sa,{size:15})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("h1",{className:"text-base font-bold text-main flex items-center gap-2",children:[r.jsx(An,{size:17,className:"text-indigo-500"}),n?"我的测评":"My assessments"]}),r.jsx("p",{className:"text-xs text-muted",children:n?"按截止时间排序。作答过程自动保存,断线后可续答;超时以服务端时间为准。":"Sorted by deadline. Answers autosave and resume after reconnecting; timing is server-authoritative."})]}),r.jsxs("button",{type:"button",onClick:()=>void m(),disabled:c,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-theme bg-surface text-xs font-semibold text-main disabled:opacity-50 cursor-pointer",children:[r.jsx(Hr,{size:13,className:c?"animate-spin":""}),n?"刷新":"Refresh"]})]}),d&&r.jsx("p",{role:"alert",className:"mx-5 mt-3 px-3 py-2 rounded-xl border border-rose-200 bg-rose-50 text-rose-700 text-xs",children:d}),r.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-5",children:o===null&&c?r.jsxs("p",{className:"text-xs text-muted flex items-center gap-2",children:[r.jsx(mt,{size:13,className:"animate-spin"}),n?"加载中…":"Loading…"]}):(o?.length??0)===0?r.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[r.jsx(An,{size:36,className:"text-muted opacity-40"}),r.jsx("p",{className:"text-sm font-semibold text-main",children:n?"暂无待完成测评":"No assessments yet"}),r.jsx("p",{className:"text-xs text-muted",children:n?"老师发布测评后会出现在这里。":"Published assessments will show up here."})]}):r.jsxs(r.Fragment,{children:[r.jsxs("section",{"aria-labelledby":"pending-heading",children:[r.jsxs("h2",{id:"pending-heading",className:"text-xs font-bold text-main mb-2",children:[n?"待完成":"To do","(",h.length,")"]}),h.length===0?r.jsx("p",{className:"text-xs text-muted",children:n?"没有待完成的测评。":"Nothing pending."}):r.jsx("ul",{"data-testid":"student-pending-list",className:"space-y-2",children:h.map(y=>r.jsx("li",{children:r.jsx(wc,{entry:y,lang:e,disabled:c,onOpen:()=>void p(y)})},y.assignmentId))})]}),g.length>0&&r.jsxs("section",{"aria-labelledby":"done-heading",children:[r.jsxs("h2",{id:"done-heading",className:"text-xs font-bold text-main mb-2",children:[n?"已完成":"Completed","(",g.length,")"]}),r.jsx("ul",{"data-testid":"student-completed-list",className:"space-y-2",children:g.map(y=>r.jsx("li",{children:r.jsx(wc,{entry:y,lang:e,disabled:c,onOpen:()=>void p(y)})},y.assignmentId))})]})]})})]})}function wc({entry:e,lang:t,disabled:n,onOpen:s}){const i=t==="zh",o=e.windowState==="after_close",a=e.windowState==="before_open",c=!e.completed&&(o||a),l=e.kind==="quiz"?i?"测试":"Quiz":e.kind==="exam"?i?"考试":"Exam":i?"问卷":"Survey";return r.jsxs("div",{"data-testid":`student-assessment-${e.assignmentId}`,className:"bg-surface border border-theme rounded-xl px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-3",children:[r.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"font-bold text-sm text-main truncate",children:e.title}),r.jsx("span",{className:"px-2 py-0.5 rounded-full bg-surface-secondary border border-theme text-2xs font-semibold text-main",children:l}),e.completed&&e.attempt?.needsManualReview&&r.jsx("span",{className:"px-2 py-0.5 rounded-full text-2xs font-semibold bg-amber-50 text-amber-700 border border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-800",children:i?"待批改":"Pending review"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-2xs text-muted flex-wrap",children:[r.jsxs("span",{className:"inline-flex items-center gap-1",children:[r.jsx(zs,{size:11}),o?i?"已截止":"Closed":a?i?"未开始":"Not open yet":e.closesAt?`${i?"截止":"Due"} ${new Date(e.closesAt).toLocaleString()}`:i?"不限时":"No deadline"]}),e.durationSec&&r.jsx("span",{children:i?`限时 ${Math.round(e.durationSec/60)} 分钟`:`${Math.round(e.durationSec/60)} min`}),e.completed&&e.attempt&&r.jsx("span",{children:e.attempt.score===null?i?"成绩待发布":"Score pending":`${i?"得分":"Score"} ${e.attempt.score}/${e.attempt.maxScore??"—"}`})]})]}),r.jsxs("button",{type:"button",onClick:s,disabled:n||c,className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold shrink-0 ${c?"bg-surface-secondary text-muted border border-theme cursor-not-allowed":e.completed?"border border-theme text-main hover:bg-surface-secondary cursor-pointer":"bg-indigo-600 text-white hover:bg-indigo-700 cursor-pointer"}`,children:[!c&&!e.completed&&r.jsx(Yo,{size:12}),c?o?i?"已截止":"Closed":i?"未开始":"Not open":e.completed?i?"查看结果":"View result":i?"开始作答":"Start"]})]})}function Pa({lang:e,payload:t,initialAnswers:n,onSubmitted:s,onExit:i}){const o=e==="zh",a=t.attempt.id,c=t.assignment.kind==="exam"||!!t.assignment.settings?.strictProctor,[l,d]=f.useState(n),[u,m]=f.useState(new Set),[p,h]=f.useState(t.attempt.remainingSeconds??null),[g,y]=f.useState(!1),[x,b]=f.useState(null),[v,S]=f.useState(null),[T,k]=f.useState(!!document.fullscreenElement),[w,I]=f.useState(0),[_,R]=f.useState(null),L=f.useRef({}),E=f.useRef(l),A=f.useRef(!1);E.current=l;const D=f.useCallback(async j=>{if(!(!c||A.current))try{I(q=>q+1),R({blur:o?"检测到窗口失去焦点,已记录监考日志!":"Window lost focus — logged to proctor record!",visibility_hidden:o?"检测到切换屏幕/应用,已记录监考日志!":"Screen/tab switched — logged to proctor record!",fullscreen_exit:o?"检测到退出全屏作答,已记录监考日志!":"Exited fullscreen — logged to proctor record!"}[j]),await $t.reportProctor(a,{type:j})}catch{}},[a,c,o]);f.useEffect(()=>{if(!c)return;const j=()=>{document.visibilityState==="hidden"&&D("visibility_hidden")},B=()=>{D("blur")},q=()=>{const G=!!document.fullscreenElement;k(G),!G&&!A.current&&D("fullscreen_exit")},C=G=>{G.preventDefault()},K=G=>{G.preventDefault()};return document.addEventListener("visibilitychange",j),window.addEventListener("blur",B),document.addEventListener("fullscreenchange",q),document.addEventListener("contextmenu",C),document.addEventListener("copy",K),document.addEventListener("cut",K),document.addEventListener("paste",K),()=>{document.removeEventListener("visibilitychange",j),window.removeEventListener("blur",B),document.removeEventListener("fullscreenchange",q),document.removeEventListener("contextmenu",C),document.removeEventListener("copy",K),document.removeEventListener("cut",K),document.removeEventListener("paste",K)}},[c,D]);const F=async()=>{try{document.fullscreenElement||await document.documentElement.requestFullscreen()}catch{}},P=f.useCallback(async j=>{try{await $t.saveAnswer(a,j,E.current[j]??null),S(Date.now()),m(B=>{const q=new Set(B);return q.delete(j),q})}catch(B){b(B?.message??String(B))}},[a]),$=(j,B)=>{d(q=>({...q,[j]:B})),m(q=>new Set(q).add(j)),L.current[j]&&clearTimeout(L.current[j]),L.current[j]=setTimeout(()=>void P(j),Ak)},V=f.useCallback(async()=>{if(!A.current){A.current=!0,y(!0),b(null);try{for(const q of Object.keys(L.current))L.current[q]&&clearTimeout(L.current[q]);const j=[...u];await Promise.all(j.map(q=>$t.saveAnswer(a,q,E.current[q]??null)));const B=await $t.submitAttempt(a);document.fullscreenElement&&document.exitFullscreen().catch(()=>{}),s(B)}catch(j){A.current=!1,b(j?.message??String(j))}finally{y(!1)}}},[a,u,s]);f.useEffect(()=>{if(p===null)return;if(p<=0){V();return}const j=setTimeout(()=>h(B=>B===null?null:B-1),1e3);return()=>clearTimeout(j)},[p,V]),f.useEffect(()=>()=>{Object.values(L.current).forEach(j=>clearTimeout(j))},[]);const z=f.useMemo(()=>[...t.items].sort((j,B)=>j.sortOrder-B.sortOrder),[t.items]),U=z.filter(j=>{const B=l[j.id];return B==null||B===""?!1:Array.isArray(B)?B.length>0:!0}).length;return r.jsxs("div",{className:`flex-1 flex flex-col min-h-0 bg-surface border border-theme rounded-2xl shadow-xl overflow-hidden relative ${c?"select-none":""}`,children:[c&&r.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 opacity-[0.035] dark:opacity-[0.06] overflow-hidden flex flex-wrap items-center justify-around gap-16 select-none p-4",children:Array.from({length:24}).map((j,B)=>r.jsxs("div",{className:"transform -rotate-25 text-xs font-mono font-bold tracking-widest text-main",children:[t.assignment.title," · #",a.slice(-6)]},B))}),r.jsxs("div",{className:"relative z-10 px-5 py-3 border-b border-theme bg-surface-secondary/70 flex flex-wrap items-center gap-3 shrink-0",children:[!c&&r.jsx("button",{type:"button",onClick:i,className:"p-1.5 rounded-lg border border-theme bg-surface text-muted hover:text-main cursor-pointer","aria-label":o?"返回测评列表(作答已自动保存)":"Back to list (answers are saved)",children:r.jsx(sa,{size:15})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h1",{className:"text-sm font-bold text-main truncate",children:t.assignment.title}),c&&r.jsx("span",{className:"px-2 py-0.5 rounded-full text-2xs font-extrabold bg-rose-50 text-rose-700 border border-rose-200 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-800",children:o?"严格考试模式":"Exam Mode"})]}),r.jsxs("p",{className:"text-2xs text-muted",children:[o?"已作答":"Answered"," ",U,"/",z.length,v&&` · ${o?"已自动保存":"autosaved"}`,u.size>0&&` · ${o?"保存中…":"saving…"}`,c&&w>0&&r.jsx("span",{className:"text-rose-600 font-semibold ml-2",children:o?`异常记录 ${w} 次`:`Violations: ${w}`})]})]}),c&&!T&&r.jsx("button",{type:"button",onClick:()=>void F(),className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-xl bg-amber-600 text-white text-xs font-bold hover:bg-amber-700 cursor-pointer animate-pulse",children:o?"进入全屏锁定":"Enter Fullscreen"}),p!==null&&r.jsxs("span",{"data-testid":"assessment-countdown",className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-xl border text-xs font-bold ${p<=60?"border-rose-300 bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300":"border-theme bg-surface text-main"}`,role:"timer","aria-live":"off",children:[r.jsx(zs,{size:12}),Ik(p)]}),r.jsxs("button",{type:"button",onClick:()=>void V(),disabled:g,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-700 text-white text-xs font-bold hover:bg-emerald-800 disabled:opacity-50 cursor-pointer",children:[g?r.jsx(mt,{size:13,className:"animate-spin"}):r.jsx(lt,{size:13}),o?"提交交卷":"Submit"]}),r.jsx($e,{slot:"assessment.attempt.toolbar",slotProps:{assignmentId:t.assignment.id,attemptId:a,lang:e},lang:e})]}),_&&r.jsxs("div",{role:"alert",className:"relative z-10 mx-5 mt-3 px-3 py-2 rounded-xl border border-amber-200 bg-amber-50 text-amber-800 text-xs flex items-center justify-between gap-2",children:[r.jsxs("span",{children:["⚠️ ",_]}),r.jsx("button",{type:"button",onClick:()=>R(null),className:"text-2xs font-bold underline cursor-pointer",children:o?"知道了":"Dismiss"})]}),x&&r.jsx("p",{role:"alert",className:"relative z-10 mx-5 mt-3 px-3 py-2 rounded-xl border border-rose-200 bg-rose-50 text-rose-700 text-xs",children:x}),r.jsx("div",{className:"relative z-10 flex-1 overflow-y-auto p-5",children:r.jsx("ol",{className:"space-y-4 max-w-3xl mx-auto",children:z.map((j,B)=>{const C=Ct.get(j.type)?.Answer??Ek;return r.jsxs("li",{"data-testid":`answer-item-${j.id}`,className:"border border-theme rounded-xl p-4 space-y-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("span",{className:"text-2xs font-bold text-muted mt-0.5",children:["#",B+1]}),r.jsx("p",{className:"text-sm font-semibold text-main whitespace-pre-wrap break-words flex-1",children:j.stem}),r.jsxs("span",{className:"text-2xs text-muted shrink-0",children:[j.maxScore," 分"]})]}),r.jsx(C,{config:j.config,value:l[j.id],onChange:K=>$(j.id,K),lang:e})]},j.id)})})})]})}function za({lang:e,result:t,onBack:n}){const s=e==="zh",{attempt:i,assignment:o}=t;return r.jsxs("div",{className:"flex-1 flex flex-col min-h-0 bg-surface border border-theme rounded-2xl shadow-xl overflow-hidden",children:[r.jsxs("div",{className:"px-5 py-3 border-b border-theme bg-surface-secondary/70 flex flex-wrap items-center gap-3 shrink-0",children:[r.jsx("button",{type:"button",onClick:n,className:"p-1.5 rounded-lg border border-theme bg-surface text-muted hover:text-main cursor-pointer","aria-label":s?"返回测评列表":"Back to assessments",children:r.jsx(sa,{size:15})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("h1",{className:"text-sm font-bold text-main truncate",children:o.title}),r.jsx("p",{className:"text-2xs text-muted",children:i?.submittedAt?`${s?"交卷时间":"Submitted"} ${new Date(i.submittedAt).toLocaleString()}`:s?"已交卷":"Submitted"})]}),t.showScore&&i&&r.jsxs("span",{"data-testid":"result-score",className:"text-sm font-bold text-main",children:[i.score??"—","/",i.maxScore??"—"]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-4 max-w-3xl mx-auto w-full",children:[!t.showScore&&r.jsx("p",{className:"text-xs text-muted border border-theme rounded-xl px-3 py-2 bg-surface-secondary/40",children:s?"本次成绩待老师发布后可见。你的作答已保存,可以关闭页面。":"Your score will be visible after the teacher releases it. Your answers are saved."}),t.showScore&&i?.needsManualReview&&r.jsx("p",{className:"text-xs border border-amber-200 bg-amber-50 text-amber-700 rounded-xl px-3 py-2 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-800",children:s?"主观题待人工批改,最终分数可能变化。":"Some items await manual grading; the score may change."}),t.aggregate.consideredAttempts>1&&t.aggregate.score!==null&&r.jsxs("p",{className:"text-xs text-muted",children:[s?`多次作答聚合(${t.aggregate.consideredAttempts} 次)`:`Aggregated over ${t.aggregate.consideredAttempts} attempts`,":",t.aggregate.score,"/",t.aggregate.maxScore??"—",t.aggregate.provisional&&(s?"(含待批改)":" (provisional)")]}),r.jsx("ul",{className:"space-y-3",children:t.items.map((a,c)=>r.jsxs("li",{"data-testid":`result-item-${a.itemId}`,className:"border border-theme rounded-xl p-4 space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("span",{className:"text-2xs font-bold text-muted mt-0.5",children:["#",c+1]}),r.jsx("p",{className:"text-sm font-semibold text-main whitespace-pre-wrap break-words flex-1",children:a.stem}),t.showAnalysis&&(a.needsManualReview?r.jsx("span",{className:"text-2xs text-amber-700 dark:text-amber-300 shrink-0",children:s?"待批改":"pending"}):a.isCorrect?r.jsx(lt,{size:15,className:"text-emerald-600 shrink-0","aria-label":s?"正确":"Correct"}):r.jsx(Sg,{size:15,className:"text-rose-600 shrink-0","aria-label":s?"错误":"Incorrect"}))]}),r.jsxs("p",{className:"text-xs text-main bg-surface-secondary rounded-lg px-2 py-1.5 whitespace-pre-wrap break-words",children:[r.jsx("span",{className:"text-muted mr-1",children:s?"你的作答:":"Your answer:"}),yc(a.answer)]}),t.showAnalysis&&a.answerKey!==void 0&&a.answerKey!==null&&r.jsxs("p",{className:"text-2xs text-muted",children:[s?"参考答案:":"Reference answer:"," ",yc(a.answerKey)]}),t.showAnalysis&&a.feedback&&r.jsxs("p",{className:"text-2xs text-indigo-700 dark:text-indigo-300",children:[s?"教师评语:":"Feedback:"," ",a.feedback]}),t.showAnalysis&&a.score!==null&&r.jsxs("p",{className:"text-2xs text-muted",children:[s?"本题得分":"Item score",":",a.score,"/",a.maxScore]})]},a.itemId))}),!o.scoreReleased&&t.showScore&&r.jsxs("p",{className:"text-2xs text-muted flex items-center gap-1",children:[r.jsx(Bt,{size:11}),s?"成绩尚未正式发布。":"Scores are not officially released yet."]})]})]})}const IE=Object.freeze(Object.defineProperty({__proto__:null,AssessmentRunner:Pa,ResultView:za,StudentAssessmentsView:Pk},Symbol.toStringTag,{value:"Module"}));function zk({lessonId:e,studentId:t,studentName:n="我",classId:s,lang:i="zh",interactionLocked:o=!1}){const[a,c]=f.useState(null),[l,d]=f.useState(null),[u,m]=f.useState("IN_CLASS_TEACHING"),[p,h]=f.useState(null),[g,y]=f.useState({}),[x,b]=f.useState(null),[v,S]=f.useState(null),[T,k]=f.useState(!1),[w,I]=f.useState("IDLE"),[_,R]=f.useState(null),[L,E]=f.useState(null),[A,D]=f.useState(!1),[F,P]=f.useState(!1),[$,V]=f.useState(null),[z,U]=f.useState(null),[j,B]=f.useState(5),[q,C]=f.useState(""),[K,G]=f.useState(""),[Q,ee]=f.useState(null),[ue,we]=f.useState("closed"),[X,pe]=f.useState(null),[ke,je]=f.useState(null),[M,Y]=f.useState(!1),[te,ne]=f.useState(null),ie=f.useRef(Date.now()),oe=f.useRef(null),be=f.useRef(0),le=f.useRef(0),Ne=f.useRef(null),Te=f.useRef(null),Je=f.useRef(!1);f.useEffect(()=>{if(!e)return;let H=!0;const Z=async()=>{const fe=++be.current;try{const xe=await fetch(`/api/classroom/sessions/${e}`);if(xe.ok&&H){const re=await xe.json();if(re.hasActiveSession){if(m(re.stage),re.session?.current_segment_id&&h(re.session.current_segment_id),re.stage==="WRAP_UP_EXIT_TICKET"&&!Je.current&&D(!0),re.exitTicketCoreQuestion!==void 0&&V(re.exitTicketCoreQuestion),re.exitTicketChallengeQuestion!==void 0&&U(re.exitTicketChallengeQuestion),re.activeCountdown)try{window.dispatchEvent(new CustomEvent("openlearn:countdown:updated",{detail:re.activeCountdown}))}catch{}re.activePoll&&(!Ne.current||Ne.current.id!==re.activePoll.id)?(Ne.current=re.activePoll,c(re.activePoll),S(null),k(!1)):!re.activePoll&&Ne.current&&(Ne.current=null,c(null));const Be=Te.current;if(re.activeBuzzer)if(!Be||Be.id!==re.activeBuzzer.id)Te.current=re.activeBuzzer,d(re.activeBuzzer),I("IDLE"),R(null),oe.current=null,ie.current=Date.now();else if(re.activeBuzzer.status==="LOCKED"){const Me=oe.current,Fe=Me&&Me.buzzerId===re.activeBuzzer.id?Me.status:t&&re.activeBuzzer.winner_student_id===t?"WINNER":"MISSED";oe.current={buzzerId:re.activeBuzzer.id,status:Fe},Te.current=re.activeBuzzer,I(Fe),d(re.activeBuzzer)}else re.activeBuzzer.status==="READY"&&!(fe<=le.current)&&oe.current?.buzzerId===re.activeBuzzer.id&&(oe.current=null,Te.current=re.activeBuzzer,I("IDLE"),d(re.activeBuzzer),R(null),ie.current=Date.now());else Be&&(Te.current=null,d(null),I("IDLE"),oe.current=null)}}}catch{}};Z();const he=setInterval(Z,2500);return()=>{H=!1,clearInterval(he)}},[e,t]),f.useEffect(()=>{const H=ct();if(!H||!e)return;const Z=fe=>{fe?.lessonId===e&&fe?.activeSegmentId&&h(fe.activeSegmentId)},he=fe=>{fe?.lessonId===e&&fe?.assignmentId&&(ee({assignmentId:fe.assignmentId,title:fe.title||(i==="zh"?"随堂测评":"Classroom Assessment"),kind:fe.kind||"quiz",durationSec:fe.durationSec??null,totalItems:fe.totalItems??0,maxScore:fe.maxScore??0}),we("prompt"))};return H.on("student-active-segment-changed",Z),H.on("classroom:assessment_started",he),()=>{typeof H.off=="function"&&(H.off("student-active-segment-changed",Z),H.off("classroom:assessment_started",he))}},[e,i]);const se=async()=>{if(Q){Y(!0),ne(null);try{const H=await $t.startAttempt(Q.assignmentId);pe(H),we("answering")}catch(H){ne(H?.message||String(H))}finally{Y(!1)}}};if(f.useEffect(()=>{e&&fetch(`/api/lessons/${e}`).then(H=>H.ok?H.json():null).then(H=>{if(H?.timeline)try{const Z=typeof H.timeline=="string"?JSON.parse(H.timeline):H.timeline;if(Array.isArray(Z)){const he={};Z.forEach(fe=>{fe?.id&&fe?.title&&(he[fe.id]=fe.title)}),y(he)}}catch{}}).catch(()=>{})},[e]),f.useEffect(()=>{if(!e)return;fetch(`/api/classroom/sessions/${e}/pacing-summary?segmentId=${encodeURIComponent(p||"default")}`).then(Z=>Z.ok?Z.json():null).then(Z=>{Z?.success&&b(Z.mySignal||null)}).catch(()=>{})},[e,p]),!e)return null;const N=async H=>{try{const Z=x===H,he=await fetch(`/api/classroom/sessions/${e}/pacing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signal:Z?null:H,action:Z?"cancel":void 0,toggle:!0,segmentId:p||"default"})});if(he.ok){const fe=await he.json();b(fe.currentSignal??null),fe.currentSignal?E(H==="TOO_FAST"?i==="zh"?"已反馈: 🐇 讲太快":"Pacing: Too Fast":H==="SLOW"?i==="zh"?"已反馈: 🐢 讲太慢":"Pacing: Too Slow":H==="CONFUSED"?i==="zh"?"已反馈: ❓ 有疑问":"Pacing: Confused":i==="zh"?"已反馈: 💡 听懂了":"Pacing: Clear"):E(i==="zh"?"已取消反馈":"Feedback cleared"),setTimeout(()=>E(null),2500)}}catch{}},O=async H=>{if(!(!a||T))try{S(H),k(!0),await fetch(`/api/classroom/sessions/${e}/quick-poll/${a.id}/vote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({option:H})})}catch{}},W=async()=>{if(!l||l.status!=="READY"||w!=="IDLE")return;const H=Date.now()-ie.current;le.current=be.current,I("BUZZED");try{const Z=await fetch(`/api/classroom/sessions/${e}/buzzer/${l.id}/buzz`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentName:n,responseTimeMs:H})});if(Z.ok){const he=await Z.json(),fe=he.won??he.winner===!0,xe=fe?"WINNER":"MISSED";if(oe.current={buzzerId:l.id,status:xe},I(xe),!fe&&he.winner){const re={...l,status:"LOCKED",winner_student_id:he.winner.studentId??null,winner_student_name:he.winner.studentName??null,winner_response_time_ms:he.winner.responseTimeMs??null};Te.current=re,d(re)}}else I("IDLE")}catch{I("IDLE")}};return r.jsxs(r.Fragment,{children:[r.jsx(dk,{lessonId:e,lang:i}),r.jsx($e,{slot:"student.classroom.overlay",slotProps:{studentId:t,studentName:n,lessonId:e,classId:s},locked:o}),r.jsx($e,{slot:"student.fullscreen",slotProps:{studentId:t,studentName:n,lessonId:e}}),r.jsxs("aside",{"aria-label":i==="zh"?"课堂互动工具栏":"Classroom interaction toolbar",className:"fixed bottom-6 right-6 z-40 flex items-center gap-2.5 bg-surface/95 backdrop-blur-md border border-theme p-2 rounded-2xl shadow-2xl transition-all",children:[r.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-surface-secondary/70 rounded-xl border border-theme text-2xs font-bold text-muted",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary-theme animate-pulse"}),r.jsx("span",{className:"truncate max-w-[120px]",children:p&&g[p]?g[p]:i==="zh"?"当前环节":"Current Segment"})]}),L&&r.jsx("span",{className:"text-2xs font-bold text-primary-ink px-1.5 py-0.5 animate-fade-in whitespace-nowrap",children:L}),o&&r.jsxs("span",{"data-testid":"student-overlay-lock-chip",className:"px-2 py-1 rounded-xl bg-slate-900/70 text-white text-2xs font-bold whitespace-nowrap",title:i==="zh"?"老师已开启全班专注锁定,互动组件已暂停":"Classroom focus lock is on — interactions are paused",children:["🔒 ",i==="zh"?"专注锁定中":"Focus locked"]}),r.jsxs("div",{className:`flex items-center gap-1${o?" pointer-events-none opacity-40":""}`,"aria-disabled":o||void 0,children:[r.jsxs("button",{type:"button",disabled:o,onClick:()=>N("CLEAR"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="CLEAR"?"bg-emerald-500/20 text-emerald-700 dark:text-emerald-300 ring-2 ring-emerald-500/60 shadow-xs":"hover:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"}`,title:i==="zh"?"听懂了,节奏适宜(再次点击取消)":"Clear & Optimal (Click again to cancel)",children:[r.jsx("span",{children:"💡"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"听懂了":"Clear"}),x==="CLEAR"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,onClick:()=>N("CONFUSED"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="CONFUSED"?"bg-amber-500/20 text-amber-700 dark:text-amber-300 ring-2 ring-amber-500/60 shadow-xs":"hover:bg-amber-500/10 text-amber-700 dark:text-amber-400"}`,title:i==="zh"?"有点困惑,希望老师点拨(再次点击取消)":"Confused (Click again to cancel)",children:[r.jsx("span",{children:"❓"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"有疑问":"Confused"}),x==="CONFUSED"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,onClick:()=>N("TOO_FAST"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="TOO_FAST"?"bg-rose-500/20 text-rose-700 dark:text-rose-300 ring-2 ring-rose-500/60 shadow-xs":"hover:bg-rose-500/10 text-rose-700 dark:text-rose-400"}`,title:i==="zh"?"讲得太快了,希望能慢一点(再次点击取消)":"Too fast (Click again to cancel)",children:[r.jsx("span",{children:"🐇"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"讲太快":"Too Fast"}),x==="TOO_FAST"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,onClick:()=>N("SLOW"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="SLOW"?"bg-indigo-500/20 text-indigo-600 dark:text-indigo-300 ring-2 ring-indigo-500/60 shadow-xs":"hover:bg-indigo-500/10 text-indigo-600 dark:text-indigo-400"}`,title:i==="zh"?"讲太慢了,希望快一点(再次点击取消)":"Too slow (Click again to cancel)",children:[r.jsx("span",{children:"🐢"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"讲太慢":"Too Slow"}),x==="SLOW"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]})]})]}),a&&a.status==="ACTIVE"&&r.jsxs("div",{"data-testid":"student-quick-poll-card",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:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"text-xs font-extrabold text-amber-700 dark:text-amber-400 flex items-center gap-1.5",children:[r.jsx(wt,{size:14}),i==="zh"?"极速答题进行中":"Quick Poll Active"]}),T&&r.jsxs("span",{className:"text-[11px] text-emerald-700 dark:text-emerald-400 font-bold flex items-center gap-1",children:[r.jsx(lt,{size:12}),i==="zh"?"已提交":"Submitted"]})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:a.title}),r.jsx("div",{className:"grid grid-cols-2 gap-2 mt-1",children:(a.options||["A","B","C","D"]).map(H=>{const Z=v===H;return r.jsx("button",{disabled:T,onClick:()=>O(H),className:`p-3 rounded-xl font-bold text-center text-sm transition-all cursor-pointer ${Z?"bg-primary-solid text-white ring-2 ring-primary-theme shadow-md scale-95":T?"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:H},H)})})]}),l&&_!==l.id&&r.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4",onClick:()=>R(l.id),children:r.jsxs("div",{className:"relative 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",onClick:H=>H.stopPropagation(),children:[r.jsx("button",{onClick:()=>R(l.id),"aria-label":i==="zh"?"关闭抢答":"Close buzzer",className:"absolute top-3 right-3 p-1.5 rounded-full text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:r.jsx(Re,{size:18})}),r.jsxs("h3",{className:"text-xl font-black text-foreground flex items-center gap-2",children:[r.jsx(na,{size:22,className:"text-rose-700 dark:text-rose-400 animate-bounce"}),r.jsx("span",{children:l.title||"全班极速抢答"})]}),w==="BUZZED"&&r.jsxs("div",{className:"my-4 p-6 bg-amber-500/10 border border-amber-500/30 rounded-2xl flex flex-col items-center text-center",children:[r.jsx("span",{className:"text-4xl mb-2 animate-pulse",children:"⚡"}),r.jsx("span",{className:"text-base font-bold text-foreground",children:"正在提交抢答…"}),r.jsx("span",{className:"text-xs text-muted mt-1",children:"请稍候,马上公布结果"})]}),w==="IDLE"&&l.status==="READY"&&r.jsxs("div",{className:"my-4 flex flex-col items-center gap-3",children:[r.jsxs("button",{onClick:W,className:"w-36 h-36 rounded-full bg-gradient-to-tr from-rose-700 to-rose-600 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:[r.jsx(jg,{size:32,className:"mb-1"}),r.jsx("span",{children:"抢!"})]}),r.jsx("span",{className:"text-xs text-muted",children:"点击红色大按钮抢得首答权"})]}),w==="WINNER"&&r.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:[r.jsx("span",{className:"text-4xl mb-2",children:"🎉"}),r.jsx("span",{className:"text-lg font-black text-emerald-700 dark:text-emerald-400",children:"恭喜你率先抢答!"}),r.jsx("span",{className:"text-xs text-muted mt-1",children:"请起立或开麦回答老师的问题"}),r.jsx("button",{onClick:()=>R(l.id),className:"mt-3 px-4 py-1.5 rounded-xl text-xs font-bold text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:i==="zh"?"知道了,返回课堂":"Got it, back to class"})]}),w==="MISSED"&&r.jsxs("div",{className:"my-4 p-6 bg-slate-800/20 border border-border rounded-2xl flex flex-col items-center text-center",children:[r.jsx("span",{className:"text-4xl mb-2",children:"⚡"}),r.jsxs("span",{className:"text-base font-bold text-foreground",children:["已被 ",l.winner_student_name||"其他同学"," 抢先一步!"]}),r.jsx("span",{className:"text-xs text-muted mt-1",children:"下次手速要更快哦"}),r.jsx("button",{onClick:()=>R(l.id),className:"mt-3 px-4 py-1.5 rounded-xl text-xs font-bold text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:i==="zh"?"知道了,返回课堂":"Got it, back to class"})]})]})}),r.jsx(uk,{isOpen:A,onClose:()=>D(!1),lessonId:e,studentName:n,lang:i,coreQuestion:$,challengeQuestion:z,onSubmitSuccess:()=>{Je.current=!0,P(!0)}}),Q&&ue==="prompt"&&r.jsxs("div",{"data-testid":"student-classroom-assessment-card",className:"fixed bottom-20 left-6 z-50 bg-surface rounded-2xl border border-indigo-500/40 p-5 shadow-2xl w-80 flex flex-col gap-3 animate-slide-up",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"text-xs font-extrabold text-indigo-700 dark:text-indigo-400 flex items-center gap-1.5",children:[r.jsx(An,{size:14}),i==="zh"?"随堂测评已发起":"Classroom Assessment"]}),r.jsx("button",{onClick:()=>we("closed"),"aria-label":i==="zh"?"关闭":"Close",className:"p-1 rounded-lg text-muted hover:text-foreground cursor-pointer",children:r.jsx(Re,{size:14})})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:Q.title}),r.jsxs("div",{className:"flex items-center gap-2 text-2xs text-muted flex-wrap",children:[r.jsx("span",{className:"px-2 py-0.5 rounded-full bg-surface-secondary border border-theme",children:Q.kind==="exam"?i==="zh"?"考试":"Exam":Q.kind==="survey"?i==="zh"?"问卷":"Survey":i==="zh"?"测试":"Quiz"}),r.jsxs("span",{children:[Q.totalItems," ",i==="zh"?"道题":"items"]}),r.jsxs("span",{children:[i==="zh"?"满分":"Total"," ",Q.maxScore]}),Q.durationSec&&r.jsxs("span",{className:"inline-flex items-center gap-1",children:[r.jsx(zs,{size:11}),Math.round(Q.durationSec/60)," ",i==="zh"?"分钟":"min"]})]}),te&&r.jsx("p",{className:"text-2xs text-rose-600 bg-rose-50 dark:bg-rose-950/40 p-1.5 rounded-lg",children:te}),r.jsxs("button",{type:"button",onClick:()=>void se(),disabled:M,className:"w-full py-2 px-3 rounded-xl bg-indigo-600 text-white font-bold text-xs hover:bg-indigo-700 transition-colors flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-50",children:[M?r.jsx("span",{className:"animate-spin text-xs",children:"⏳"}):r.jsx(Yo,{size:13}),i==="zh"?"立即开始作答":"Start Assessment"]})]}),ue==="answering"&&X&&r.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6 animate-fade-in",children:r.jsx("div",{className:"w-full max-w-4xl h-[92vh] flex flex-col",children:r.jsx(Pa,{lang:i,payload:X,initialAnswers:X.answers,onSubmitted:H=>{je(H),we("result")},onExit:()=>we("closed")})})}),ue==="result"&&ke&&r.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6 animate-fade-in",children:r.jsx("div",{className:"w-full max-w-4xl h-[92vh] flex flex-col",children:r.jsx(za,{lang:i,result:ke,onBack:()=>{we("closed"),ee(null),pe(null),je(null)}})})})]})}function Lk(e){const t=kt(),n=e.pickedAnnouncement!==void 0?e.pickedAnnouncement:t?.pickedAnnouncement,s=e.setPickedAnnouncement??t?.setPickedAnnouncement,i=e.pickedAlertData!==void 0?e.pickedAlertData:t?.pickedAlertData,o=e.setPickedAlertData??t?.setPickedAlertData,a=e.lang??t?.lang??"zh",c=e.selectedLesson!==void 0?e.selectedLesson:t?.selectedLesson??null,l=e.liveClassSelectedClassId!==void 0?e.liveClassSelectedClassId:t?.liveClassSelectedClassId??null,d=e.activeStudentId!==void 0?e.activeStudentId:t?.activeStudentId??null,u=e.students??t?.students??[],m=e.activeRole??t?.activeRole??"teacher",p=e.isStudentLiveMode??t?.isStudentLiveMode??!1,h=e.liveStudentParam!==void 0?e.liveStudentParam:t?.liveStudentParam??null,g=e.isInteractionLocked!==void 0?e.isInteractionLocked:t?.isInteractionLocked??!1,y=e.addToast??t?.addToast??(()=>{}),x=e.setReadNotifications??t?.setReadNotifications??(()=>{});return r.jsxs(r.Fragment,{children:[n&&!i&&r.jsx("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-[9990] animate-in slide-in-from-top-4 duration-300 pointer-events-auto max-w-lg w-auto",children:r.jsxs("div",{className:"flex items-center gap-3 px-5 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-full shadow-xl shadow-amber-500/25 backdrop-blur-xs text-sm font-bold border border-amber-300/40",children:[r.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-75"}),r.jsx("span",{className:"relative inline-flex rounded-full h-2.5 w-2.5 bg-white"})]}),r.jsx(wt,{size:16,className:"text-amber-200 shrink-0"}),r.jsx("span",{className:"truncate",children:a==="zh"?`🎯 课堂抽问:老师随机抽中了【${n.studentName}】同学回答问题!`:`🎯 Classroom Pick: Teacher randomly selected [${n.studentName}] to answer!`}),s&&r.jsx("button",{type:"button",onClick:()=>s(null),className:"ml-2 hover:bg-white/20 rounded-full p-1 transition-colors cursor-pointer text-white/80 hover:text-white shrink-0","aria-label":"Close announcement",children:r.jsx(Re,{size:14})})]})}),i&&r.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/70 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200",children:r.jsxs("div",{className:"bg-surface border-4 border-amber-500 rounded-3xl shadow-2xl shadow-amber-500/40 ring-8 ring-amber-500/20 p-7 max-w-md w-full text-center space-y-5 animate-in zoom-in-95 duration-300",children:[r.jsxs("div",{className:"relative w-20 h-20 mx-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-amber-500/30 rounded-full animate-ping"}),r.jsx("div",{className:"relative w-20 h-20 bg-gradient-to-tr from-amber-500 to-orange-500 text-white rounded-full flex items-center justify-center shadow-lg shadow-amber-500/40",children:r.jsx(wt,{size:40,className:"animate-pulse"})})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("h3",{className:"text-2xl font-black text-main tracking-tight",children:a==="zh"?"⚡️ 闪电抽问:老师抽中了你!":"⚡️ Classroom Pick: Teacher Selected You!"}),r.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-amber-500/10 border border-amber-500/30 text-amber-600 dark:text-amber-400 font-black text-lg",children:[r.jsx("span",{children:"🎯"}),r.jsx("span",{children:i.studentName})]}),r.jsx("p",{className:"text-sm text-muted leading-relaxed",children:a==="zh"?r.jsx(r.Fragment,{children:"老师在课堂随机抽问中抽中了你,请立即集中注意力参与互动回答!"}):r.jsx(r.Fragment,{children:"The teacher selected you in the classroom random pick. Please respond and participate now!"})})]}),r.jsx("div",{className:"pt-2",children:r.jsxs("button",{type:"button",onClick:()=>{const b=new Cu(void 0,c,l);if(b.acknowledgePick(i.studentId),b.destroy(),i.rollcallId){const v=i.rollcallId;d&&rk(d,v).catch(console.error),x(S=>new Set(S).add(v))}o?.(null),y(a==="zh"?"🙋‍♂️ 已确认答到":"🙋‍♂️ Acknowledged",a==="zh"?"已向老师中控台发送举手答到信号!":"Sent acknowledge signal to teacher!","success")},className:"w-full py-3.5 bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-black text-base rounded-2xl shadow-xl shadow-amber-500/35 transition-all active:scale-95 cursor-pointer flex items-center justify-center gap-2",children:[r.jsx(lt,{size:20}),r.jsx("span",{children:a==="zh"?"🙋‍♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋‍♂️ Ready / Acknowledge to Teacher"})]})})]})}),(m==="student"||p)&&r.jsx(zk,{lessonId:c,studentId:d||h||void 0,studentName:u.find(b=>b.id===(d||h))?.name||void 0,classId:l||u.find(b=>b.id===(d||h))?.class_id||u.find(b=>b.id===(d||h))?.classId||void 0,lang:a,interactionLocked:g})]})}const La=f.createContext({});function Ra(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const Rk=typeof window<"u",Au=Rk?f.useLayoutEffect:f.useEffect,Zr=f.createContext(null),_a=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function vc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _k(...e){return t=>{let n=!1;const s=e.map(i=>{const o=vc(i,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let i=0;i<s.length;i++){const o=s[i];typeof o=="function"?o():vc(e[i],null)}}}}function Ok(...e){return f.useCallback(_k(...e),e)}class Dk extends f.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(ci(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,i=ci(s)&&s.offsetWidth||0,o=ci(s)&&s.offsetHeight||0,a=getComputedStyle(n),c=this.props.sizeRef.current;c.height=parseFloat(a.height),c.width=parseFloat(a.width),c.top=n.offsetTop,c.left=n.offsetLeft,c.right=i-c.width-c.left,c.bottom=o-c.height-c.top,c.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function Mk({children:e,isPresent:t,anchorX:n,anchorY:s,root:i,pop:o}){const a=f.useId(),c=f.useRef(null),l=f.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:d}=f.useContext(_a),u=e.props?.ref??e?.ref,m=Ok(c,u);return f.useInsertionEffect(()=>{const{width:p,height:h,top:g,left:y,right:x,bottom:b,direction:v}=l.current;if(t||o===!1||!c.current||!p||!h)return;const S=v==="rtl",T=n==="left"?S?`right: ${x}`:`left: ${y}`:S?`left: ${y}`:`right: ${x}`,k=s==="bottom"?`bottom: ${b}`:`top: ${g}`;c.current.dataset.motionPopId=a;const w=document.createElement("style");d&&(w.nonce=d);const I=i??document.head;return I.appendChild(w),w.sheet&&w.sheet.insertRule(`
66
+ [data-motion-pop-id="${a}"] {
67
+ position: absolute !important;
68
+ width: ${p}px !important;
69
+ height: ${h}px !important;
70
+ ${T}px !important;
71
+ ${k}px !important;
72
+ }
73
+ `),()=>{c.current?.removeAttribute("data-motion-pop-id"),I.contains(w)&&I.removeChild(w)}},[t]),r.jsx(Dk,{isPresent:t,childRef:c,sizeRef:l,pop:o,children:o===!1?e:f.cloneElement(e,{ref:m})})}const $k=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:i,presenceAffectsLayout:o,mode:a,anchorX:c,anchorY:l,root:d})=>{const u=Ra(Fk),m=f.useId();let p=!0,h=f.useMemo(()=>(p=!1,{id:m,initial:t,isPresent:n,custom:i,onExitComplete:g=>{u.set(g,!0);for(const y of u.values())if(!y)return;s&&s()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,s]);return o&&p&&(h={...h}),f.useMemo(()=>{u.forEach((g,y)=>u.set(y,!1))},[n]),f.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),e=r.jsx(Mk,{pop:a==="popLayout",isPresent:n,anchorX:c,anchorY:l,root:d,children:e}),r.jsx(Zr.Provider,{value:h,children:e})};function Fk(){return new Map}function Iu(e=!0){const t=f.useContext(Zr);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:i}=t,o=f.useId();f.useEffect(()=>{if(e)return i(o)},[e]);const a=f.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,a]:[!0]}const er=e=>e.key||"";function Sc(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const Pu=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:i=!0,mode:o="sync",propagate:a=!1,anchorX:c="left",anchorY:l="top",root:d})=>{const[u,m]=Iu(a),p=f.useMemo(()=>Sc(e),[e]),h=a&&!u?[]:p.map(er),g=f.useRef(!0),y=f.useRef(p),x=Ra(()=>new Map),b=f.useRef(new Set),[v,S]=f.useState(p),[T,k]=f.useState(p);Au(()=>{g.current=!1,y.current=p;for(let _=0;_<T.length;_++){const R=er(T[_]);h.includes(R)?(x.delete(R),b.current.delete(R)):x.get(R)!==!0&&x.set(R,!1)}},[T,h.length,h.join("-")]);const w=[];if(p!==v){let _=[...p];for(let R=0;R<T.length;R++){const L=T[R],E=er(L);h.includes(E)||(_.splice(R,0,L),w.push(L))}return o==="wait"&&w.length&&(_=w),k(Sc(_)),S(p),null}const{forceRender:I}=f.useContext(La);return r.jsx(r.Fragment,{children:T.map(_=>{const R=er(_),L=a&&!u?!1:p===T||h.includes(R),E=()=>{if(b.current.has(R))return;if(x.has(R))b.current.add(R),x.set(R,!0);else return;let A=!0;x.forEach(D=>{D||(A=!1)}),A&&(I?.(),k(y.current),a&&m?.(),s&&s())};return r.jsx($k,{isPresent:L,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:d,onExitComplete:L?void 0:E,anchorX:c,anchorY:l,children:_},R)})})},zu=f.createContext({strict:!1}),jc={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 kc=!1;function Bk(){if(kc)return;const e={};for(const t in jc)e[t]={isEnabled:n=>jc[t].some(s=>!!n[s])};gd(e),kc=!0}function Lu(){return Bk(),Tg()}function Uk(e){const t=Lu();for(const n in e)t[n]={...t[n],...e[n]};gd(t)}const Vk=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 Mr(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Vk.has(e)}let Ru=e=>!Mr(e);function Wk(e){typeof e=="function"&&(Ru=t=>t.startsWith("on")?!Mr(t):e(t))}try{Wk(require("@emotion/is-prop-valid").default)}catch{}function Hk(e,t,n){const s={};for(const i in e)i==="values"&&typeof e.values=="object"||ia(e[i])||(Ru(i)||n===!0&&Mr(i)||!t&&!Mr(i)||e.draggable&&i.startsWith("onDrag"))&&(s[i]=e[i]);return s}const Xr=f.createContext({});function qk(e,t){if(xd(e)){const{initial:n,animate:s}=e;return{initial:n===!1||al(n)?n:void 0,animate:al(s)?s:void 0}}return e.inherit!==!1?t:{}}function Gk(e){const{initial:t,animate:n}=qk(e,f.useContext(Xr));return f.useMemo(()=>({initial:t,animate:n}),[Nc(t),Nc(n)])}function Nc(e){return Array.isArray(e)?e.join(" "):e}const Oa=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function _u(e,t,n){for(const s in t)!ia(t[s])&&!Ag(s,n)&&(e[s]=t[s])}function Qk({transformTemplate:e},t){return f.useMemo(()=>{const n=Oa();return Ig(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Jk(e,t){const n=e.style||{},s={};return _u(s,n,e),Object.assign(s,Qk(e,t)),s}function Kk(e,t){const n={},s=Jk(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 Ou=()=>({...Oa(),attrs:{}});function Yk(e,t,n,s){const i=f.useMemo(()=>{const o=Ou();return Pg(o,t,zg(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};_u(o,e.style,e),i.style={...o,...i.style}}return i}const Zk=["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 Da(e){return typeof e!="string"||e.includes("-")?!1:!!(Zk.indexOf(e)>-1||/[A-Z]/u.test(e))}function Xk(e,t,n,{latestValues:s},i,o=!1,a){const l=(a??Da(e)?Yk:Kk)(t,s,i,e),d=Hk(t,typeof e=="string",o),u=e!==f.Fragment?{...d,...l,ref:n}:{},{children:m}=t,p=f.useMemo(()=>ia(m)?m.get():m,[m]);return f.createElement(e,{...u,children:p})}function eN({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,i){return{latestValues:tN(n,s,i,e),renderState:t()}}function tN(e,t,n,s){const i={},o=s(e,{});for(const p in o)i[p]=Lg(o[p]);let{initial:a,animate:c}=e;const l=xd(e),d=Rg(e);t&&d&&!l&&e.inherit!==!1&&(a===void 0&&(a=t.initial),c===void 0&&(c=t.animate));let u=n?n.initial===!1:!1;u=u||a===!1;const m=u?c:a;if(m&&typeof m!="boolean"&&!bd(m)){const p=Array.isArray(m)?m:[m];for(let h=0;h<p.length;h++){const g=_g(e,p[h]);if(g){const{transitionEnd:y,transition:x,...b}=g;for(const v in b){let S=b[v];if(Array.isArray(S)){const T=u?S.length-1:0;S=S[T]}S!==null&&(i[v]=S)}for(const v in y)i[v]=y[v]}}}return i}const Du=e=>(t,n)=>{const s=f.useContext(Xr),i=f.useContext(Zr),o=()=>eN(e,t,s,i);return n?o():Ra(o)},nN=Du({scrapeMotionValuesFromProps:Og,createRenderState:Oa}),sN=Du({scrapeMotionValuesFromProps:Dg,createRenderState:Ou}),rN=Symbol.for("motionComponentSymbol");function iN(e,t,n){const s=f.useRef(n);f.useInsertionEffect(()=>{s.current=n});const i=f.useRef(null);return f.useCallback(o=>{o&&e.onMount?.(o),t&&(o?t.mount(o):t.unmount());const a=s.current;if(typeof a=="function")if(o){const c=a(o);typeof c=="function"&&(i.current=c)}else i.current?(i.current(),i.current=null):a(o);else a&&(a.current=o)},[t])}const Mu=f.createContext({});function vn(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function oN(e,t,n,s,i,o){const{visualElement:a}=f.useContext(Xr),c=f.useContext(zu),l=f.useContext(Zr),d=f.useContext(_a),u=d.reducedMotion,m=d.skipAnimations,p=f.useRef(null),h=f.useRef(!1);s=s||c.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:a,props:n,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:u,skipAnimations:m,isSVG:o}),h.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,y=f.useContext(Mu);g&&!g.projection&&i&&(g.type==="html"||g.type==="svg")&&aN(p.current,n,i,y);const x=f.useRef(!1);f.useInsertionEffect(()=>{g&&x.current&&g.update(n,l)});const b=n[Mg],v=f.useRef(!!b&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(b)&&window.MotionHasOptimisedAnimation?.(b));return Au(()=>{h.current=!0,g&&(x.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),v.current&&g.animationState&&g.animationState.animateChanges())}),f.useEffect(()=>{g&&(!v.current&&g.animationState&&g.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(b)}),v.current=!1),g.enteringChildren=void 0)}),g}function aN(e,t,n,s){const{layoutId:i,layout:o,drag:a,dragConstraints:c,layoutScroll:l,layoutRoot:d,layoutAnchor:u,layoutCrossfade:m}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:$u(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!a||c&&vn(c),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:m,layoutScroll:l,layoutRoot:d,layoutAnchor:u})}function $u(e){if(e)return e.options.allowProjection!==!1?e.projection:$u(e.parent)}function qi(e,{forwardMotionProps:t=!1,type:n}={},s,i){s&&Uk(s);const o=n?n==="svg":Da(e),a=o?sN:nN;function c(d,u){let m;const p={...f.useContext(_a),...d,layoutId:lN(d)},{isStatic:h}=p,g=Gk(d),y=a(d,h);if(!h&&typeof window<"u"){cN();const x=dN(p);m=x.MeasureLayout,g.visualElement=oN(e,y,p,i,x.ProjectionNode,o)}return r.jsxs(Xr.Provider,{value:g,children:[m&&g.visualElement?r.jsx(m,{visualElement:g.visualElement,...p}):null,Xk(e,d,iN(y,g.visualElement,u),y,h,t,o)]})}c.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const l=f.forwardRef(c);return l[rN]=e,l}function lN({layoutId:e}){const t=f.useContext(La).id;return t&&e!==void 0?t+"-"+e:e}function cN(e,t){f.useContext(zu).strict}function dN(e){const t=Lu(),{drag:n,layout:s}=t;if(!n&&!s)return{};const i={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function uN(e,t){if(typeof Proxy>"u")return qi;const n=new Map,s=(o,a)=>qi(o,a,e,t),i=(o,a)=>s(o,a);return new Proxy(i,{get:(o,a)=>a==="create"?s:(n.has(a)||n.set(a,qi(a,void 0,e,t)),n.get(a))})}const hN=(e,t)=>t.isSVG??Da(e)?new $g(t):new Fg(t,{allowProjection:e!==f.Fragment});class fN extends Vt{constructor(t){super(t),t.animationState||(t.animationState=Bg(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();bd(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 mN=0;class pN extends Vt{constructor(){super(...arguments),this.id=mN++,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:o,custom:a}=this.node.getProps();if(typeof o=="string"||typeof o=="object"&&o!==null&&!Array.isArray(o)){const c=Ug(this.node,o,a);if(c){const{transition:l,transitionEnd:d,...u}=c;for(const m in u)this.node.getValue(m)?.jump(u[m])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const i=this.node.animationState.setActive("exit",!t);n&&!t&&i.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 gN={animation:{Feature:fN},exit:{Feature:pN}};function Os(e){return{point:{x:e.pageX,y:e.pageY}}}const xN=e=>t=>yd(t)&&e(t,Os(t));function ks(e,t,n,s){return Ar(e,t,xN(n),s)}const Fu=({current:e})=>e?e.ownerDocument.defaultView:null,Cc=(e,t)=>Math.abs(e-t);function bN(e,t){const n=Cc(e.x,t.x),s=Cc(e.y,t.y);return Math.sqrt(n**2+s**2)}const Ec=new Set(["auto","scroll"]);class Bu{constructor(t,n,{transformPagePoint:s,contextWindow:i=window,dragSnapToOrigin:o=!1,distanceThreshold:a=3,element:c}={}){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=tr(this.lastRawMoveEventInfo,this.transformPagePoint));const h=Gi(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=bN(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:x}=h,{timestamp:b}=ll;this.history.push({...x,timestamp:b});const{onStart:v,onMove:S}=this.handlers;g||(v&&v(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=tr(g,this.transformPagePoint),ft.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:y,onSessionEnd:x,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=Gi(h.type==="pointercancel"?this.lastMoveEventInfo:tr(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(h,v),x&&x(h,v)},!yd(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=i||window;const l=Os(t),d=tr(l,this.transformPagePoint),{point:u}=d,{timestamp:m}=ll;this.history=[{...u,timestamp:m}];const{onSessionStart:p}=n;p&&p(t,Gi(d,this.history)),this.removeListeners=wd(ks(this.contextWindow,"pointermove",this.handlePointerMove),ks(this.contextWindow,"pointerup",this.handlePointerUp),ks(this.contextWindow,"pointercancel",this.handlePointerUp)),c&&this.startScrollTracking(c)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(Ec.has(s.overflowX)||Ec.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,i=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},o={x:i.x-n.x,y:i.y-n.y};o.x===0&&o.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=o.x,this.lastMoveEventInfo.point.y+=o.y):this.history.length>0&&(this.history[0].x-=o.x,this.history[0].y-=o.y),this.scrollPositions.set(t,i),ft.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Vg(this.updatePoint)}}function tr(e,t){return t?{point:t(e.point)}:e}function Tc(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Gi({point:e},t){return{point:e,delta:Tc(e,Uu(t)),offset:Tc(e,yN(t)),velocity:wN(t,.1)}}function yN(e){return e[0]}function Uu(e){return e[e.length-1]}function wN(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const i=Uu(e);for(;n>=0&&(s=e[n],!(i.timestamp-s.timestamp>cl(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&i.timestamp-s.timestamp>cl(t)*2&&(s=e[1]);const o=Wg(i.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const a={x:(i.x-s.x)/o,y:(i.y-s.y)/o};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function vN(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?Ir(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?Ir(n,e,s.max):Math.min(e,n)),e}function Ac(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 SN(e,{top:t,left:n,bottom:s,right:i}){return{x:Ac(e.x,n,i),y:Ac(e.y,t,s)}}function Ic(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 jN(e,t){return{x:Ic(e.x,t.x),y:Ic(e.y,t.y)}}function kN(e,t){let n=.5;const s=uo(e),i=uo(t);return i>s?n=dl(t.min,t.max-s,e.min):s>i&&(n=dl(e.min,e.max-i,t.min)),Hg(0,1,n)}function NN(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 Do=.35;function CN(e=Do){return e===!1?e=0:e===!0&&(e=Do),{x:Pc(e,"left","right"),y:Pc(e,"top","bottom")}}function Pc(e,t,n){return{min:zc(e,t),max:zc(e,n)}}function zc(e,t){return typeof e=="number"?e:e[t]||0}const EN=new WeakMap;class TN{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=qg(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const o=m=>{n&&this.snapToCursor(Os(m).point),this.stopAnimation()},a=(m,p)=>{const{drag:h,dragPropagation:g,onDragStart:y}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Yg(h),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rt(b=>{let v=this.getAxisMotionValue(b).get()||0;if(Zg.test(v)){const{projection:S}=this.visualElement;if(S&&S.layout){const T=S.layout.layoutBox[b];T&&(v=uo(T)*(parseFloat(v)/100))}}this.originPoint[b]=v}),y&&ft.update(()=>y(m,p),!1,!0),ul(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},c=(m,p)=>{this.latestPointerEvent=m,this.latestPanInfo=p;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:y,onDrag:x}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:b}=p;if(g&&this.currentDirection===null){this.currentDirection=IN(b),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",p.point,b),this.updateAxis("y",p.point,b),this.visualElement.render(),x&&ft.update(()=>x(m,p),!1,!0)},l=(m,p)=>{this.latestPointerEvent=m,this.latestPanInfo=p,this.stop(m,p),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new Bu(t,{onSessionStart:o,onStart:a,onMove:c,onSessionEnd:l,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:Fu(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,i=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!i||!s)return;const{velocity:a}=i;this.startAnimation(a);const{onDragEnd:c}=this.getProps();c&&ft.postRender(()=>c(s,i))}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:i}=this.getProps();if(!s||!nr(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=vN(a,this.constraints[t],this.elastic[t])),o.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,i=this.constraints;t&&vn(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=SN(s.layoutBox,t):this.constraints=!1,this.elastic=CN(n),i!==this.constraints&&!vn(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Rt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=NN(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!vn(t))return!1;const s=t.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;i.root&&(i.root.scroll=void 0,i.root.updateScroll());const o=Gg(s,i.root,this.visualElement.getTransformPagePoint());let a=jN(i.layout.layoutBox,o);if(n){const c=n(Qg(a));this.hasMutatedConstraints=!!c,c&&(a=Jg(c))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:i,dragTransition:o,dragSnapToOrigin:a,onDragTransitionEnd:c}=this.getProps(),l=this.constraints||{},d=Rt(u=>{if(!nr(u,n,this.currentDirection))return;let m=l&&l[u]||{};(a===!0||a===u)&&(m={min:0,max:0});const p=i?200:1e6,h=i?40:1e7,g={type:"inertia",velocity:s?t[u]:0,bounceStiffness:p,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...o,...m};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(c)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ul(this.visualElement,t),s.start(Kg(t,s,0,n,this.visualElement,!1))}stopAnimation(){Rt(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps()[n];return i||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){Rt(n=>{const{drag:s}=this.getProps();if(!nr(n,s,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(n);if(i&&i.layout){const{min:a,max:c}=i.layout.layoutBox[n],l=o.get()||0;o.set(t[n]-Ir(a,c,.5)+l)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!vn(n)||!s||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Rt(a=>{const c=this.getAxisMotionValue(a);if(c&&this.constraints!==!1){const l=c.get();i[a]=kN({min:l,max:l},this.constraints[a])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.constraints=!1,this.resolveConstraints(),Rt(a=>{if(!nr(a,t,null))return;const c=this.getAxisMotionValue(a),{min:l,max:d}=this.constraints[a];c.set(Ir(l,d,i[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;EN.set(this.visualElement,this);const t=this.visualElement.current,n=ks(t,"pointerdown",d=>{const{drag:u,dragListener:m=!0}=this.getProps(),p=d.target,h=p!==t&&Xg(p);u&&m&&!h&&this.start(d)});let s;const i=()=>{const{dragConstraints:d}=this.getProps();vn(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),s||(s=AN(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:o}=this.visualElement,a=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),ft.read(i);const c=Ar(window,"resize",()=>this.scalePositionWithinConstraints()),l=o.addEventListener("didUpdate",(({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(Rt(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=d[m].translate,p.set(p.get()+d[m].translate))}),this.visualElement.render())}));return()=>{c(),n(),a(),l&&l(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:i=!1,dragConstraints:o=!1,dragElastic:a=Do,dragMomentum:c=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:i,dragConstraints:o,dragElastic:a,dragMomentum:c}}}function Lc(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function AN(e,t,n){const s=hl(e,Lc(n)),i=hl(t,Lc(n));return()=>{s(),i()}}function nr(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function IN(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class PN extends Vt{constructor(t){super(t),this.removeGroupControls=ar,this.removeListeners=ar,this.controls=new TN(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ar}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 Qi=e=>(t,n)=>{e&&ft.update(()=>e(t,n),!1,!0)};class zN extends Vt{constructor(){super(...arguments),this.removePointerDownListener=ar}onPointerDown(t){this.session=new Bu(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Fu(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:i}=this.node.getProps();return{onSessionStart:Qi(t),onStart:Qi(n),onMove:Qi(s),onEnd:(o,a)=>{delete this.session,i&&ft.postRender(()=>i(o,a))}}}mount(){this.removePointerDownListener=ks(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 Ji=!1;class LN extends f.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:i}=this.props,{projection:o}=t;o&&(n.group&&n.group.add(o),s&&s.register&&i&&s.register(o),Ji&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),tx.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:i,isPresent:o}=this.props,{projection:a}=s;return a&&(a.isPresent=o,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),Ji=!0,i||t.layoutDependency!==n||n===void 0||t.isPresent!==o?a.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?a.promote():a.relegate()||ft.postRender(()=>{const c=a.getStack();(!c||!c.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),ex.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:i}=t;Ji=!0,i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),s&&s.deregister&&s.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Vu(e){const[t,n]=Iu(),s=f.useContext(La);return r.jsx(LN,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Mu),isPresent:t,safeToRemove:n})}const RN={pan:{Feature:zN},drag:{Feature:PN,ProjectionNode:vd,MeasureLayout:Vu}};function Rc(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const i="onHover"+n,o=s[i];o&&ft.postRender(()=>o(t,Os(t)))}class _N extends Vt{mount(){const{current:t}=this.node;t&&(this.unmount=nx(t,(n,s)=>(Rc(this.node,s,"Start"),i=>Rc(this.node,i,"End"))))}unmount(){}}class ON extends Vt{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=wd(Ar(this.node.current,"focus",()=>this.onFocus()),Ar(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function _c(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 i="onTap"+(n==="End"?"":n),o=s[i];o&&ft.postRender(()=>o(t,Os(t)))}class DN extends Vt{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=sx(t,(i,o)=>(_c(this.node,o,"Start"),(a,{success:c})=>_c(this.node,a,c?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Mo=new WeakMap,Ki=new WeakMap,MN=e=>{const t=Mo.get(e.target);t&&t(e)},$N=e=>{e.forEach(MN)};function FN({root:e,...t}){const n=e||document;Ki.has(n)||Ki.set(n,{});const s=Ki.get(n),i=JSON.stringify(t);return s[i]||(s[i]=new IntersectionObserver($N,{root:e,...t})),s[i]}function BN(e,t,n){const s=FN(t);return Mo.set(e,n),s.observe(e),()=>{Mo.delete(e),s.unobserve(e)}}const UN={some:0,all:1};class VN extends Vt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:i="some",once:o}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof i=="number"?i:UN[i]},c=l=>{const{isIntersecting:d}=l;if(this.isInView===d||(this.isInView=d,o&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:u,onViewportLeave:m}=this.node.getProps(),p=d?u:m;p&&p(l)};this.stopObserver=BN(this.node.current,a,c)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(WN(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function WN({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const HN={inView:{Feature:VN},tap:{Feature:DN},focus:{Feature:ON},hover:{Feature:_N}},qN={layout:{ProjectionNode:vd,MeasureLayout:Vu}},GN={...gN,...HN,...RN,...qN},xr=uN(GN,hN);async function $r(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 QN(){const e=zx(o=>o.toasts),[t,n]=f.useState(null),s=async(o,a)=>{o.stopPropagation();const c=`[${a.title}] ${a.message}`;await $r(c)&&(n(a.id),setTimeout(()=>n(null),2e3))},i=o=>{switch(o){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:r.jsx(Cs,{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:r.jsx(Bt,{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:r.jsx(dd,{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:r.jsx(lt,{size:16})}}};return r.jsx("div",{className:"fixed bottom-6 right-6 z-50 flex flex-col gap-3 min-w-[320px] max-w-sm pointer-events-none",children:r.jsx(Pu,{children:e.map(o=>{const a=i(o.type),c=t===o.id;return r.jsxs(xr.div,{initial:{y:50,x:50,scale:.9},animate:{y:0,x:0,scale:1},exit:{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-${o.id}`,children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`p-1 rounded-full shrink-0 ${a.iconBg}`,children:a.icon}),r.jsx("p",{className:"font-semibold text-sm font-sans truncate",children:o.title})]}),(o.type==="error"||o.type==="warning")&&r.jsxs("button",{type:"button",onClick:l=>s(l,o),className:`text-xs font-bold px-1.5 py-0.5 rounded transition-all flex items-center gap-1 cursor-pointer shrink-0 ${c?"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:[c?r.jsx(ot,{size:11}):r.jsx(jn,{size:11}),r.jsx("span",{children:c?"已复制":"复制"})]})]}),r.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mt-2 leading-relaxed font-sans break-words",children:o.message}),o.action&&r.jsx("div",{className:"mt-2.5",children:r.jsx("button",{type:"button",onClick:()=>{o.action?.onClick(),Ve.getState().removeToast(o.id)},className:"px-3 py-1 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-lg shadow-xs transition-colors cursor-pointer flex items-center gap-1",children:r.jsx("span",{children:o.action.label})})})]}),r.jsx("button",{type:"button",onClick:()=>Ve.getState().removeToast(o.id),"aria-label":"关闭提示",className:"text-subtle hover:text-main hover:bg-gray-50 dark:hover:bg-slate-800 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:r.jsx(Re,{size:14})})]},o.id)})})})}class JN{constructor(){this.commands=new Map,this.recents=[],this.favorites=new Set}register(t){if(!t||!t.id)throw new Error("CommandRegistry Error: Command descriptor must have a valid ID.");this.commands.set(t.id,t)}unregister(t){return this.recents=this.recents.filter(n=>n!==t),this.favorites.delete(t),this.commands.delete(t)}getCommand(t){return this.commands.get(t)}search(t="",n){const s=t.trim().toLowerCase(),i=Array.from(this.commands.values());return Object.freeze(i.filter(o=>{if(n&&o.category!==n)return!1;if(!s)return!0;const a=o.title.toLowerCase().includes(s),c=o.description?.toLowerCase().includes(s)??!1,l=o.keywords?.some(d=>d.toLowerCase().includes(s))??!1;return a||c||l}))}async executeCommand(t,n){const s=this.commands.get(t);if(!s)throw new Error(`CommandRegistry Error: Command '${t}' not found.`);this.recents=[t,...this.recents.filter(i=>i!==t)].slice(0,10),await s.execute(n)}getRecents(){const t=this.recents.map(n=>this.commands.get(n)).filter(n=>n!==void 0);return Object.freeze(t)}getFavorites(){const t=Array.from(this.favorites).map(n=>this.commands.get(n)).filter(n=>n!==void 0);return Object.freeze(t)}toggleFavorite(t){this.favorites.has(t)?this.favorites.delete(t):this.commands.has(t)&&this.favorites.add(t)}listAll(){return Object.freeze(Array.from(this.commands.values()))}clear(){this.commands.clear(),this.recents=[],this.favorites.clear()}}function KN(e){if(e==null)return{};const t={};for(const n of Object.keys(e))t[n]=Reflect.get(e,n);return t}function sr(e,t){const n=e[t];return typeof n=="string"?n:void 0}function YN(e){if(!Array.isArray(e))return;const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];typeof s=="string"&&t.push(s)}return t.length>0?t:void 0}function ZN(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t={};for(const n of Object.keys(e))t[n]=Reflect.get(e,n);return t}function XN(e,t,n){if(typeof e!="string")return n;for(const s of t)if(s===e)return s;return n}class Wu{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 i=`${this.baseUrl}${n}`,o={method:t,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return s!==void 0&&t!=="GET"&&t!=="DELETE"&&(o.body=JSON.stringify(s)),await(await fetch(i,o)).json()}catch(i){return{success:!1,error:i.message??"Network error"}}}}const eC=new Wu,tC=["Lesson","Whiteboard","Plugin","AI","Workspace","Analytics","Resource"],$o=new JN,nC=({isOpen:e,onClose:t,registry:n=$o})=>{const[s,i]=f.useState(""),[o,a]=f.useState("All"),[c,l]=f.useState(0),d=Ce(p=>p.extensionPoints),u=f.useMemo(()=>{const p=o==="All"?void 0:o,h=n.search(s,p),y=(d.get("command_palette.item")??[]).map(x=>{const b=KN(x.slotProps),v=XN(b.category,tC,"Plugin"),S=sr(b,"title"),T=sr(b,"commandType"),k=ZN(b.payload);return{id:x.id,title:x.label||S||x.id,description:sr(b,"description"),icon:typeof x.icon=="string"?x.icon:void 0,category:v,keywords:YN(b.keywords),shortcut:sr(b,"shortcut"),execute:async w=>{if(T){const I=await eC.post("/api/plugins/execute-command",{type:T,payload:k??w});I.success||Ve.getState().addToast({id:`plugin-cmd-error-${Date.now()}`,type:"error",title:"插件命令执行失败",message:I.error||`命令 ${T} 未能执行`})}}}}).filter(x=>{if(p&&x.category!==p)return!1;if(!s.trim())return!0;const b=s.trim().toLowerCase(),v=x.title.toLowerCase().includes(b),S=x.description?.toLowerCase().includes(b)??!1,T=x.keywords?.some(k=>k.toLowerCase().includes(b))??!1;return v||S||T});return[...h,...y]},[n,s,o,d]),m=f.useCallback(p=>{if(p.key==="ArrowDown")p.preventDefault(),l(h=>h+1<u.length?h+1:0);else if(p.key==="ArrowUp")p.preventDefault(),l(h=>h-1>=0?h-1:u.length-1);else if(p.key==="Enter"){p.preventDefault();const h=u[c];h&&(n.getCommand?.(h.id)?n.executeCommand(h.id):h.execute(),t())}else p.key==="Escape"&&(p.preventDefault(),t())},[u,c,n,t]);return f.useEffect(()=>{l(0)},[s,o]),e?r.jsx("div",{className:"command-palette-backdrop fixed inset-0 bg-slate-950/70 backdrop-blur-sm z-50 flex items-start justify-center pt-24",onClick:t,"data-testid":"command-palette-backdrop",children:r.jsxs("div",{className:"command-palette-container w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-xl shadow-2xl overflow-hidden flex flex-col",onClick:p=>p.stopPropagation(),"data-testid":"command-palette-modal",children:[r.jsxs("div",{className:"flex items-center px-4 py-3 border-b border-slate-800 bg-slate-900/90",children:[r.jsx("input",{type:"text",className:"w-full bg-transparent text-slate-100 placeholder-slate-400 outline-none text-base font-medium",placeholder:"Type a command or search...",value:s,onChange:p=>i(p.target.value),onKeyDown:m,autoFocus:!0,"data-testid":"command-search-input"}),r.jsx("kbd",{className:"text-xs bg-slate-800 text-slate-400 px-2 py-1 rounded border border-slate-700 font-mono",children:"ESC"})]}),r.jsx("div",{className:"flex items-center space-x-1 px-3 py-2 border-b border-slate-800 bg-slate-900/50 overflow-x-auto",children:["All","Lesson","Whiteboard","Plugin","AI","Workspace","Analytics","Resource"].map(p=>r.jsx("button",{className:`px-2.5 py-1 text-xs rounded-md transition-colors font-medium ${o===p?"bg-indigo-600 text-white":"text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,onClick:()=>a(p),children:p},p))}),r.jsx("div",{className:"max-h-96 overflow-y-auto p-2 divide-y divide-slate-800/50",children:u.length===0?r.jsx("div",{className:"py-8 text-center text-slate-500 text-sm",children:"No commands found."}):u.map((p,h)=>r.jsxs("div",{className:`flex items-center justify-between px-3 py-2.5 rounded-lg cursor-pointer transition-colors ${h===c?"bg-indigo-600/20 text-white":"text-slate-300 hover:bg-slate-800/60"}`,onClick:()=>{n.getCommand?.(p.id)?n.executeCommand(p.id):p.execute(),t()},"data-testid":`command-item-${p.id}`,children:[r.jsxs("div",{className:"flex items-center space-x-3",children:[r.jsx("span",{className:"text-xs font-semibold px-2 py-0.5 rounded bg-slate-800 text-indigo-400 border border-slate-700",children:p.category}),r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-medium text-slate-100",children:p.title}),p.description&&r.jsx("div",{className:"text-xs text-slate-400",children:p.description})]})]}),p.shortcut&&r.jsx("kbd",{className:"text-xs font-mono text-slate-400 bg-slate-800 px-2 py-0.5 rounded border border-slate-700",children:p.shortcut})]},p.id))})]})}):null},Fr={teaching:{key:"teaching",label:{zh:"教学工具",en:"TEACHING"},position:10},system:{key:"system",label:{zh:"系统管理",en:"SYSTEM MANAGEMENT"},position:20},extensions:{key:"extensions",label:{zh:"扩展应用",en:"EXTENSIONS"},position:30},support:{key:"support",label:{zh:"帮助支持",en:"HELP & SUPPORT"},position:40}},sC=[{id:"courses",tab:"courses",label:{zh:"课程管理",en:"Courses"},icon:Is,group:"teaching",position:10},{id:"live_class",tab:"live_class",label:{zh:"互动课堂",en:"Live Class"},icon:Wr,group:"teaching",position:20,highlight:!0},{id:"classes",tab:"classes",label:{zh:"班级管理",en:"Classes & Students"},icon:Jo,group:"teaching",position:30},{id:"assessments",tab:"assessments",label:{zh:"测评中心",en:"Assessment Center"},icon:An,group:"teaching",position:40},{id:"timetable",tab:"timetable",label:{zh:"课表管理",en:"Timetable Routine"},icon:kg,group:"system",position:10},{id:"computer_labs",tab:"computer_labs",label:{zh:"机房管理",en:"Computer Lab Seating"},icon:md,group:"system",position:20},{id:"plugins",tab:"plugins",label:{zh:"插件中心",en:"App Store / Plugins"},icon:Vr,group:"system",position:30},{id:"admin_directory",tab:"admin_directory",label:{zh:"管理后台",en:"⭐ Admin Center"},icon:td,group:"system",position:40,administratorOnly:!0},{id:"help",tab:"help",label:{zh:"帮助文档",en:"System Commands / Help"},icon:Ko,group:"support",position:10}];function rC(e,t){return sC.filter(n=>!n.administratorOnly||e==="administrator").map(n=>({id:n.id,tab:n.tab,label:n.label[t]??n.label.zh,labelZh:n.label.zh,labelEn:n.label.en,icon:n.icon,group:n.group,position:n.position,administratorOnly:n.administratorOnly??!1,highlight:n.highlight??!1})).sort((n,s)=>{const i=Fr[n.group].position,o=Fr[s.group].position;return i!==o?i-o:n.position-s.position})}function PE(e,t){return Fr[e].label[t]??Fr[e].label.zh}const iC=e=>e==="zh",en="builtin.";function oC(e){const t=iC(e.lang),n=[];for(const i of rC(e.role,e.lang))n.push({id:`${en}goto.${i.id}`,title:t?`前往${i.labelZh}`:`Go to ${i.labelEn}`,description:t?"切换到左侧导航中的对应工作区":"Switch to the matching workspace",category:"Workspace",keywords:t?[i.labelZh,"跳转","导航"]:[i.labelEn,"go","navigate"],execute:()=>e.setTeacherTab(i.tab)});n.push({id:`${en}ui.toggleSidebar`,title:t?"折叠 / 展开左侧导航":"Collapse / expand sidebar",description:t?"切换左侧导航栏的宽度":"Toggle the left navigation width",category:"Workspace",keywords:t?["侧边栏","折叠","展开"]:["sidebar","collapse","expand"],execute:()=>e.toggleSidebar()}),n.push({id:`${en}ui.toggleLanguage`,title:t?"切换界面语言(中 / 英)":"Toggle interface language (ZH / EN)",category:"Workspace",keywords:t?["语言","中英文"]:["language","locale","i18n"],execute:()=>e.toggleLanguage()}),n.push({id:`${en}ui.openNotifications`,title:t?"打开通知中心":"Open notifications",category:"Workspace",keywords:t?["通知","消息"]:["notification","inbox"],execute:()=>e.openNotifications()}),n.push({id:`${en}ui.openSystemResourceLibrary`,title:t?"打开系统资源库":"Open system resource library",category:"Resource",keywords:t?["资源库","素材"]:["resource","library","material"],execute:()=>e.openSystemResourceLibrary()}),n.push({id:`${en}ui.openProfile`,title:t?"打开个人资料":"Open profile",category:"Workspace",keywords:t?["个人","资料","头像"]:["profile","account","avatar"],execute:()=>e.openProfile()});const s=[{id:"light",zh:"浅色",en:"Light"},{id:"dark",zh:"深色",en:"Dark"},{id:"eyecare",zh:"护眼",en:"Eyecare"},{id:"chalkboard",zh:"黑板",en:"Chalkboard"}];for(const i of s)n.push({id:`${en}theme.${i.id}`,title:t?`切换主题:${i.zh}`:`Switch theme: ${i.en}`,category:"Workspace",keywords:t?["主题","配色",i.zh]:["theme","appearance",i.en],execute:()=>e.setTheme(i.id)});return n}function aC(e,t){for(const n of oC(t))e.register(n)}function lC(){const[e,t]=f.useState(!1),n=kt(),s=ae(l=>l.lang),i=ae(l=>l.setTeacherTab),o=_n(l=>l.setTheme),a=n?.session?.subRole==="administrator"?"administrator":"teacher";f.useEffect(()=>{aC($o,{setTeacherTab:i,role:a,lang:s,toggleSidebar:()=>{const l=n?.mainNavCollapsed;l!==void 0&&n?.setMainNavCollapsed?.(!l)},toggleLanguage:()=>n?.toggleLanguage?.(),setTheme:o,openNotifications:()=>n?.setIsNotificationsOpen?.(!0),openSystemResourceLibrary:()=>n?.setIsSystemResourceLibraryOpen?.(!0),openProfile:()=>n?.setProfileOpen?.(!0)})},[n,s,a,i,o]);const c=f.useCallback(()=>t(!1),[]);return f.useEffect(()=>{const l=d=>{d.key.toLowerCase()==="k"&&(!d.metaKey&&!d.ctrlKey||(d.preventDefault(),t(u=>!u)))};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[]),f.useEffect(()=>{if(!e)return;const l=d=>{d.key==="Escape"&&t(!1)};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),e?r.jsx(nC,{isOpen:e,onClose:c,registry:$o}):null}const Fo=new Set;function cC(e){return Fo.add(e),()=>{Fo.delete(e)}}const Oc=30,Dc=(e,t)=>Math.min(e,t.length);function Ma(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(`
74
+ `)}function Hu(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(`
75
+ `)}function dC(e,t=[]){const n=new Date().toLocaleString(),s=typeof window<"u"?window.location.href:"Unknown",i=typeof navigator<"u"?navigator.userAgent:"Unknown";if(e.length===0&&t.length===0)return`# 🛠️ OpenLearn 系统诊断报告
76
+ - 生成时间: ${n}
77
+ - 暂无记录的系统异常。`;const o=e.length+t.length,a=["# 🛠️ OpenLearn 系统异常诊断报告",`- **生成时间**: ${n}`,`- **当前页面**: ${s}`,`- **异常总数**: ${o} 项`,`- **本机异常数**: ${e.length} 项`,`- **学生端异常数**: ${t.length} 项`,`- **运行环境**: ${i}`,"","---",""].join(`
78
+ `),c=e.length>0?`## 💻 本机异常记录 (${e.length})
79
+
80
+ `+e.map((d,u)=>`#### 错误 #${u+1} (${d.type.toUpperCase()})
81
+ `+Ma(d)).join(`
82
+
83
+ ---
84
+
85
+ `):"",l=t.length>0?`## 🎒 学生端异常记录 (${t.length})
86
+
87
+ `+t.map((d,u)=>`#### 学生异常 #${u+1}
88
+ `+Hu(d)).join(`
89
+
90
+ ---
91
+
92
+ `):"";return[a,c,l].filter(Boolean).join(`
93
+
94
+ ---
95
+
96
+ `)}const tn=jt((e,t)=>({errors:[],studentErrors:[],activeTab:"local",isErrorCenterOpen:!1,unreadCount:0,addError:n=>{const s=Date.now(),i=n.url||(typeof window<"u"?window.location.href:""),o=n.userAgent||(typeof navigator<"u"?navigator.userAgent:""),a=t().errors.findIndex(l=>l.type===n.type&&l.message===n.message&&s-l.timestamp<2e3);if(a>=0)return t().errors[a];const c={id:`err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:n.timestamp||s,url:i,userAgent:o,type:n.type,title:n.title,message:n.message,stack:n.stack,componentStack:n.componentStack,endpoint:n.endpoint,status:n.status};return e(l=>{const d=[c,...l.errors].slice(0,Oc);return{errors:d,unreadCount:Dc(l.unreadCount+1,d)}}),Fo.forEach(l=>{try{l(c)}catch(d){console.error("[ErrorStore] Error in errorListener:",d)}}),c},removeError:n=>e(s=>{const i=s.errors.filter(o=>o.id!==n);return{errors:i,unreadCount:Dc(s.unreadCount,i)}}),clearErrors:()=>e({errors:[],unreadCount:0}),addStudentError:n=>{const s=Date.now(),i=n.timestamp||s;e(o=>o.studentErrors.some(d=>d.studentId===n.studentId&&d.type===n.type&&d.message===n.message&&Math.abs(i-d.timestamp)<2e3)?o:{studentErrors:[{...n,id:n.id||`st_err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:i},...o.studentErrors].slice(0,Oc)})},removeStudentError:n=>e(s=>({studentErrors:s.studentErrors.filter(i=>i.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 gt(e){return Ut(tn,e||(t=>t))}function uC(){const e=ae(E=>E.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=gt(E=>E.errors),i=gt(E=>E.studentErrors),o=gt(E=>E.activeTab),a=gt(E=>E.setActiveTab),c=gt(E=>E.isErrorCenterOpen),l=gt(E=>E.setIsErrorCenterOpen),d=gt(E=>E.clearErrors),u=gt(E=>E.clearStudentErrors),m=gt(E=>E.removeError),p=gt(E=>E.removeStudentError),[h,g]=f.useState(!1),[y,x]=f.useState(null),[b,v]=f.useState(new Set),[S,T]=f.useState(!1),k=s.length+(n?0:i.length),w=s.length>0||!n&&i.length>0,I=E=>{v(A=>{const D=new Set(A);return D.has(E)?D.delete(E):D.add(E),D})},_=async()=>{const E=dC(s,n?[]:i);await $r(E)&&(g(!0),setTimeout(()=>g(!1),2500))},R=async(E,A,D=!1)=>{E.stopPropagation();const F=D?Hu(A):Ma(A);await $r(F)&&(x(A.id),setTimeout(()=>x(null),2500))},L=E=>{switch(E){case"react":return r.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 r.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 r.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 r.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 r.jsxs(r.Fragment,{children:[w&&!c&&!S&&(n?r.jsxs(xr.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:()=>l(!0),id:"system-error-pill",title:`系统状态提示: ${s.length} 处异常`,children:[r.jsx(Bt,{size:15}),r.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})]}):r.jsxs(xr.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&&i.length>0&&a("student"),l(!0)},id:"system-error-pill",children:[r.jsxs("div",{className:"relative flex items-center justify-center",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-3 w-3 rounded-full bg-rose-400 opacity-75"}),r.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-rose-500"})]}),r.jsx(Bt,{size:15,className:"text-rose-400 group-hover:scale-110 transition-transform"}),r.jsxs("div",{className:"text-xs font-semibold flex items-center gap-1.5",children:[r.jsx("span",{children:"捕获到"}),r.jsx("span",{className:"bg-rose-500/80 text-white font-mono px-1.5 py-0.2 rounded-md text-xs font-bold",children:k}),r.jsx("span",{children:"处系统异常"}),i.length>0&&r.jsxs("span",{className:"text-[10px] text-rose-300 font-normal",children:["(含学生端 ",i.length,")"]})]}),r.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:"查看与复制"}),r.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),T(!0)},className:"text-gray-400 hover:text-gray-200 p-0.5 hover:bg-white/10 rounded transition-colors ml-0.5",title:"暂时隐藏胶囊",children:r.jsx(Re,{size:13})})]})),r.jsx(Pu,{children:c&&r.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:r.jsxs(xr.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:[r.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:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-xl",children:r.jsx(Ng,{size:18})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2",children:[r.jsx("span",{children:"系统异常诊断中心 (System Diagnostics)"}),r.jsxs("span",{className:"text-xs font-normal text-gray-500 dark:text-gray-400",children:["(",k," 项记录)"]})]})}),r.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:"自动捕获运行时、Promise 及接口 5xx 异常,支持一键导出 Markdown 格式排查报告。"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:_,disabled:k===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?r.jsx(ot,{size:13}):r.jsx(jn,{size:13}),r.jsx("span",{children:h?"已复制全部!":"一键复制全部诊断日志"})]}),r.jsx("button",{type:"button",onClick:()=>{!n&&o==="student"?u():d()},disabled:o==="student"?i.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:o==="student"?"清空学生端异常记录":"清空记录",children:r.jsx(qr,{size:16})}),r.jsx("button",{type:"button",onClick:()=>l(!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:r.jsx(Re,{size:16})})]})]}),!n&&r.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:[r.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 ${o==="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:[r.jsx(Cg,{size:13}),r.jsxs("span",{children:["本机异常 (",s.length,")"]})]}),r.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 ${o==="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:[r.jsx(kr,{size:14}),r.jsxs("span",{children:["学生端异常 (",i.length,")"]}),i.length>0&&r.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-rose-500 animate-pulse"})]})]}),r.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&&o==="student"?i.length===0?r.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[r.jsx(ot,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),r.jsx("p",{className:"text-sm font-semibold",children:"暂无学生端上报的系统异常"}),r.jsx("p",{className:"text-xs opacity-75",children:"全班学生端运行良好,未发生未捕获的前端崩溃或接口 5xx 故障。"})]}):i.map((E,A)=>{const D=b.has(E.id),F=y===E.id;return r.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:[r.jsxs("div",{onClick:()=>I(E.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:[r.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[r.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:D?r.jsx(Tn,{size:15}):r.jsx(En,{size:15})}),r.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.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:[r.jsx(kr,{size:11}),r.jsx("span",{children:E.studentName||E.studentId})]}),L(E.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",i.length-A," ",E.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(E.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:E.message}),r.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[r.jsxs("span",{children:["学生学号/ID: ",E.studentId]}),E.lessonId&&r.jsxs("span",{children:["课节: ",E.lessonId]}),E.classId&&r.jsxs("span",{children:["班级: ",E.classId]}),E.endpoint&&r.jsxs("span",{children:["接口: ",E.endpoint]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:P=>R(P,E,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${F?"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:[F?r.jsx(ot,{size:11}):r.jsx(jn,{size:11}),r.jsx("span",{children:F?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),p(E.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(Re,{size:13})})]})]}),D&&r.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:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[r.jsxs("span",{children:["学生: ",E.studentName||"未知"," (",E.studentId,")"]}),r.jsxs("span",{children:["页面地址: ",E.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(E.timestamp).toLocaleString()]})]}),E.stack&&r.jsxs("div",{children:[r.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:E.stack})]}),E.componentStack&&r.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[r.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:E.componentStack})]})]})]},E.id)}):s.length===0?r.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[r.jsx(ot,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),r.jsx("p",{className:"text-sm font-semibold",children:"暂无捕获到的系统异常"}),r.jsx("p",{className:"text-xs opacity-75",children:"系统运行顺畅,所有模块均在正常状态下运作。"})]}):s.map((E,A)=>{const D=b.has(E.id),F=y===E.id;return r.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:[r.jsxs("div",{onClick:()=>I(E.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:[r.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[r.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:D?r.jsx(Tn,{size:15}):r.jsx(En,{size:15})}),r.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[L(E.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-A," ",E.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(E.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:E.message}),E.endpoint&&r.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",E.endpoint]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:P=>R(P,E,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${F?"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:[F?r.jsx(ot,{size:11}):r.jsx(jn,{size:11}),r.jsx("span",{children:F?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),m(E.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(Re,{size:13})})]})]}),D&&r.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:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[r.jsxs("span",{children:["页面地址: ",E.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(E.timestamp).toLocaleString()]})]}),E.stack&&r.jsxs("div",{children:[r.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:E.stack})]}),E.componentStack&&r.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[r.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:E.componentStack})]})]})]},E.id)})})]})})})]})}let Mc=!1;function hC(){if(Mc)return;Mc=!0;const e=()=>He(()=>import("./ActivityWorkspaceWidget-TtBuNORs.js"),__vite__mapDeps([7,1,2,6,8])).then(t=>({default:()=>r.jsx(t.ActivityWorkspaceWidget,{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})}function fC(){return{addToast:f.useCallback((t,n,s="info")=>{const i=Math.random().toString(36).substring(2,9);Se.getState().addToast({id:i,title:t,message:n,type:s}),setTimeout(()=>{Se.getState().removeToast(i)},6e3)},[])}}function $c(e){if(typeof window>"u")return;const t=JSON.stringify({source:e.source,message:e.message.slice(0,500),stack:e.stack?e.stack.slice(0,2e3):void 0,path:window.location.pathname});try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon("/api/client-errors",new Blob([t],{type:"application/json"})))return}catch{}fetch("/api/client-errors",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}).catch(()=>{})}function Fc(e,t){if(t?.aborted)return!0;if(!e||typeof e!="object")return!1;const n=e;return n.name==="AbortError"||n.code===20}function mC(e){const t=e[1];return t?t instanceof Request?t.signal:t.signal??null:null}function pC(){f.useEffect(()=>{if(typeof window>"u")return;const e=o=>{const a=o.reason;if(Fc(a)){console.warn("[GlobalErrorCapture] Ignored aborted request rejection:",a);return}const c=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",l=a instanceof Error?a.stack:void 0;tn.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:c,stack:l}),$c({source:"promise",message:c,stack:l}),console.warn("[GlobalErrorCapture] Caught unhandled rejection:",a)},t=o=>{if(!o.message&&!o.error)return;const a=o.message||(o.error?.message??"Unknown script error"),c=o.error?.stack;tn.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:c}),$c({source:"runtime",message:a,stack:c}),console.warn("[GlobalErrorCapture] Caught window error:",o.error||o.message)},n=window.fetch,s=async(...o)=>{try{const a=await n(...o);if(!a.ok&&a.status>=500)try{const l=await a.clone().text();let d="";try{const p=JSON.parse(l);d=p.error||p.message||p.details||l}catch{d=l.slice(0,300)}const u=o[0],m=typeof u=="string"?u:u instanceof Request?u.url:String(u);tn.getState().addError({type:"api",title:`服务端接口错误 (HTTP ${a.status})`,message:d||`Request failed with status ${a.status}`,endpoint:m,status:a.status})}catch{}return a}catch(a){const c=o[0],l=typeof c=="string"?c:c instanceof Request?c.url:String(c);throw!Fc(a,mC(o))&&l&&(l.startsWith("/api")||l.includes("/api/"))&&tn.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:l,stack:a?.stack}),a}},i=cC(o=>{try{const a=Se.getState(),c=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||c))return;const d=typeof window<"u"?new URLSearchParams(window.location.search):null,u=a.session?.userId||d?.get("studentId")||"anonymous_student",m=a.session?.name||a.session?.username||d?.get("studentName")||u,p=a.selectedLesson||d?.get("lessonId")||null,h=a.liveClassSelectedClassId||d?.get("classId")||null,g={studentId:u,studentName:m,lessonId:p,classId:h,error:o},y=ct();if(y&&y.connected)y.emit("student-client-error",g);else{const x="/api/diagnostics/report",b=JSON.stringify(g);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(x,new Blob([b],{type:"application/json"})):fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:b}).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),i()}},[])}function gC(e){const{fetchStudents:t}=e,n=ae(S=>S.session),s=ae(S=>S.setSession),i=ae(S=>S.lang),o=ae(S=>S.setLang),[a,c]=f.useState("teacher"),[l,d]=f.useState(!0),[u,m]=f.useState("normal"),[p,h]=f.useState(null),[g,y]=f.useState(!1);return f.useEffect(()=>{if(!n||n.role!=="teacher")return;const S=async()=>{try{const{ok:k,status:w,data:I}=await ix();k?(I.status==="warning"||I.warning?m("warning"):m("normal"),d(!0)):w===429||w===503?(m("warning"),d(!0)):(m("error"),d(!1))}catch{m("error"),d(!1)}};S();const T=setInterval(S,5e3);return()=>clearInterval(T)},[n]),f.useEffect(()=>{(async()=>{try{const{ok:T,data:k}=await Sd();T&&Se.getState().setSiteInfo({siteName:k.siteName||"",slogan:k.slogan||"",logoUrl:k.logoUrl||null})}catch(T){console.warn("Failed to fetch site settings:",T)}})()},[]),{session:n,setSession:s,lang:i,setLang:o,activeRole:a,setActiveRole:c,setActiveStudentId:h,activeStudentId:p,dbConnected:l,dbStatus:u,profileOpen:g,setProfileOpen:y,handleLoginSuccess:S=>{if(s(S),S.role==="teacher"){c("teacher");const T=typeof window<"u"?ys(window.location.hash):null;Se.getState().setTeacherTab(T||"live_class")}else c("student"),h(S.studentId),t()},handleLogout:async()=>{try{await ax()}catch(S){console.error("Logout failed",S)}s(null)},toggleLanguage:()=>{o(i==="zh"?"en":"zh")}}}function xC(e){const{activeStudentId:t,activeRole:n,students:s,liveClassFocusLocked:i,setIsFollowingTeacher:o,lang:a,addToast:c}=e,[l,d]=f.useState("dashboard"),u=s.find(D=>D.id===t),m=n==="student"&&(!!t&&!!u?.locked_lesson_id||i),p=u?.lock_mode||"full",h=m,g=m&&p==="full",y=(()=>{if(!u?.lock_target)return null;try{return typeof u.lock_target=="string"?JSON.parse(u.lock_target):u.lock_target}catch{return null}})(),x=f.useRef(h),b=f.useRef(p),v=f.useRef(l);f.useEffect(()=>{x.current=h,b.current=p,v.current=l},[h,p,l]),f.useEffect(()=>{h&&(o(!0),d("lesson"))},[h,o]);const[S,T]=f.useState("whiteboard");f.useEffect(()=>{h&&y?.tab&&T(y.tab)},[h,y?.tab]);const k=D=>{const F=typeof D=="function"?D(v.current):D;if(x.current&&F!=="lesson"){w();return}d(F)},w=()=>{const D=b.current==="navigation";c(a==="zh"?D?"🔒 答题锁定":"🔒 全班专注锁定":D?"🔒 Answer Locked":"🔒 Class Focus Locked",a==="zh"?D?"老师已开启答题锁定,请在当前页面完成作答并提交,暂时无法离开本页。":"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":D?"The teacher locked the screen for answering. Please complete your work on this page before leaving.":"The teacher locked the class focus. Navigation is disabled — please follow the current lesson.","warning")},[I,_]=f.useState(null),[R,L]=f.useState("none"),[E,A]=f.useState(!0);return f.useEffect(()=>{l!=="lesson"&&A(!0)},[l]),{studentViewStatus:l,setStudentViewStatus:k,isStudentLocked:m,isNavigationLocked:h,isInteractionLocked:g,studentLockMode:p,studentLockTarget:y,studentLessonTab:S,setStudentLessonTab:T,studentSelectedCourseware:I,setStudentSelectedCourseware:_,studentFullscreenPanel:R,setStudentFullscreenPanel:L,isStudentLessonContentCollapsed:E,setIsStudentLessonContentCollapsed:A,notifyLockedNavigation:w}}function bC({lang:e,addToast:t,fetchStudents:n}){const[s,i]=f.useState(!1),o=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,c=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null,l=typeof window<"u"?new URLSearchParams(window.location.search).get("classId"):null,d=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="stage_display"||window.location.hash.includes("stage_display")),u=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null,m=typeof window<"u"?new URLSearchParams(window.location.search).get("title"):null,p=typeof window<"u"?new URLSearchParams(window.location.search).get("lang"):null,h=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_preview"||window.location.hash.includes("student_preview")),g=o||h,[y,x]=f.useState(!0),[b,v]=f.useState(!1);f.useEffect(()=>{_n.getState().initTheme(),Sn.getState().initFontSize();const O=W=>{(W.ctrlKey||W.metaKey)&&W.altKey&&(W.key==="+"||W.key==="="?(W.preventDefault(),Sn.getState().increaseScale()):W.key==="-"||W.key==="_"?(W.preventDefault(),Sn.getState().decreaseScale()):W.key==="0"&&(W.preventDefault(),Sn.getState().resetScale()))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[]);const S=ae(O=>O.session),T=ae(O=>O.setSession),[k,w]=f.useState(!0),I=gC({fetchStudents:n}),{activeRole:_,setActiveRole:R,activeStudentId:L,setActiveStudentId:E,dbConnected:A,dbStatus:D,profileOpen:F,setProfileOpen:P,handleLoginSuccess:$,handleLogout:V,toggleLanguage:z}=I,U=ae(O=>O.students);ae(O=>O.dataVersion);const j=ae(O=>O.setSelectedLesson),B=xC({activeStudentId:L,activeRole:_,students:U,liveClassFocusLocked:b,setIsFollowingTeacher:x,lang:e,addToast:t}),{studentViewStatus:q,setStudentViewStatus:C,isStudentLocked:K,isNavigationLocked:G,isInteractionLocked:Q,studentLockMode:ee,studentLockTarget:ue,studentLessonTab:we,setStudentLessonTab:X,studentSelectedCourseware:pe,setStudentSelectedCourseware:ke,studentFullscreenPanel:je,setStudentFullscreenPanel:M,isStudentLessonContentCollapsed:Y,setIsStudentLessonContentCollapsed:te,notifyLockedNavigation:ne}=B;f.useEffect(()=>{(async()=>{try{const{ok:W,data:H}=await ox();if(W&&H&&H.session)if(T(H.session),g){R("student"),C("lesson");const Z=a||H.session.studentId;Z&&E(Z),c&&j(c),n()}else R(H.session.role),c&&j(c),H.session.role==="student"&&H.session.studentId&&(E(H.session.studentId),n())}catch(W){console.warn("Session check failed",W)}finally{w(!1)}})()},[]);const ie=ae(O=>O.teacherTab),oe=ae(O=>O.setTeacherTab),be=f.useRef(!0);f.useEffect(()=>{if(g||d)return;const O=()=>{const H=ys(window.location.hash);H&&H!==Se.getState().teacherTab&&oe(H)};window.addEventListener("hashchange",O);const W=ys(window.location.hash);return W&&W!==Se.getState().teacherTab&&oe(W),()=>window.removeEventListener("hashchange",O)},[oe,g,d]),f.useEffect(()=>{if(g||d)return;if(be.current){be.current=!1;const W=ys(window.location.hash);if(W&&W!==ie)return}const O=kd(ie);window.location.hash!==O&&(window.location.hash=O)},[ie,oe,g,d]);const[le,Ne]=f.useState(!1),[Te,Je]=f.useState(!1),[se,N]=f.useState(!1);return f.useEffect(()=>{S?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&Ne(!0)},[S]),f.useEffect(()=>{ie==="live_class"&&i(!0)},[ie]),{mainNavCollapsed:s,setMainNavCollapsed:i,isStudentLiveMode:o,liveStudentParam:a,liveLessonParam:c,liveClassParam:l,isStageDisplayMode:d,stageLessonParam:u,stageTitleParam:m,stageLangParam:p,isStudentPreviewMode:h,isStudentTabMode:g,isFollowingTeacher:y,setIsFollowingTeacher:x,liveClassFocusLocked:b,setLiveClassFocusLocked:v,session:S,setSession:T,sessionLoading:k,fetchStudents:n,sessionBootstrapData:I,activeRole:_,setActiveRole:R,activeStudentId:L,setActiveStudentId:E,dbConnected:A,dbStatus:D,profileOpen:F,setProfileOpen:P,handleLoginSuccess:$,handleLogout:V,toggleLanguage:z,students:U,setSelectedLesson:j,studentViewStateData:B,studentViewStatus:q,setStudentViewStatus:C,isStudentLocked:K,isNavigationLocked:G,isInteractionLocked:Q,studentLockMode:ee,studentLockTarget:ue,studentLessonTab:we,setStudentLessonTab:X,studentSelectedCourseware:pe,setStudentSelectedCourseware:ke,studentFullscreenPanel:je,setStudentFullscreenPanel:M,isStudentLessonContentCollapsed:Y,setIsStudentLessonContentCollapsed:te,notifyLockedNavigation:ne,teacherTab:ie,setTeacherTab:oe,isTourOpen:le,setIsTourOpen:Ne,isApprovalsCollapsed:Te,setIsApprovalsCollapsed:Je,isProcessesCollapsed:se,setIsProcessesCollapsed:N}}function yC(e){const[t,n]=f.useState(""),[s,i]=f.useState("recent"),[o,a]=f.useState(!1),[c,l]=f.useState(!1),[d,u]=f.useState(!1),[m,p]=f.useState(null),h=f.useMemo(()=>{let g=[...e];if(t.trim()){const y=t.toLowerCase();g=g.filter(x=>x.title.toLowerCase().includes(y)||x.content.toLowerCase().includes(y))}if(o&&(g=g.filter(y=>(y.enrollment_count||0)>0)),c&&(g=g.filter(y=>y.content&&y.content.trim().length>0)),d){const y=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();g=g.filter(x=>(x.created_at||0)>=y)}return s==="recent"?g.sort((y,x)=>(x.created_at||0)-(y.created_at||0)):s==="alphabetical"?g.sort((y,x)=>y.title.localeCompare(x.title)):s==="enrollment"&&g.sort((y,x)=>(x.enrollment_count||0)-(y.enrollment_count||0)),g},[e,t,s,o,c,d]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:i,filterEnrollment:o,setFilterEnrollment:a,filterHasContent:c,setFilterHasContent:l,filterThisMonth:d,setFilterThisMonth:u,copyingLessonId:m,setCopyingLessonId:p,filteredAndSortedLessons:h}}function wC(){const e=ux(),t=e?.academicYear==="all"?null:e?.academicYear??null,[n,s]=f.useState([]),[i,o]=f.useState(!1),[a,c]=f.useState({lab_id:null,seats:[]}),[l,d]=f.useState(!1),[u,m]=f.useState([]),[p,h]=f.useState({}),[g,y]=f.useState({}),[x,b]=f.useState(null),[v,S]=f.useState(""),[T,k]=f.useState(""),w=f.useCallback(async()=>{try{o(!0);const E=await fetch("/api/labs");E.ok&&s(await E.json())}catch(E){console.error(E)}finally{o(!1)}},[]),I=f.useCallback(async E=>{try{const A=await fetch(`/api/classes/${E}/seats`);if(A.ok){const D=await A.json();c(D)}}catch(A){console.error(A)}},[]),_=f.useCallback(async()=>{try{const E=new Date().toISOString().split("T")[0],A=await fetch(`/api/schedules/today?date=${E}`);if(A.ok){const D=await A.json();D.success&&D.schedules&&m(D.schedules)}}catch(E){console.warn("Failed to fetch today schedules",E)}},[]),R=f.useCallback(async E=>{try{const A=await fetch(`/api/classes/${E}/schedules${t?`?academicYear=${encodeURIComponent(t)}`:""}`);if(A.ok){const D=await A.json();h(F=>({...F,[E]:D}))}}catch{}},[t]),L=f.useCallback(async E=>{try{const A=await fetch(`/api/schedules/${E}/attendance`);if(A.ok){const D=await A.json();y(F=>({...F,[E]:D}))}}catch{}},[]);return{computerLabs:n,setComputerLabs:s,loadingLabs:i,setLoadingLabs:o,fetchLabs:w,classSeats:a,setClassSeats:c,savingSeats:l,setSavingSeats:d,fetchClassSeats:I,todaySchedules:u,setTodaySchedules:m,fetchTodaySchedules:_,classSchedulesMap:p,setClassSchedulesMap:h,fetchClassSchedules:R,scheduleAttendanceMap:g,setScheduleAttendanceMap:y,fetchScheduleAttendance:L,expandedScheduleId:x,setExpandedScheduleId:b,newScheduleDate:v,setNewScheduleDate:S,newScheduleLessonId:T,setNewScheduleLessonId:k}}function vC(e){const{lang:t,addToast:n,setCopyingLessonId:s}=e,i=ae(h=>h.selectedLesson),o=ae(h=>h.setSelectedLesson),a=ae(h=>h.setElements),c=f.useRef(new Map),l=async()=>{await Se.getState().loadLessons()};return{fetchLessons:l,handleQuickCreateLesson:async(h,g)=>{try{const{ok:y,data:x}=await px({title:h,content:g});if(y)return await l(),x.id||"lesson-created"}catch(y){console.error("Quick create lesson failed",y)}return""},handleDeleteCourse:async h=>{const{ok:g,data:y}=await gx(h);if(!g)throw new Error(y.error||"Failed to delete course");await l(),i===h&&o(null),n(t==="zh"?"课程已删除":"Course Deleted",t==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},handleCopyCourse:async h=>{s(h);try{const{ok:g,data:y}=await xx(h);if(!g)throw new Error(y.error||"Failed to copy course");await l(),n(t==="zh"?"复制成功":"Course Copied",t==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(g){n(t==="zh"?"复制失败":"Copy Failed",g.message||(t==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{s(null)}},fetchElements:async h=>{try{const{ok:g,data:y}=await bx(h);if(!g)return;const x=JSON.stringify(y);x!==c.current.get(h)&&(c.current.set(h,x),a(y))}catch{}},lastElementsJsonByRoomRef:c}}async function SC(){const e=await fetch("/api/commands/registered");return e.ok?{ok:!0,data:await e.json(),contentType:e.headers.get("content-type")}:{ok:!1,contentType:e.headers.get("content-type")}}async function jC(e){const t=await fetch(`/api/vfs${e?`?parentId=${e}`:""}`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function kC(){const e=await fetch("/api/processes");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function NC(e){const t=await fetch(`/api/processes/${e}/logs`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function CC(e,t){return{ok:(await fetch(`/api/classes/${e}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function EC(e,t){return{ok:(await fetch(`/api/assignments/${e}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function TC(e,t){const n=await fetch(`/api/classes/${e}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:t})});return n.ok?{ok:!0,data:await n.json().catch(()=>({}))}:{ok:!1}}async function AC(e){const t=await fetch(`/api/classes/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function IC(e){const t=await fetch(`/api/classes/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function PC(e){const t=await fetch(`/api/students/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function zE(e,t){let n=`/api/students/${e}/academic-year-comparison`;if(t){const i=Array.isArray(t)?t.join(","):t;n+=`?years=${encodeURIComponent(i)}`}const s=await fetch(n);if(!s.ok)try{return{ok:!1,error:(await s.json()).error||"Request failed"}}catch{return{ok:!1,error:"Request failed"}}return{ok:!0,data:await s.json()}}function zC(e){const{fetchClassSchedules:t}=e,[n,s]=f.useState({}),[i,o]=f.useState({}),[a,c]=f.useState({}),[l,d]=f.useState({}),[u,m]=f.useState({}),[p,h]=f.useState([]),g=async T=>{try{const{ok:k,data:w}=await jx(T);k&&s(I=>({...I,[T]:w}))}catch{}},y=async T=>{try{const{ok:k,data:w}=await AC(T);k&&o(I=>({...I,[T]:w}))}catch{}},x=async T=>{try{const{ok:k,data:w}=await IC(T);k&&c(I=>({...I,[T]:w}))}catch{}};return{classStudentsMap:n,setClassStudentsMap:s,classProgressMap:i,setClassProgressMap:o,classDashboardMap:a,setClassDashboardMap:c,classAssignmentsMap:l,setClassAssignmentsMap:d,assignmentSubmissionsMap:u,setAssignmentSubmissionsMap:m,liveClassStudentProgress:p,setLiveClassStudentProgress:h,fetchClassStudents:g,fetchClassProgress:y,fetchClassDashboard:x,fetchLiveClassStudentProgress:async(T,k)=>{try{const{ok:w,data:I}=await ok(T,k);w&&h(I)}catch{}},handleQuickScheduleClass:async(T,k,w)=>{try{const{ok:I}=await CC(T,{lessonId:k,scheduledDate:w});if(I)return await t(T),!0}catch(I){console.error("Quick schedule class failed",I)}return!1},handleQuickGenerateAssignment:async(T,k,w)=>{const I=k||w||"Assignment";try{const{ok:_,data:R}=await TC(T,I);if(_)return await x(T),R.id||"assignment-created"}catch(_){console.error("Quick generate assignment failed",_)}return null}}}function LC(e){const[t,n]=f.useState([]),[s,i]=f.useState([]),[o,a]=f.useState([]),[c,l]=f.useState(null),[d,u]=f.useState(""),[m,p]=f.useState(!1),[h,g]=f.useState(null);return{registeredCommands:t,setRegisteredCommands:n,vfsNodes:s,setVfsNodes:i,processes:o,setProcesses:a,showProcessLogs:c,setShowProcessLogs:l,processLogsContent:d,setProcessLogsContent:u,showLogs:m,setShowLogs:p,currentVfsParent:h,setCurrentVfsParent:g,fetchRegisteredCommands:async()=>{try{const{ok:S,data:T,contentType:k}=await SC();S&&k&&k.includes("application/json")&&Array.isArray(T)&&n(T)}catch(S){console.warn("Failed to fetch registered commands",S)}},fetchVfs:async S=>{if(e)try{const{ok:T,data:k}=await jC(S);T&&i(k)}catch(T){console.warn("Failed to fetch VFS nodes",T)}},fetchProcesses:async()=>{try{const{ok:S,data:T}=await kC();S&&a(T)}catch{}},fetchProcessLogs:async S=>{try{const{ok:T,data:k}=await NC(S);T&&(u(k.logs||""),l(S))}catch{}}}}function Ns(e,t=","){const n=[];let s="",i=!1;for(let o=0;o<e.length;o++){const a=e[o];a==='"'?i&&e[o+1]==='"'?(s+='"',o++):i=!i:a===t&&!i?(n.push(s.trim()),s=""):s+=a}return n.push(s.trim()),n}function RC(e){const t=[];let n="",s=!1;for(const i of e){const o=i.replace(/\r$/,"");if(!(!n&&!s&&!o.trim())){n=n?n+`
97
+ `+o:o;for(let a=0;a<o.length;a++)o[a]==='"'&&(s&&o[a+1]==='"'?a++:s=!s);s||(t.push(n),n="")}}return n&&t.push(n),t}function Ot(e,t){const n=i=>i.replace(/[\s_\-()()]/g,""),s=e.map(n);for(const i of t){const o=s.indexOf(n(i));if(o!==-1)return o}for(const i of[...t].sort((o,a)=>n(a).length-n(o).length)){const o=n(i),a=s.findIndex(c=>c.includes(o));if(a!==-1)return a}return-1}function Bc(e){return{name:e?.name||e?.studentName||e?.student_name||"",email:e?.email||e?.studentEmail||e?.student_email||"",student_number:e?.student_number||e?.studentNumber||e?.studentNo||"",password:e?.password||e?.initialPassword||e?.initial_password||"",private_notes:e?.private_notes||e?.privateNotes||e?.notes||e?.note||"",gender:e?.gender||e?.sex||""}}function Uc(e,t){if(!e||e.length===0)return"";const n=e.map(s=>`${s.student_number||"-"} / ${s.name} / ${s.initial_password}`).join(`
98
+ `);return t==="zh"?`
99
+
100
+ 🔑 以下 ${e.length} 名学生使用系统生成的初始密码(仅本次显示,请及时分发):
101
+ ${n}`:`
102
+
103
+ 🔑 Initial passwords for ${e.length} student(s) (shown once — distribute them now):
104
+ ${n}`}const _C={zh:{className:"班级名称",classDesc:"班级描述",studentNumber:"学生学号",studentName:"学生姓名",studentEmail:"学生邮箱",password:"初始密码",notes:"学生备注",gender:"性别"},en:{className:"Class Name",classDesc:"Class Desc",studentNumber:"Student Number",studentName:"Student Name",studentEmail:"Student Email",password:"Initial Password",notes:"Student Notes",gender:"Gender"}};function xt(e){return e.map(t=>{const n=t??"";return/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}).join(",")}function Vc(e,t){const n=_C[t==="zh"?"zh":"en"];let s,i,o;e==="class"?(s=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",i=xt([n.className,n.classDesc,n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes,n.gender]),o=t==="zh"?[xt(["高一A班","基础英语课程","20260101","李明","liming@example.com","","","男"]),xt(["高一A班","基础英语课程","20260102","王华","wanghua@example.com","","数学较弱","女"])]:[xt(["Class 101","Introduction to English","20260101","John Doe","john@example.com","","","Male"]),xt(["Class 101","Introduction to English","20260102","Jane Smith","jane@example.com","","","Female"])]):(s=t==="zh"?"学生批量导入模板.csv":"student_import_template.csv",i=xt([n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes,n.gender]),o=t==="zh"?[xt(["20260101","张三","zhangsan@example.com","","","男"]),xt(["20260102","李四","lisi@example.com","","","女"])]:[xt(["20260101","Alice Cooper","alice@example.com","","","Male"]),xt(["20260102","Bob Dylan","bob@example.com","","","Female"])]);const a=new Blob(["\uFEFF"+i+`
105
+ `+o.join(`
106
+ `)+`
107
+ `],{type:"text/csv;charset=utf-8;"}),c=URL.createObjectURL(a),l=document.createElement("a");l.href=c,l.setAttribute("download",s),document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(c)}async function OC(e,t){const{lang:n,fetchClasses:s,fetchStudents:i}=t;return new Promise((o,a)=>{const c=new FileReader;c.onload=async l=>{try{const d=l.target?.result;if(!d)throw new Error("File content is empty");let u=[],m=[],p=!0;if(e.name.endsWith(".json")){const h=JSON.parse(d);if(!Array.isArray(h))throw new Error("JSON structure must be an array");h.some(y=>y.className||y.name&&(y.students||y.classDescription))?(p=!0,u=h.map(y=>{const x=y.name||y.className||y.class_name,b=y.description||y.classDescription||"",v=y.students||y.studentList||[],S=(Array.isArray(v)?v:[]).map(Bc).filter(T=>T.name);return{name:x,description:b,students:S}}).filter(y=>y.name)):(p=!1,m=h.map(Bc).filter(y=>y.name))}else{const h=d.split(/\r?\n/);if(h.length<2)throw new Error("CSV has empty or insufficient data");const g=Ns(h[0]).map(_=>_.trim().toLowerCase()),y=Ot(g,["班级名称","class name","classname","class_name","班级"]),x=Ot(g,["班级描述","class desc","classdesc","class_desc","描述"]),b=Ot(g,["学生学号","student number","studentnumber","student_number","student no","学号","编号"]),v=Ot(g,["学生姓名","student name","studentname","student_name","姓名","学生"]),S=Ot(g,["学生邮箱","student email","studentemail","student_email","邮箱","email","mail"]),T=Ot(g,["初始密码","initial password","password","passwd","pwd","密码"]),k=Ot(g,["学生备注","student notes","private_notes","备注","note","remark"]),w=Ot(g,["性别","gender","sex","学生性别"]);if(v===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');const I=_=>({name:_[v]||"",email:S!==-1&&_[S]||"",student_number:b!==-1&&_[b]||"",password:T!==-1&&_[T]||"",private_notes:k!==-1&&_[k]||"",gender:w!==-1&&_[w]||""});if(y!==-1){p=!0;const _={};for(let R=1;R<h.length;R++){const L=h[R].trim();if(!L)continue;const E=Ns(L),A=E[y];if(!A)continue;const D=x!==-1&&E[x]||"",F=I(E);_[A]||(_[A]={name:A,description:D,students:[]}),F.name&&_[A].students.push(F)}u=Object.values(_)}else{p=!1;for(let _=1;_<h.length;_++){const R=h[_].trim();if(!R)continue;const L=I(Ns(R));L.name&&m.push(L)}}}if(p){if(u.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:u})});if(!h.ok){const v=await h.json();throw new Error(v.error||"Server importation failed")}const g=await h.json();await s(),await i();const y=g.imported.length,x=g.imported.reduce((v,S)=>v+(S.studentsCount||0),0),b=Uc(g.credentials,n);o({success:!0,message:n==="zh"?`成功导入 ${y} 个班级、${x} 名学生。${b}`:`Imported ${y} class(es) and ${x} student(s).${b}`})}else{if(m.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:m})});if(!h.ok){const S=await h.json();throw new Error(S.error||"Server student importation failed")}const g=await h.json();await i();const y=g.created??g.imported.filter(S=>S.new).length,x=g.existing??g.imported.filter(S=>!S.new).length,b=(g.imported||[]).filter(S=>S.created&&S.initial_password).map(S=>({student_number:S.student_number,name:S.name,initial_password:S.initial_password})),v=Uc(b,n);o({success:!0,message:n==="zh"?`成功导入 ${y} 名新学生${x?`,${x} 名已存在(按邮箱或学号匹配,已跳过重复创建)`:""}。${v}`:`Imported ${y} new student(s)${x?`, skipped ${x} existing one(s) matched by email or student number`:""}.${v}`})}}catch(d){a(d)}},c.onerror=()=>{a(new Error("Failed to read file from disk."))},c.readAsText(e)})}function DC(e,t){return new Promise((n,s)=>{const i=new FileReader;i.onload=o=>{try{const a=o.target?.result;if(!a)throw new Error("Empty CSV file");const c=a.split(/\r?\n/);if(c.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const l=Ns(c[0]).map(h=>h.trim().toLowerCase()),d=l.findIndex(h=>h.includes("title")||h.includes("标题")||h.includes("课程")),u=l.findIndex(h=>h.includes("content")||h.includes("内容")||h.includes("正文"));if(d===-1||u===-1)throw new Error(t==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const m=RC(c.slice(1)),p=[];for(const h of m){if(!h.trim())continue;const g=Ns(h),y=g[d]?.trim(),x=g[u]?.trim();y&&x&&p.push({title:y,content:x})}if(p.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(p)}catch(a){s(a)}},i.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},i.readAsText(e)})}async function MC(e,t){const{lang:n,setImportProgress:s,fetchLessons:i}=t;let o=0;for(let a=0;a<e.length;a++){const c=e[a];try{const l=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:c.title,content:c.content})});if(l.ok)o++;else{const d=await l.json();console.warn(`Failed to import item ${a+1}:`,d)}}catch(l){console.warn(`Error importing item ${a+1}:`,l)}s(a+1)}return o>0?(await i(),{success:!0}):{success:!1,errorMsg:n==="zh"?"所有课程项导入均失败。请检查控制台或格式。":"Failed to import any of the courses. Please check your console or schema."}}const Wc="openlearn.course-package",$a=20*1024*1024,Bo=Math.round($a/(1024*1024));function Uo(e){return`${(e/(1024*1024)).toFixed(1)}MB`}async function $C(){try{const e=await fetch("/api/course-packages/template");if(!e.ok){let n="";try{n=(await e.json())?.error||""}catch{}return{ok:!1,error:n||`模板下载失败(HTTP ${e.status})`}}const t=await e.blob();return qu(t,"openlearn-course-template.json"),{ok:!0}}catch(e){return{ok:!1,error:e?.message||String(e)}}}async function FC(e){try{const t=await fetch(`/api/lessons/${encodeURIComponent(e)}/export-package`);if(!t.ok){let c="";try{c=(await t.json())?.error||""}catch{}return{ok:!1,error:c||`课程包导出失败(HTTP ${t.status})`}}const n=t.headers.get("X-Course-Package-Filename");let s="course-package.openlearn-package.json";if(n)try{s=decodeURIComponent(n)}catch{}const i=await t.blob();qu(i,s);const o=Number(t.headers.get("X-Course-Package-Assets")||"0"),a=Number(t.headers.get("X-Course-Package-Skipped")||"0");return{ok:!0,filename:s,assets:Number.isFinite(o)?o:0,skipped:Number.isFinite(a)?a:0}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}function qu(e,t){const n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.setAttribute("download",t),document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}async function BC(e){if(e.size>$a)return{ok:!1,error:`课程包文件 ${Uo(e.size)} 超过 ${Bo}MB 上限。请精简包内附件后重试(附件以 base64 内联,体积约放大 1.37 倍)。`};let t;try{t=await e.text()}catch(o){return{ok:!1,error:o?.message||"无法读取所选文件"}}let n;try{n=JSON.parse(t)}catch{return{ok:!1,error:"文件不是合法的 JSON,无法作为课程包导入"}}if(!n||n.format!==Wc)return{ok:!1,error:`不是 OpenLearn 课程包文件(format 应为 "${Wc}")`};const s=Array.isArray(n.elements)?n.elements:[],i=Array.from(new Set(s.map(o=>String(o?.type||"")).filter(Boolean))).sort();return{ok:!0,package:n,preview:{fileName:e.name,title:String(n?.lesson?.title||"(未命名课程)"),metaName:String(n?.meta?.name||""),segments:Array.isArray(n?.lesson?.timeline)?n.lesson.timeline.length:0,elements:s.length,assets:Array.isArray(n?.assets)?n.assets.length:0,componentTypes:i}}}async function UC(e,t={}){try{const n=await fetch("/api/course-packages/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,allowDuplicate:t.allowDuplicate===!0})}),s=await n.json().catch(()=>({}));if(!n.ok||s?.success===!1){const i=s?.duplicate;return{ok:!1,error:s?.error||`课程包导入失败(HTTP ${n.status})`,...i?{duplicate:i}:{}}}return{ok:!0,result:s.result}}catch(n){return{ok:!1,error:n?.message||String(n)}}}const VC=$a;function WC(e){const{lang:t,fetchClasses:n,fetchStudents:s,fetchLessons:i,addToast:o}=e,[a,c]=f.useState(!1),[l,d]=f.useState(null),[u,m]=f.useState(!1),[p,h]=f.useState("system"),[g,y]=f.useState(null),[x,b]=f.useState([]),[v,S]=f.useState(!1),[T,k]=f.useState(!1),w=async()=>{try{S(!0);const{ok:se,data:N}=await rx();se&&b(N)}catch(se){console.warn("Error fetching library resources:",se)}finally{S(!1)}};f.useEffect(()=>{u&&w()},[u]);const[I,_]=f.useState(!1),[R,L]=f.useState("idle"),[E,A]=f.useState(0),[D,F]=f.useState(0),[P,$]=f.useState(""),[V,z]=f.useState([]),[U,j]=f.useState(!1),[B,q]=f.useState(null),[C,K]=f.useState(null),[G,Q]=f.useState(null),ee=()=>{Vc("class",t)},ue=async se=>{if(se){if(!se.name.toLowerCase().endsWith(".csv")){L("error"),$(t==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}L("parsing"),$("");try{const N=await DC(se,t);z(N)}catch(N){L("error"),$(N.message||String(N))}}},we=async se=>{if(!se)return;if(se.size>VC){L("error"),$(t==="zh"?`文件 ${Uo(se.size)} 超过 ${Bo}MB 上限,请精简后重试。`:`File is ${Uo(se.size)}, over the ${Bo}MB limit.`),q(null),K(null);return}if(se.name.toLowerCase().endsWith(".json")){$("");try{const O=await BC(se);if(!O.ok){q(null),K(null),L("error"),$(O.error);return}K(O.package),q(O.preview),z([]),L("parsing")}catch(O){L("error"),$(O?.message||String(O))}return}q(null),K(null),await ue(se)},X=async()=>{const se=await $C();if(!se.ok){L("error"),$(se.error||(t==="zh"?"模板下载失败":"Failed to download template"));return}o(t==="zh"?"模板已下载":"Template downloaded",t==="zh"?"openlearn-course-template.json 可直接拖回导入框完成导入。":"Drag openlearn-course-template.json back into the import dialog to finish.","success")},pe=async se=>{const N=await FC(se);if(!N.ok)return o(t==="zh"?"课程包导出失败":"Course package export failed",N.error||(t==="zh"?"请稍后重试":"Please try again later"),"error"),N;const O=N.skipped??0;return o(t==="zh"?"课程包已导出":"Course package exported",t==="zh"?`${N.filename}(内联 ${N.assets??0} 个附件${O>0?`,${O} 个引用未内联`:""})可直接拖回导入框复用。`:`${N.filename} (${N.assets??0} embedded assets${O>0?`, ${O} reference(s) skipped`:""}). Drop it back into the import dialog to reuse.`,O>0?"warning":"success"),N},ke=async(se=!1)=>{if(!C)return;L("importing"),$("");const N=await UC(C,{allowDuplicate:se});if(N.ok&&N.result){L("success"),Q(null),await i(),o(t==="zh"?"课程包导入成功":"Course package imported",t==="zh"?`已导入「${N.result.title}」:${N.result.segments} 个教学环节、${N.result.elements} 个白板元素、${N.result.assets} 份课件附件。`:`Imported "${N.result.title}": ${N.result.segments} segments, ${N.result.elements} elements, ${N.result.assets} assets.`,"success");return}if(N.duplicate){Q(N.duplicate),L("error"),$(N.error||"");return}L("error"),$(N.error||(t==="zh"?"课程包导入失败":"Course package import failed"))},je=()=>{Q(null),$(""),L("parsing")},M=async()=>{if(V.length===0)return;L("importing"),A(0),F(V.length);const se=await MC(V,{lang:t,setImportProgress:A,fetchLessons:i});se.success?L("success"):(L("error"),$(se.errorMsg||""))},[Y,te]=f.useState(!1),[ne,ie]=f.useState(!1),[oe,be]=f.useState(null),[le,Ne]=f.useState(null);return{isCloudDriveOpen:a,setIsCloudDriveOpen:c,cloudDrivePreviewNode:l,setCloudDrivePreviewNode:d,isSystemResourceLibraryOpen:u,setIsSystemResourceLibraryOpen:m,systemResourceTab:p,setSystemResourceTab:h,selectedLibraryResourceId:g,setSelectedLibraryResourceId:y,libraryResources:x,setLibraryResources:b,loadingLibraryResources:v,setLoadingLibraryResources:S,showCoursewareHub:T,setShowCoursewareHub:k,fetchLibraryResources:w,isImportLessonsOpen:I,setIsImportLessonsOpen:_,importStatus:R,setImportStatus:L,importProgress:E,setImportProgress:A,importProgressTotal:D,setImportProgressTotal:F,importErrorMsg:P,setImportErrorMsg:$,previewImportData:V,setPreviewImportData:z,isDraggingImport:U,setIsDraggingImport:j,downloadCsvTemplate:ee,handleCSVFileChange:ue,handleCSVImportSubmit:M,packagePreview:B,setPackagePreview:q,pendingCoursePackage:C,packageDuplicate:G,handlePackageDuplicateDismiss:je,handleImportFileChange:we,handlePackageImportSubmit:ke,downloadCourseTemplate:X,exportCoursePackage:pe,showImportModal:Y,setShowImportModal:te,isImporting:ne,setIsImporting:ie,importError:oe,setImportError:be,importSuccess:le,setImportSuccess:Ne,downloadCSVTemplate:se=>{Vc(se,t)},handleImportFile:async se=>{ie(!0),be(null),Ne(null);try{const N=await OC(se,{lang:t,fetchClasses:n,fetchStudents:s});Ne(N.message)}catch(N){be(N.message||String(N))}finally{ie(!1)}}}}function HC(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:i,setTeacherTab:o}=e,[a,c]=f.useState(!1),[l,d]=f.useState(1),[u,m]=f.useState(""),[p,h]=f.useState("Mathematics"),[g,y]=f.useState(""),[x,b]=f.useState(""),[v,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:"15m",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"}]),[T,k]=f.useState(!1),[w,I]=f.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:c,wizardStep:l,setWizardStep:d,wizardCourseTitle:u,setWizardCourseTitle:m,wizardCourseCategory:p,setWizardCourseCategory:h,wizardCourseDescription:g,setWizardCourseDescription:y,wizardCourseContent:x,setWizardCourseContent:b,wizardCourseTimeline:v,setWizardCourseTimeline:S,wizardIsSubmitting:T,setWizardIsSubmitting:k,wizardIsGeneratingOutline:w,handleGenerateOutline:async()=>{if(!w){if(!u.trim()){n(t==="zh"?"请先填写课程课题":"Course Title Required",t==="zh"?"AI 需要课题名称才能生成大纲。":"AI needs a course title to generate the outline.","warning");return}I(!0);try{const L=await fetch("/api/lessons/generate-outline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:u,category:p,description:g,timeline:v,lang:t})}),E=await L.json().catch(()=>null);if(!L.ok||!E?.success)throw new Error(E?.error||E?.message||`HTTP ${L.status}`);const A=(E.content||"").trim();if(!A)throw new Error(t==="zh"?"AI 返回了空内容":"AI returned empty content");b(A),n(t==="zh"?"✨ AI 大纲生成成功":"✨ AI Outline Generated",t==="zh"?`已根据《${u}》生成 ${A.length} 字的专家级教学大纲。`:`Generated a ${A.length}-character outline for "${u}".`,"success")}catch(L){console.error(L),n(t==="zh"?"AI 大纲生成失败":"AI Outline Generation Failed",L?.message||(t==="zh"?"请确认「系统管理 -> AI 提供商管理」中已配置可用的模型服务。":"Please configure a working AI Provider in System Management."),"error")}finally{I(!1)}}},handleDeployWizardCourse:async()=>{if(!u.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}k(!0);try{const L=x.trim()||`Course outline for ${u} (${p})`,E=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:u,content:L})});if(E.ok){const D=(await E.json()).result?.lessonId;D&&await fetch(`/api/lessons/${D}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:v})}),await s(),D&&(i(D),o("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${u}》已成功保存到核心SQLite并已自动激活!`:`Course "${u}" is now live in SQLite and auto-activated.`,"success"),c(!1),m(""),h("Mathematics"),y(""),b(""),d(1)}else n("Error","SQLite save failed","warning")}catch(L){console.error(L),n("Error","Launch Exception","warning")}finally{k(!1)}}}}const qC=`exports.default = {
108
+ manifest: {
109
+ id: "@my-scope/hello-world",
110
+ name: "Hello World Plugin",
111
+ version: "1.0.0",
112
+ capabilitiesProposed: ["lesson:read"]
113
+ },
114
+ activate: async (ctx) => {
115
+ ctx.log.info('Hello World plugin activated');
116
+ }
117
+ };`;function GC(e){const{session:t,host:n,lang:s,addToast:i,setChatLog:o,setTeacherTab:a,fetchLessons:c}=e,[l,d]=f.useState([]),[u,m]=f.useState([]),[p,h]=f.useState(!1),[g,y]=f.useState(null),[x,b]=f.useState(""),[v,S]=f.useState(""),[T,k]=f.useState(""),[w,I]=f.useState(""),[_,R]=f.useState(null),[L,E]=f.useState(!1),[A,D]=f.useState("store"),[F,P]=f.useState(qC),[$,V]=f.useState(!1),[z,U]=f.useState([]),[j,B]=f.useState([]),[q,C]=f.useState({}),[K,G]=f.useState([]),[Q,ee]=f.useState(!1),ue=f.useCallback(async()=>{ee(!0);try{const N=await fetch("/api/plugins/orphan-data");if(N.ok){const O=await N.json();G(Array.isArray(O.items)?O.items:[])}}catch(N){console.warn("Failed to fetch plugin orphan data",N)}finally{ee(!1)}},[]),we=f.useCallback(async N=>{try{const O=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(N.pluginId)}/export`,{method:"POST"}),W=await O.json().catch(()=>({}));O.ok&&W?.success?(i(s==="zh"?"导出完成":"Export finished",s==="zh"?`已导出 ${W.tables?.length??0} 张表 / ${W.rowCount??0} 行到 ${W.file}`:`Exported ${W.tables?.length??0} tables / ${W.rowCount??0} rows to ${W.file}`,"success"),await ue()):i(s==="zh"?"导出失败":"Export failed",W?.error||"Unknown error","error")}catch(O){i(s==="zh"?"导出失败":"Export failed",String(O?.message??O),"error")}},[i,ue,s]),X=f.useCallback(async N=>{try{const O=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(N.pluginId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:N.pluginId})}),W=await O.json().catch(()=>({}));O.ok&&W?.success?(i(s==="zh"?"已清除插件数据":"Plugin data purged",s==="zh"?`删除 ${W.droppedTables?.length??0} 张表;归档:${W.exportFile??"(无)"}`:`Dropped ${W.droppedTables?.length??0} tables; archive: ${W.exportFile??"(none)"}`,"success"),await ue()):i(s==="zh"?"清除失败":"Purge failed",W?.error||"Unknown error","error")}catch(O){i(s==="zh"?"清除失败":"Purge failed",String(O?.message??O),"error")}},[i,ue,s]),pe=f.useCallback(N=>{window.open(`/api/plugins/orphan-data/${encodeURIComponent(N.pluginId)}/archive`,"_blank")},[]),ke=f.useRef(new Set),je=f.useCallback(async()=>{try{const N=await fetch("/api/plugins");if(N.ok){const O=await N.json();d(O)}}catch(N){console.warn("Failed to fetch plugins",N)}},[]),M=f.useCallback(async()=>{try{const N=await fetch("/api/ai-providers");if(N.ok){const O=await N.json();m(O)}}catch(N){console.warn("Failed to fetch AI Providers",N)}},[]);f.useEffect(()=>{je(),t&&t.role!=="student"&&M()},[je,M,t?.role]);const Y=f.useCallback(async()=>{try{const N=await fetch("/api/events");N.ok&&U(await N.json())}catch{}},[]),te=f.useCallback(async()=>{try{const N=await fetch("/api/approvals");N.ok&&B(await N.json())}catch{}},[]);return{plugins:l,setPlugins:d,fetchPlugins:je,aiProviders:u,setAiProviders:m,fetchAIProviders:M,isAIProviderModalOpen:p,setIsAIProviderModalOpen:h,editingAIProvider:g,setEditingAIProvider:y,providerName:x,setProviderName:b,providerApiUrl:v,setProviderApiUrl:S,providerApiKey:T,setProviderApiKey:k,providerModelName:w,setProviderModelName:I,testingProviderId:_,setTestingProviderId:R,showPluginModal:L,setShowPluginModal:E,storeTab:A,setStoreTab:D,pluginCode:F,setPluginCode:P,installingPlugin:$,setInstallingPlugin:V,events:z,setEvents:U,fetchEvents:Y,approvals:j,setApprovals:B,fetchApprovals:te,scoreOverrides:q,setScoreOverrides:C,handleSaveAIProvider:async()=>{if(!x.trim()||!v.trim()||!w.trim()){i(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let N;if(g?N=await fetch(`/api/ai-providers/${g.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:v,api_key:T,model_name:w})}):N=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:v,api_key:T,model_name:w})}),N.ok)i(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${x}] 已保存。`:`AI Provider [${x}] has been updated.`,"success"),h(!1),y(null),b(""),S(""),k(""),I(""),M();else{const O=await N.json().catch(()=>({}));i(s==="zh"?"保存失败":"Failed to Save",O.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(N){console.error(N),i(s==="zh"?"保存异常":"Execution Error",N.message||"Error occurred","warning")}},handleDeleteAIProvider:async(N,O)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${O}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${O}]?`))try{(await fetch(`/api/ai-providers/${N}`,{method:"DELETE"})).ok?(i(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${O}] 已经被清除。`:`AI Provider [${O}] has been removed.`,"success"),M()):i(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(W){console.error(W),i(s==="zh"?"操作异常":"Execution Error",W.message||"Error occurred","warning")}},handleTestAIProvider:async N=>{R(N.id);try{const O=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:N.api_url,api_key:N.api_key,model_name:N.model_name})}),W=await O.json();O.ok&&W.success?i(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${N.name}]。${W.message}`:`Successfully connected to [${N.name}]. ${W.message}`,"success"):i(s==="zh"?"测试失败":"Test Failed",W.error||"Connection error","warning")}catch(O){console.error(O),i(s==="zh"?"连接异常":"Connection Exception",O.message||"Error occurred","warning")}finally{R(null)}},handleInstallPlugin:async()=>{if(F.trim()){V(!0);try{const O=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:F})})).json();O.success?(await je(),E(!1),o(W=>[...W,{role:"agent",content:`[System] Plugin "${O.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+O.error)}catch(N){alert("Error: "+N.message)}finally{V(!1)}}},handleZipPluginUpload:async(N,O,W)=>{V(!0);const H=W?.mode==="update";try{const Z={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(N.name),"X-Execution-Mode":O,"X-Install-Mode":H?"update":"install","X-Allow-Downgrade":W?.allowDowngrade?"true":"false"};W?.approvePublicRoutes&&(Z["X-Approve-Public-Routes"]="true"),W?.approveCapabilities&&(Z["X-Approve-Capabilities"]="true"),W?.approveNetworkHosts&&(Z["X-Approve-Network-Hosts"]="true"),H&&(Z["X-Acknowledge-Risk"]="true"),W?.targetPluginId&&(Z["X-Target-Plugin-Id"]=encodeURIComponent(W.targetPluginId));const he=H&&W?.targetPluginId?`/api/plugins/${encodeURIComponent(W.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",fe=await fetch(he,{method:"POST",headers:Z,body:N}),xe=await fe.json().catch(()=>({}));if(!fe.ok||!xe.success){const et=xe.error||"Unknown error";throw i(s==="zh"?H?"更新失败":"安装失败":H?"Update Failed":"Installation Failed",et,"error"),new Error(et)}const re=xe.pluginId||xe.manifest?.pluginId||xe.manifest?.id,Be=!!(xe.updated||H);if(!Be&&re)await fetch(`/api/plugins/${encodeURIComponent(re)}/toggle`,{method:"POST"}).catch(()=>{});else if(Be&&xe.wasActive&&re)try{await n.deactivatePlugin(re)}catch{}a("plugins"),D("store"),await je(),setTimeout(()=>{je()},1e3);const Ae=xe.manifest?.name||re||N.name,Me=typeof xe.executionMode=="string"?xe.executionMode:O,Fe=Me==="process"?s==="zh"?"子进程隔离":"process isolation":Me==="worker"?s==="zh"?"Worker 线程":"worker thread":Me==="inline"?s==="zh"?"主进程":"in-process":Me,At=xe.executionModeCoerced===!0?s==="zh"?"(未受信任插件已强制改为子进程,清单里的 inline/worker 不会生效)":" (untrusted plugin was forced into a child process)":"";if(Be){const et=xe.oldVersion||"?",Nt=xe.newVersion||xe.manifest?.version||"?";i(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${Ae}" 已从 v${et} 更新到 v${Nt}(配置与数据已保留)`:`"${Ae}" updated v${et} → v${Nt} (config & data preserved)`,"success"),o(Ht=>[...Ht,{role:"agent",content:`[System] Plugin "${Ae}" updated ${et} → ${Nt}.`}])}else i(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${Ae}" 已上传,实际运行模式为 [${Fe}]${At}`:`Plugin "${Ae}" installed in [${Fe}] mode${At}`,"success"),o(et=>[...et,{role:"agent",content:`[System] Plugin "${Ae}" installed successfully from ZIP file.`}])}catch(Z){const he=Z?.message?String(Z.message):"";throw he&&he!=="Failed to fetch"&&he!=="Network error"||i(s==="zh"?"网络错误":"Network Error",he||"Network error","error"),Z}finally{V(!1)}},handleTogglePlugin:async N=>{if(!ke.current.has(N)){ke.current.add(N);try{const O=await fetch(`/api/plugins/${encodeURIComponent(N)}/toggle`,{method:"POST"}),W=await O.json().catch(()=>({}));if(O.ok)await je();else{const H=W.error||"Unknown error";H.includes("requires human approval")||H.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await te()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+H)}}catch(O){console.error("Failed to toggle plugin:",O),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{ke.current.delete(N)}}},handleDeletePlugin:async(N,O="keep")=>{try{const W=O==="purge"?`/api/plugins/${encodeURIComponent(N)}?dataPolicy=purge&confirm=purge`:`/api/plugins/${encodeURIComponent(N)}`,H=await fetch(W,{method:"DELETE"});if(H.ok){const Z=await H.json().catch(()=>({}));a("plugins"),D("store"),await je();const he=O==="purge"?s==="zh"?`插件已卸载,数据已清除(归档:${Z.exportFile??"无数据需归档"})。`:`Plugin uninstalled and data purged (archive: ${Z.exportFile??"nothing to archive"}).`:s==="zh"?`插件已卸载,数据已保留(${Z.keptTables?.length??0} 张表),可在「插件数据」中管理。`:`Plugin uninstalled with data kept (${Z.keptTables?.length??0} tables). Manage it under Plugin Data.`;o(fe=>[...fe,{role:"agent",content:`[System] ${he}`}]),i(s==="zh"?"卸载完成":"Uninstalled",he,"success")}else{const Z=await H.json().catch(()=>({}));alert(Z.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(W){console.error("Failed to delete plugin:",W),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},orphanData:K,orphanDataLoading:Q,fetchOrphanData:ue,handleExportOrphanData:we,handlePurgeOrphanData:X,handleDownloadOrphanArchive:pe,handleApprove:async(N,O)=>{try{const H=await(await fetch(`/api/approvals/${N}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:O})})).json();H.success?(await te(),await c(),await je()):alert("Action failed: "+H.error)}catch(W){console.error(W)}},handleReject:async N=>{try{await fetch(`/api/approvals/${N}/reject`,{method:"POST"}),await te(),await je()}catch(O){console.error(O)}}}}function QC(){const[e,t]=f.useState(!1),[n,s]=f.useState(null),[i,o]=f.useState("scan_lesson"),[a,c]=f.useState(""),[l,d]=f.useState(""),[u,m]=f.useState(!1),[p,h]=f.useState([]),[g,y]=f.useState([]),[x,b]=f.useState(!1),[v,S]=f.useState({}),[T,k]=f.useState(10),[w,I]=f.useState("quiz"),_=f.useRef(v);return f.useEffect(()=>{_.current=v},[v]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:i,setQuizGenMode:o,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:c,quizGenTopic:l,setQuizGenTopic:d,isGeneratingSuggestions:u,setIsGeneratingSuggestions:m,suggestedObjectives:p,setSuggestedObjectives:h,suggestedQuestions:g,setSuggestedQuestions:y,savingQuiz:x,setSavingQuiz:b,quizStudentAnswers:v,setQuizStudentAnswers:S,quizGenTimeLimit:T,setQuizGenTimeLimit:k,quizStudentAnswersRef:_,subAssignmentTab:w,setSubAssignmentTab:I}}function JC(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:i,fetchClassStudents:o,handleExportAllClassesCombined:a}=e,[c,l]=f.useState(!1),[d,u]=f.useState(new Set),[m,p]=f.useState(new Set),[h,g]=f.useState(null),[y,x]=f.useState(""),[b,v]=f.useState(""),[S,T]=f.useState("");return{batchMode:c,setBatchMode:l,selectedClassIds:d,setSelectedClassIds:u,selectedStudentIds:m,setSelectedStudentIds:p,batchPicker:h,setBatchPicker:g,batchPickerLesson:y,setBatchPickerLesson:x,batchPickerDate:b,setBatchPickerDate:v,batchPickerTargetClass:S,setBatchPickerTargetClass:T,toggleClassSelection:z=>{u(U=>{const j=new Set(U);return j.has(z)?j.delete(z):j.add(z),j})},toggleSelectAllClasses:()=>{u(z=>z.size===n.length&&n.length>0?new Set:new Set(n.map(U=>U.id)))},toggleStudentSelection:z=>{p(U=>{const j=new Set(U);return j.has(z)?j.delete(z):j.add(z),j})},toggleSelectAllStudents:z=>{p(U=>U.size===z.length&&z.length>0?new Set:new Set(z.map(j=>j.id)))},handleBatchDeleteClasses:async()=>{if(d.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${d.size} 个班级吗?该操作不可恢复。`:`Delete ${d.size} selected classes permanently?`)){for(const z of d)await fetch(`/api/classes/${z}`,{method:"DELETE"});u(new Set),await i()}},handleBatchExportClasses:async()=>{d.size!==0&&await a(n.filter(z=>d.has(z.id)))},handleBatchSetPasscode:async()=>{if(d.size===0)return;const z=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(z!==null){for(const U of d)await fetch(`/api/classes/${U}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:z===""?null:z})});u(new Set),await i()}},handleBatchScheduleClasses:()=>{d.size!==0&&(x(""),v(new Date().toISOString().split("T")[0]),g("schedule"))},handleBatchDeleteStudents:async()=>{if(!(m.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${m.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${m.size} selected student accounts?`)){for(const z of m)await fetch(`/api/students/${z}`,{method:"DELETE"});p(new Set),await o(s)}},handleBatchResetPassword:async()=>{if(m.size===0||!s)return;const z=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(z===null||z.trim()==="")){for(const U of m)await fetch(`/api/students/${U}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:z})});p(new Set),await o(s)}},handleBatchTransferStudents:()=>{m.size===0||!s||(T(""),g("transfer"))},handleBatchSetLockedLesson:()=>{m.size===0||!s||(x(""),g("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(h==="schedule"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const z of d)await fetch(`/api/classes/${z}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:y,scheduledDate:b+" 09:00:00",status:"scheduled"})});u(new Set)}else if(h==="lockedLesson"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const z of m)await fetch(`/api/students/${z}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:y})});p(new Set)}else if(h==="transfer"){if(!S||S===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const z of m)await fetch(`/api/classes/${s}/students/${z}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:z})});p(new Set)}g(null),s&&await o(s)}}}}function KC(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[i,o]=f.useState([]),[a,c]=f.useState("seg-1"),[l,d]=f.useState(null),[u,m]=f.useState(null),[p,h]=f.useState("none"),[g,y]=f.useState(null),[x,b]=f.useState(!1),v=f.useRef(null),S=async(T,k)=>{h("saving");try{(await fetch(`/api/lessons/${T}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:k})})).ok?(s(I=>I.map(_=>_.id===T?{..._,timeline:JSON.stringify(k)}:_)),o(k),h("saved"),y(new Date)):h("error")}catch(w){console.error("Failed to save timeline:",w),h("error")}};return f.useEffect(()=>{if(t){const T=n.find(k=>k.id===t);if(T){let k=[];if(T.timeline)try{k=typeof T.timeline=="string"?JSON.parse(T.timeline):T.timeline}catch{k=[{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 k=[{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"}];o(k);const w=v.current!==t;v.current=t,k.length>0?(w||!k.some(I=>I.id===a))&&c(k[0].id):c(null)}}},[t,n]),{timelineSegments:i,setTimelineSegments:o,activeSegmentId:a,setActiveSegmentId:c,segmentToEdit:l,setSegmentToEdit:d,draggedSegmentIdx:u,setDraggedSegmentIdx:m,editorSaveStatus:p,setEditorSaveStatus:h,editorLastSavedTime:g,setEditorLastSavedTime:y,editorPanelsExpanded:x,setEditorPanelsExpanded:b,saveTimeline:S}}function Gu(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
118
+ `)?`"${t.replace(/"/g,'""')}"`:t}async function YC(e){const{classId:t,className:n,students:s,dashData:i,lang:o,addToast:a,setIsGeneratingPDFReport:c}=e;c(l=>({...l,[t]:!0}));try{if(!i){a(o==="zh"?"暂无班级评分数据":"No Class Performance Data",o==="zh"?"请确保在此班级加载了作业与测验。":"Please check if assignments or quizzes are present for this class.","warning");return}const l=i.performance||[],d=i.assignments||[],u={};s.forEach(z=>{u[z.id]={id:z.id,name:z.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),l.forEach(z=>{const U=z.student_id;u[U]&&(u[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&u[U].submittedCount++,z.score!==null&&z.score!==void 0&&(u[U].totalGradesSum+=z.score,u[U].gradedCount++))});const m=Object.values(u).map(z=>{const U=z.gradedCount>0?z.totalGradesSum/z.gradedCount:0,j=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avgScore:U,submissionRate:j}});m.sort((z,U)=>U.avgScore-z.avgScore);let p=0,h=0,g=0,y=0;l.forEach(z=>{y++,(z.submission_status==="submitted"||z.submission_status==="graded")&&g++,z.score!==null&&z.score!==void 0&&(p+=z.score,h++)});const x=h>0?p/h:0,b=y>0?g/y*100:0,v={};d.forEach(z=>{v[z.id]={id:z.id,title:z.title,scores:[],submittedCount:0,totalCount:0}}),l.forEach(z=>{const U=z.assignment_id;v[U]&&(v[U].totalCount++,(z.submission_status==="submitted"||z.submission_status==="graded")&&v[U].submittedCount++,z.score!==null&&z.score!==void 0&&v[U].scores.push(z.score))});const S=Object.values(v).map(z=>{const U=z.scores.length,j=z.scores.reduce((G,Q)=>G+Q,0),B=U>0?j/U:0,q=U>0?Math.max(...z.scores):0,C=U>0?Math.min(...z.scores):0,K=z.totalCount>0?z.submittedCount/z.totalCount*100:0;return{...z,avg:B,max:q,min:C,subRate:K}}),{jsPDF:T}=await He(async()=>{const{jsPDF:z}=await import("./vendor-pdf-DVWGghIL.js").then(U=>U.j);return{jsPDF:z}},[]),{applyPlugin:k}=await He(async()=>{const{applyPlugin:z}=await import("./vendor-pdf-DVWGghIL.js").then(U=>U.b);return{applyPlugin:z}},[]);k(T);const w=new T({orientation:"p",unit:"mm",format:"a4"}),I=[15,23,42],_=[79,70,229],R=[51,65,85],L=[226,232,240],E=z=>{w.setDrawColor(L[0],L[1],L[2]),w.setLineWidth(.3),w.line(14,z,196,z)};w.setFillColor(I[0],I[1],I[2]),w.rect(0,0,210,42,"F"),w.setTextColor(255,255,255),w.setFont("helvetica","bold"),w.setFontSize(20),w.text("CLASS PERFORMANCE REPORT",14,18),w.setFont("helvetica","normal"),w.setFontSize(10),w.setTextColor(194,205,225),w.text("Academic Insights • Generative Report Summary",14,25),w.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),w.setFillColor(_[0],_[1],_[2]),w.rect(172,10,24,24,"F"),w.setFont("helvetica","bold"),w.setFontSize(14),w.setTextColor(255,255,255),w.text("OS",180,26);let A=52;w.setTextColor(I[0],I[1],I[2]),w.setFont("helvetica","bold"),w.setFontSize(12),w.text("I. EXECUTIVE OVERVIEW",14,A),A+=6;const D=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${d.length} items`],["Global Assignment Submission Rate",`${b.toFixed(1)}%`],["Class Average Performance Score",`${x.toFixed(1)}%`]];w.autoTable({startY:A,head:[["Metric Indicator","Class-wide Metric Value"]],body:D,theme:"striped",headStyles:{fillColor:I,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:R,fontSize:9.5},margin:{left:14,right:14}}),A=w.lastAutoTable.finalY+12,w.setTextColor(I[0],I[1],I[2]),w.setFont("helvetica","bold"),w.setFontSize(12),w.text("II. STUDENT RANKING DISTRIBUTION",14,A),A+=6;const F=m.map((z,U)=>{let j="Excellent";return z.avgScore>=90?j="Excellent (A)":z.avgScore>=75?j="Good (B)":z.avgScore>=60?j="Satisfactory (C)":j="Needs Improvement (D)",[`${U+1}`,z.name,`${z.submittedCount}/${z.totalCount} (${z.submissionRate.toFixed(0)}%)`,`${z.avgScore.toFixed(1)}%`,j]});w.autoTable({startY:A,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:F,theme:"grid",headStyles:{fillColor:_,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}}),A=w.lastAutoTable.finalY+12,A>210&&(w.addPage(),A=20),w.setTextColor(I[0],I[1],I[2]),w.setFont("helvetica","bold"),w.setFontSize(12),w.text("III. ASSIGNMENT PERFORMANCE METRICS",14,A),A+=6;const P=S.map(z=>[z.title,`${z.subRate.toFixed(0)}%`,`${z.avg.toFixed(1)}%`,`${z.min.toFixed(0)}% - ${z.max.toFixed(0)}%`]);w.autoTable({startY:A,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:P.length>0?P:[["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}}),A=w.lastAutoTable.finalY+15,E(275),w.setFontSize(8),w.setTextColor(148,163,184),w.text("Generated by OpenLearn Next • Educational Operating System",14,282),w.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const $=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),V=new Date().toISOString().split("T")[0];w.save(`Class_Report_${$}_${V}.pdf`),a(o==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",o==="zh"?`班级【${n}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${n} saved to your device.`,"success")}catch(l){console.error("PDF Generation Failed:",l),a(o==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",l.message||"Error occurred during PDF generation","warning")}finally{c(l=>({...l,[t]:!1}))}}function ZC(e){const{className:t,students:n,dashData:s,qWeight:i=40,aWeight:o=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 c=s.assignments||[],l=s.performance||[],d=c.map(S=>{let T="assignment";if(a[S.id])T=a[S.id];else{const k=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));T=k||w?"quiz":"assignment"}return{...S,category:T}}),u=["Student Name","Student Email"];d.forEach(S=>{const T=S.category==="quiz"?"Quiz":"Assignment";u.push(`${T}: ${S.title}`)}),u.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${o}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const m=[u];n.forEach(S=>{const T=[S.name,S.email];let k=0,w=0,I=0,_=0,R=0,L=0,E=0;d.forEach(z=>{const U=l.find(j=>j.assignment_id===z.id&&j.student_id===S.id);if(U&&U.score!==null&&U.score!==void 0){T.push(`${U.score}%`);const j=Number(U.score);z.category==="quiz"?(k+=j,w++):(I+=j,_++),R+=j,L++,E++}else U&&U.submission_status==="submitted"?(T.push("Pending Grade"),E++):T.push("Not Submitted")});const A=w>0?Math.round(k/w):null,D=_>0?Math.round(I/_):null;let F="N/A";if(A!==null&&D!==null){const z=A*(i/100)+D*(o/100);F=`${Math.round(z)}%`}else A!==null?F=`${A}%`:D!==null&&(F=`${D}%`);const P=A!==null?`${A}%`:"N/A",$=D!==null?`${D}%`:"N/A",V=L>0?`${Math.round(R/L)}%`:"N/A";T.push(P,$,F,V,`${E}`,`${c.length}`),m.push(T.map(Gu))});const p=m.map(S=>S.join(",")).join(`
119
+ `),h=new Blob(["\uFEFF"+p],{type:"text/csv;charset=utf-8;"}),g=URL.createObjectURL(h),y=document.createElement("a"),x=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),b=new Date().toISOString().split("T")[0],v=`${x}_grades_report_${b}.csv`;y.setAttribute("href",g),y.setAttribute("download",v),y.style.visibility="hidden",document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(g)}function XC(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:i,assignmentsWeight:o,customCategoryOverrides:a,lang:c}=e;if(!t)return null;const l=n[t]||[],d=s[t];if(!d||!d.assignments||l.length===0)return null;const u=d.assignments||[],m=d.performance||[],p=u.map(x=>{let b="assignment";if(a[x.id])b=a[x.id];else{const v=x.content&&x.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=x.title&&(x.title.toLowerCase().includes("quiz")||x.title.toLowerCase().includes("test")||x.title.includes("测验")||x.title.includes("测试"));b=v||S?"quiz":"assignment"}return{...x,category:b}}),h=["Student Name","Student Email"];p.forEach(x=>{const b=x.category==="quiz"?"Quiz":"Assignment";h.push(`${b}: ${x.title}`)}),h.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${o}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const g=[];return l.slice(0,5).forEach(x=>{const b=[x.name,x.email];let v=0,S=0,T=0,k=0,w=0,I=0,_=0;p.forEach(P=>{const $=m.find(V=>V.assignment_id===P.id&&V.student_id===x.id);if($&&$.score!==null&&$.score!==void 0){b.push(`${$.score}%`);const V=Number($.score);P.category==="quiz"?(v+=V,S++):(T+=V,k++),w+=V,I++,_++}else $&&$.submission_status==="submitted"?(b.push(c==="zh"?"待评分":"Pending Grade"),_++):b.push(c==="zh"?"未提交":"Not Submitted")});const R=S>0?Math.round(v/S):null,L=k>0?Math.round(T/k):null;let E="N/A";if(R!==null&&L!==null){const P=R*(i/100)+L*(o/100);E=`${Math.round(P)}%`}else R!==null?E=`${R}%`:L!==null&&(E=`${L}%`);const A=R!==null?`${R}%`:"N/A",D=L!==null?`${L}%`:"N/A",F=I>0?`${Math.round(w/I)}%`:"N/A";b.push(A,D,E,F,`${_}`,`${u.length}`),g.push(b)}),{headers:h,rows:g,totalStudents:l.length}}function e1(e){const{classes:t,classStudentsMap:n,classDashboardMap:s,lang:i}=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(u=>{const m=n[u.id]||[],p=s[u.id];if(!p||!p.assignments||m.length===0)return;const h=p.assignments||[],g=h.map(y=>{const x=y.content&&y.content.startsWith('{"quizType":"mcq_learning_objectives"'),b=y.title&&(y.title.toLowerCase().includes("quiz")||y.title.toLowerCase().includes("test")||y.title.includes("测验")||y.title.includes("测试"));return{...y,category:x||b?"quiz":"assignment"}});m.forEach(y=>{let x=0,b=0,v=0,S=0,T=0,k=0;g.forEach(E=>{const A=p.performance?.find(D=>D.student_id===y.id&&D.assignment_id===E.id&&D.submission_status==="graded"&&D.score!==null);if(A){const D=Number(A.score);T+=D,k++,E.category==="quiz"?(x+=D,b++):(v+=D,S++)}});const w=b>0?Math.round(x/b):null,I=S>0?Math.round(v/S):null;let _=0;w!==null&&I!==null?_=Math.round(w*.4+I*.6):w!==null?_=Math.round(w):I!==null&&(_=Math.round(I));const R=k>0?Math.round(T/k):0,L=[u.name,y.name,y.email,w!==null?`${w}%`:"N/A",I!==null?`${I}%`:"N/A",`${_}%`,`${R}%`,`${k}`,`${h.length}`];a.push(L)})}),a.length<=1){alert(i==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const c="data:text/csv;charset=utf-8,\uFEFF"+a.map(u=>u.map(Gu).join(",")).join(`
120
+ `),l=encodeURI(c),d=document.createElement("a");d.setAttribute("href",l),d.setAttribute("download",`All_Classes_Combined_Grades_${new Date().toISOString().slice(0,10)}.csv`),document.body.appendChild(d),d.click(),document.body.removeChild(d)}function t1(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:i,fetchClassStudents:o,fetchClassDashboard:a,fetchClassProgress:c,addToast:l=()=>{}}=e,[d,u]=f.useState(!1),[m,p]=f.useState(""),[h,g]=f.useState(""),[y,x]=f.useState(40),[b,v]=f.useState(60),[S,T]=f.useState({}),[k,w]=f.useState(!1),[I,_]=f.useState(!1),[R,L]=f.useState(null),[E,A]=f.useState(!1),[D,F]=f.useState({}),P=f.useCallback(C=>{const K=Math.min(100,Math.max(0,C));x(K),v(100-K)},[]),$=f.useCallback(C=>{const K=Math.min(100,Math.max(0,C));v(K),x(100-K)},[]),V=f.useMemo(()=>XC({exportClassId:m,classStudentsMap:s,classDashboardMap:i,quizzesWeight:y,assignmentsWeight:b,customCategoryOverrides:S,lang:t}),[m,y,b,S,s,i,t]),z=f.useCallback(async(C,K)=>{L(C);try{await o(C),await a(C),await c(C),p(C),g(K),x(40),v(60),T({}),u(!0)}catch(G){console.error(G)}finally{L(null),w(!1)}},[o,a,c]),U=f.useCallback((C,K,G=40,Q=60,ee={})=>{ZC({className:K,students:s[C]||[],dashData:i[C],qWeight:G,aWeight:Q,overrides:ee})},[s,i]),j=f.useCallback(async(C,K)=>{await o(C),await a(C),await c(C),await YC({classId:C,className:K,students:s[C]||[],dashData:i[C],lang:t,addToast:l,setIsGeneratingPDFReport:F})},[s,i,t,l,o,a,c]),B=f.useCallback(async()=>{A(!0);try{await e1({classes:n,classStudentsMap:s,classDashboardMap:i,lang:t})}catch(C){console.error("Export all classes error:",C)}finally{A(!1),w(!1)}},[n,s,i,t]),q=f.useCallback((C,K)=>{const G=i[K];if(!G||!G.performance)return null;const Q=Date.now()-2592e6,ue=G.performance.filter(pe=>pe.student_id===C).filter(pe=>pe.submitted_at&&pe.submitted_at>=Q&&pe.score!==null&&pe.score!==void 0);if(ue.length===0)return null;const X=ue.reduce((pe,ke)=>pe+Number(ke.score),0)/ue.length;return X<60?Math.round(X):null},[i]);return{isExportWeightModalOpen:d,setIsExportWeightModalOpen:u,exportClassId:m,setExportClassId:p,exportClassName:h,setExportClassName:g,quizzesWeight:y,setQuizzesWeight:x,assignmentsWeight:b,setAssignmentsWeight:v,customCategoryOverrides:S,setCustomCategoryOverrides:T,exportDropdownOpen:k,setExportDropdownOpen:w,exportTooltipOpen:I,setExportTooltipOpen:_,loadingExportClassId:R,setLoadingExportClassId:L,isExportingAllCombined:E,setIsExportingAllCombined:A,isGeneratingPDFReport:D,setIsGeneratingPDFReport:F,handleQuizzesWeightChange:P,handleAssignmentsWeightChange:$,csvPreviewData:V,triggerExportForClass:z,handleExportGrades:U,handleGeneratePDFReport:j,handleExportAllClassesCombined:B,get30DayAverageWarning:q}}const LE={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"}},RE=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],n1=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:Wr,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
121
+ ---
122
+ ## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
123
+ ---
124
+ ## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:or,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:ta,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:Tr,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
125
+ <div style='padding:20px; text-align:center;'>
126
+ <h2>Interactive Web Courseware</h2>
127
+ <p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
128
+ </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:Vr,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:An,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:od,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:wt,color:"pink",group:"manage",defaultData:{},editFields:[]}],s1=n1.reduce((e,t)=>(e[t.type]=t,e),{});function r1(e){return s1[e]||Nn.get(e)}const Hc="openlearnv2.agentProviderId";function i1({lang:e,addToast:t,host:n,session:s,fetchStudents:i,fetchClasses:o,chatLogRef:a}){const c=ae(ce=>ce.lessons),l=ae(ce=>ce.setLessons),d=yC(c),{lessonsSearchQuery:u,setLessonsSearchQuery:m,lessonsSortOrder:p,setLessonsSortOrder:h,filterEnrollment:g,setFilterEnrollment:y,filterHasContent:x,setFilterHasContent:b,filterThisMonth:v,setFilterThisMonth:S,copyingLessonId:T,setCopyingLessonId:k,filteredAndSortedLessons:w}=d,I=ae(ce=>ce.selectedLesson),_=ae(ce=>ce.setSelectedLesson),R=ae(ce=>ce.elements),L=ae(ce=>ce.setElements),[E,A]=f.useState(!1),[D,F]=f.useState("agent"),P=ae(ce=>ce.classes),$=ae(ce=>ce.setClasses),V=ae(ce=>ce.students),z=ae(ce=>ce.setStudents);ae(ce=>ce.dataVersion);const U=wC(),{computerLabs:j,setComputerLabs:B,loadingLabs:q,setLoadingLabs:C,fetchLabs:K,classSeats:G,setClassSeats:Q,savingSeats:ee,setSavingSeats:ue,fetchClassSeats:we,todaySchedules:X,setTodaySchedules:pe,fetchTodaySchedules:ke,classSchedulesMap:je,setClassSchedulesMap:M,fetchClassSchedules:Y,scheduleAttendanceMap:te,setScheduleAttendanceMap:ne,fetchScheduleAttendance:ie,expandedScheduleId:oe,setExpandedScheduleId:be,newScheduleDate:le,setNewScheduleDate:Ne,newScheduleLessonId:Te,setNewScheduleLessonId:Je}=U,se=vC({lang:e,addToast:t,setCopyingLessonId:k}),{fetchLessons:N,handleQuickCreateLesson:O,handleDeleteCourse:W,handleCopyCourse:H,fetchElements:Z}=se,he=zC({fetchClassSchedules:Y}),{classStudentsMap:fe,setClassStudentsMap:xe,classProgressMap:re,setClassProgressMap:Be,classDashboardMap:Ae,setClassDashboardMap:Me,classAssignmentsMap:Fe,setClassAssignmentsMap:At,assignmentSubmissionsMap:et,setAssignmentSubmissionsMap:Nt,liveClassStudentProgress:Ht,setLiveClassStudentProgress:Dn,fetchClassStudents:qt,fetchClassProgress:_e,fetchClassDashboard:an,fetchLiveClassStudentProgress:Mn,handleQuickScheduleClass:$n,handleQuickGenerateAssignment:Fn}=he,[ln,Bn]=f.useState(null),cn=ce=>{Bn(ce)},[Un,Vn]=f.useState(null),Wn=ce=>{Vn(ce)},It=f.useRef(null),[dn,Gt]=f.useState(null),Hn=ce=>{const os=r1(ce);os&&Gt({type:ce,data:{...os.defaultData}})},qn=async ce=>{const os=dn;if(Gt(null),!os)return;const Bp=Date.now()+15e3;for(;Date.now()<Bp;){const tl=It.current?.addElementAtCenter;if(typeof tl=="function"){await tl(os.type,ce);return}await new Promise(Up=>setTimeout(Up,50))}},Pt=ae(ce=>ce.siteInfo),un=ae(ce=>ce.setSiteInfo),hn=KC({selectedLesson:I,lessons:c,setLessons:l}),{timelineSegments:Oe,setTimelineSegments:Gn,activeSegmentId:Qn,setActiveSegmentId:Jn,segmentToEdit:Kn,setSegmentToEdit:Yn,draggedSegmentIdx:Zn,setDraggedSegmentIdx:Xn,editorSaveStatus:es,setEditorSaveStatus:ts,editorLastSavedTime:ns,setEditorLastSavedTime:ss,editorPanelsExpanded:rs,setEditorPanelsExpanded:is,saveTimeline:ye}=hn,Ke=LC(s),{registeredCommands:Qt,setRegisteredCommands:ge,vfsNodes:qe,setVfsNodes:Ze,processes:Xe,setProcesses:pt,showProcessLogs:rt,setShowProcessLogs:zt,processLogsContent:Jt,setProcessLogsContent:Ds,showLogs:ni,setShowLogs:Ms,currentVfsParent:si,setCurrentVfsParent:ri,fetchRegisteredCommands:$s,fetchVfs:ii,fetchProcesses:oi,fetchProcessLogs:Ge}=Ke,Ha=WC({lang:e,fetchClasses:o,fetchStudents:i,fetchLessons:N,addToast:t}),{isCloudDriveOpen:lh,setIsCloudDriveOpen:ch,cloudDrivePreviewNode:dh,setCloudDrivePreviewNode:uh,isSystemResourceLibraryOpen:hh,setIsSystemResourceLibraryOpen:fh,systemResourceTab:mh,setSystemResourceTab:ph,selectedLibraryResourceId:gh,setSelectedLibraryResourceId:xh,libraryResources:bh,setLibraryResources:yh,loadingLibraryResources:wh,setLoadingLibraryResources:vh,showCoursewareHub:Sh,setShowCoursewareHub:jh,fetchLibraryResources:kh,isImportLessonsOpen:Nh,setIsImportLessonsOpen:Ch,importStatus:Eh,setImportStatus:Th,importProgress:Ah,setImportProgress:Ih,importProgressTotal:Ph,setImportProgressTotal:zh,importErrorMsg:Lh,setImportErrorMsg:Rh,previewImportData:_h,setPreviewImportData:Oh,isDraggingImport:Dh,setIsDraggingImport:Mh,downloadCsvTemplate:$h,handleCSVFileChange:Fh,handleCSVImportSubmit:Bh,showImportModal:Uh,setShowImportModal:Vh,isImporting:Wh,setIsImporting:Hh,importError:qh,setImportError:Gh,importSuccess:Qh,setImportSuccess:Jh,downloadCSVTemplate:Kh,handleImportFile:Yh}=Ha,qa=ae(ce=>ce.setTeacherTab),Ga=HC({lang:e,addToast:t,fetchLessons:N,setSelectedLesson:_,setTeacherTab:qa}),{isCourseWizardOpen:Zh,setIsCourseWizardOpen:Xh,wizardStep:ef,setWizardStep:tf,wizardCourseTitle:nf,setWizardCourseTitle:sf,wizardCourseCategory:rf,setWizardCourseCategory:of,wizardCourseDescription:af,setWizardCourseDescription:lf,wizardCourseContent:cf,setWizardCourseContent:df,wizardCourseTimeline:uf,setWizardCourseTimeline:hf,wizardIsSubmitting:ff,wizardIsGeneratingOutline:mf,handleGenerateOutline:pf,handleDeployWizardCourse:gf}=Ga,Qa=GC({session:s,host:n,lang:e,addToast:t,setChatLog:ce=>a.current(ce),setTeacherTab:qa,fetchLessons:N}),{plugins:xf,setPlugins:bf,fetchPlugins:yf,aiProviders:Lt,setAiProviders:wf,fetchAIProviders:vf,isAIProviderModalOpen:Sf,setIsAIProviderModalOpen:jf,editingAIProvider:kf,setEditingAIProvider:Nf,providerName:Cf,setProviderName:Ef,providerApiUrl:Tf,setProviderApiUrl:Af,providerApiKey:If,setProviderApiKey:Pf,providerModelName:zf,setProviderModelName:Lf,testingProviderId:Rf,setTestingProviderId:_f,showPluginModal:Of,setShowPluginModal:Df,storeTab:Mf,setStoreTab:$f,pluginCode:Ff,setPluginCode:Bf,installingPlugin:Uf,setInstallingPlugin:Vf,events:Wf,setEvents:Hf,fetchEvents:qf,approvals:Gf,setApprovals:Qf,fetchApprovals:Jf,scoreOverrides:Kf,setScoreOverrides:Yf,handleSaveAIProvider:Zf,handleDeleteAIProvider:Xf,handleTestAIProvider:em,handleInstallPlugin:tm,handleZipPluginUpload:nm,handleTogglePlugin:sm,handleDeletePlugin:rm,handleApprove:im,handleReject:om}=Qa,[Kt,Ja]=f.useState(()=>typeof window>"u"?"":window.localStorage.getItem(Hc)||""),Ka=Lt.some(ce=>ce.id===Kt)?Kt:Lt[0]?.id||"",am=Lt.find(ce=>ce.id===Ka)||null;f.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(Hc,Kt)},[Kt]),f.useEffect(()=>{Lt.length>0&&!Lt.some(ce=>ce.id===Kt)&&Ja(Lt[0].id)},[Lt,Kt]);const Ya=QC(),{isQuizGeneratorOpen:lm,setIsQuizGeneratorOpen:cm,quizGeneratorClassId:dm,setQuizGeneratorClassId:um,quizGenMode:hm,setQuizGenMode:fm,quizGenSelectedLessonId:mm,setQuizGenSelectedLessonId:pm,quizGenTopic:gm,setQuizGenTopic:xm,isGeneratingSuggestions:bm,setIsGeneratingSuggestions:ym,suggestedObjectives:wm,setSuggestedObjectives:vm,suggestedQuestions:Sm,setSuggestedQuestions:jm,savingQuiz:km,setSavingQuiz:Nm,quizStudentAnswers:Cm,setQuizStudentAnswers:Em,quizGenTimeLimit:Tm,setQuizGenTimeLimit:Am,quizStudentAnswersRef:Im,subAssignmentTab:Pm,setSubAssignmentTab:zm}=Ya,[Lm,Rm]=f.useState(null),[_m,Om]=f.useState("dueDate"),[Dm,Mm]=f.useState({}),Za=t1({lang:e,classes:P,classStudentsMap:fe,classDashboardMap:Ae,fetchClassStudents:qt,fetchClassDashboard:an,fetchClassProgress:_e}),{isExportWeightModalOpen:$m,setIsExportWeightModalOpen:Fm,exportClassId:Bm,setExportClassId:Um,exportClassName:Vm,setExportClassName:Wm,quizzesWeight:Hm,setQuizzesWeight:qm,assignmentsWeight:Gm,setAssignmentsWeight:Qm,customCategoryOverrides:Jm,setCustomCategoryOverrides:Km,exportDropdownOpen:Ym,setExportDropdownOpen:Zm,exportTooltipOpen:Xm,setExportTooltipOpen:ep,loadingExportClassId:tp,setLoadingExportClassId:np,isExportingAllCombined:sp,setIsExportingAllCombined:rp,isGeneratingPDFReport:ip,setIsGeneratingPDFReport:op,handleQuizzesWeightChange:ap,handleAssignmentsWeightChange:lp,csvPreviewData:cp,triggerExportForClass:dp,handleExportGrades:up,handleGeneratePDFReport:hp,handleExportAllClassesCombined:Xa,get30DayAverageWarning:fp}=Za,el=JC({lang:e,classes:P,expandedClassId:ln,fetchClasses:o,fetchClassStudents:qt,handleExportAllClassesCombined:Xa}),{batchMode:mp,setBatchMode:pp,selectedClassIds:gp,setSelectedClassIds:xp,selectedStudentIds:bp,setSelectedStudentIds:yp,batchPicker:wp,setBatchPicker:vp,batchPickerLesson:Sp,setBatchPickerLesson:jp,batchPickerDate:kp,setBatchPickerDate:Np,batchPickerTargetClass:Cp,setBatchPickerTargetClass:Ep,toggleClassSelection:Tp,toggleSelectAllClasses:Ap,toggleStudentSelection:Ip,toggleSelectAllStudents:Pp,handleBatchDeleteClasses:zp,handleBatchExportClasses:Lp,handleBatchSetPasscode:Rp,handleBatchScheduleClasses:_p,handleBatchDeleteStudents:Op,handleBatchResetPassword:Dp,handleBatchTransferStudents:Mp,handleBatchSetLockedLesson:$p,confirmBatchPicker:Fp}=el;return{lessons:c,setLessons:l,lessonFilteringData:d,lessonsSearchQuery:u,setLessonsSearchQuery:m,lessonsSortOrder:p,setLessonsSortOrder:h,filterEnrollment:g,setFilterEnrollment:y,filterHasContent:x,setFilterHasContent:b,filterThisMonth:v,setFilterThisMonth:S,copyingLessonId:T,setCopyingLessonId:k,filteredAndSortedLessons:w,selectedLesson:I,setSelectedLesson:_,elements:R,setElements:L,showRightSidebar:E,setShowRightSidebar:A,rightSidebarTab:D,setRightSidebarTab:F,classes:P,setClasses:$,students:V,setStudents:z,labAndScheduleData:U,computerLabs:j,setComputerLabs:B,loadingLabs:q,setLoadingLabs:C,fetchLabs:K,classSeats:G,setClassSeats:Q,savingSeats:ee,setSavingSeats:ue,fetchClassSeats:we,todaySchedules:X,setTodaySchedules:pe,fetchTodaySchedules:ke,classSchedulesMap:je,setClassSchedulesMap:M,fetchClassSchedules:Y,scheduleAttendanceMap:te,setScheduleAttendanceMap:ne,fetchScheduleAttendance:ie,expandedScheduleId:oe,setExpandedScheduleId:be,newScheduleDate:le,setNewScheduleDate:Ne,newScheduleLessonId:Te,setNewScheduleLessonId:Je,lessonCrudData:se,fetchLessons:N,handleQuickCreateLesson:O,handleDeleteCourse:W,handleCopyCourse:H,fetchElements:Z,classOpsData:he,classStudentsMap:fe,setClassStudentsMap:xe,classProgressMap:re,setClassProgressMap:Be,classDashboardMap:Ae,setClassDashboardMap:Me,classAssignmentsMap:Fe,setClassAssignmentsMap:At,assignmentSubmissionsMap:et,setAssignmentSubmissionsMap:Nt,liveClassStudentProgress:Ht,setLiveClassStudentProgress:Dn,fetchClassStudents:qt,fetchClassProgress:_e,fetchClassDashboard:an,fetchLiveClassStudentProgress:Mn,handleQuickScheduleClass:$n,handleQuickGenerateAssignment:Fn,expandedClassId:ln,setExpandedClassId:cn,expandedStudentId:Un,setExpandedStudentId:Wn,whiteboardRef:It,paletteEdit:dn,setPaletteEdit:Gt,handlePaletteActivate:Hn,handlePaletteConfirm:qn,siteInfo:Pt,setSiteInfo:un,lessonTimelineData:hn,timelineSegments:Oe,setTimelineSegments:Gn,activeSegmentId:Qn,setActiveSegmentId:Jn,segmentToEdit:Kn,setSegmentToEdit:Yn,draggedSegmentIdx:Zn,setDraggedSegmentIdx:Xn,editorSaveStatus:es,setEditorSaveStatus:ts,editorLastSavedTime:ns,setEditorLastSavedTime:ss,editorPanelsExpanded:rs,setEditorPanelsExpanded:is,saveTimeline:ye,systemData:Ke,registeredCommands:Qt,setRegisteredCommands:ge,vfsNodes:qe,setVfsNodes:Ze,processes:Xe,setProcesses:pt,showProcessLogs:rt,setShowProcessLogs:zt,processLogsContent:Jt,setProcessLogsContent:Ds,showLogs:ni,setShowLogs:Ms,currentVfsParent:si,setCurrentVfsParent:ri,fetchRegisteredCommands:$s,fetchVfs:ii,fetchProcesses:oi,fetchProcessLogs:Ge,resourceLibraryData:Ha,isCloudDriveOpen:lh,setIsCloudDriveOpen:ch,cloudDrivePreviewNode:dh,setCloudDrivePreviewNode:uh,isSystemResourceLibraryOpen:hh,setIsSystemResourceLibraryOpen:fh,systemResourceTab:mh,setSystemResourceTab:ph,selectedLibraryResourceId:gh,setSelectedLibraryResourceId:xh,libraryResources:bh,setLibraryResources:yh,loadingLibraryResources:wh,setLoadingLibraryResources:vh,showCoursewareHub:Sh,setShowCoursewareHub:jh,fetchLibraryResources:kh,isImportLessonsOpen:Nh,setIsImportLessonsOpen:Ch,importStatus:Eh,setImportStatus:Th,importProgress:Ah,setImportProgress:Ih,importProgressTotal:Ph,setImportProgressTotal:zh,importErrorMsg:Lh,setImportErrorMsg:Rh,previewImportData:_h,setPreviewImportData:Oh,isDraggingImport:Dh,setIsDraggingImport:Mh,downloadCsvTemplate:$h,handleCSVFileChange:Fh,handleCSVImportSubmit:Bh,showImportModal:Uh,setShowImportModal:Vh,isImporting:Wh,setIsImporting:Hh,importError:qh,setImportError:Gh,importSuccess:Qh,setImportSuccess:Jh,downloadCSVTemplate:Kh,handleImportFile:Yh,courseWizard:Ga,isCourseWizardOpen:Zh,setIsCourseWizardOpen:Xh,wizardStep:ef,setWizardStep:tf,wizardCourseTitle:nf,setWizardCourseTitle:sf,wizardCourseCategory:rf,setWizardCourseCategory:of,wizardCourseDescription:af,setWizardCourseDescription:lf,wizardCourseContent:cf,setWizardCourseContent:df,wizardCourseTimeline:uf,setWizardCourseTimeline:hf,wizardIsSubmitting:ff,wizardIsGeneratingOutline:mf,handleGenerateOutline:pf,handleDeployWizardCourse:gf,pluginManagementData:Qa,plugins:xf,setPlugins:bf,fetchPlugins:yf,aiProviders:Lt,setAiProviders:wf,fetchAIProviders:vf,isAIProviderModalOpen:Sf,setIsAIProviderModalOpen:jf,editingAIProvider:kf,setEditingAIProvider:Nf,providerName:Cf,setProviderName:Ef,providerApiUrl:Tf,setProviderApiUrl:Af,providerApiKey:If,setProviderApiKey:Pf,providerModelName:zf,setProviderModelName:Lf,testingProviderId:Rf,setTestingProviderId:_f,showPluginModal:Of,setShowPluginModal:Df,storeTab:Mf,setStoreTab:$f,pluginCode:Ff,setPluginCode:Bf,installingPlugin:Uf,setInstallingPlugin:Vf,events:Wf,setEvents:Hf,fetchEvents:qf,approvals:Gf,setApprovals:Qf,fetchApprovals:Jf,scoreOverrides:Kf,setScoreOverrides:Yf,handleSaveAIProvider:Zf,handleDeleteAIProvider:Xf,handleTestAIProvider:em,handleInstallPlugin:tm,handleZipPluginUpload:nm,handleTogglePlugin:sm,handleDeletePlugin:rm,handleApprove:im,handleReject:om,agentProviderId:Kt,setAgentProviderId:Ja,effectiveAgentProviderId:Ka,selectedAgentProvider:am,quizGenerator:Ya,isQuizGeneratorOpen:lm,setIsQuizGeneratorOpen:cm,quizGeneratorClassId:dm,setQuizGeneratorClassId:um,quizGenMode:hm,setQuizGenMode:fm,quizGenSelectedLessonId:mm,setQuizGenSelectedLessonId:pm,quizGenTopic:gm,setQuizGenTopic:xm,isGeneratingSuggestions:bm,setIsGeneratingSuggestions:ym,suggestedObjectives:wm,setSuggestedObjectives:vm,suggestedQuestions:Sm,setSuggestedQuestions:jm,savingQuiz:km,setSavingQuiz:Nm,quizStudentAnswers:Cm,setQuizStudentAnswers:Em,quizGenTimeLimit:Tm,setQuizGenTimeLimit:Am,quizStudentAnswersRef:Im,subAssignmentTab:Pm,setSubAssignmentTab:zm,isGeneratingAssignment:Lm,setIsGeneratingAssignment:Rm,assignmentSortOrder:_m,setAssignmentSortOrder:Om,isGrading:Dm,setIsGrading:Mm,gradeExport:Za,isExportWeightModalOpen:$m,setIsExportWeightModalOpen:Fm,exportClassId:Bm,setExportClassId:Um,exportClassName:Vm,setExportClassName:Wm,quizzesWeight:Hm,setQuizzesWeight:qm,assignmentsWeight:Gm,setAssignmentsWeight:Qm,customCategoryOverrides:Jm,setCustomCategoryOverrides:Km,exportDropdownOpen:Ym,setExportDropdownOpen:Zm,exportTooltipOpen:Xm,setExportTooltipOpen:ep,loadingExportClassId:tp,setLoadingExportClassId:np,isExportingAllCombined:sp,setIsExportingAllCombined:rp,isGeneratingPDFReport:ip,setIsGeneratingPDFReport:op,handleQuizzesWeightChange:ap,handleAssignmentsWeightChange:lp,csvPreviewData:cp,triggerExportForClass:dp,handleExportGrades:up,handleGeneratePDFReport:hp,handleExportAllClassesCombined:Xa,get30DayAverageWarning:fp,classBatch:el,batchMode:mp,setBatchMode:pp,selectedClassIds:gp,setSelectedClassIds:xp,selectedStudentIds:bp,setSelectedStudentIds:yp,batchPicker:wp,setBatchPicker:vp,batchPickerLesson:Sp,setBatchPickerLesson:jp,batchPickerDate:kp,setBatchPickerDate:Np,batchPickerTargetClass:Cp,setBatchPickerTargetClass:Ep,toggleClassSelection:Tp,toggleSelectAllClasses:Ap,toggleStudentSelection:Ip,toggleSelectAllStudents:Pp,handleBatchDeleteClasses:zp,handleBatchExportClasses:Lp,handleBatchSetPasscode:Rp,handleBatchScheduleClasses:_p,handleBatchDeleteStudents:Op,handleBatchResetPassword:Dp,handleBatchTransferStudents:Mp,handleBatchSetLockedLesson:$p,confirmBatchPicker:Fp,handleSeedSuccess:async ce=>{await o(),await N(),await ke().catch(()=>{}),Se.getState().setLiveClassSelectedClassId(ce.classId),_(ce.lessonId),Se.getState().setLiveClassIsActive(!0),t(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")}}}function o1(){const[e,t]=f.useState(null),[n,s]=f.useState(null);f.useEffect(()=>{if(n){const h=setTimeout(()=>{s(null)},8e3);return()=>clearTimeout(h)}},[n]),f.useEffect(()=>{if(e)try{const h=window.AudioContext||window.webkitAudioContext;if(h){const g=new h,y=g.currentTime,x=g.createOscillator(),b=g.createGain();x.type="sine",x.frequency.setValueAtTime(587.33,y),x.frequency.exponentialRampToValueAtTime(880,y+.25),b.gain.setValueAtTime(.25,y),b.gain.exponentialRampToValueAtTime(.001,y+.8),x.connect(b),b.connect(g.destination),x.start(y),x.stop(y+.8)}}catch{}},[e]);const[i,o]=f.useState([]),a=h=>{o(g=>{const y=typeof h=="function"?h(g):h;return Array.isArray(y)&&y.length>200?y.slice(0,200):y})},[c,l]=f.useState(new Map),[d,u]=f.useState([]),[m,p]=f.useState({});return{pickedAlertData:e,setPickedAlertData:t,pickedAnnouncement:n,setPickedAnnouncement:s,liveClassFeed:i,setLiveClassFeed:a,liveClassAcknowledgedMap:c,setLiveClassAcknowledgedMap:l,onlineStudentIds:d,setOnlineStudentIds:u,activeStudentLessons:m,setActiveStudentLessons:p}}function a1(e){const{activeStudentId:t,activeRole:n,selectedLesson:s,quizStudentAnswersRef:i,setStudentViewStatus:o}=e,a=ae(v=>v.session),c=ae(v=>v.setSelectedLesson),[l,d]=f.useState(null),[u,m]=f.useState({}),[p,h]=f.useState(null),g=async v=>{try{const{ok:S,data:T}=await PC(v);if(S){if(d(T),T.profile){const k=T.profile,w=Se.getState().students,I=w.findIndex(L=>L.id===T.profile.id),_=I>=0?w[I]:null;if(!_||_.locked_lesson_id!==k.locked_lesson_id||_.lock_mode!==k.lock_mode||JSON.stringify(_.lock_target)!==JSON.stringify(k.lock_target)||_.name!==k.name)if(I>=0){const L=[...w];L[I]={...L[I],...k},Se.getState().setStudents(L)}else Se.getState().setStudents([k])}T.profile&&T.profile.locked_lesson_id&&(c(T.profile.locked_lesson_id),o("lesson"))}}catch{}},y=async(v=!1)=>{if(!p||!t)return;const T=p?.content&&p.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(i.current):"Submitted via Whiteboard";try{const{ok:k}=await EC(p.id,{studentId:t,content:T});k&&(v&&alert("Time is up! Your assessment was successfully submitted automatically."),await g(t),o("dashboard"),h(null))}catch(k){console.error(k)}};return f.useEffect(()=>{a&&n==="student"&&t&&g(t)},[a,n,t]),{studentDashboardData:l,setStudentDashboardData:d,studentProgressMap:u,setStudentProgressMap:m,selectedAssignment:p,setSelectedAssignment:h,fetchStudentDashboard:g,fetchStudentProgress:async v=>{try{const{ok:S,data:T}=await ak(v);S&&m(k=>({...k,[v]:T}))}catch{}},updateStudentProgress:async v=>{if(n==="student"&&t&&s)try{await ik(t,{lessonId:s,completed:v===100,progressPercent:v})}catch(S){console.error("Failed to update student progress:",S)}},submitQuizAssignment:y}}function l1(e,t,n){const[s,i]=f.useState(new Set),[o,a]=f.useState(null),[c,l]=f.useState(!1),d=f.useMemo(()=>{if(e!=="student"||!t)return[];const m=[],p=t.assignments||[];for(const h of p)if(!h.submission_status)m.push({id:`new-${h.id}`,type:"new_assignment",title:n==="zh"?"新发布作业":"New Assignment",message:n==="zh"?`您有一项新作业:"${h.title}"`:`You have a new assignment: ${h.title}`,date:h.created_at,relatedId:h.id});else if(h.submission_status==="graded"){const g=!!h.feedback;m.push({id:`graded-${h.id}`,type:"graded",title:g?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:g?n==="zh"?`您的作业"${h.title}"已评分,得分:${h.score}%。反馈:"${h.feedback}"`:`Your assignment "${h.title}" was graded. Score: ${h.score}%. Teacher feedback: "${h.feedback}"`:n==="zh"?`您的作业"${h.title}"已评分,得分:${h.score}%`:`Your assignment "${h.title}" was graded. Score: ${h.score}%`,date:h.submitted_at||h.created_at,relatedId:h.id})}return m.sort((h,g)=>g.date-h.date)},[e,t,n]),u=f.useMemo(()=>d.filter(m=>!s.has(m.id)),[d,s]);return{studentNotifications:d,unreadNotifications:u,readNotifications:s,setReadNotifications:i,selectedNotificationForModal:o,setSelectedNotificationForModal:a,isNotificationsOpen:c,setIsNotificationsOpen:l}}function c1(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:i,expandedClassId:o,fetchLessons:a,fetchClasses:c,fetchStudents:l,fetchClassStudents:d,fetchClassProgress:u,fetchClassDashboard:m,fetchElements:p}=e,[h,g]=f.useState([{role:"agent",content:n.agentIntro||""}]),[y,x]=f.useState(""),[b,v]=f.useState(!1),[S,T]=f.useState([]),[k,w]=f.useState("");f.useEffect(()=>{h.length===1&&h[0].role==="agent"&&g([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const I=f.useCallback(async A=>{try{const D=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(A||"")}`);if(!D.ok)return;const F=await D.json(),P=Array.isArray(F.messages)?F.messages:[];P.length>0?g(P.map($=>({role:$.role==="assistant"?"agent":"user",content:$.content}))):g([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),_=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(()=>{I(s)},[s,I]),{personaId:k,setPersonaId:w,chatLog:h,setChatLog:g,input:y,setInput:x,loading:b,setLoading:v,chatAttachments:S,setChatAttachments:T,handleChatFileChange:A=>{A.target.files&&Array.from(A.target.files).forEach(D=>{const F=new FileReader;F.onload=P=>{P.target?.result&&T($=>[...$,{name:D.name,content:P.target.result}])},D.name.endsWith(".zip")?F.readAsDataURL(D):F.readAsText(D)})},handleChatDrop:A=>{A.preventDefault(),A.dataTransfer.files&&Array.from(A.dataTransfer.files).forEach(D=>{const F=new FileReader;F.onload=P=>{P.target?.result&&T($=>[...$,{name:D.name,content:P.target.result}])},D.name.endsWith(".zip")?F.readAsDataURL(D):F.readAsText(D)})},handleSend:async A=>{if(A.preventDefault(),!y.trim()||b)return;const D=[...S];let F=y;D.length>0&&(F+=`
129
+ (📁 ${t==="zh"?"附件":"Attachments"}: ${D.map(P=>P.name).join(", ")})`),g(P=>[...P,{role:"user",content:F}]),x(""),T([]),v(!0);try{const P=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:y,lang:t,currentLessonId:s,attachments:D,providerId:i||null,personaId:k||null})}),$=await P.json();let V="";!P.ok||$.success===!1?V=`⚠️ ${$.message||$.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(V=$.agentText||"",$.toolResults&&$.toolResults.length>0&&(V+=`
130
+
131
+ ${n.executedCommands}`+$.toolResults.map(z=>z.callName).join(", "))),g(z=>[...z,{role:"agent",content:V}]),await a(),await c(),await l(),o&&(await d(o),await u(o),await m(o)),s&&await p(s)}catch{g(P=>[...P,{role:"agent",content:n.simulationError}])}finally{v(!1)}},handleClearAgentMemory:_,restoreAgentMemory:I}}function d1(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:i,selectedLesson:o,selectedAssignment:a,expandedClassId:c,fetchLessons:l,fetchPlugins:d,fetchRegisteredCommands:u,fetchEvents:m,fetchApprovals:p,fetchProcesses:h,fetchClasses:g,fetchTodaySchedules:y,fetchStudents:x,fetchLabs:b,fetchVfs:v,fetchProcessLogs:S,fetchClassStudents:T,fetchElements:k}=e,w=f.useRef(i),I=f.useRef(o),_=f.useRef(a),R=f.useRef(c);f.useEffect(()=>{w.current=i},[i]),f.useEffect(()=>{I.current=o},[o]),f.useEffect(()=>{_.current=a},[a]),f.useEffect(()=>{R.current=c},[c]),f.useEffect(()=>{if(!t)return;const L=t.role==="teacher",E=L&&(t.subRole==="administrator"||t.username==="admin"||t.userId==="usr_admin");l(),d(),u(),y().catch(()=>{}),E&&(m(),p(),h()),L&&(g(),x(),b(),v(w.current));let A=!1;const D=setInterval(async()=>{if(!A){A=!0;try{if(E&&(await m(),await p(),await h(),n&&await S(n)),await l(),await u(),await y().catch(()=>{}),L&&(await g(),await x(),await b(),await v(w.current),R.current&&await T(R.current)),_.current){const F=s||_.current.student_id;await k(`assignment-${_.current.id}-student-${F}`)}else I.current&&await k(I.current)}finally{A=!1}}},2e3);return()=>clearInterval(D)},[t,n,s]),f.useEffect(()=>{t&&t.role==="teacher"&&v(i)},[i,t]),f.useEffect(()=>{o&&k(o)},[o])}const St=Object.create(null);St.open="0";St.close="1";St.ping="2";St.pong="3";St.message="4";St.upgrade="5";St.noop="6";const br=Object.create(null);Object.keys(St).forEach(e=>{br[St[e]]=e});const Vo={type:"error",data:"parser error"},Qu=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ju=typeof ArrayBuffer=="function",Ku=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Fa=({type:e,data:t},n,s)=>Qu&&t instanceof Blob?n?s(t):qc(t,s):Ju&&(t instanceof ArrayBuffer||Ku(t))?n?s(t):qc(new Blob([t]),s):s(St[e]+(t||"")),qc=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function Gc(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Yi;function u1(e,t){if(Qu&&e.data instanceof Blob)return e.data.arrayBuffer().then(Gc).then(t);if(Ju&&(e.data instanceof ArrayBuffer||Ku(e.data)))return t(Gc(e.data));Fa(e,!1,n=>{Yi||(Yi=new TextEncoder),t(Yi.encode(n))})}const Qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Qc.length;e++)bs[Qc.charCodeAt(e)]=e;const h1=e=>{let t=e.length*.75,n=e.length,s,i=0,o,a,c,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),u=new Uint8Array(d);for(s=0;s<n;s+=4)o=bs[e.charCodeAt(s)],a=bs[e.charCodeAt(s+1)],c=bs[e.charCodeAt(s+2)],l=bs[e.charCodeAt(s+3)],u[i++]=o<<2|a>>4,u[i++]=(a&15)<<4|c>>2,u[i++]=(c&3)<<6|l&63;return d},f1=typeof ArrayBuffer=="function",Ba=(e,t)=>{if(typeof e!="string")return{type:"message",data:Yu(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:m1(e.substring(1),t)}:br[n]?e.length>1?{type:br[n],data:e.substring(1)}:{type:br[n]}:Vo},m1=(e,t)=>{if(f1){const n=h1(e);return Yu(n,t)}else return{base64:!0,data:e}},Yu=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Zu="",p1=(e,t)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((o,a)=>{Fa(o,!1,c=>{s[a]=c,++i===n&&t(s.join(Zu))})})},g1=(e,t)=>{const n=e.split(Zu),s=[];for(let i=0;i<n.length;i++){const o=Ba(n[i],t);if(s.push(o),o.type==="error")break}return s};function x1(){return new TransformStream({transform(e,t){u1(e,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,s)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let Zi;function rr(e){return e.reduce((t,n)=>t+n.length,0)}function ir(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)n[i]=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 b1(e,t){Zi||(Zi=new TextDecoder);const n=[];let s=0,i=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(s===0){if(rr(n)<1)break;const l=ir(n,1);o=(l[0]&128)===128,i=l[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(rr(n)<2)break;const l=ir(n,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(rr(n)<8)break;const l=ir(n,8),d=new DataView(l.buffer,l.byteOffset,l.length),u=d.getUint32(0);if(u>Math.pow(2,21)-1){c.enqueue(Vo);break}i=u*Math.pow(2,32)+d.getUint32(4),s=3}else{if(rr(n)<i)break;const l=ir(n,i);c.enqueue(Ba(o?l:Zi.decode(l),t)),s=0}if(i===0||i>e){c.enqueue(Vo);break}}}})}const Xu=4;function We(e){if(e)return y1(e)}function y1(e){for(var t in We.prototype)e[t]=We.prototype[t];return e}We.prototype.on=We.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};We.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};We.prototype.off=We.prototype.removeListener=We.prototype.removeAllListeners=We.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,i=0;i<n.length;i++)if(s=n[i],s===t||s.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+e],this};We.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,i=n.length;s<i;++s)n[s].apply(this,t)}return this};We.prototype.emitReserved=We.prototype.emit;We.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};We.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ei=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),ut=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),w1="arraybuffer";function eh(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const v1=ut.setTimeout,S1=ut.clearTimeout;function ti(e,t){t.useNativeTimers?(e.setTimeoutFn=v1.bind(ut),e.clearTimeoutFn=S1.bind(ut)):(e.setTimeoutFn=ut.setTimeout.bind(ut),e.clearTimeoutFn=ut.clearTimeout.bind(ut))}const j1=1.33;function k1(e){return typeof e=="string"?N1(e):Math.ceil((e.byteLength||e.size)*j1)}function N1(e){let t=0,n=0;for(let s=0,i=e.length;s<i;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 th(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function C1(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function E1(e){let t={},n=e.split("&");for(let s=0,i=n.length;s<i;s++){let o=n[s].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}class T1 extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class Ua extends We{constructor(t){super(),this.writable=!1,ti(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 T1(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=Ba(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=C1(t);return n.length?"?"+n:""}}class A1 extends Ua{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)};g1(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,p1(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]=th()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let nh=!1;try{nh=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const I1=nh;function P1(){}class z1 extends A1{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",(i,o)=>{this.onError("xhr post error",i,o)})}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 Cn=class yr extends We{constructor(t,n,s){super(),this.createRequest=t,ti(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=eh(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}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 i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.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(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=yr.requestsCount++,yr.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=P1,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete yr.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()}};Cn.requestsCount=0;Cn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Jc);else if(typeof addEventListener=="function"){const e="onpagehide"in ut?"pagehide":"unload";addEventListener(e,Jc,!1)}}function Jc(){for(let e in Cn.requests)Cn.requests.hasOwnProperty(e)&&Cn.requests[e].abort()}const L1=(function(){const e=sh({xdomain:!1});return e&&e.responseType!==null})();class R1 extends z1{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=L1&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Cn(sh,this.uri(),t)}}function sh(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||I1))return new XMLHttpRequest}catch{}if(!t)try{return new ut[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class _1 extends Ua{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=rh?{}:eh(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(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=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],i=n===t.length-1;Fa(s,this.supportsBinary,o=>{try{this.doWrite(s,o)}catch{}i&&ei(()=>{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]=th()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Xi=ut.WebSocket||ut.MozWebSocket;class O1 extends _1{createSocket(t,n,s){return rh?new Xi(t,n,s):n?new Xi(t,n):new Xi(t)}doWrite(t,n){this.ws.send(n)}}class D1 extends Ua{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=b1(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),i=x1();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{s.read().then(({done:c,value:l})=>{c||(this.onPacket(l),o())}).catch(c=>{})};o();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],i=n===t.length-1;this._writer.write(s).then(()=>{i&&ei(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const M1={websocket:O1,webtransport:D1,polling:R1},$1=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,F1=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Wo(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 i=$1.exec(e||""),o={},a=14;for(;a--;)o[F1[a]]=i[a]||"";return n!=-1&&s!=-1&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=B1(o,o.path),o.queryKey=U1(o,o.query),o}function B1(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 U1(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,o){i&&(n[i]=o)}),n}const Ho=typeof addEventListener=="function"&&typeof removeEventListener=="function",wr=[];Ho&&addEventListener("offline",()=>{wr.forEach(e=>e())},!1);class Ft extends We{constructor(t,n){if(super(),this.binaryType=w1,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=Wo(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=Wo(n.host).host);ti(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 i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=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=E1(this.opts.query)),Ho&&(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"})},wr.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=Xu,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&&Ft.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",Ft.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 i=this.writeBuffer[s].data;if(i&&(n+=k1(i)),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,ei(()=>{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,i){if(typeof n=="function"&&(i=n,n=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const o={type:t,data:n,options:s};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),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(Ft.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(),Ho&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=wr.indexOf(this._offlineEventListener);s!==-1&&wr.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Ft.protocol=Xu;class V1 extends Ft{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;Ft.priorWebsocketSuccess=!1;const i=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Ft.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(u(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const p=new Error("probe error");p.transport=n.name,this.emitReserved("upgradeError",p)}}))};function o(){s||(s=!0,u(),n.close(),n=null)}const a=m=>{const p=new Error("probe error: "+m);p.transport=n.name,o(),this.emitReserved("upgradeError",p)};function c(){a("transport closed")}function l(){a("socket closed")}function d(m){n&&m.name!==n.name&&o()}const u=()=>{n.removeListener("open",i),n.removeListener("error",a),n.removeListener("close",c),this.off("close",l),this.off("upgrading",d)};n.once("open",i),n.once("error",a),n.once("close",c),this.once("close",l),this.once("upgrading",d),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 W1=class extends V1{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(i=>M1[i]).filter(i=>!!i)),super(t,s)}};function H1(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=Wo(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 o=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+o+":"+s.port+t,s.href=s.protocol+"://"+o+(n&&n.port===s.port?"":":"+s.port),s}const q1=typeof ArrayBuffer=="function",G1=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,ih=Object.prototype.toString,Q1=typeof Blob=="function"||typeof Blob<"u"&&ih.call(Blob)==="[object BlobConstructor]",J1=typeof File=="function"||typeof File<"u"&&ih.call(File)==="[object FileConstructor]";function Va(e){return q1&&(e instanceof ArrayBuffer||G1(e))||Q1&&e instanceof Blob||J1&&e instanceof File}function vr(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(vr(e[n]))return!0;return!1}if(Va(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vr(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vr(e[n]))return!0;return!1}function K1(e){const t=[],n=e.data,s=e;return s.data=Sr(n,t),s.attachments=t.length,{packet:s,buffers:t}}function Sr(e,t,n){if(!e)return e;if(Va(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 i=0;i<e.length;i++)s[i]=Sr(e[i],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return Sr(e.toJSON(),t,!0);const s={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=Sr(e[i],t));return s}return e}function Y1(e,t){return e.data=qo(e.data,t),delete e.attachments,e}function qo(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]=qo(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=qo(e[n],t));return e}const Z1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ve;(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"})(ve||(ve={}));class X1{constructor(t){this.replacer=t}encode(t){return(t.type===ve.EVENT||t.type===ve.ACK)&&vr(t)?this.encodeAsBinary({type:t.type===ve.EVENT?ve.BINARY_EVENT:ve.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ve.BINARY_EVENT||t.type===ve.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=K1(t),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}class Wa extends We{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===ve.BINARY_EVENT;s||n.type===ve.BINARY_ACK?(n.type=s?ve.EVENT:ve.ACK,this.reconstructor=new eE(n)):super.emitReserved("decoded",n)}else if(Va(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(ve[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ve.BINARY_EVENT||s.type===ve.BINARY_ACK){const o=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const a=t.substring(o,n);if(a!=Number(a)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const c=Number(a);if(!tE(c)||c<1)throw new Error("Illegal attachments");if(c>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=c}if(t.charAt(n+1)==="/"){const o=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););s.nsp=t.substring(o,n)}else s.nsp="/";const i=t.charAt(n+1);if(i!==""&&Number(i)==i){const o=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(o,n+1))}if(t.charAt(++n)){const o=this.tryParse(t.substr(n));if(Wa.isPayloadValid(s.type,o))s.data=o;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 ve.CONNECT:return Kc(n);case ve.DISCONNECT:return n===void 0;case ve.CONNECT_ERROR:return typeof n=="string"||Kc(n);case ve.EVENT:case ve.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Z1.indexOf(n[0])===-1);case ve.ACK:case ve.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class eE{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=Y1(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const tE=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Kc(e){return Object.prototype.toString.call(e)==="[object Object]"}const nE=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Wa,Encoder:X1,get PacketType(){return ve}},Symbol.toStringTag,{value:"Module"}));function ht(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const sE=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class oh extends We{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=[ht(t,"open",this.onopen.bind(this)),ht(t,"packet",this.onpacket.bind(this)),ht(t,"error",this.onerror.bind(this)),ht(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,i,o;if(sE.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:ve.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const u=this.ids++,m=n.pop();this._registerAckCallback(u,m),a.id=u}const c=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,l=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!c||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,n){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[t]=n;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===t&&this.sendBuffer.splice(c,1);n.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(o),n.apply(this,c)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((s,i)=>{const o=(a,c)=>a?i(a):s(c);o.withError=!0,n.push(o),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((i,...o)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...o)),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:ve.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 ve.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 ve.EVENT:case ve.BINARY_EVENT:this.onevent(t);break;case ve.ACK:case ve.BINARY_ACK:this.onack(t);break;case ve.DISCONNECT:this.ondisconnect();break;case ve.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(...i){s||(s=!0,n.packet({type:ve.ACK,id:t,data:i}))}}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:ve.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 On(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}On.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};On.prototype.reset=function(){this.attempts=0};On.prototype.setMin=function(e){this.ms=e};On.prototype.setMax=function(e){this.max=e};On.prototype.setJitter=function(e){this.jitter=e};class Go extends We{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,ti(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 On({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const i=n.parser||nE;this.encoder=new i.Encoder,this.decoder=new i.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 W1(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=ht(n,"open",function(){s.onopen(),t&&t()}),o=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),t?t(c):this.maybeReconnectOnOpen()},a=ht(n,"error",o);if(this._timeout!==!1){const c=this._timeout,l=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),n.close()},c);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),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(ht(t,"ping",this.onping.bind(this)),ht(t,"data",this.ondata.bind(this)),ht(t,"error",this.onerror.bind(this)),ht(t,"close",this.onclose.bind(this)),ht(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){ei(()=>{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 oh(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(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):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 ms={};function jr(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=H1(e,t.path||"/socket.io"),s=n.source,i=n.id,o=n.path,a=ms[i]&&o in ms[i].nsps,c=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let l;return c?l=new Go(s,t):(ms[i]||(ms[i]=new Go(s,t)),l=ms[i]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(jr,{Manager:Go,Socket:oh,io:jr,connect:jr});class rE{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 i=typeof t=="string"?new Blob([t],{type:s}):t,o=URL.createObjectURL(i),a=document.createElement("a");a.href=o,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)}}class iE{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 Qo=jt(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null}),remoteBrowserFullscreenElementId:null,setRemoteBrowserFullscreenElementId:t=>e({remoteBrowserFullscreenElementId:t})})),OE=e=>Ut(Qo,e),eo=new Set,ah=jt((e,t)=>({lastEvent:null,version:0,subscribe:n=>(eo.add(n),()=>{eo.delete(n)}),record:n=>{e({lastEvent:n,version:t().version+1});for(const s of eo)try{s(n)}catch(i){console.error("[pointsLedgerStore] listener error:",i)}},reset:()=>{e({lastEvent:null,version:0})}})),DE=e=>Ut(ah,e),oE={excellent:{rating:"excellent",label:"卓越表现",labelEn:"Excellent",score:3,rewardCoins:10,badge:"🌟",colorClass:"from-amber-400 to-yellow-500 text-yellow-950"},good:{rating:"good",label:"良好完成",labelEn:"Good",score:2,rewardCoins:5,badge:"👍",colorClass:"from-emerald-400 to-teal-500 text-emerald-950"},encourage:{rating:"encourage",label:"值得鼓励",labelEn:"Encourage",score:1,rewardCoins:2,badge:"💪",colorClass:"from-orange-400 to-amber-500 text-orange-950"}};function Yc(e){const t=Math.max(0,e.lesson_picked_count||0),n=Math.max(0,e.term_picked_count||0);return 1/(1+3*t+n)}function ME(e,t){if(!e||e.length===0)return[];if(!t.lessonId)return e;const n=new Set(t.onlineStudentIds??[]),s=t.activeStudentLessons??{};return e.filter(i=>n.has(i.id)&&s[i.id]===t.lessonId)}function $E(e,t){if(!e||e.length===0)return{filtered:[],fallback:!1};const n=e.filter(s=>s.tier===t);return n.length>0?{filtered:n,fallback:!1}:{filtered:e,fallback:!0}}function FE(e,t=Math.random){if(!e||e.length===0)return null;if(e.length===1)return{student:e[0],weight:Yc(e[0])};const n=e.map(a=>Yc(a)),s=n.reduce((a,c)=>a+c,0);if(s<=0){const a=Math.floor(t()*e.length);return{student:e[a],weight:1}}const i=t()*s;let o=0;for(let a=0;a<e.length;a++)if(o+=n[a],i<=o||a===e.length-1)return{student:e[a],weight:n[a]};return{student:e[0],weight:n[0]}}function aE(e){const{session:t,host:n,activeRole:s,activeStudentId:i,selectedLesson:o,activeSegmentId:a,studentViewStatus:c,lang:l,students:d,addToast:u,setOnlineStudentIds:m,setActiveStudentLessons:p,setLessons:h,setActiveSegmentId:g,setLiveClassStudentProgress:y,setLiveClassAcknowledgedMap:x,setLiveClassFeed:b,setSelectedLesson:v,setStudentViewStatus:S,studentLessonTab:T,setStudentLessonTab:k,selectedAssignment:w,setSelectedAssignment:I,setLocalProgressPercent:_,fetchStudentDashboard:R,fetchStudents:L,fetchElements:E,setPickedAlertData:A,setPickedAnnouncement:D,onStudentProgressUpdated:F}=e,P=f.useRef(null),$=f.useRef(s),V=f.useRef(i),z=f.useRef(l),U=f.useRef(d),j=f.useRef(u),B=f.useRef(o),q=f.useRef(null),C=f.useRef(c),K=f.useRef(new Map),G=f.useRef(T),Q=f.useRef(A),ee=f.useRef(D),ue=f.useRef(F),we=f.useRef(null);return f.useEffect(()=>{$.current=s},[s]),f.useEffect(()=>{V.current=i},[i]),f.useEffect(()=>{z.current=l},[l]),f.useEffect(()=>{U.current=d},[d]),f.useEffect(()=>{j.current=u},[u]),f.useEffect(()=>{B.current=o},[o]),f.useEffect(()=>{C.current=c},[c]),f.useEffect(()=>{G.current=T},[T]),f.useEffect(()=>{q.current=w},[w]),f.useEffect(()=>{Q.current=A},[A]),f.useEffect(()=>{ee.current=D},[D]),f.useEffect(()=>{ue.current=F},[F]),f.useEffect(()=>{if(!t)return;const X=jr();P.current=X,bu(X),n.isInitialized()||n.initialize(new Wu,new aS(X),new rE(j.current),new iE("__app__"));const pe=()=>{X.emit("join-room","whiteboard-broadcast");const M=Se.getState().liveClassSelectedClassId;$.current==="teacher"&&M&&X.emit("join-room",`class-${M}`),$.current==="student"&&V.current?(X.emit("register-student",{studentId:V.current,name:U.current.find(Y=>Y.id===V.current)?.name||V.current}),C.current==="lesson"&&B.current&&X.emit("enter-lesson",{studentId:V.current,lessonId:B.current})):X.emit("request-presence")};pe(),X.on("presence-update",M=>{m(M.onlineStudentIds),p(M.activeStudentLessons)}),X.on("lesson-progress-mode-changed",M=>{const{lessonId:Y,progressMode:te,progressConditions:ne}=M;h(ie=>ie.map(oe=>oe.id===Y?{...oe,progress_mode:te,progress_conditions:ne}:oe))}),X.on("student-active-segment-changed",M=>{const{activeSegmentId:Y}=M;g(Y)}),X.on("segment-gate-changed",M=>{window.dispatchEvent(new CustomEvent("openlearn:segment-gate-changed",{detail:M}))}),X.on("student-pinged",M=>{const Y=M.message||(z.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");u(z.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",Y,"warning")}),X.on("student-progress-updated",M=>{const{studentId:Y,lessonId:te,progressPercent:ne,completed:ie}=M;y(oe=>{const be=oe.findIndex(le=>le.student_id===Y);if(be!==-1){const le=[...oe];return le[be]={...le[be],progress_percent:ne,completed:ie?1:0},le}else return[...oe,{student_id:Y,progress_percent:ne,completed:ie?1:0}]}),ue.current?.({studentId:Y,lessonId:te,progressPercent:ne,completed:!!ie,verified:M.verified===!0})}),X.on("student-error-alert",M=>{if(!(!M||!M.error)&&($.current==="teacher"||t?.role==="administrator")){tn.getState().addStudentError({...M.error,studentId:M.studentId,studentName:M.studentName||M.studentId,lessonId:M.lessonId,classId:M.classId});const Y=M.studentName?`${M.studentName} (${M.studentId})`:M.studentId;u(z.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${Y}: ${M.error.title||M.error.message}`,"warning")}}),X.on("assignment-graded-toast",M=>{if($.current==="student"&&V.current&&M.studentId===V.current){const Y=M.assignmentTitle||M.assignmentId,te=z.current==="zh"?`您的作业"${Y}"已完成评分!得分:${M.score}%。建议反馈已收到,快去查看。`:`Your assignment "${Y}" was graded. Score: ${M.score}%. Tutoring feedback has been posted.`;u(z.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",te,"success"),R(V.current)}}),X.on("student-picked",M=>{const Y=`${M.studentId}:${M.pickedTime??""}`,te=Date.now(),ne=K.current.get(Y),ie=ne!==void 0&&te-ne<1e4;if(!ie){K.current.set(Y,te);for(const[le,Ne]of K.current)te-Ne>=1e4&&K.current.delete(le)}const oe=V.current,be=$.current==="student"&&oe&&M.studentId===oe;if(be&&oe&&!ie){Q.current?.({studentId:M.studentId,studentName:M.studentName,rollcallId:M.rollcallId});const le=z.current==="zh"?"闪电警报!您已被老师在课程随机抽问中抽中!请立即集中注意力参与课堂回答。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";u(z.current==="zh"?"⚡️ 闪电抽问:老师抽中了你!":"⚡️ Classroom Pick Alert",le,"warning"),R(oe)}else if($.current==="student"&&!be&&!ie){const le=M.studentName||"同学";ee.current?.({studentName:le,studentId:M.studentId});const Ne=z.current==="zh"?`老师在课堂中随机抽中了【${le}】同学回答问题!`:`Teacher randomly selected [${le}] to answer!`;u(z.current==="zh"?"🎯 课堂随机抽问":"🎯 Classroom Random Pick",Ne,"info")}b(le=>[{id:`feed-pick-${M.studentId}-${M.pickedTime||Date.now()}`,time:new Date(M.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:z.current==="zh"?`点名互动:随机抽中学生【${M.studentName}】。`:`Classroom Pick: Randomly selected student "${M.studentName}".`},...le])}),X.on("rollcall:evaluated",M=>{if($.current!=="student"||M?.lessonId&&B.current&&M.lessonId!==B.current)return;const Y=!!V.current&&M?.studentId===V.current,te=z.current==="zh",ne=oE[M?.rating];ne&&(Y?(u(te?`${ne.badge} ${ne.label} +${M.rewardCoins} 金币`:`${ne.badge} ${ne.labelEn} +${M.rewardCoins} coins`,te?`老师在随机抽问中给了你「${ne.label}」的评价,成长金币 +${M.rewardCoins} 已到账!`:`The teacher rated you "${ne.labelEn}" in the random pick. +${M.rewardCoins} growth coins credited!`,"success"),V.current&&R(V.current)):u(te?`${ne.badge} 课堂表现评定`:`${ne.badge} Classroom Evaluation`,te?`老师给【${M.studentName||"某位同学"}】评了「${ne.label}」。`:`The teacher rated "${M.studentName||"a student"}" as "${ne.labelEn}".`,"info"),b(ie=>[{id:`feed-eval-${M.rollcallId||M.studentId}-${M.timestamp||Date.now()}`,time:new Date(M.timestamp||Date.now()).toLocaleTimeString(),type:"picked",message:te?`点名评价:${M.studentName||"学生"} 获评「${ne.label}」+${M.rewardCoins}金币。`:`Roll-call evaluation: "${M.studentName||"a student"}" rated ${ne.labelEn} +${M.rewardCoins} coins.`},...ie]))}),X.on("classroom:points_awarded",M=>{if(!M?.studentId)return;const Y=z.current==="zh",te=Number(M.deltaPoints)||0;ah.getState().record({studentId:M.studentId,classId:M.classId??"",deltaPoints:te,reason:M.reason??"",dimensionId:M.dimensionId,createdAt:M.createdAt}),!!V.current&&M.studentId===V.current&&(u(Y?te>=0?"🎁 获得成长积分":"📉 积分调整":te>=0?"Points earned":"Points adjusted",Y?`${te>=0?"+":""}${te} 积分${M.reason?`:${M.reason}`:""}`:`${te>=0?"+":""}${te} points${M.reason?`: ${M.reason}`:""}`,te>=0?"success":"warning"),V.current&&R(V.current))}),X.on("student-acknowledged",M=>{const{studentId:Y}=M;x(te=>{const ne=new Map(te);return ne.set(Y,!0),ne}),b(te=>[{id:`feed-ack-${Y}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:z.current==="zh"?`学生已确认收到提问点名(学生 ID: ${Y})。`:`Student acknowledged the classroom call (Student ID: ${Y}).`},...te]),L()}),X.on("class-lock-status-changed",M=>{const{lessonId:Y,locked:te,mode:ne,target:ie}=M||{};if($.current==="student"&&V.current){const oe=V.current,be=Se.getState().students,le=be.findIndex(Te=>Te.id===oe),Ne=le>=0?{...be[le]}:{id:oe,name:""};if(Ne.locked_lesson_id=te?Y:null,Ne.lock_mode=te&&ne||"full",Ne.lock_target=te?ie:null,le>=0){const Te=[...be];Te[le]=Ne,Se.getState().setStudents(Te)}else Se.getState().setStudents([Ne]);if(te&&Y){v(Y),S("lesson"),ie?.tab&&k(ie.tab);const Te=ne==="navigation";u(z.current==="zh"?Te?"🔒 答题锁定已开启":"🔒 课程已被锁定":Te?"🔒 Answer Lock Active":"🔒 Lesson Locked",z.current==="zh"?Te?"老师已开启答题锁定,请完成作答后提交,暂时无法离开本页。":"老师已锁定当前授课,您将无法切换到其他页面。":Te?"The teacher activated answer lock. Please complete and submit your work on this page.":"The teacher has locked the active lesson. You cannot leave this page.","info")}R(oe)}else L()}),X.on("student-lesson-tab-changed",M=>{$.current==="student"&&M?.tab&&(!M.lessonId||M.lessonId===B.current)&&k(M.tab)}),X.on("teacher-switched-lesson",M=>{$.current==="student"&&M?.lessonId&&(v(M.lessonId),S("lesson"))}),X.on("whiteboard-sync",M=>{const{roomId:Y,type:te}=M||{};if(te!=="refresh"||!Y)return;const ne=B.current;ne&&ne!==Y||(E(Y),!ne&&$.current==="student"&&(v(Y),S("lesson")),X.emit("join-room",Y))});const ke=()=>{Qo.getState().clearRemoteFullscreen();const M=we.current;we.current=null,M&&(k(M.lessonTab),M.viewStatus==="assignment"&&(I(M.assignment??null),M.lessonId&&v(M.lessonId),S("assignment")))};X.on("whiteboard-fullscreen-changed",M=>{if($.current!=="student")return;const Y=M?.lessonId,te=M?.elementId??null,ne=M?.mode==="browser",ie=Qo.getState();if(!te){if(ne){ie.setRemoteBrowserFullscreenElementId(null),ie.remoteFullscreenElementId||ke();return}ke();return}if(!Y)return;const oe=C.current;(oe==="lesson"?B.current===Y:oe==="assignment")&&(!ie.remoteFullscreenElementId&&!ie.remoteBrowserFullscreenElementId&&(we.current={viewStatus:oe,lessonTab:G.current,lessonId:B.current,assignment:oe==="assignment"?q.current:null}),ne?ie.setRemoteBrowserFullscreenElementId(te):ie.setRemoteFullscreenElementId(te),oe==="assignment"&&I(null),v(Y),E(Y),S("lesson"),k("whiteboard"))}),X.on("connect",()=>{pe(),ke(),Promise.resolve(L()).catch(()=>{}),$.current==="student"&&V.current&&Promise.resolve(R(V.current)).catch(()=>{})}),X.io?.on("reconnect",()=>{pe()});const je=M=>{try{if(!M)return;Mt.ingest({source:"widget.quiz",type:"quiz.answered",lessonId:M.lessonId,elementId:M.elementId,studentId:M.studentId,studentName:M.studentName,payload:{answer:M.answer,score:typeof M.score=="number"?M.score:void 0,isCorrect:!!M.isCorrect,correctAnswer:M.correctAnswer,correctIndex:typeof M.correctIndex=="number"?M.correctIndex:void 0,question:M.question,time:M.time},raw:M})}catch(Y){console.error("[useClassroomSocket] quiz.answered ingest failed",Y)}};return X.on("whiteboard-quiz-answered-staff",M=>{$.current!=="teacher"&&t?.role!=="administrator"||je(M)}),X.on("whiteboard-quiz-answered",M=>{$.current==="teacher"||t?.role==="administrator"||je(M)}),X.on("courseware-attempt-updated",M=>{try{if(!M||typeof M.attemptId!="string")return;const Y=M.type==="log"?"courseware.event_logged":M.type==="submit"?"courseware.submitted":M.type==="promote"?"courseware.finished":"courseware.event_logged";Mt.ingest({source:"iframe.bridge",type:Y,attemptId:M.attemptId,payload:{attemptId:M.attemptId,attemptType:M.type},raw:M})}catch(Y){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",Y)}}),()=>{X.disconnect(),P.current=null}},[t,s,i]),f.useEffect(()=>{P.current&&s==="student"&&i&&(c==="lesson"&&o?(P.current.emit("enter-lesson",{studentId:i,lessonId:o}),fetch(`/api/students/${i}/progress`).then(X=>X.json()).then(X=>{if(Array.isArray(X)){const pe=X.find(ke=>ke.lesson_id===o);_(pe?pe.progress_percent:0)}}).catch(console.error)):P.current.emit("leave-lesson",{studentId:i}))},[c,o,s,i]),f.useEffect(()=>{s==="teacher"&&o&&a&&P.current&&P.current.emit("teacher-broadcast-segment",{lessonId:o,activeSegmentId:a})},[a,o,s]),{socketRef:P}}function to(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Zc(e){if(!e||typeof e!="object")return[];const t=to(e.capabilitiesProposed);if(t.length>0)return t;const n=e.manifest;if(typeof n=="string"&&n.length>0)try{return to(JSON.parse(n)?.capabilitiesProposed)}catch{return[]}return n&&typeof n=="object"?to(n.capabilitiesProposed):[]}function lE(e){const t=e.isolation_mode??e.execution_mode;return t==="inline"||t==="worker"||t==="legacy"?t:"process"}function cE(e){const{lang:t,t:n,addToast:s,host:i,session:o,activeStudentId:a,activeRole:c,setStudentViewStatus:l,studentViewStatus:d,studentLessonTab:u,setStudentLessonTab:m,setLiveClassFocusLocked:p,isStudentLiveMode:h,isFollowingTeacher:g,liveStudentParam:y,fetchStudents:x,fetchLessons:b,fetchElements:v,fetchClasses:S,fetchClassStudents:T,fetchClassProgress:k,fetchClassDashboard:w,fetchLiveClassStudentProgress:I,setLiveClassStudentProgress:_,fetchRegisteredCommands:R,fetchVfs:L,fetchProcesses:E,fetchProcessLogs:A,fetchTodaySchedules:D,fetchLabs:F,fetchPlugins:P,fetchEvents:$,fetchApprovals:V,showProcessLogs:z,currentVfsParent:U,expandedClassId:j,activeSegmentId:B,setActiveSegmentId:q,quizStudentAnswersRef:C,effectiveAgentProviderId:K,plugins:G}=e,[Q,ee]=f.useState(0),ue=o1(),{pickedAlertData:we,setPickedAlertData:X,pickedAnnouncement:pe,setPickedAnnouncement:ke,liveClassFeed:je,setLiveClassFeed:M,liveClassAcknowledgedMap:Y,setLiveClassAcknowledgedMap:te,onlineStudentIds:ne,setOnlineStudentIds:ie,activeStudentLessons:oe,setActiveStudentLessons:be}=ue,le=ae(ye=>ye.liveClassSelectedClassId),Ne=ae(ye=>ye.setLiveClassSelectedClassId),Te=ae(ye=>ye.liveClassIsActive),Je=ae(ye=>ye.setLiveClassIsActive),se=ae(ye=>ye.selectedLesson),N=ae(ye=>ye.setSelectedLesson),O=ae(ye=>ye.setLessons),W=ae(ye=>ye.students);ae(ye=>ye.dataVersion);const H=a1({activeStudentId:a,activeRole:c,selectedLesson:se,quizStudentAnswersRef:C,setStudentViewStatus:l}),{studentDashboardData:Z,setStudentDashboardData:he,studentProgressMap:fe,setStudentProgressMap:xe,selectedAssignment:re,setSelectedAssignment:Be,fetchStudentDashboard:Ae,fetchStudentProgress:Me,updateStudentProgress:Fe,submitQuizAssignment:At}=H,[et,Nt]=f.useState(""),[Ht,Dn]=f.useState("all"),[qt,_e]=f.useState("grid"),[an,Mn]=f.useState({}),[$n,Fn]=f.useState({}),[ln,Bn]=f.useState({}),cn=l1(c,Z,t),{studentNotifications:Un,unreadNotifications:Vn,readNotifications:Wn,setReadNotifications:It,selectedNotificationForModal:dn,setSelectedNotificationForModal:Gt,isNotificationsOpen:Hn,setIsNotificationsOpen:qn}=cn;f.useEffect(()=>{a&&sk(a).then(({ok:ye,data:Ke})=>{It(ye&&Array.isArray(Ke)?new Set(Ke):new Set)}).catch(ye=>{console.warn("Failed to load read notifications from DB",ye),It(new Set)})},[a]);const Pt=f.useRef(new Set);f.useEffect(()=>{if(!i.isInitialized()||G.length===0)return;const ye=Ce.getState(),Ke=G.filter(ge=>ge.status==="active");for(const ge of Ke){if(Pt.current.has(ge.id))continue;const qe=ye.activePlugins.find(rt=>rt.id===ge.id),Ze=!!(qe&&ge.version&&qe.version!==ge.version);if(!(!qe||Ze||qe.state!==Le.ACTIVE&&qe.state!==Le.ACTIVATING))continue;Pt.current.add(ge.id);const pt=()=>{if(!ye.activePlugins.find(rt=>rt.id===ge.id))ye.addPlugin({id:ge.id,name:ge.name,version:ge.version??"",state:Le.INSTALLED,executionMode:lE(ge),capabilitiesProposed:Zc(ge),hasFrontend:ge.has_frontend});else if(Ze)try{const rt=Zc(ge);Ce.setState(zt=>({activePlugins:zt.activePlugins.map(Jt=>Jt.id===ge.id?{...Jt,version:ge.version??"",name:ge.name,capabilitiesProposed:rt,hasFrontend:ge.has_frontend}:Jt)}))}catch{}try{const rt=JSON.parse(ge.manifest);i.activateRemotePlugin(ge.id,rt,{hasFrontend:ge.has_frontend}).catch(zt=>{console.error(`[App] Failed to activate remote plugin "${ge.name}":`,zt)}).finally(()=>{Pt.current.delete(ge.id)})}catch(rt){Pt.current.delete(ge.id),console.error(`[App] Failed to parse manifest for plugin "${ge.name}":`,rt)}};qe&&qe.state===Le.ACTIVE&&Ze?i.deactivatePlugin(ge.id).catch(()=>{}).finally(pt):pt()}const Qt=G.filter(ge=>ge.status!=="active");for(const ge of Qt){const qe=ye.activePlugins.find(Ze=>Ze.id===ge.id);qe&&qe.state===Le.ACTIVE&&i.deactivatePlugin(ge.id).catch(Ze=>{console.error(`[App] Failed to deactivate remote plugin "${ge.name}":`,Ze)})}},[G,i]),f.useEffect(()=>{if(!i.isInitialized()||G.length===0)return;const ye=Ce.getState();for(const Ke of G)Ke.status==="active"&&(ye.dashboardVisibility.has(Ke.id)||ye.setDashboardVisibility(Ke.id,!0))},[G,i]),f.useEffect(()=>{le&&se?I(le,se):_([])},[le,se]),f.useEffect(()=>{le&&T(le)},[le]),iS(o);const un=c1({lang:t,t:n,selectedLesson:se,effectiveAgentProviderId:K,expandedClassId:j,fetchLessons:b,fetchClasses:S,fetchStudents:x,fetchClassStudents:T,fetchClassProgress:k,fetchClassDashboard:w,fetchElements:v}),{personaId:hn,setPersonaId:Oe,chatLog:Gn,setChatLog:Qn,input:Jn,setInput:Kn,loading:Yn,setLoading:Zn,chatAttachments:Xn,setChatAttachments:es,handleChatFileChange:ts,handleChatDrop:ns,handleSend:ss,handleClearAgentMemory:rs}=un;d1({session:o,showProcessLogs:z,activeStudentId:a,currentVfsParent:U,selectedLesson:se,selectedAssignment:re,expandedClassId:j,fetchLessons:b,fetchPlugins:P,fetchRegisteredCommands:R,fetchEvents:$,fetchApprovals:V,fetchProcesses:E,fetchClasses:S,fetchTodaySchedules:D,fetchStudents:x,fetchLabs:F,fetchVfs:L,fetchProcessLogs:A,fetchClassStudents:T,fetchElements:v});const{socketRef:is}=aE({session:o,host:i,activeRole:c,activeStudentId:a,selectedLesson:se,activeSegmentId:B,studentViewStatus:d,lang:t,students:W,addToast:s,setOnlineStudentIds:ie,setActiveStudentLessons:be,setLessons:O,setActiveSegmentId:q,setLiveClassStudentProgress:_,setLiveClassAcknowledgedMap:te,setLiveClassFeed:M,setSelectedLesson:N,setStudentViewStatus:l,studentLessonTab:u,setStudentLessonTab:m,selectedAssignment:re,setSelectedAssignment:Be,setLocalProgressPercent:ee,fetchStudentDashboard:Ae,fetchStudents:x,fetchElements:v,setPickedAlertData:X,setPickedAnnouncement:ke,onStudentProgressUpdated:({studentId:ye,lessonId:Ke,progressPercent:Qt,completed:ge,verified:qe})=>{xe(Ze=>{const Xe=Ze[ye];return Xe?{...Ze,[ye]:Xe.map(pt=>Ke&&pt.lesson_id!==Ke?pt:{...pt,progress_percent:Qt,completed:ge?1:0,...qe!==void 0?{verified:qe?1:0}:{}})}:Ze})}});return{localProgressPercent:Q,setLocalProgressPercent:ee,classroomLiveData:ue,pickedAlertData:we,setPickedAlertData:X,pickedAnnouncement:pe,setPickedAnnouncement:ke,liveClassFeed:je,setLiveClassFeed:M,liveClassAcknowledgedMap:Y,setLiveClassAcknowledgedMap:te,onlineStudentIds:ne,setOnlineStudentIds:ie,activeStudentLessons:oe,setActiveStudentLessons:be,liveClassSelectedClassId:le,setLiveClassSelectedClassId:Ne,liveClassIsActive:Te,setLiveClassIsActive:Je,studentOpsData:H,studentDashboardData:Z,setStudentDashboardData:he,studentProgressMap:fe,setStudentProgressMap:xe,selectedAssignment:re,setSelectedAssignment:Be,fetchStudentDashboard:Ae,fetchStudentProgress:Me,updateStudentProgress:Fe,submitQuizAssignment:At,rosterSearchQuery:et,setRosterSearchQuery:Nt,rosterTagFilter:Ht,setRosterTagFilter:Dn,rosterViewMode:qt,setRosterViewMode:_e,classSubmissionFilters:an,setClassSubmissionFilters:Mn,classActiveTabs:$n,setClassActiveTabs:Fn,studentActiveTabs:ln,setStudentActiveTabs:Bn,studentNotificationsHook:cn,studentNotifications:Un,unreadNotifications:Vn,readNotifications:Wn,setReadNotifications:It,selectedNotificationForModal:dn,setSelectedNotificationForModal:Gt,isNotificationsOpen:Hn,setIsNotificationsOpen:qn,agentChatData:un,personaId:hn,setPersonaId:Oe,chatLog:Gn,setChatLog:Qn,input:Jn,setInput:Kn,loading:Yn,setLoading:Zn,chatAttachments:Xn,setChatAttachments:es,handleChatFileChange:ts,handleChatDrop:ns,handleSend:ss,handleClearAgentMemory:rs,socketRef:is}}hC();function dE(){pC();const e=ae(h=>h.lang),t=fo[e]??fo.zh,{addToast:n}=fC(),s=Dx(),i=async()=>{await Se.getState().loadStudents()},o=async()=>{await Se.getState().loadClasses()},a=f.useRef(()=>{}),c=bC({lang:e,addToast:n,fetchStudents:i}),l=i1({lang:e,addToast:n,host:s,session:c.session,fetchStudents:i,fetchClasses:o,chatLogRef:a}),d=cE({lang:e,t,addToast:n,host:s,session:c.session,activeStudentId:c.activeStudentId,activeRole:c.activeRole,setStudentViewStatus:c.setStudentViewStatus,studentViewStatus:c.studentViewStatus,studentLessonTab:c.studentLessonTab,setStudentLessonTab:c.setStudentLessonTab,setLiveClassFocusLocked:c.setLiveClassFocusLocked,isStudentLiveMode:c.isStudentLiveMode,isFollowingTeacher:c.isFollowingTeacher,liveStudentParam:c.liveStudentParam,fetchStudents:i,fetchLessons:l.fetchLessons,fetchElements:l.fetchElements,fetchClasses:o,fetchClassStudents:l.fetchClassStudents,fetchClassProgress:l.fetchClassProgress,fetchClassDashboard:l.fetchClassDashboard,fetchLiveClassStudentProgress:l.fetchLiveClassStudentProgress,setLiveClassStudentProgress:l.setLiveClassStudentProgress,fetchRegisteredCommands:l.fetchRegisteredCommands,fetchVfs:l.fetchVfs,fetchProcesses:l.fetchProcesses,fetchProcessLogs:l.fetchProcessLogs,fetchTodaySchedules:l.fetchTodaySchedules,fetchLabs:l.fetchLabs,fetchPlugins:l.fetchPlugins,fetchEvents:l.fetchEvents,fetchApprovals:l.fetchApprovals,showProcessLogs:l.showProcessLogs,currentVfsParent:l.currentVfsParent,expandedClassId:l.expandedClassId,activeSegmentId:l.activeSegmentId,setActiveSegmentId:l.setActiveSegmentId,quizStudentAnswersRef:l.quizStudentAnswersRef,effectiveAgentProviderId:l.effectiveAgentProviderId,plugins:l.plugins});a.current=d.setChatLog;const u=ae(h=>h.setSelectedLesson),m=ae(h=>h.setTeacherTab);return{appData:{addToast:n,...l.systemData,...l.resourceLibraryData,...l.lessonCrudData,...l.classOpsData,...c.studentViewStateData,...d.studentOpsData,...c.sessionBootstrapData,...d.classroomLiveData,...l.labAndScheduleData,...l.pluginManagementData,...d.agentChatData,...l.quizGenerator,...l.courseWizard,...l.classBatch,...l.lessonTimelineData,...d.studentNotificationsHook,...l.gradeExport,...l.lessonFilteringData,mainNavCollapsed:c.mainNavCollapsed,setMainNavCollapsed:c.setMainNavCollapsed,batchMode:l.batchMode,setBatchMode:l.setBatchMode,selectedClassIds:l.selectedClassIds,setSelectedClassIds:l.setSelectedClassIds,setSelectedStudentIds:l.setSelectedStudentIds,expandedClassId:l.expandedClassId,setExpandedClassId:l.setExpandedClassId,exportTooltipOpen:l.exportTooltipOpen,setExportTooltipOpen:l.setExportTooltipOpen,exportDropdownOpen:l.exportDropdownOpen,setExportDropdownOpen:l.setExportDropdownOpen,expandedStudentId:l.expandedStudentId,setExpandedStudentId:l.setExpandedStudentId,selectedStudentIds:l.selectedStudentIds,rosterViewMode:d.rosterViewMode,setRosterViewMode:d.setRosterViewMode,rosterSearchQuery:d.rosterSearchQuery,setRosterSearchQuery:d.setRosterSearchQuery,rosterTagFilter:d.rosterTagFilter,setRosterTagFilter:d.setRosterTagFilter,classSubmissionFilters:d.classSubmissionFilters,setClassSubmissionFilters:d.setClassSubmissionFilters,classActiveTabs:d.classActiveTabs,setClassActiveTabs:d.setClassActiveTabs,assignmentSortOrder:l.assignmentSortOrder,setAssignmentSortOrder:l.setAssignmentSortOrder,isGeneratingAssignment:l.isGeneratingAssignment,isGrading:l.isGrading,setIsGrading:l.setIsGrading,setStudents:l.setStudents,setImportError:l.setImportError,setImportSuccess:l.setImportSuccess,setShowImportModal:l.setShowImportModal,studentActiveTabs:d.studentActiveTabs,setStudentActiveTabs:d.setStudentActiveTabs,fetchStudents:i,fetchClasses:o,onLogout:c.handleLogout,onAIProvidersChanged:l.fetchAIProviders,onDeleteCourse:l.handleDeleteCourse,onCopyCourse:l.handleCopyCourse,socketRef:d.socketRef,liveClassSelectedClassId:d.liveClassSelectedClassId,setLiveClassSelectedClassId:d.setLiveClassSelectedClassId,liveClassIsActive:d.liveClassIsActive,setLiveClassIsActive:d.setLiveClassIsActive,setSelectedLesson:u,setTeacherTab:m,teacherTab:c.teacherTab,onViewCourse:h=>{m("lesson_editor"),u(h)},t,readNotifications:d.readNotifications,setReadNotifications:d.setReadNotifications,localProgressPercent:d.localProgressPercent,setLocalProgressPercent:d.setLocalProgressPercent,lessons:l.lessons,selectedLesson:l.selectedLesson,elements:l.elements,classes:l.classes,students:l.students,isApprovalsCollapsed:c.isApprovalsCollapsed,setIsApprovalsCollapsed:c.setIsApprovalsCollapsed,isProcessesCollapsed:c.isProcessesCollapsed,setIsProcessesCollapsed:c.setIsProcessesCollapsed,whiteboardRef:l.whiteboardRef,paletteEdit:l.paletteEdit,handlePaletteActivate:l.handlePaletteActivate,handlePaletteConfirm:l.handlePaletteConfirm,setPaletteEdit:l.setPaletteEdit,session:c.session,showRightSidebar:l.showRightSidebar,setShowRightSidebar:l.setShowRightSidebar,rightSidebarTab:l.rightSidebarTab,setRightSidebarTab:l.setRightSidebarTab,agentProviderId:l.agentProviderId,setAgentProviderId:l.setAgentProviderId,effectiveAgentProviderId:l.effectiveAgentProviderId,selectedAgentProvider:l.selectedAgentProvider,isTourOpen:c.isTourOpen,setIsTourOpen:c.setIsTourOpen,handleSeedSuccess:l.handleSeedSuccess,wizardIsGeneratingOutline:l.wizardIsGeneratingOutline,handleGenerateOutline:l.handleGenerateOutline,activeRole:c.activeRole,setActiveRole:c.setActiveRole,isStudentPreviewMode:c.isStudentPreviewMode,isNotificationsOpen:d.isNotificationsOpen,setIsNotificationsOpen:d.setIsNotificationsOpen,selectedNotificationForModal:d.selectedNotificationForModal,setSelectedNotificationForModal:d.setSelectedNotificationForModal,setProfileOpen:c.setProfileOpen,notifyLockedNavigation:c.notifyLockedNavigation,handleLogout:c.handleLogout,toggleLanguage:c.toggleLanguage,setIsSystemResourceLibraryOpen:l.setIsSystemResourceLibraryOpen,siteInfo:l.siteInfo,isStudentLiveMode:c.isStudentLiveMode,liveStudentParam:c.liveStudentParam,isFollowingTeacher:c.isFollowingTeacher,setIsFollowingTeacher:c.setIsFollowingTeacher},sessionLoading:c.sessionLoading,session:c.session,setSession:c.setSession,handleLoginSuccess:c.handleLoginSuccess,handleLogout:c.handleLogout,isStageDisplayMode:c.isStageDisplayMode,stageLessonParam:c.stageLessonParam,stageTitleParam:c.stageTitleParam,stageLangParam:c.stageLangParam,activeRole:c.activeRole,selectedLesson:l.selectedLesson,lessons:l.lessons,profileOpen:c.profileOpen,setProfileOpen:c.setProfileOpen,lang:e}}function uE(){const{appData:e,sessionLoading:t,session:n,setSession:s,handleLoginSuccess:i,handleLogout:o,isStageDisplayMode:a,stageLessonParam:c,stageTitleParam:l,stageLangParam:d,activeRole:u,selectedLesson:m,lessons:p,profileOpen:h,setProfileOpen:g,lang:y}=dE();return t?r.jsx(Bs,{children:r.jsx(Fs,{value:e,children:r.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[r.jsx(mt,{size:48,className:"text-indigo-500 animate-spin"}),r.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:y==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]})})}):n?n.mustChangePassword?r.jsx(Bs,{children:r.jsx(Fs,{value:e,children:r.jsx(fx,{lang:y,username:n.username,onDone:()=>s({...n,mustChangePassword:!1}),onLogout:o})})}):r.jsx(Bs,{children:r.jsx(Fs,{value:e,children:r.jsxs(r.Fragment,{children:[a&&r.jsx(yj,{lessonId:c||m,lessonTitle:l||p.find(x=>x.id===(c||m))?.title,lang:d==="en"?"en":"zh"}),!a&&r.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[r.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[r.jsx(wj,{}),n.role==="student"&&n.usedDefaultPassword&&r.jsx(vj,{userId:n.studentId||n.userId,lang:y,onOpenProfile:()=>g(!0)}),r.jsx(Aj,{}),r.jsx(Lj,{open:h,session:n,lang:y,onClose:()=>g(!1),onSaved:x=>{n&&s({...n,name:x}),g(!1)},onAvatar:x=>{n&&s({...n,avatar:x??void 0})}}),r.jsx($j,{activeRole:u}),r.jsx(Pj,{})]}),r.jsx(Uj,{}),r.jsx(tk,{}),r.jsx(Lk,{}),r.jsx(QN,{}),r.jsx(lC,{}),r.jsx(uC,{})]})]})})}):r.jsx(Bs,{children:r.jsx(Fs,{value:e,children:r.jsx(hx,{onLoginSuccess:i,lang:y})})})}class hE 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 i=Ma({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 $r(i)&&(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}),tn.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:i}=this.state,o=this.props.fallbackTitle||"界面渲染遇到意外错误";return r.jsx("div",{className:"min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4 select-text",children:r.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:[r.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:[r.jsx("div",{className:"p-2.5 bg-white/20 rounded-xl backdrop-blur-xs shrink-0",children:r.jsx(Eg,{size:24,className:"text-white"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h1",{className:"text-lg font-bold leading-snug",children:o}),r.jsx("p",{className:"text-xs text-rose-100 mt-0.5",children:"OpenLearn 捕获到界面异常,已阻止整页崩溃并为您保留了诊断报告。"})]})]}),r.jsxs("div",{className:"p-6 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider block mb-1.5",children:"错误摘要 (Error Summary)"}),r.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||"未知异常"]})]}),r.jsxs("div",{className:"border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>this.setState({showDetails:!i}),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:[r.jsx("span",{children:"查看调用堆栈与排查信息"}),i?r.jsx(Tn,{size:14}):r.jsx(En,{size:14})]}),i&&r.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&&r.jsxs("div",{children:[r.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-90",children:t.stack})]}),n?.componentStack&&r.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[r.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),r.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-80",children:n.componentStack})]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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?r.jsx(ot,{size:14}):r.jsx(jn,{size:14}),r.jsx("span",{children:s?"✓ 诊断报告已复制!":"一键复制错误报告"})]}),r.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:[r.jsx(Hr,{size:14}),r.jsx("span",{children:"重新加载界面"})]})]}),r.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:[r.jsx(fd,{size:14}),r.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}window.React=no;window.ReactDOM=so;window.HostSharedDeps={React:no,ReactDOM:so,ReactDOMClient:sl,Recharts:fl,LucideReact:Cr,jsxRuntime:nl,react:no,"react-dom":so,"react-dom/client":sl,"react/jsx-runtime":nl,recharts:fl,"lucide-react":Cr};const fE=new LS;window.addEventListener("vite:preloadError",e=>{e.preventDefault();const t=sessionStorage.getItem("openlearn_chunk_reload"),n=Date.now();(!t||n-parseInt(t,10)>1e4)&&(sessionStorage.setItem("openlearn_chunk_reload",String(n)),window.location.reload())});Wp.createRoot(document.getElementById("root")).render(r.jsx(f.StrictMode,{children:r.jsx(hE,{children:r.jsx(Ox,{host:fE,children:r.jsx(uE,{})})})}));export{bj as $,Pu as A,n1 as B,$a as C,Vi as D,$e as E,NE as F,RE as G,AE as H,TE as I,EE as J,CE as K,Yr as L,Lv as M,Or as N,Cd as O,xn as P,Cu as Q,r1 as R,_o as S,Se as T,ct as U,KS as V,uj as W,DE as X,Gu as Y,gt as Z,GS as _,$t as a,In as a0,nk as a1,tn as a2,Pd as a3,ux as a4,Ns as a5,Ot as a6,Sj as a7,jj as a8,zx as a9,zj as aa,jE as ab,SE as ac,Zx as ad,Oo as ae,Ct as af,_n as ag,eS as ah,gu as ai,Ca as aj,Mt as ak,ME as al,$E as am,oE as an,FE as ao,Nn as ap,Oi as aq,kE as ar,Sn as as,OE as at,Qo as au,oS as av,mS as aw,pr as ax,IE as ay,vE as b,kt as c,Ce as d,ae as e,PE as f,zE as g,ac as h,Ox as i,rn as j,Di as k,Ea as l,xr as m,LE as n,Ix as o,KN as p,XN as q,rC as r,mr as s,fo as t,lk as u,sr as v,ZN as w,eC as x,Ve as y,YN as z};