openlearn-next 0.4.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -21
- package/cli-data.mjs +535 -40
- package/cli-doctor.mjs +456 -17
- package/cli.mjs +214 -12
- package/dist/assets/AcademicYearFilter-DUUGpDKt.js +1 -0
- package/dist/assets/ActivityWorkspaceWidget-5PzyxF6a.js +1 -0
- package/dist/assets/AdminDirectoryView-BCtmQTEK.js +5 -0
- package/dist/assets/AssessmentCenter-B43ojHG-.js +1 -0
- package/dist/assets/BatchPickerModal-CbmjInp7.js +1 -0
- package/dist/assets/ClassesView-DEnMaDOt.js +32 -0
- package/dist/assets/ClassroomCountdownWidget-CHq4983w.js +2 -0
- package/dist/assets/CloudDriveModal-D2t3Uyzr.js +1 -0
- package/dist/assets/ComputerLabView-YtnoT5Rb.js +1 -0
- package/dist/assets/CourseManagement-DOXyJ_j-.js +1 -0
- package/dist/assets/CourseWizardModal-Dbi6Caw2.js +3 -0
- package/dist/assets/CoursewareHubPanel-CyxDIJAF.js +1 -0
- package/dist/assets/Dashboard-2rLu_ZBy.js +8 -0
- package/dist/assets/ExportWeightModal-BrmAh6VX.js +1 -0
- package/dist/assets/GLTFLoader-CZJbo_y1.js +1 -0
- package/dist/assets/HelpTour-D_q1z_MI.js +1 -0
- package/dist/assets/HelpView-CVBrKDrd.js +204 -0
- package/dist/assets/ImportLessonsModal-PhHtX31R.js +1 -0
- package/dist/assets/ImportModal-DqjqNeH4.js +2 -0
- package/dist/assets/InteractiveCoursewareViewer-Vi6lLz7a.js +1 -0
- package/dist/assets/InteractiveWhiteboard-lTzeayX5.js +65 -0
- package/dist/assets/LazyCourseware-KIt0rGtW.js +2 -0
- package/dist/assets/LazyWhiteboard-CCN3pYcW.js +2 -0
- package/dist/assets/LessonEditorView-D_GVhHuM.js +1 -0
- package/dist/assets/LiveClassroomView-BRsZ6QEq.js +61 -0
- package/dist/assets/NotificationDetailModal-tY5rxYCN.js +1 -0
- package/dist/assets/OrbitControls-CQjN_uwS.js +1 -0
- package/dist/assets/PluginView-CedpAW6d.js +77 -0
- package/dist/assets/ProcessLogsModal-Cfr-T9Gd.js +1 -0
- package/dist/assets/QuizGeneratorModal-bUA002kP.js +1 -0
- package/dist/assets/StudentAssignmentView-BhAz6Hfk.js +1 -0
- package/dist/assets/StudentLessonView-DC1yX4kG.js +1 -0
- package/dist/assets/StudentView-PHKxIV9T.js +2 -0
- package/dist/assets/SystemResourceLibraryModal-DgXYe6_x.js +1 -0
- package/dist/assets/TeacherView-DscJtOJ9.js +2 -0
- package/dist/assets/TimetableView-D2ozoj_D.js +6 -0
- package/dist/assets/UTIF-FfCsrHhe.js +1 -0
- package/dist/assets/__vite-optional-peer-dep_ai_ooxml-ui-BIHI7g3E.js +1 -0
- package/dist/assets/browser-DEI0QxZC.js +1 -0
- package/dist/assets/html2canvas-pro.esm-Bo50djkB.js +12 -0
- package/dist/assets/index-2676X8YB.js +131 -0
- package/dist/assets/index-C6hlh8pw.css +1 -0
- package/dist/assets/{index.es-C5eWEO4o.js → index.es-DyEF0CZ9.js} +1 -1
- package/dist/assets/pluginParsers-e4PSm2Iy.js +1 -0
- package/dist/assets/react_pptx-react-viewer-BIHI7g3E.js +1 -0
- package/dist/assets/teaching-modes-client-BeVaDdJ-.js +1 -0
- package/dist/assets/three.module-iOYB3rD4.js +4228 -0
- package/dist/assets/timeline-duration-BgdJCSrW.js +1 -0
- package/dist/assets/{vendor-charts-qLbgF1eL.js → vendor-charts-SrpBsvM3.js} +2 -2
- package/dist/assets/{vendor-icons-BRmhY6fg.js → vendor-icons-CXrZ3R2V.js} +2 -2
- package/dist/assets/{vendor-konva-CEOq4dcl.js → vendor-konva-Dne0Z-WC.js} +1 -1
- package/dist/assets/{vendor-pdf-D7rGevI1.js → vendor-pdf-C1Vh2Aqq.js} +56 -56
- package/dist/assets/vendor-pptx-Bzn6whfK.js +11311 -0
- package/dist/assets/vendor-pptx-DIWdXF1L.css +1 -0
- package/dist/assets/{vendor-react-B0t7H3hh.js → vendor-react-Kv_JATwr.js} +1 -1
- package/dist/assets/vendor-utils-aM7aYvPP.js +1 -0
- package/dist/cli-migrator.cjs +310 -0
- package/dist/env-validation.cjs +351 -0
- package/dist/index.html +13 -10
- package/dist/plugin-net-preload.cjs +263 -0
- package/dist/server.cjs +51140 -27229
- package/migrations/000_initial_schema.sql +410 -0
- package/migrations/001_add_execution_mode.sql +6 -0
- package/migrations/002_add_client_session_expiry.sql +6 -0
- package/migrations/003_classroom_runtime.sql +33 -0
- package/migrations/004_courseware_score_config.sql +26 -0
- package/migrations/005_assignment_hub.sql +155 -0
- package/migrations/006_classroom_event_bus.sql +28 -0
- package/migrations/007_interactive_classroom.sql +119 -0
- package/migrations/008_teaching_modes.sql +36 -0
- package/migrations/009_classroom_peer_review.sql +159 -0
- package/migrations/010_class_groups.sql +33 -0
- package/migrations/011_classroom_feed.sql +34 -0
- package/migrations/012_auto_record_score.sql +48 -0
- package/migrations/013_score_source_strategy.sql +81 -0
- package/migrations/014_performance_indexes.sql +21 -0
- package/migrations/015_demo_data_registry.sql +26 -0
- package/migrations/016_preset_polls_and_passcode_expiry.sql +33 -0
- package/migrations/017_pacing_signals_segment.sql +6 -0
- package/migrations/018_processes_plugin_owner.sql +26 -0
- package/migrations/019_plugins_version.sql +61 -0
- package/migrations/020_upload_max_file_mb.sql +14 -0
- package/migrations/021_class_owner_and_password_gate.sql +11 -0
- package/migrations/022_plugin_public_routes.sql +14 -0
- package/migrations/023_encrypt_class_passcodes.sql +18 -0
- package/migrations/024_segment_gates.sql +37 -0
- package/migrations/025_assignment_lookup_indexes.sql +11 -0
- package/migrations/026_plugin_grants.sql +21 -0
- package/migrations/027_academic_year.sql +26 -0
- package/migrations/028_classroom_indexes.sql +14 -0
- package/migrations/029_clean_lesson_think_artifacts.sql +13 -0
- package/migrations/030_backfill_academic_year.sql +30 -0
- package/migrations/031_assessment_core.sql +158 -0
- package/migrations/032_progress_verification.sql +17 -0
- package/migrations/033_student_lock_mode.sql +9 -0
- package/migrations/034_plugin_orphan_data.sql +27 -0
- package/migrations/035_icebreaker_checkins.sql +26 -0
- package/migrations/036_student_read_notifications_created_at.sql +19 -0
- package/migrations/037_plugin_config_scopes.sql +40 -0
- package/migrations/038_assessment_ai_grading_suggestion.sql +10 -0
- package/migrations/039_question_bank_sharing_and_papers.sql +14 -0
- package/migrations/040_assignment_grade_history.sql +37 -0
- package/migrations/041_course_package_idempotency.sql +33 -0
- package/migrations/042_assignment_grade_resubmit_audit.sql +12 -0
- package/migrations/043_mark_sha256_passwords.sql +31 -0
- package/migrations/README.md +61 -0
- package/migrations/schema-golden.json +640 -0
- package/package.json +54 -28
- package/dist/assets/AdminDirectoryView-DY--WM5Z.js +0 -1
- package/dist/assets/BatchPickerModal-BpWu0Lil.js +0 -1
- package/dist/assets/ClassesView-KbHEqJto.js +0 -22
- package/dist/assets/ClassroomCountdownWidget-96WFRO9A.js +0 -2
- package/dist/assets/CloudDriveModal-DEQ1nkNk.js +0 -1
- package/dist/assets/ComputerLabView-1qWDNRQ2.js +0 -1
- package/dist/assets/CourseManagement-D3ZpxY0l.js +0 -1
- package/dist/assets/CourseWizardModal-Ck_-M8pk.js +0 -3
- package/dist/assets/CoursewareHubPanel-CaEizhxl.js +0 -1
- package/dist/assets/Dashboard-CYbpbofV.js +0 -8
- package/dist/assets/ExportWeightModal-DW2bu9Zz.js +0 -1
- package/dist/assets/HelpTour-CMJbbGne.js +0 -1
- package/dist/assets/HelpView-CtzdqhBq.js +0 -204
- package/dist/assets/ImportLessonsModal-jBuIK453.js +0 -1
- package/dist/assets/ImportModal-D7L-KNhZ.js +0 -1
- package/dist/assets/InteractiveCoursewareViewer-Bj7ahXMs.js +0 -1
- package/dist/assets/InteractiveWhiteboard-B7JcJvDu.js +0 -77
- package/dist/assets/LazyCourseware-CuiPxhDg.js +0 -2
- package/dist/assets/LazyWhiteboard-BJwCEZAU.js +0 -2
- package/dist/assets/LessonEditorView-DFrOp2qp.js +0 -1
- package/dist/assets/LiveClassroomView-BZ5nGee3.js +0 -59
- package/dist/assets/NotificationDetailModal-Baqnc5pU.js +0 -1
- package/dist/assets/PluginView-CCbIuZ24.js +0 -66
- package/dist/assets/ProcessLogsModal-DmFXg9mG.js +0 -1
- package/dist/assets/QuizGeneratorModal-BBEDssp7.js +0 -1
- package/dist/assets/StudentAssignmentView-DgIjUsXz.js +0 -1
- package/dist/assets/StudentLessonView-CBJbI5x6.js +0 -1
- package/dist/assets/StudentPreviewModal-Bh8OZs0t.js +0 -1
- package/dist/assets/StudentView--uGxc5TJ.js +0 -2
- package/dist/assets/SystemResourceLibraryModal-BVCclcqA.js +0 -1
- package/dist/assets/TeacherView-D4Zsc0eZ.js +0 -2
- package/dist/assets/TimetableView-BQG-rEb5.js +0 -6
- package/dist/assets/index-BKBCBKvy.js +0 -217
- package/dist/assets/index-CvGu7LSj.css +0 -1
- package/dist/assets/purify.es-CYR4BTuT.js +0 -3
- package/dist/assets/vendor-pptx-C5-U7ieS.js +0 -39
- package/dist/assets/vendor-utils-m0Urvtws.js +0 -1
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/StudentView-PHKxIV9T.js","assets/vendor-react-Kv_JATwr.js","assets/vendor-utils-aM7aYvPP.js","assets/vendor-icons-CXrZ3R2V.js","assets/vendor-motion-BFAPOs-b.js","assets/TeacherView-DscJtOJ9.js","assets/ImportModal-DqjqNeH4.js","assets/CourseWizardModal-Dbi6Caw2.js","assets/ImportLessonsModal-PhHtX31R.js","assets/QuizGeneratorModal-bUA002kP.js","assets/ProcessLogsModal-Cfr-T9Gd.js","assets/CloudDriveModal-D2t3Uyzr.js","assets/LazyCourseware-KIt0rGtW.js","assets/SystemResourceLibraryModal-DgXYe6_x.js","assets/BatchPickerModal-CbmjInp7.js","assets/ExportWeightModal-BrmAh6VX.js","assets/NotificationDetailModal-tY5rxYCN.js","assets/HelpTour-D_q1z_MI.js","assets/CoursewareHubPanel-CyxDIJAF.js","assets/ActivityWorkspaceWidget-5PzyxF6a.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as f,j as r,R as De,u as Fc,g as Bc,b as kp,d as Wi,h as qi,J as Ba,i as Ua,k as Cp}from"./vendor-react-Kv_JATwr.js";import{G as xr,S as Np,U as Uc,C as br,a as vs,L as Gi,A as yr,b as Ep,c as $t,K as Lo,d as zr,X as Oe,e as Vc,T as Mt,P as Hc,I as wr,E as Wc,R as Lr,f as Cn,g as qc,h as Tp,i as Ro,j as Pp,H as Ip,F as _o,M as Ap,k as Oo,l as Qi,m as Do,n as Gc,o as at,p as vr,q as Mo,r as Qc,s as zp,t as Lp,u as Ns,v as Kr,w as Jc,D as Ji,x as Rp,W as Ki,y as _p,z as yt,B as Rr,J as Yi,N as Op,O as Kc,Q as Va,V as Yc,Y as Dp,Z as Mp,_ as Zc,$ as Es,a0 as $p,a1 as Fp,a2 as $o,a3 as Bp,a4 as Fo,a5 as Up,a6 as Nn,a7 as Zi,a8 as Ha,a9 as ht,aa as Vp,ab as Xc,ac as _r,ad as ed,ae as Hp,af as vn,ag as Wp,ah as qp,ai as Gp,aj as Qp,ak as Bo,al as td,am as Jp,an as Ss,ao as Xi,ap as Kp,aq as Yp,ar as Yr,as as Xs,at as Zp,au as Xp,av as eg,aw as tg,ax as ng,ay as Uo,az as sg,aA as rg,aB as ig,aC as og,aD as ag,aE as lg,aF as cg}from"./vendor-icons-CXrZ3R2V.js";import{f as St,h as Ft,j as Vo}from"./vendor-utils-aM7aYvPP.js";import{_ as Je}from"./vendor-pdf-C1Vh2Aqq.js";import{i as Zr,g as dg,s as nd,a as Ho,b as sd,c as Wa,d as ug,e as hg,f as fg,h as mg,r as pg,j as gg,k as rd,l as xg,m as bg,n as yg,o as wg,S as vg,H as Sg,F as Bt,p as jg,q as kg,t as id,u as Sr,v as qa,w as ft,x as od,y as Cg,z as Ga,A as Ng,B as jr,C as eo,D as Qa,E as Eg,G as Tg,I as zt,J as Pg,K as Ig,L as Ag,M as Ja,N as zg,O as Lg,P as Ka,Q as Rg,R as _g,T as er,U as Og,V as Dg,W as ad,X as Mg,Y as $g}from"./vendor-motion-BFAPOs-b.js";import{R as Ya}from"./vendor-charts-SrpBsvM3.js";const Wo=f.createContext(null);function _s({value:e,children:t}){return r.jsx(Wo.Provider,{value:e,children:t})}function CN(){const e=f.useContext(Wo);if(!e)throw new Error("useAppData must be used within <AppDataProvider>");return e}function nn(){return f.useContext(Wo)}async function Fg(){const e=await fetch("/api/resources");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Bg(){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 Ug(){const e=await fetch("/api/auth/session");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function ld(){const e=await fetch("/api/site-settings");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Vg(){await fetch("/api/auth/logout",{method:"POST"})}const cd=f.createContext(null),to="openlearn_academic_year";function Hg(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get("academicYear");return t||null}function Wg(){if(typeof window>"u")return null;try{return window.localStorage.getItem(to)}catch{return null}}function qg(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(to,e):window.localStorage.removeItem(to)}catch{}}function Os({children:e}){const[t,n]=f.useState(()=>Hg()||Wg()||null),[s,i]=f.useState(null),[o,a]=f.useState(!0);f.useEffect(()=>{let u=!0;return(async()=>{try{const m=await ld();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 l=u=>{const m=u==="all"?null:u;if(n(m),qg(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())}},c=t==="all"||t===null?null:t,d=f.useMemo(()=>({academicYear:t,setAcademicYear:l,apiAcademicYear:c,currentAcademicYear:s,loading:o}),[t,c,s,o]);return r.jsx(cd.Provider,{value:d,children:e})}function Gg(){return f.useContext(cd)}function En(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.data)?e.data:[]}const Qg=De.memo(function({onLoginSuccess:t,lang:n}){const[s,i]=f.useState("teacher"),[o,a]=f.useState(null),[l,c]=f.useState(""),[d,u]=f.useState(""),[m,p]=f.useState(""),[h,x]=f.useState(!1),[g,b]=f.useState([]),[w,y]=f.useState(""),[S,C]=f.useState(""),[k,v]=f.useState(""),[N,O]=f.useState(""),[D,_]=f.useState(!1);f.useEffect(()=>{(async()=>{try{const $=await fetch("/api/students?pageSize=all");if($.ok){const I=En(await $.json());b(I),I.length>0&&y(I[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 I=await $.json();a(I)}}catch($){console.warn("Failed to fetch site settings for login branding:",$)}})()},[]);const T=async R=>{if(R.preventDefault(),!l.trim()||!d){p(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{p(""),x(!0);const $=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:l.trim(),password:d})});if($.ok){const I=await $.json();t(I.session)}else{const I=await $.json();p(I.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{p(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{x(!1)}},z=async R=>{R.preventDefault();const $=w||S.trim();if(!$){O(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!k.trim()){O(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{O(""),_(!0);const I=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:$,password:k.trim()})});if(I.ok){const B=await I.json();t(B.session)}else{const B=await I.json();O(B.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{O(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{_(!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(xr,{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")})]}),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(Np,{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(Uc,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?r.jsxs("form",{onSubmit:T,className:"space-y-4",children:[m&&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(br,{size:15,className:"shrink-0"}),r.jsx("span",{children:m})]}),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(vs,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),r.jsx("input",{type:"text",value:l,onChange:R=>c(R.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(Gi,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),r.jsx("input",{type:"password",value:d,onChange:R=>u(R.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:h,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:h?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),r.jsx(yr,{size:15})]})]}):r.jsxs("form",{onSubmit:z,className:"space-y-4",children:[N&&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(br,{size:15,className:"shrink-0"}),r.jsx("span",{children:N})]}),g.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(xr,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),r.jsx("select",{value:w,onChange:R=>{y(R.target.value),C("")},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:g.map(R=>r.jsxs("option",{value:R.id,children:[R.name," (",R.student_number||R.id,")"]},R.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(vs,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),r.jsx("input",{type:"text",value:S,onChange:R=>{C(R.target.value),y("")},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(Gi,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),r.jsx("input",{type:"password",required:!0,value:k,onChange:R=>v(R.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:D,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:D?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),r.jsx(yr,{size:15})]})]})]})]})});function Jg({lang:e,username:t,onDone:n,onLogout:s}){const[i,o]=f.useState(""),[a,l]=f.useState(""),[c,d]=f.useState(""),[u,m]=f.useState(null),[p,h]=f.useState(!1),x=e==="zh",g=()=>!i||!a||!c?x?"请填写完整":"All fields are required":a.length<8?x?"新密码至少 8 位":"Password must be at least 8 characters long":!/[a-zA-Z]/.test(a)||!/[0-9]/.test(a)?x?"新密码需同时包含字母和数字":"Password must contain both letters and numbers":a===i?x?"新密码不能与当前密码相同":"New password must differ from the current one":a!==c?x?"两次输入的新密码不一致":"Passwords do not match":null,b=async()=>{const y=g();if(y){m(y);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})}),C=await S.json().catch(()=>({}));if(!S.ok){m(C.error||(x?"修改失败,请重试":"Change failed, please retry"));return}n()}catch{m(x?"网络异常,请重试":"Network error, please retry")}finally{h(!1)}},w="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(Ep,{size:20,className:"text-amber-600"})}),r.jsx("h1",{className:"text-lg font-bold text-slate-800",children:x?"安全要求:修改默认密码":"Security: Change Default Password"})]}),r.jsx("p",{className:"text-xs text-slate-500 leading-relaxed mb-5",children:x?`当前账号${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:x?"当前密码":"Current password"}),r.jsx("input",{type:"password",value:i,onChange:y=>o(y.target.value),className:w,autoComplete:"current-password"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:x?"新密码(至少 8 位,含字母和数字)":"New password (8+ chars, letters & numbers)"}),r.jsx("input",{type:"password",value:a,onChange:y=>l(y.target.value),className:w,autoComplete:"new-password"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:x?"确认新密码":"Confirm new password"}),r.jsx("input",{type:"password",value:c,onChange:y=>d(y.target.value),className:w,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:b,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($t,{size:16,className:"animate-spin"}):r.jsx(Lo,{size:16}),x?"修改密码并继续":"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(zr,{size:13}),x?"退出登录":"Log out"]})]})})}async function Kg(){const e=await fetch("/api/lessons?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Yg(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 Zg(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 Xg(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 ex(e){const t=await fetch(`/api/lessons/${e}/whiteboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const tx=(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 Kg();if(n){const i=En(s);e(o=>({lessons:i,selectedLesson:o.selectedLesson??(nx(t())&&i.length>0?i[0].id:o.selectedLesson)}))}}catch(n){console.warn("Failed to fetch lessons",n)}}});function nx(e){return e.session?.role==="teacher"}async function sx(){const e=await fetch("/api/classes?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function rx(){const e=await fetch("/api/students?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function ix(e){const t=await fetch(`/api/classes/${e}/students`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const ox=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 sx();t&&e(s=>({classes:En(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch classes",t)}},loadStudents:async()=>{try{const{ok:t,data:n}=await rx();t&&e(s=>({students:En(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch students",t)}}}),ax=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})}),lx=e=>({session:null,sessionLoading:!0,dbConnected:!1,setSession:t=>e({session:t}),setSessionLoading:t=>e({sessionLoading:t}),setDbConnected:t=>e({dbConnected:t})}),cx=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})}),dx=e=>({studentDashboardData:null,notifications:[],setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t})});function dd(e){return"#/"+e}function ms(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}function ux(e){return window.location.pathname+window.location.search+dd(e)}function hx(e){const t=ux(e);window.open(t,"_blank","noopener,noreferrer")}function fx(){if(typeof window<"u"&&window.location?.hash){const e=ms(window.location.hash);if(e)return e}return"live_class"}const Ve=St(e=>({lang:"zh",activeRole:"teacher",teacherTab:fx(),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})})),mx=e=>Ft(Ve,e),px=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})}}),ve=St()((...e)=>({...tx(...e),...ox(...e),...ax(...e),...lx(...e),...cx(...e),...dx(...e),...px(...e)})),de=e=>Ft(ve,e);class gx{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 c=this.handlers.get(t.type);if(c&&c.size>0){const d=Array.from(c);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 l=(async()=>{let c=-1;const d=async u=>{if(u<=c)throw new Error("next() called multiple times in middleware");if(c=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 c;const d=new Promise((u,m)=>{c=setTimeout(()=>{m(new Error(`Action "${t.type}" timed out after ${n.timeoutMs}ms`))},n.timeoutMs)});l=Promise.race([l,d]).finally(()=>{clearTimeout(c)})}try{const c=await l;return this.notifySubscribers(i,c,void 0),c}catch(c){throw this.notifySubscribers(i,void 0,c),c}}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=ve.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 l=typeof a?.confirmed=="boolean"?a.confirmed:!1;i({confirmed:l})}};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{ve.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{ve.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(l){console.error("[HostActionDispatcher] Subscriber threw error:",l)}})};i(this.subscribers.get(t.action.type)),i(this.subscribers.get("*"))}}const ud=new gx,xx=({dispatcher:e})=>{const t=e||ud,[n,s]=f.useState([]);if(f.useEffect(()=>{const g=t;if(typeof g.subscribeModals=="function"){const b=g.subscribeModals(w=>{s([...w])});return()=>{b.dispose()}}},[t]),f.useEffect(()=>{if(n.length===0)return;const g=b=>{if(b.key==="Escape"){const w=n[n.length-1],y=t;y.resolveModal&&(w.type==="confirm"?y.resolveModal(w.id,{confirmed:!1}):y.resolveModal(w.id,{closed:!0}))}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n,t]),n.length===0)return null;const i=n[n.length-1],o=t,a=()=>{o.resolveModal?.(i.id,{confirmed:!0})},l=()=>{o.resolveModal?.(i.id,{confirmed:!1})},c=()=>{i.type==="confirm"?o.resolveModal?.(i.id,{confirmed:!1}):o.resolveModal?.(i.id,{closed:!0})},d=(g,b)=>{o.resolveModal?.(i.id,{actionId:g,closed:!!b})},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(Mt,{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(br,{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(Vc,{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"}},x=g=>{switch(g){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:g=>{g.target===g.currentTarget&&i.closableByBackdrop!==!1&&c()},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:g=>g.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:c,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(Oe,{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: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: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(g=>r.jsx("button",{onClick:()=>d(g.actionId,g.isClose),className:`px-4 py-2 text-xs font-bold rounded-xl transition-all cursor-pointer ${x(g.variant)}`,children:g.label},g.actionId)):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:"关闭"})})]})})},qo=f.createContext(null);function bx({children:e,host:t}){return r.jsxs(qo.Provider,{value:t,children:[e,r.jsx(xx,{dispatcher:t?.getDispatcher?.()})]})}function yx(){const e=f.useContext(qo);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}function hd(){return f.useContext(qo)}typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("storage",e=>{e.key===Go&&Ne.setState({dashboardVisibility:fd()})});const Go="openlearn:dashboardVisibility";function fd(){try{const e=localStorage.getItem(Go);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function Za(e){try{localStorage.setItem(Go,JSON.stringify([...e.entries()]))}catch{}}const Ne=Vo()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:fd(),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(c=>c.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 c=new Map(i.extensionPoints);return c.set(n,o.map(d=>d.id===s.id?s:d)),{extensionPoints:c}}const l=new Map(i.extensionPoints);return l.set(n,[...o,s]),{extensionPoints:l}}),unregisterExtensionPoint:(n,s,i)=>e(o=>{const a=o.extensionPoints.get(n);if(!a)return o;const l=a.find(u=>u.id===s);if(!l)return o;if(i&&l.pluginId!==i)return console.warn(`[PluginHost] Plugin "${i}" cannot unregister extension point "${n}/${s}" owned by "${l.pluginId}".`),o;const c=a.filter(u=>u.id!==s),d=new Map(o.extensionPoints);return c.length===0?d.delete(n):d.set(n,c),{extensionPoints:d}}),unregisterPluginExtensionPoints:n=>e(s=>{const i=new Map(s.extensionPoints);for(const[o,a]of i){const l=a.filter(c=>c.pluginId!==n);l.length===0?i.delete(o):i.set(o,l)}return{extensionPoints:i}}),unregisterPluginRuntimeExtensionPoints:n=>e(s=>{const i=new Map(s.extensionPoints);let o=!1;for(const[a,l]of i){const c=l.filter(d=>d.pluginId!==n||d.origin==="manifest");c.length!==l.length&&(o=!0,c.length===0?i.delete(a):i.set(a,c))}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),Za(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 Za(i),{dashboardVisibility:i}})}));function wx(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 vx(e){return!(!e||e.length>8||/^[a-zA-Z0-9_-]+$/.test(e))}function Sx(e){if(!e)return null;const t=wr;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 un({icon:e,size:t=18,className:n="shrink-0",fallback:s=Hc,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 l=e;return r.jsx(l,{size:t,className:n})}if(typeof e=="string"){const l=e.trim();if(!l)return r.jsx(s,{size:t,className:n});if(wx(l))return o?r.jsx(s,{size:t,className:n}):r.jsx("img",{src:l,alt:i,style:{width:`${t}px`,height:`${t}px`},className:`object-contain rounded-xs ${n}`,onError:()=>a(!0),loading:"lazy"});if(vx(l))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:l});const c=Sx(l);if(c)return r.jsx(c,{size:t,className:n})}return r.jsx(s,{size:t,className:n})}const Qo="zh",Ct={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 Jo(e){return e?e.toLowerCase().startsWith("en")?"en":"zh":Qo}const Tn=new Map;let Ko="zh";function jx(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=Jo(i);n[a]={...n[a]||{},...o}}const s=Tn.get(e)||{};Tn.set(e,{...s,...n,...Object.fromEntries(Object.entries(n).map(([i,o])=>[i,{...s[i]||{},...o}]))})}function kx(e){Tn.delete(e)}function Cx(){return Ko}function Jt(e,t){return!e||!t?e:e.replace(/\{([^{}]+)\}/g,(n,s)=>{const i=t[s.trim()];return i!=null?String(i):n})}function md(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 pd(e,t,n,s){let i,o,a=s||Ko;typeof t=="string"?(i=t,o=n):t&&typeof t=="object"&&(o=t,n&&typeof n=="object"&&"defaultValue"in n&&(i=n.defaultValue));const l=Jo(a),c=Qo;if(e.includes(":")){const d=e.indexOf(":"),u=e.substring(0,d),m=e.substring(d+1),p=Tn.get(u);if(p){if(p[l]&&p[l][m]!==void 0)return Jt(p[l][m],o);if(p[c]&&p[c][m]!==void 0)return Jt(p[c][m],o)}}if(Ct[l]?.[e]!==void 0)return Jt(Ct[l][e],o);if(Ct[c]?.[e]!==void 0)return Jt(Ct[c][e],o);for(const[,d]of Tn){if(d[l]?.[e]!==void 0)return Jt(d[l][e],o);if(d[c]?.[e]!==void 0)return Jt(d[c][e],o)}return i!=null?Jt(i,o):md(e)}function hn(e,t,n){if(!e)return"";const s=String(e).trim();if(/^%([\w.-]+)%$/.test(s)){const o=s.slice(1,-1),a=Jo(n||Ko),l=Qo;if(t){const c=Tn.get(t);if(c){if(c[a]?.[o]!==void 0)return c[a][o];if(c[l]?.[o]!==void 0)return c[l][o]}}return Ct[a]?.[o]!==void 0?Ct[a][o]:Ct[l]?.[o]!==void 0?Ct[l][o]:md(o)}return s.includes(":")&&!s.includes(" ")&&!s.includes("/")?pd(s,void 0,void 0,n):s}const no=Ct,gd=3,Nx=300*1e3,js=new Map;function Ex(e){const t=Date.now(),n=js.get(e);if(!n||t-n.lastAt>Nx)return js.set(e,{count:1,lastAt:t,blown:!1}),{shouldBreak:!1,count:1};n.count+=1,n.lastAt=t;const s=n.count>=gd;return s&&(n.blown=!0),{shouldBreak:s,count:n.count}}function Tx(e){js.delete(e)}function Xr(e){return js.get(e)?.blown??!1}function ei(e){js.delete(e)}function ti(e,t){Ne.getState().unregisterPluginRuntimeExtensionPoints(e),(t?.suspendPlugin?t.suspendPlugin(e):t?.deactivatePlugin(e))?.catch(i=>console.error(`[ExtensionBreaker] auto-deactivate "${e}" failed:`,i))}function ni(){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($t,{size:24,className:"text-gray-400 animate-spin"}),r.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}function fn({pluginId:e,message:t,lang:n="zh",compact:s=!1}){const i=hd(),[o,a]=De.useState(!1),l=n==="zh",c=De.useCallback(()=>{!i||o||(a(!0),i.retryPlugin(e).catch(()=>!1).finally(()=>a(!1)))},[i,e,o]),d=l?"插件加载失败":"Plugin failed to load",u=l?"重试":"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(Mt,{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:c,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($t,{size:13,className:"animate-spin","aria-hidden":"true"}):r.jsx(Lr,{size:13,"aria-hidden":"true"}),o?l?"重试中…":"Retrying…":u]})]})}class si 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}=Ex(n);if(console.error(`[ExtensionBreaker] Plugin "${n}" frontend crash #${i}/${gd}`+(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 ri({pluginId:e,children:t}){return De.useEffect(()=>{e&&Tx(e)}),r.jsx(r.Fragment,{children:t})}function ii({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 l=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return r.jsx("div",{ref:i,className:`w-full ${l}`})}const Ds=new WeakMap;function oi(e){const t=e?.component;if(typeof t!="function")return()=>null;const n=Ds.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=De.lazy(t);return Ds.set(t,s),s}if(typeof t=="function"&&!t.prototype?.isReactComponent){let s=!1;try{const i=t();i&&typeof i.then=="function"&&(s=!0)}catch{}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 i=De.lazy(t);return Ds.set(t,i),i}}return Ds.set(t,t),t}function ss(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 Me({slot:e,fallback:t,lang:n,route:s,slotProps:i,placement:o}){const a=De.useRef(new Set),l=hd(),c=Ne(g=>g.activePlugins),d=Ne(g=>g.dashboardVisibility),u=Ne(g=>g.pluginErrors),m=de(g=>g.selectedLesson),p=de(g=>g.liveClassSelectedClassId);if(!l)return t??null;let h=l.getExtensions(e);if(o&&(h=h.filter(g=>(g.placement??"after")===o)),h.length===0)return null;const x=(g,b,w)=>{const y=u.get(g.pluginId);if(y)return r.jsx(fn,{pluginId:g.pluginId,message:y});if(Xr(g.pluginId))return a.current.has(g.pluginId)||(a.current.add(g.pluginId),console.warn(`[ExtensionBreaker] Plugin "${g.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(fn,{pluginId:g.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"});const S=typeof g.component=="function",C=typeof g.render=="function";if(!S&&!C)return null;const k={...g.slotProps,...b,dispatcher:ss(l,g.pluginId,i?.dispatcher)};return r.jsx(si,{pluginId:g.pluginId,onBreakerTrip:v=>ti(v,l),fallback:r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:w}),children:r.jsx(f.Suspense,{fallback:r.jsx(ni,{}),children:r.jsx(ri,{pluginId:g.pluginId,children:S?De.createElement(oi(g),k):r.jsx(ii,{ext:g,route:g.route||s,slotProps:k,slot:e})})})},`${g.pluginId}/${g.id}`)};if(e==="class.tab"&&i?.renderType==="button"){const g=i?.lang||"zh";return r.jsx(r.Fragment,{children:h.map(b=>{const w=`plugin:${b.pluginId}/${b.id}`,y=i?.classActiveTab===w,S=b.title||b.label||b.id,C=hn(S,b.pluginId,g),k=c.find(N=>N.id===b.pluginId),v=b.icon||k?.icon;return r.jsxs("button",{onClick:N=>{N.stopPropagation(),i?.setClassActiveTab?.(w)},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 ${y?"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:C,children:[r.jsx(un,{icon:v,size:12,className:"shrink-0",alt:C}),r.jsx("span",{children:C})]},`${b.pluginId}/${b.id}`)})})}if(e==="class.tab"&&i?.renderType==="panel"){const g=i?.classActiveTab,b=h.find(w=>`plugin:${w.pluginId}/${w.id}`===g);return b?x(b,{classId:i?.classId,students:i?.students,lang:i?.lang},"扩展 Tab 加载失败"):null}if(e==="timetable.tab"&&i?.renderType==="button"){const g=i?.lang||"zh";return r.jsx(r.Fragment,{children:h.map(b=>{const w=`plugin:${b.pluginId}/${b.id}`,y=i?.timetableActiveTab===w,S=b.title||b.label||b.id,C=hn(S,b.pluginId,g),k=c.find(N=>N.id===b.pluginId),v=b.icon||k?.icon;return r.jsxs("button",{onClick:N=>{N.stopPropagation(),i?.setTimetableActiveTab?.(w)},className:`px-3 py-1.5 rounded-lg text-xs font-semibold tracking-wide transition-all cursor-pointer flex items-center gap-1.5 ${y?"bg-white text-indigo-700 shadow-sm font-bold":"text-gray-500 hover:text-gray-800"}`,title:C,children:[r.jsx(un,{icon:v,size:14,className:"shrink-0",alt:C}),r.jsx("span",{children:C})]},`${b.pluginId}/${b.id}`)})})}if(e==="timetable.tab"&&i?.renderType==="panel"){const g=i?.timetableActiveTab,b=h.find(w=>`plugin:${w.pluginId}/${w.id}`===g);return b?x(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 g=i?.lang||"zh";return r.jsx(r.Fragment,{children:h.map(b=>{const w=`plugin:${b.pluginId}/${b.id}`,y=i?.activeTab===w,S=b.title||b.label||b.id,C=hn(S,b.pluginId,g),k=c.find(N=>N.id===b.pluginId),v=b.icon||k?.icon;return r.jsxs("button",{onClick:N=>{N.stopPropagation(),i?.setActiveTab?.(w)},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 ${y?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,title:C,children:[r.jsx(un,{icon:v,size:14,className:"shrink-0",alt:C}),r.jsx("span",{className:"truncate",children:C})]},`${b.pluginId}/${b.id}`)})})}if(e==="ai_sidebar.tab"&&i?.renderType==="panel"){const g=i?.activeTab,b=h.find(w=>`plugin:${w.pluginId}/${w.id}`===g);return b?x(b,{activeTab:i?.activeTab,lang:i?.lang},"扩展面板加载失败"):null}if(e==="admin.tab"&&i?.renderType==="button"){const g=i?.lang||"zh";return r.jsx(r.Fragment,{children:h.map(b=>{const w=`plugin:${b.pluginId}/${b.id}`,y=i?.adminActiveTab===w,S=b.title||b.label||b.id,C=hn(S,b.pluginId,g),k=c.find(N=>N.id===b.pluginId),v=b.icon||k?.icon;return r.jsxs("button",{onClick:N=>{N.stopPropagation(),i?.setAdminActiveTab?.(w)},className:`px-3.5 py-1.5 text-xs font-bold rounded-lg flex items-center gap-1.5 transition-all cursor-pointer ${y?"bg-white text-indigo-700 shadow-xs":"text-gray-500 hover:text-gray-800"}`,title:C,children:[r.jsx(un,{icon:v,size:14,className:"shrink-0",alt:C}),r.jsx("span",{children:C})]},`${b.pluginId}/${b.id}`)})})}if(e==="admin.tab"&&i?.renderType==="panel"){const g=i?.adminActiveTab,b=h.find(w=>`plugin:${w.pluginId}/${w.id}`===g);return b?x(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 g=i?.lang||"zh";return r.jsx(r.Fragment,{children:h.map(b=>{const w=`plugin:${b.pluginId}/${b.id}`,y=i?.studentActiveTab===w,S=b.title||b.label||b.id,C=hn(S,b.pluginId,g),k=c.find(N=>N.id===b.pluginId),v=b.icon||k?.icon;return r.jsxs("button",{onClick:N=>{N.stopPropagation(),i?.setStudentActiveTab?.(w)},className:`px-3 py-1.5 text-xs font-bold rounded-lg flex items-center gap-1.5 transition-all cursor-pointer ${y?"bg-surface text-primary-theme shadow-xs border border-theme/60":"text-muted hover:text-main"}`,title:C,children:[r.jsx(un,{icon:v,size:14,className:"shrink-0",alt:C}),r.jsx("span",{children:C})]},`${b.pluginId}/${b.id}`)})})}if(e==="student.profile.tab"&&i?.renderType==="panel"){const g=i?.studentActiveTab,b=h.find(w=>`plugin:${w.pluginId}/${w.id}`===g);return b?x(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 g=[...h].sort((y,S)=>(y.position??100)-(S.position??100)),b=i?.lang??"zh",w=no[b];return r.jsx(r.Fragment,{children:g.map(y=>{const S=`${y.pluginId}/${y.id}`,C=i?.teacherTab===S,k=y.title||y.label||y.id,v=hn(k,y.pluginId,b),N=c.find(z=>z.id===y.pluginId),O=y.icon||N?.icon,D=u.has(y.pluginId),_=b==="zh"?`在新标签页打开"${v}"`:`Open "${v}" in a new tab`,T=S.replace(/[^a-zA-Z0-9_-]/g,"_");return r.jsxs("div",{className:`group relative flex items-center rounded-xl transition-all duration-150 ${C?"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"} ${D?"ring-1 ring-amber-400/70":""} ${i?.mainNavCollapsed?"justify-center":""}`,title:v,children:[r.jsxs("button",{type:"button",onClick:()=>i?.setTeacherTab?.(S),id:`nav_btn_${T}`,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 ${C?"font-bold":""} ${i?.mainNavCollapsed?"justify-center px-2":"pl-2.5 pr-8"}`,children:[r.jsx(un,{icon:O,size:18,className:"shrink-0",alt:v}),r.jsx("span",{className:i?.mainNavCollapsed?"hidden":"block truncate",children:v})]}),!i?.mainNavCollapsed&&r.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),hx(S)},id:`nav_btn_${T}_newtab`,"aria-label":_,title:w.openInNewTab,"data-testid":`nav_newtab_${T}`,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(Wc,{size:12,className:"shrink-0"})})]},`${y.pluginId}/${y.id}`)})})}if(e==="whiteboard.renderer"){const g=i?.elementType;if(!g)return null;const b=h.find(C=>{const k=C;return k.targetType===g||C.id===g||C.route===g||`${C.pluginId}/${C.id}`===g||k.slotProps?.elementType===g||k.slotProps?.targetType===g});if(!b)return null;const w=u.get(b.pluginId);if(w)return r.jsx(fn,{pluginId:b.pluginId,message:w,compact:!0});if(Xr(b.pluginId))return a.current.has(b.pluginId)||(a.current.add(b.pluginId),console.warn(`[ExtensionBreaker] Plugin "${b.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(fn,{pluginId:b.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh",compact:!0});const y=typeof b.component=="function",S=typeof b.render=="function";return!y&&!S?null:r.jsx(si,{pluginId:b.pluginId,onBreakerTrip:C=>ti(C,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(ni,{}),children:r.jsx(ri,{pluginId:b.pluginId,children:y?De.createElement(oi(b),{...b.slotProps,...i,dispatcher:ss(l,b.pluginId,i?.dispatcher)}):r.jsx(ii,{ext:b,route:b.route||s,slotProps:{...b.slotProps,...i,dispatcher:ss(l,b.pluginId,i?.dispatcher)},slot:e})})})},`${b.pluginId}/${b.id}`)}return r.jsx(r.Fragment,{children:h.map(g=>{const b=typeof g.component=="function",w=typeof g.render=="function";if(e==="teacher.dashboard.widget"&&d.get(g.pluginId)===!1||!b&&!w)return null;const y=u.get(g.pluginId);return y?r.jsx(fn,{pluginId:g.pluginId,message:y},`${g.pluginId}/${g.id}`):Xr(g.pluginId)?(a.current.has(g.pluginId)||(a.current.add(g.pluginId),console.warn(`[ExtensionBreaker] Plugin "${g.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(fn,{pluginId:g.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"},`${g.pluginId}/${g.id}`)):r.jsx(si,{pluginId:g.pluginId,onBreakerTrip:S=>ti(S,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(ni,{}),children:r.jsx(ri,{pluginId:g.pluginId,children:b?De.createElement(oi(g),{route:g.route||s,lessonId:m,classId:p,dispatcher:ss(l,g.pluginId,i?.dispatcher),...g.slotProps,...i}):r.jsx(ii,{ext:g,route:g.route||s,slotProps:{lessonId:m,classId:p,dispatcher:ss(l,g.pluginId,i?.dispatcher),...g.slotProps,...i},slot:e})})})},`${g.pluginId}/${g.id}`)})})}const Px=({state:e,onToggleAnonymous:t,onOpenRubricModal:n,onToggleVoiceDanmaku:s,onAdvanceStage:i,onAddMinute:o,onTogglePauseTimer:a,isFullscreen:l,onToggleFullscreen:c,onClose:d})=>{const u=p=>{const h=Math.floor(Math.max(0,p)/60),x=Math.max(0,p)%60;return`${String(h).padStart(2,"0")}:${String(x).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(Cn,{size:13,className:"text-[#908fa0]"}),r.jsx("span",{children:"收卷归档"}),r.jsx(Cn,{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(qc,{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(Tp,{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(Ro,{size:12,className:"text-[#4edea3]"}):r.jsx(Pp,{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(Ip,{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(_o,{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(Ap,{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(Oo,{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(Me,{slot:"peer_review.action"}),c&&r.jsx("button",{type:"button",onClick:c,className:"p-1.5 rounded-xl text-[#c7c4d7] hover:text-white hover:bg-[#222a3d] transition-colors ml-1",title:l?"退出全屏":"全屏展示",children:l?r.jsx(Qi,{size:16}):r.jsx(Do,{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(Oe,{size:16})})]})]})},Ix=({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(Gc,{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),l=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(at,{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(yr,{size:12,className:"text-[#908fa0] shrink-0"}),r.jsxs("span",{className:"text-[#c0c1ff] font-medium truncate",children:[l," · ",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((c,d)=>r.jsx(vr,{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(Mo,{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(Me,{slot:"peer_review.badge"})]})]})},Ax=["http:","https:"],zx=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,Lx=/[\u0000-\u001f\u007f]/;function tr(e){if(typeof e!="string")return null;const t=e.trim();if(!t||Lx.test(t)||t.startsWith("//")||t.startsWith("\\\\"))return null;if(zx.exec(t)){const s=t.slice(0,t.indexOf(":")+1).toLowerCase();if(!Ax.includes(s))return null}return t}const Rx=({workA:e,workB:t,annotations:n,isAnonymous:s=!1,onFullscreenCanvas:i,onSyncSandboxToClass:o,onAddAnnotation:a})=>{const[l,c]=f.useState("visual"),[d,u]=f.useState(!1),[m,p]=f.useState(""),[h,x]=f.useState(null),g=(y,S)=>!S||y.length<=1?y:`${y[0]}**`,b=y=>{y.preventDefault(),m.trim()&&(a?.(m.trim()),p(""),u(!1))},w=y=>{const S=y.files?.filter(k=>k.isImage||/\.(jpe?g|png|gif|webp|svg)$/i.test(k.name||k.url||""))||[],C=y.files?.filter(k=>!S.includes(k))||[];return r.jsxs("div",{"data-testid":`work-preview-${y.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(Me,{slot:"peer_review.work.preview",slotProps:{work:y,slot:y.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,v)=>r.jsxs("div",{onClick:()=>k.url&&x(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(Ns,{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})]},v)),C.length>0&&r.jsx("div",{className:"h-full flex flex-col justify-center gap-1 shrink-0 pl-1",children:C.map((k,v)=>{const N=tr(k.url);return N?r.jsxs("a",{href:N,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(Kr,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:k.name}),r.jsx(Wc,{size:11,className:"opacity-70"})]},v):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(Kr,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:k.name})]},v)})})]}):C.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(Jc,{size:13,className:"text-[#8083ff]"}),r.jsxs("span",{children:["提交附件 (",C.length," 个文件)"]})]}),C.map((k,v)=>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(Kr,{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&&tr(k.url)&&r.jsxs("a",{href:tr(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(Ji,{size:12}),r.jsx("span",{children:"下载"})]})]},v))]}):y.codeLines&&y.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:y.codeLines.map((k,v)=>r.jsx("div",{className:k.isHighlight?"text-[#4edea3]":"",style:{paddingLeft:`${(k.indent||0)*12}px`},children:k.text},v))}):y.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:y.textContent}):r.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 px-6 text-center",children:[r.jsx(Rp,{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:"(原始作答流水为空或为纯数值型)"})]})]}),y.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:["真实作答 · ",y.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(Qc,{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:["标杆创新解法 (",g(e.studentName,s),") ⟷ 经典逆风翻盘解法 (",g(t.studentName,s),")"]})]})]}),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(Do,{size:16})})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[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:[g(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(vr,{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((y,S)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${y.colorClass}`,children:y.label},S))}),w(e),e.codeLines?.some(y=>y.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(y=>y.comment).map((y,S)=>r.jsx("div",{className:y.isHighlight?"bg-[#8083ff]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#908fa0]",children:y.comment})},S))]}):null]}),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:[g(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(vr,{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((y,S)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${y.colorClass}`,children:y.label},S))}),w(t),t.codeLines?.some(y=>y.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(y=>y.comment).map((y,S)=>r.jsx("div",{className:y.isSuccess?"bg-[#00a572]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#4edea3] text-[10px]",children:y.comment})},S))]}):null]})]}),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(Lp,{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:b,className:"flex gap-2",children:[r.jsx("input",{type:"text",value:m,onChange:y=>p(y.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(y=>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:y.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 ${y.authorType==="teacher"?"bg-[#8083ff] text-white":"bg-[#00a572] text-white"}`,children:y.authorRole}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:g(y.authorName,s)})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0]",children:y.timeAgo})]}),r.jsx("p",{className:"text-xs text-[#dae2fd] pl-2 leading-relaxed",children:y.content})]},y.id))})]}),r.jsx(Me,{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:()=>x(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:y=>y.stopPropagation(),children:[r.jsx("button",{type:"button",onClick:()=>x(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(Oe,{size:18})}),r.jsx("img",{src:h,alt:"Work preview",className:"max-w-full max-h-[85vh] object-contain rounded-lg"})]})})]})},_x=({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(Me,{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(Ki,{size:13,className:"text-[#4edea3]"}),typeof i=="number"?`${i}台学生端已同步点赞动画`:"学生端同步状态未知"]})]})]}),Ox=({podiumStudents:e,isAnonymous:t=!1,onAwardPeerReviewPoints:n,onArchiveTopWorks:s,onCallStudentMic:i,onInviteScreenShare:o,onAdvanceToStage3:a})=>{const l=(c,d)=>!d||c.length<=1?c:`${c[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(_p,{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(c=>r.jsxs("div",{className:`p-3 rounded-lg border transition-all ${c.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 ${c.rankBadgeClass}`,children:c.rank}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:l(c.name,t)})]}),r.jsxs("span",{className:"font-mono text-xs font-semibold text-[#ffb95f]",children:[c.votes," 票推荐"]})]}),r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsx("span",{className:"text-[#c7c4d7] truncate max-w-[140px]",children:c.workTitle}),r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${c.tagBadgeClass}`,children:c.honorTitle})]})]},c.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(Oo,{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(yt,{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(Rr,{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 c=e[0]?.name,d=e[1]?.name??c;return r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",disabled:!c,onClick:()=>c&&i(c),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(Yi,{size:14,className:"text-[#c0c1ff]"}),r.jsx("span",{children:c?`连麦作者 ${l(c,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(qc,{size:14,className:"text-[#4edea3]"}),r.jsx("span",{children:d?`邀请 ${l(d,t)} 投屏分享`:"暂无提名,无法投屏"})]}),r.jsx("span",{className:"text-[#908fa0] text-[10px] font-mono",children:"邀请"})]})]})})()}),r.jsx(Me,{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(yr,{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"})})]})]})]})},Dx=({isVisible:e,danmakuList:t,onSendDanmaku:n,isAnonymous:s=!1})=>{const[i,o]=f.useState(""),[a,l]=f.useState(!1);if(!e)return null;const c=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(Yi,{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:c,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(Op,{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(Yi,{size:13})}),r.jsx("button",{type:"button",onClick:()=>l(!1),className:"px-2 text-xs text-[#908fa0] hover:text-white",children:"收起"})]}):r.jsxs("button",{type:"button",onClick:()=>l(!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(Kc,{size:13,className:"text-[#c0c1ff]"}),r.jsx("span",{children:"发弹幕"})]})})]})},Mx=({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(_o,{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(Oe,{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(Me,{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 $x(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 Fx=({isOpen:e,onClose:t,onAdvanceToStage3:n,lessonTitle:s="",addToast:i,workA:o,workB:a,showcaseWorks:l=[],onSelectSpotlightWork:c,reviewProgress:d,countdownSeconds:u,onAutoAssign:m,autoAssigning:p=!1,matchingItems:h,badges:x,annotations:g,rubricDimensions:b,reactions:w,podiumStudents:y,danmaku:S,syncedStudentsCount:C,teacherName:k,stageLabel:v})=>{const[N,O]=f.useState({stage:v||"",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}),[D,_]=f.useState(!1),[T,z]=f.useState(!1),[R,$]=f.useState(!1),[I,B]=f.useState(h??[]),[H,A]=f.useState(x??[]),[U,j]=f.useState(o??null),[V,G]=f.useState(a??null),[E,W]=f.useState(g??[]),[Y,K]=f.useState(b??[]),[ne,fe]=f.useState(w??[]),[je,X]=f.useState(y??[]),[me,ke]=f.useState(S??[]);f.useEffect(()=>{o!==void 0&&j(o)},[o]),f.useEffect(()=>{a!==void 0&&G(a)},[a]),f.useEffect(()=>{h&&B(h)},[h]),f.useEffect(()=>{x&&A(x)},[x]),f.useEffect(()=>{g&&W(g)},[g]),f.useEffect(()=>{b&&K(b)},[b]),f.useEffect(()=>{w&&fe(w)},[w]),f.useEffect(()=>{y&&X(y)},[y]),f.useEffect(()=>{S&&ke(S)},[S]),f.useEffect(()=>{if(!e||N.isPaused)return;const P=setInterval(()=>{O(L=>L.timeRemainingSeconds<=1?{...L,timeRemainingSeconds:0,isPaused:!0}:{...L,timeRemainingSeconds:L.timeRemainingSeconds-1})},1e3);return()=>clearInterval(P)},[e,N.isPaused]);const Se=f.useCallback(P=>{e&&(P.key==="Enter"?(P.preventDefault(),re()):P.key==="Escape"?(P.preventDefault(),t()):P.code==="Space"&&P.target===document.body&&(P.preventDefault(),ee()))},[e,t]);if(f.useEffect(()=>(window.addEventListener("keydown",Se),()=>window.removeEventListener("keydown",Se)),[Se]),!e)return null;const M=()=>{O(P=>({...P,isAnonymous:!P.isAnonymous})),i?.("互评模式已切换",N.isAnonymous?"已恢复显示真实学生姓名":"已开启双盲匿名评价模式","info")},Z=()=>{O(P=>({...P,timeRemainingSeconds:P.timeRemainingSeconds+60,totalTimeSeconds:P.totalTimeSeconds+60})),i?.("互评加时","倒计时已增加 1 分钟","success")},ee=()=>{O(P=>({...P,isPaused:!P.isPaused}))},te=()=>{document.fullscreenElement?document.exitFullscreen&&(document.exitFullscreen().catch(()=>{}),_(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),_(!0))},ce=P=>{fe(L=>L.map(F=>F.id===P?{...F,count:F.count+1}:F)),O(L=>({...L,totalLikes:L.totalLikes+1}))},oe=P=>{const L={id:`ann-${Date.now()}`,authorType:"teacher",authorRole:"主讲教师",authorName:k||"教师",timeAgo:"刚刚",content:P,borderColor:"#8083ff"};W(F=>[L,...F]),i?.("批注已挂载","协同板书批注已同步至大屏","success")},xe=(P,L="text")=>{const F={id:`d-${Date.now()}`,sender:k||"教师",text:P,type:L,voiceDuration:void 0,color:"text-[#4edea3]"};ke(q=>[...q,F])},ie=()=>{i?.("功能尚未接入","批量积分发放通道建设中,本次未写入任何积分。","warning")},Pe=()=>{i?.("功能尚未接入","作品归档通道建设中,本次未做任何存储。","warning")},ze=P=>{i?.("功能尚未接入",`向 ${P} 发起连麦的信令通道建设中。`,"warning")},ue=P=>{i?.("功能尚未接入",`向 ${P} 的投屏邀请通道建设中。`,"warning")},re=()=>{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(Px,{state:N,onToggleAnonymous:M,onOpenRubricModal:()=>z(!0),onToggleVoiceDanmaku:()=>O(P=>({...P,showDanmaku:!P.showDanmaku})),onAdvanceStage:re,onAddMinute:Z,onTogglePauseTimer:ee,isFullscreen:D,onToggleFullscreen:te,onClose:t}),r.jsxs("main",{className:"relative flex-1 overflow-y-auto w-full px-6 py-5",children:[!U&&!V&&l.length===0&&I.length===0&&je.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?"分配中…":"一键分配互评"})]}),l&&l.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:["本节提交作品池(跨来源已聚合 ",l.length," 份作品)"]}),r.jsx("span",{className:"text-[10px] text-[#908fa0]",children:"包含课件作答、课堂作业与插件提交,点击可设为大屏焦点 A / B"})]}),r.jsx("button",{type:"button",onClick:()=>$(!R),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:R?"收起作品池 ▲":`展开作品池 (${l.length}) ▼`})]}),R&&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:l.map(P=>{const L=U?.id===P.workId,F=V?.id===P.workId,q=N.isAnonymous&&P.studentName.length>1?`${P.studentName[0]}**`:P.studentName;return r.jsxs("div",{className:`p-2.5 rounded-lg border text-xs flex flex-col gap-1.5 transition-all ${L?"bg-[#8083ff]/15 border-[#8083ff]":F?"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:q}),r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-medium border ${P.source==="plugin"?"bg-[#8083ff]/20 text-[#c0c1ff] border-[#8083ff]/30":P.source==="assignment"?"bg-[#00a572]/20 text-[#4edea3] border-[#00a572]/30":"bg-[#ca8100]/20 text-[#ffb95f] border-[#ca8100]/30"}`,children:P.sourceLabel})]}),r.jsx("div",{className:"text-[11px] text-[#908fa0] truncate",title:P.title,children:P.title}),P.files&&P.files.length>0&&r.jsxs("div",{className:"text-[10px] text-[#8083ff] truncate",children:["📎 ",P.files.length," 个附件 (",P.files.map(J=>J.name).join(", "),")"]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-auto pt-1",children:[r.jsx("button",{type:"button",onClick:()=>c?.("A",P.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${L?"bg-[#8083ff] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#8083ff]/40 text-[#dae2fd]"}`,children:L?"焦点 A ★":"设为焦点 A"}),r.jsx("button",{type:"button",onClick:()=>c?.("B",P.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${F?"bg-[#00a572] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#00a572]/40 text-[#dae2fd]"}`,children:F?"焦点 B ★":"设为焦点 B"})]})]},P.workId)})})]}),r.jsx(Dx,{isVisible:N.showDanmaku,danmakuList:me,onSendDanmaku:xe,isAnonymous:N.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(Ix,{matchingItems:I,badges:H,isAnonymous:N.isAnonymous,onSelectMatchingItem:P=>{i?.(`查看互评明细 ${P.code}`,`${P.reviewerName} 正在审阅 ${P.targetStudentName} 的作业`,"info")}})}),r.jsxs("div",{className:"col-span-12 lg:col-span-6 flex flex-col gap-4",children:[!U&&!V&&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||V?r.jsx(Rx,{workA:U,workB:V,annotations:E,isAnonymous:N.isAnonymous,onFullscreenCanvas:te,onSyncSandboxToClass:()=>{i?.("沙箱广播已生效",`对比范本已同步至全班 ${N.totalStudents||0} 台学生机控制台`,"success")},onAddAnnotation:oe}):null,r.jsx(_x,{dimensions:Y,averagePercentage:$x(Y),reactions:ne,onReactionClick:ce,syncedStudentsCount:C})]}),r.jsx("div",{className:"col-span-12 lg:col-span-3",children:r.jsx(Ox,{podiumStudents:je,isAnonymous:N.isAnonymous,onAwardPeerReviewPoints:ie,onArchiveTopWorks:Pe,onCallStudentMic:ze,onInviteScreenShare:ue,onAdvanceToStage3:re})})]})]}),r.jsx(Mx,{isOpen:T,onClose:()=>z(!1)})]})};let Pn=null;const so=new Set;function xd(e){if(Pn=e,!!e)for(const t of so)try{t(e)}catch(n){console.error("[socket-service] socket-ready listener error:",n)}}function Yo(e){if(so.add(e),Pn)try{e(Pn)}catch(t){console.error("[socket-service] socket listener error:",t)}return()=>{so.delete(e)}}function Bx(){if(!Pn)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return Pn}function lt(){return Pn}class Ux{constructor(t){this.socket=t,xd(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 nr={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},Vx=["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"],Hx=4e3;function Wx(e,t={}){const{enabled:n=!0,reconcileMs:s=Hx}=t,[i,o]=f.useState(nr),[a,l]=f.useState("polling"),[c,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 x=await fetch(`/api/classroom/stage/${encodeURIComponent(e)}/data`);if(!x.ok)throw new Error(`stage data HTTP ${x.status}`);const g=await x.json();if(!m.current||h!==u.current)return;o({...nr,...g,pacing:{...nr.pacing,...g.pacing||{}}}),d(Date.now()),l(b=>b==="reconnecting"?"live":b==="error"?"polling":b)}catch(x){if(!m.current)return;l(g=>g==="live"?"reconnecting":g),console.warn("[StageDisplay] sync failed:",x)}},[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 x=()=>{h||(h=setTimeout(()=>{h=null,p()},120))};let g=null;const b=Yo(w=>{g?.(),w.emit("join-room",e);const y=Vx.map(v=>{const N=O=>{const D=O?.lessonId;D&&D!==e||x()};return w.on(v,N),[v,N]}),S=()=>{l("live"),p()},C=()=>l("reconnecting"),k=()=>l("reconnecting");w.on("connect",S),w.on("disconnect",C),w.on("connect_error",k),w.connected&&l("live"),g=()=>{for(const[v,N]of y)w.off(v,N);w.off("connect",S),w.off("disconnect",C),w.off("connect_error",k)}});return()=>{b(),g?.(),h&&clearTimeout(h)}},[n,e,p]),{data:i,health:a,lastSyncedAt:c,refresh:p}}const qx={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 Zo(e,t="zh"){const n=qx[e];return n?t==="zh"?n.zh:n.en:e}let Xa=0;function Rt(e){return Xa+=1,`${e}-${Date.now().toString(36)}-${Xa}`}function Gx(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=Zo(t.stage,s),x=t.stage==="ARCHIVED_REPORT",g=t.stage==="WRAP_UP_EXIT_TICKET";let b;g?b=o?"请提醒学生在设备上完成 60 秒结课通票":"Remind students to complete the 60s exit ticket":x&&(b=o?"本课节已归档,大屏将展示学情简报":"Lesson archived; the stage will show the learning report");let w="info",y="🎓";g?(w="accent",y="🎫"):x&&(w="warning",y="📦"),a.push({id:Rt("stage"),tone:w,icon:y,title:o?`课堂环节已切换:${h}`:`Stage changed: ${h}`,detail:b,dedupeKey:`stage:${t.stage}`})}const l=e.activePoll?.id??null,c=t.activePoll?.id??null;if(c&&c!==l)a.push({id:Rt("poll-start"),tone:"accent",icon:"⚡",title:o?"课堂极速投票已开始":"Quick poll started",detail:t.activePoll?.title?String(t.activePoll.title):void 0,dedupeKey:`poll-start:${c}`});else if(l&&!c){const h=e.activePoll?.totalVotes??0;a.push({id:Rt("poll-end"),tone:"info",icon:"📊",title:o?"课堂投票已结束":"Quick poll closed",detail:o?`本轮共 ${h} 人作答`:`${h} responded in this round`,dedupeKey:`poll-end:${l}`})}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:Rt("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,x=t.activeBuzzer?.responseTimeMs;a.push({id:Rt("buzz-winner"),tone:"success",icon:"🏆",title:o?"抢答已产生赢家":"Buzz-in winner decided",detail:h?o?`${h}${x?` · 响应用时 ${x} 毫秒`:""}`:`${h}${x?` · ${x} ms`:""}`:void 0,dedupeKey:`buzz-winner:${u}`})}else u&&u===d&&p==="READY"&&m==="LOCKED"&&a.push({id:Rt("buzz-reset"),tone:"info",icon:"♻️",title:o?"抢答已重置,可以开始新一轮":"Buzzer reset — ready for a new round",dedupeKey:`buzz-reset:${u}`});return a}function Qx(e,t,n="zh"){const s=n==="zh";return e===t?null:e==="reconnecting"?{id:Rt("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:Rt("conn"),tone:"success",icon:"✅",title:s?"实时连接已恢复":"Live connection restored",dedupeKey:"conn:live"}:null}const el={info:{ring:"border-sky-500/50 bg-sky-500/10 text-sky-200",icon:Yc},success:{ring:"border-emerald-500/50 bg-emerald-500/10 text-emerald-200",icon:at},warning:{ring:"border-amber-500/50 bg-amber-500/10 text-amber-200",icon:Mt},accent:{ring:"border-indigo-500/50 bg-indigo-500/10 text-indigo-200",icon:yt}},Jx=6e3,tl=8e3;function Kx({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 l=setTimeout(()=>{i.current.delete(a.id),t(a.id)},Jx);i.current.set(a.id,l)}const o=new Set(s.map(a=>a.id));for(const[a,l]of i.current)o.has(a)||(clearTimeout(l),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=el[o.tone]??el.info,l=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(l,{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(Oe,{size:14})})]},o.id)})})}function Yx(e="zh"){const[t,n]=f.useState([]),s=f.useRef(new Map),i=f.useCallback(l=>{if(l.length===0)return;const c=Date.now();n(d=>{let u=d;for(const m of l){const p=s.current.get(m.dedupeKey);if(!(p&&c-p<tl)){s.current.set(m.dedupeKey,c);for(const[h,x]of s.current)c-x>tl&&s.current.delete(h);u=[...u,m]}}return u.length>40?u.slice(u.length-40):u})},[]),o=f.useCallback(l=>{n(c=>c.filter(d=>d.id!==l))},[]),a=f.useCallback(()=>n([]),[]);return{notices:t,push:i,dismiss:o,clear:a}}function Zx({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:Ki},reconnecting:{label:s?"重连中":"Reconnecting",cls:"text-amber-300 border-amber-500/40 bg-amber-500/10",dot:"bg-amber-400 animate-ping",Icon:Va},polling:{label:s?"轮询同步":"Polling",cls:"text-sky-300 border-sky-500/40 bg-sky-500/10",dot:"bg-sky-400",Icon:Ki},error:{label:s?"连接异常":"Error",cls:"text-rose-300 border-rose-500/40 bg-rose-500/10",dot:"bg-rose-400",Icon:Va}}[e],a=o.Icon,l=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?`最近同步:${l}`:`Last sync: ${l}`,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:l})]})}function Xx(){if(typeof document>"u")return!1;const e=document.documentElement;return!!(e.requestFullscreen||e.webkitRequestFullscreen)}function Ms(){return typeof document>"u"?!1:!!(document.fullscreenElement||document.webkitFullscreenElement)}function eb(){const[e,t]=f.useState(!1),[n,s]=f.useState(!1),i=f.useRef(!1);f.useEffect(()=>{if(typeof document>"u")return;const c=()=>{const d=Ms();s(d),d||(i.current=!1,t(!1))};return document.addEventListener("fullscreenchange",c),document.addEventListener("webkitfullscreenchange",c),()=>{document.removeEventListener("fullscreenchange",c),document.removeEventListener("webkitfullscreenchange",c)}},[]),f.useEffect(()=>{if(typeof window>"u")return;const c=d=>{d.key==="Escape"&&(Ms()||i.current&&(i.current=!1,t(!1)))};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[]);const o=f.useCallback(async()=>{if(t(!0),!Xx()){i.current=!0;return}try{const c=document.documentElement;await(c.requestFullscreen?.()??c.webkitRequestFullscreen?.()),s(!0)}catch(c){i.current=!0,console.warn("[ViewportFullscreen] native fullscreen rejected, falling back to viewport fill:",c)}},[]),a=f.useCallback(async()=>{if(i.current=!1,t(!1),s(!1),Ms())try{await document.exitFullscreen?.()}catch(c){console.warn("[ViewportFullscreen] exit failed:",c)}},[]),l=f.useCallback(()=>{Ms()||i.current?a():o()},[o,a]);return{isFullscreen:e,nativeActive:n,toggle:l,exit:a}}function Nt(e){return typeof e=="number"&&Number.isFinite(e)?String(e):"—"}function ps(e,t){return!t||t<=0?"—":`${Math.round(e/t*100)}%`}function tb({attendance:e,zh:t=!0}){const n=e?.onlineInClass??0,s=e?.expected??0,i=e?.attended??0,o=ps(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(Uc,{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"," ",Nt(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:Nt(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:Nt(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:Nt(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:ps(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:ps(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 nb({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(Dp,{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:Nt(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:Nt(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:[Nt(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:ps(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:ps(i,n)}})})]}):r.jsxs("p",{className:"text-[11px] text-slate-400 leading-relaxed flex items-center gap-2",children:[r.jsx(_o,{size:14,className:"shrink-0"}),t?"还没有学生打开互动课件。展示口径为平台累计(含往期课节),作答数据将在学生开始操作后实时出现。":"No courseware activity yet."]})]})}const sb={quiz_answered:"✅",checkin:"🙋",achievement:"🏅",assignment_submitted:"📄",assignment_graded:"🖊️",progress:"📈",courseware_submitted:"🖥️",answer:"💡",success:"🎉",info:"ℹ️"};function rb({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(Mo,{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:sb[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(Zc,{size:14,className:"shrink-0"}),t?"课堂动态会在学生答题、签到、提交课件时实时出现在这里。":"Live events will appear here."]})]})}function ib({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(Mp,{size:13,className:"text-indigo-400"}),n?"结课通票已提交":"Exit tickets submitted"]}),r.jsxs("span",{className:"font-mono font-bold text-white",children:[Nt(s),i>0?` / ${Nt(i)}`:""]})]})}function ob({lessonId:e,lessonTitle:t="互动课堂",data:n,lang:s="zh",health:i,lastSyncedAt:o,showCloseButton:a=!0,onClose:l,peerReview:c,syncedStudentsCount:d,peerReviewOpen:u,onOpenPeerReview:m,onClosePeerReview:p}){const{isFullscreen:h,toggle:x}=eb(),[g,b]=f.useState(""),[w,y]=f.useState(!1),S=u??w,C=N=>{u===void 0&&y(N),N?m?.():p?.()};f.useEffect(()=>{const N=()=>{b(new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}))};N();const O=setInterval(N,1e3);return()=>clearInterval(O)},[]);const k=n.pacing??nr.pacing,v=(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:Zo(n.stage,s)})]}),r.jsxs("div",{className:"flex items-center gap-6",children:[i&&r.jsx(Zx,{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(Es,{size:20,className:"text-blue-400"}),r.jsx("span",{children:g})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Me,{slot:"stage.display.action",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s,onToggleFullscreen:x,onOpenPeerReview:()=>C(!0)}}),r.jsxs("button",{id:"stage-peer-review-toggle",type:"button",onClick:()=>C(!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(Qc,{size:15}),r.jsx("span",{children:"作业互评赏析"})]}),r.jsx("button",{id:"stage-fullscreen-toggle",onClick:x,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($p,{size:20}):r.jsx(Fp,{size:20})}),a&&r.jsx("button",{id:"stage-close-button",onClick:l,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(Oe,{size:20})})]})]})]}),r.jsx("div",{className:"max-h-12 overflow-hidden shrink-0",children:r.jsx(Me,{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(Zc,{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(yt,{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(N=>{const O=n.activePoll.distribution?.[N]||0,D=Math.round(O/(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:N}),r.jsxs("span",{className:"font-semibold text-slate-200 text-lg",children:["选项 ",N]})]}),r.jsxs("span",{className:"font-mono font-bold text-xl text-blue-400",children:[D,"% (",O,")"]})]}),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:`${D}%`}})})]},N)})})]}),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($o,{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(Oo,{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(Bp,{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(Fo,{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(Me,{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(tb,{attendance:n.attendance,zh:s==="zh"}),r.jsx(nb,{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(ib,{submitted:n.exitTicketSubmitted,expected:n.attendance?.expected,zh:s==="zh"})}),r.jsx(rb,{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(Up,{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:[v," ",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:`${v>0?(k.CLEAR||0)/v*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:`${v>0?(k.CONFUSED||0)/v*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:`${v>0?(k.TOO_FAST||0)/v*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(Fx,{isOpen:S,onClose:()=>C(!1),lessonTitle:t,syncedStudentsCount:d,...c??{}}),r.jsx("div",{className:"absolute inset-0 pointer-events-none z-30 overflow-hidden",children:r.jsx(Me,{slot:"stage.display.overlay",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s}})})]})}const ab=/\b(function|const|let|var|class|def|import|return|if|for|while|print|console)\b|[{};]\s*$/;function lb(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=db(o,["code","source","src","program","html","content","answer"]);if(a&&(ab.test(a)||a.includes(`
|
|
3
|
+
`)||a.length>120))return{kind:"code",lines:a.split(`
|
|
4
|
+
`).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 l=Object.entries(o).filter(([,u])=>typeof u!="object"||u===null),c=l.filter(([u])=>!cb.has(u.toLowerCase()));if(c.length>=3)return{kind:"structured",lines:c.slice(0,10).map(([u,m])=>({text:`${u}: ${ub(m)}`,indent:0})),eventCount:t.length};if(a)return{kind:"text",lines:a.split(`
|
|
5
|
+
`).slice(0,12).map(u=>({text:u.slice(0,200),indent:0})),eventCount:t.length};const d=l.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 cb=new Set(["type","score","comment","completion","timestamp","t","watch","attemptsd","eventtype","payload"]);function db(e,t){for(const n of t){const s=e?.[n];if(typeof s=="string"&&s.trim())return s}return null}function ub(e){return e==null?"—":Array.isArray(e)?e.map(t=>String(t)).join("、"):typeof e=="object"?JSON.stringify(e):String(e)}const hb={code:"代码",text:"文本作答",structured:"结构化答案",numeric:"数值结果",empty:"无内容"},nl={workA:null,workB:null,matchingItems:[],badges:[],podiumStudents:[],danmaku:[],reactions:[],rubricDimensions:[],reviewProgress:{completed:0,total:0},fromServer:!1};function sl(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(`
|
|
6
|
+
`).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(`
|
|
7
|
+
`).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 fb({lessonId:e,enabled:t,attempts:n,studentCount:s,addToast:i,lang:o="zh"}){const[a,l]=f.useState([]),[c,d]=f.useState(null),[u,m]=f.useState([]),[p,h]=f.useState(null),[x,g]=f.useState(null),[b,w]=f.useState(!1),y=f.useCallback((D,_)=>{D==="A"?h(_):g(_)},[]);f.useEffect(()=>{if(!e){l([]);return}let D=!0;const _=async()=>{try{const z=await fetch(`/api/classroom/sessions/${e}/top-performers?limit=50`);if(!z.ok||!D)return;const R=await z.json(),$=Array.isArray(R?.topPerformers)?R.topPerformers:[];if(!D)return;l($.map(I=>({studentId:String(I.studentId??""),studentName:String(I.studentName??""),cumulativeScore:Number(I.cumulativeScore)||0,accuracy:Number(I.accuracy)||0})))}catch{}};_();const T=setInterval(()=>void _(),2e4);return()=>{D=!1,clearInterval(T)}},[e]);const[S,C]=f.useState({}),k=f.useCallback(async D=>{if(D)try{const _=await fetch(`/api/courseware/attempts/${encodeURIComponent(D)}/raw`);if(!_.ok)return;const T=await _.json(),z=Array.isArray(T?.events)?T.events:Array.isArray(T)?T:[];if(z.length===0)return;C(R=>({...R,[D]:lb(z)}))}catch{}},[]);f.useEffect(()=>{const D=[...n].filter(_=>_?.studentId&&_.studentId!=="teacher"&&_.studentId!=="guest").sort((_,T)=>(Number(T.score)||0)-(Number(_.score)||0)).slice(0,2);for(const _ of D)_.attemptId&&!S[_.attemptId]&&k(String(_.attemptId))},[n,S,k]);const v=f.useCallback(async()=>{if(!e){d(null),m([]);return}try{const[D,_]=await Promise.all([fetch(`/api/classroom/sessions/${e}/peer-review`),fetch(`/api/classroom/sessions/${e}/showcase-works`)]);if(D.ok){const T=await D.json();d(T),Array.isArray(T?.showcaseWorks)&&T.showcaseWorks.length>0&&m(T.showcaseWorks)}if(_.ok){const T=await _.json();Array.isArray(T?.works)&&T.works.length>0&&m(T.works)}}catch{}},[e]);f.useEffect(()=>{if(!t)return;v();const D=setInterval(()=>void v(),5e3);return()=>clearInterval(D)},[t,v]);const N=f.useCallback(async()=>{if(e){w(!0);try{const D=await fetch(`/api/classroom/sessions/${e}/peer-review/auto-assign`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({perStudent:2})}),_=await D.json().catch(()=>null);if(!D.ok){i?.(o==="zh"?"分配失败":"Assign failed",_?.error??`HTTP ${D.status}`,"error");return}i?.(o==="zh"?"✅ 互评已分配":"✅ Peer reviews assigned",o==="zh"?`${_.works} 份作品 · 生成 ${_.tasks} 条任务(口径:${_.scope==="lesson"?"本课节作品池":"本班全部"})`:`${_.tasks} tasks created`,"success"),await v()}finally{w(!1)}}},[e,i,o,v]);return{data:f.useMemo(()=>{const D=n.filter(I=>I?.studentId&&I.studentId!=="teacher"&&I.studentId!=="guest"),_=[...D].sort((I,B)=>(Number(B.score)||0)-(Number(I.score)||0)),T=(I,B)=>{if(!I)return null;const H=String(I.studentName||I.studentId),A=typeof I.score=="number"?I.score:null,U=String(I.attemptId??`work-${B}`),j=S[U];return{id:U,slot:B,studentName:H,studentInitial:H.slice(0,1),workTitle:`${H} · ${I.coursewareName??"课件作品"}`,workSubtitle:A===null?I.status==="completed"?"已完成提交":"作答中":`得分 ${A}${typeof I.completion=="number"?` · 完成度 ${Math.round(I.completion*100)}%`:""}`,source:"courseware",sourceLabel:"课件作答",badges:[],workContent:j??null,codeTitle:j?`真实作答内容(${hb[j.kind]})`:void 0,codeLines:j?.lines.length?j.lines:void 0}};let z=null,R=null;if(u.length>0){const I=u.find(H=>H.workId===p)||u[0],B=u.find(H=>H.workId===x)||u.find(H=>H.workId!==I?.workId)||u[1];z=sl(I,"A",S),R=sl(B,"B",S)}else z=T(_[0],"A"),R=T(_[1],"B");const $=c?.podiumStudents?.length>0?c.podiumStudents:a.slice(0,3).map((I,B)=>({rank:B+1,name:I.studentName,votes:I.cumulativeScore,workTitle:`${I.accuracy}% 正确率`,honorTitle:B===0?"本节最高分":"优秀表现",rankBadgeClass:B===0?"bg-[#ffb95f] text-[#2a1700]":"bg-[#171f33] text-[#908fa0]",tagBadgeClass:"bg-[#ca8100]/20 text-[#ffb95f]"}));return c?.matchingItems?.length||c?.podiumStudents?.length?{...nl,workA:z,workB:R,matchingItems:c.matchingItems??[],badges:c.badges??[],podiumStudents:$,danmaku:c.danmaku??[],reactions:c.reactions??[],rubricDimensions:c.dimensions??[],reviewProgress:c.progress??{completed:0,total:0},fromServer:!0}:{...nl,workA:z,workB:R,podiumStudents:$,reviewProgress:{completed:D.filter(I=>I.status==="completed").length,total:s}}},[c,n,a,s,S,u,p,x]),topPerformers:a,showcaseWorks:u,selectedWorkAId:p,selectedWorkBId:x,setSpotlightWork:y,autoAssigning:b,autoAssign:N,refresh:v}}function mb({lessonId:e,lessonTitle:t="互动课堂",lang:n="zh"}){const{data:s,health:i,lastSyncedAt:o}=Wx(e),{notices:a,push:l,dismiss:c}=Yx(n),[d,u]=f.useState(!1),[m,p]=f.useState([]),[h,x]=f.useState("");f.useEffect(()=>{if(!d||!e)return;let C=!1;return(async()=>{try{const k=await fetch("/api/courseware/attempts?pageSize=all");k.ok&&!C&&p(En(await k.json()))}catch{}})(),()=>{C=!0}},[d,e]),f.useEffect(()=>{let C=!1;return(async()=>{try{const k=await fetch("/api/auth/session");if(k.ok&&!C){const v=await k.json();x(String(v?.session?.name??v?.session?.username??""))}}catch{}})(),()=>{C=!0}},[]);const g=fb({lessonId:e,enabled:d,attempts:m,studentCount:s.attendance?.expected??0,lang:n}),b=f.useMemo(()=>({workA:g.data.workA,workB:g.data.workB,matchingItems:g.data.matchingItems,badges:g.data.badges,podiumStudents:g.data.podiumStudents,danmaku:g.data.danmaku,reactions:g.data.reactions,rubricDimensions:g.data.rubricDimensions,reviewProgress:g.data.reviewProgress,onAutoAssign:g.autoAssign,autoAssigning:g.autoAssigning,syncedStudentsCount:s.attendance?.onlineInClass,teacherName:h,stageLabel:Zo(s.stage,n)}),[g,s.attendance,h,s.stage,n]),w=f.useRef(null),y=f.useRef(!0),S=f.useRef(i);return f.useEffect(()=>{if(y.current){y.current=!1,w.current=s;return}const C=w.current;w.current=s,C&&l(Gx(C,s,{lang:n,isFirstFrame:!1}))},[s,n,l]),f.useEffect(()=>{const C=Qx(i,S.current,n);S.current=i,C&&l([C])},[i,n,l]),e?r.jsxs(r.Fragment,{children:[r.jsx(ob,{lessonId:e,lessonTitle:t,data:s,lang:n,health:i,lastSyncedAt:o,peerReviewOpen:d,onOpenPeerReview:()=>u(!0),onClosePeerReview:()=>u(!1),peerReview:b,showCloseButton:!1}),r.jsx(Kx,{notices:a,onDismiss:c,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 pb(e){const t=nn(),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,l=e.lang??t?.lang??"zh",c=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(Ns,{size:12}),l==="zh"?a?"学生视角预览":"学生模拟模式":a?"Student Preview":"Student View Mode"]}),r.jsx("span",{children:l==="zh"?`您当前正在以学生身份(${c.find(u=>u.id===d)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${c.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(Oe,{size:13}):r.jsx(zr,{size:13}),l==="zh"?a?"关闭此预览标签页":"退出模拟并返回教师端":a?"Close Preview Tab":"Exit Student View"]})]}):null}function gb({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{}},l=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(Lo,{size:13,className:"shrink-0","aria-hidden":"true"}),r.jsx("span",{className:"flex-1",children:l?"你当前仍在使用初始默认密码,建议尽快修改以保护账号安全。":"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:l?"去修改":"Change now"}),r.jsx("button",{type:"button",onClick:a,"aria-label":l?"关闭提示":"Dismiss hint",className:"shrink-0 p-1 rounded-md hover:bg-amber-100 dark:hover:bg-amber-900/60 transition-colors",children:r.jsx(Oe,{size:13,"aria-hidden":"true"})})]})}const rs="openlearn_timetable_ocr_task",ai="openlearn_timetable_ocr_draft";function rl(e){try{const t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function $s(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 il(e){try{sessionStorage.removeItem(e)}catch{}}const xb=St((e,t)=>({timetableOcrTask:rl(rs),timetableOcrDraft:rl(ai),isAnyTaskRunning:!1,startTimetableOcr:async({imageBase64:n,lang:s,providerId:i,fileName:o})=>{const a=`task_ocr_${Date.now()}`,l={id:a,type:"timetable_ocr",title:s==="zh"?"课表图片 AI 识别":"Timetable Image AI Recognition",status:"running",startedAt:Date.now(),meta:{fileName:o}};e({timetableOcrTask:l,isAnyTaskRunning:!0}),$s(rs,l),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 c=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 c.json();if(!c.ok||!d.success)throw new Error(d.error||(s==="zh"?"识别请求失败":"OCR recognition failed"));const u=Array.isArray(d.entries)?d.entries:[],m={...l,status:"completed",completedAt:Date.now(),result:{entries:u,providerUsed:d.providerUsed}};e({timetableOcrTask:m,isAnyTaskRunning:!1}),$s(rs,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:()=>{ve.getState().setTeacherTab("timetable"),Ve.getState().setPendingTimetableSubTab("ocr_import")}}})}catch(c){console.error("[AsyncTask] Timetable OCR failed:",c);const d={...l,status:"failed",completedAt:Date.now(),error:c?.message||(s==="zh"?"未知识别错误":"Unknown OCR error")};e({timetableOcrTask:d,isAnyTaskRunning:!1}),$s(rs,d),Ve.getState().addToast({id:`toast_fail_${a}`,title:s==="zh"?"AI 课表识别失败":"Timetable OCR Failed",message:c?.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}),$s(ai,s,["imagePreview","imageBase64"])},clearTimetableOcrTask:()=>{e({timetableOcrTask:null,isAnyTaskRunning:!1,timetableOcrDraft:null}),il(rs),il(ai)}})),bb=e=>Ft(xb,e);function yb({session:e,lang:t,onLogout:n,onProfile:s}){const[i,o]=f.useState(!1),a=f.useRef(null);f.useEffect(()=>{if(!i)return;const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[i]);const l=(c,d)=>t==="zh"?c:d;return r.jsxs("div",{className:"relative",ref:a,children:[r.jsxs("button",{type:"button",onClick:()=>o(c=>!c),"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(vs,{size:20})}),r.jsx(Nn,{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(vs,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),r.jsx(Me,{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(zr,{size:16}),l("注销登录","Sign Out")]})]})]})}const Qe=[];for(let e=0;e<256;++e)Qe.push((e+256).toString(16).slice(1));function wb(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 vb=new Uint8Array(16);function Sb(){return crypto.getRandomValues(vb)}const li={};function Or(e,t,n){let s;{const i=Date.now(),o=Sb();jb(li,i,o),s=kb(o,li.msecs,li.seq,t,n)}return t??wb(s)}function jb(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 kb(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 ci(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 Cb{constructor(){this.handlers=new Map,this.prefixHandlers=new Map,this.globalHandlers=new Set,this.wildcardCount=0}subscribe(t,n){const{kind:s,key:i}=ci(t);let o;if(s==="global")o=this.globalHandlers,this.wildcardCount++;else if(s==="prefix"){let l=this.prefixHandlers.get(i);l||(l=new Set,this.prefixHandlers.set(i,l)),o=l,this.wildcardCount++}else{let l=this.handlers.get(i);l||(l=new Set,this.handlers.set(i,l)),o=l}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}=ci(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}=ci(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 tn=new Cb,Nb=[{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"}],sr={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"}},di="openlearn_theme",is="openlearn_custom_themes",kr={};function Xo(e){return kr[e]?kr[e]:e in sr?sr[e]:sr.light}function ui(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function Eb(e,t){if(typeof document>"u")return;kr[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(`
|
|
8
|
+
`);s.textContent=`[data-theme="${e}"] {
|
|
9
|
+
${i}
|
|
10
|
+
}`}function Tb(e){if(typeof document>"u")return;delete kr[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function hi(e){if(!(typeof window>"u"))try{tn.publish({id:Or(),type:"theme.changed",source:"theme-store",payload:{theme:e,tokens:Xo(e)},timestamp:Date.now()})}catch{}}const Dr=Vo((e,t)=>({theme:"light",availableThemes:[...Nb],initTheme:()=>{if(typeof window>"u")return;try{const i=localStorage.getItem(is);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(di)||"light";ui(s),e({theme:s}),hi(s)},setTheme:n=>{ui(n),typeof window<"u"&&localStorage.setItem(di,n),e({theme:n}),hi(n)},registerTheme:(n,s)=>{s&&Eb(n.id,s),e(i=>({availableThemes:[...i.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{Tb(n),e(s=>{const i=s.availableThemes.filter(a=>a.id!==n),o=s.theme===n?"light":s.theme;return s.theme===n&&(ui("light"),typeof window<"u"&&localStorage.setItem(di,"light"),hi("light")),{availableThemes:i,theme:o}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const i=localStorage.getItem(is);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(is,JSON.stringify(o))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(is);if(s){let i=JSON.parse(s);Array.isArray(i)&&(i=i.filter(o=>o.spec.id!==n),localStorage.setItem(is,JSON.stringify(i)))}}catch{}t().unregisterTheme(n)}})),Pb=[{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"}}],ol={...sr.light};function Ib({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:i,deleteCustomTheme:o}=Dr(),a=f.useId(),[l,c]=f.useState("custom-mytheme"),[d,u]=f.useState("我的专属主题"),[m,p]=f.useState("自定义教学调色板配置"),[h,x]=f.useState({...ol}),[g,b]=f.useState("none"),[w,y]=f.useState(""),[S,C]=f.useState(!1),[k,v]=f.useState(null);if(!e)return null;const N=s.filter(A=>A.category==="custom"),O=A=>{v(A),setTimeout(()=>v(null),3e3)},D=A=>{c(A.id),u(A.label),p(A.description),x({...A.tokens}),O(`已载入预设: ${A.label}`)},_=A=>{c(A.id),u(A.label),p(A.description);const U=Xo(A.id);U&&Object.keys(U).length>0&&x({...U}),O(`已载入自定义主题: ${A.label}`)},T=(A,U)=>{x(j=>({...j,[A]:U}))},z=()=>{const A=l.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!A){alert("请输入有效的主题标识 (ID)");return}const U={id:A,label:d.trim()||"未命名主题",description:m.trim()||"自定义主题",previewBg:h["--bg-app"]||"#ffffff",previewPrimary:h["--color-primary"]||"#4f46e5",category:"custom"};i(U,h),O(`主题「${U.label}」已保存并成功激活!`)},R=()=>{y(JSON.stringify({version:"1.0",id:l,label:d,description:m,tokens:h},null,2)),b("export")},$=()=>{y(""),b("import")},I=()=>{try{const A=JSON.parse(w);if(!A.tokens||typeof A.tokens!="object")throw new Error("缺少合法的 tokens 字段");A.id&&c(A.id),A.label&&u(A.label),A.description&&p(A.description),x(U=>({...U,...A.tokens})),b("none"),O("主题配置导入成功!")}catch(A){alert(`导入失败: ${A.message||"JSON 格式解析错误"}`)}},B=()=>{navigator.clipboard.writeText(w),C(!0),setTimeout(()=>C(!1),2e3)},H=[{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(Zi,{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:$,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(Ha,{size:14}),n==="zh"?"导入配置":"Import"]}),r.jsxs("button",{onClick:R,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(Ji,{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(Oe,{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(ht,{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(yt,{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:Pb.map(A=>r.jsxs("button",{onClick:()=>D(A),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:A.tokens["--color-primary"]}}),A.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:A.tokens["--bg-app"]}}),r.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:A.tokens["--bg-surface"]}})]})]}),r.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:A.description})]},A.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(Vp,{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:l,onChange:A=>c(A.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:A=>u(A.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:A=>p(A.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(Zi,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),r.jsx("div",{className:"space-y-2.5",children:H.map(A=>{const U=h[A.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:A.labelZh}),r.jsx("span",{className:"text-xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:A.key})]}),r.jsx("p",{className:"text-xs text-muted mt-0.5",children:A.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=>T(A.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=>T(A.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"})]})]},A.key)})})]}),N.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(Xc,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),r.jsx("div",{className:"space-y-2",children:N.map(A=>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:A.previewPrimary}}),r.jsxs("div",{className:"truncate",children:[r.jsx("div",{className:"text-xs font-semibold text-main truncate",children:A.label}),r.jsx("div",{className:"text-xs text-muted truncate",children:A.description})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[r.jsx("button",{onClick:()=>_(A),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(`确定删除自定义主题「${A.label}」吗?`)&&(o(A.id),O(`已删除主题「${A.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:r.jsx(_r,{size:13})})]})]},A.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(Ns,{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," (",l,")"]})]}),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(Rr,{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:()=>{x({...ol}),O("已重置为系统默认调色板")},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(ed,{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:z,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(Hp,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),g!=="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:g==="export"?r.jsxs(r.Fragment,{children:[r.jsx(Ji,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):r.jsxs(r.Fragment,{children:[r.jsx(Ha,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),r.jsx("button",{onClick:()=>b("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:r.jsx(Oe,{size:16})})]}),r.jsx("div",{children:r.jsx("textarea",{value:w,readOnly:g==="export",onChange:A=>y(A.target.value),placeholder:g==="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:g==="export"?r.jsx(r.Fragment,{children:r.jsxs("button",{onClick:B,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(ht,{size:14}):r.jsx(vn,{size:14}),S?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>b("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:I,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 Ab({lang:e="zh"}){const[t,n]=f.useState(!1),[s,i]=f.useState(!1),o=f.useRef(null),{theme:a,availableThemes:l,setTheme:c}=Dr();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(qp,{size:16,className:"text-indigo-400"});case"eyecare":return r.jsx(Ns,{size:16,className:"text-emerald-500"});case"chalkboard":return r.jsx(Zi,{size:16,className:"text-green-400"});case"light":default:return r.jsx(Wp,{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:l.map(u=>{const m=a===u.id;return r.jsxs("button",{onClick:()=>{c(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(ht,{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(yt,{size:14}),r.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),r.jsx(Ib,{isOpen:s,onClose:()=>i(!1),lang:e})]})}const fi="openlearn_font_scale",gn=85,xn=140,mi=5,rr=100,al=[{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(xn,Math.max(gn,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 gi(e){if(!(typeof window>"u"))try{tn.publish({id:Or(),type:"font-scale.changed",source:"font-size-store",payload:{scale:e},timestamp:Date.now()})}catch{}}const wn=Vo((e,t)=>({scale:rr,minScale:gn,maxScale:xn,step:mi,initFontSize:()=>{if(typeof window>"u")return;let n=rr;try{const s=localStorage.getItem(fi);if(s){const i=Number(s);!isNaN(i)&&i>=gn&&i<=xn&&(n=i)}}catch{}pi(n),e({scale:n}),gi(n);try{window.addEventListener("storage",s=>{if(s.key===fi&&s.newValue){const i=Number(s.newValue);!isNaN(i)&&i>=gn&&i<=xn&&(pi(i),e({scale:i}),gi(i))}})}catch{}},setScale:n=>{const s=Math.min(xn,Math.max(gn,Math.round(n)));if(pi(s),typeof window<"u")try{localStorage.setItem(fi,String(s))}catch{}e({scale:s}),gi(s)},increaseScale:()=>{const n=t().scale,s=Math.min(xn,n+mi);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max(gn,n-mi);t().setScale(s)},resetScale:()=>{t().setScale(rr)}}));function bd({lang:e="zh"}){const[t,n]=f.useState(!1),s=f.useRef(null),{scale:i,minScale:o,maxScale:a,setScale:l,increaseScale:c,decreaseScale:d,resetScale:u}=wn();f.useEffect(()=>{function h(x){s.current&&!s.current.contains(x.target)&&n(!1)}return t&&document.addEventListener("mousedown",h),()=>{document.removeEventListener("mousedown",h)}},[t]);const m=al.find(h=>h.scale===i),p=i===rr;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(Gp,{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(ed,{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(Qp,{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:c,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(Bo,{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:al.map(h=>{const x=i===h.scale;return r.jsxs("button",{type:"button",onClick:()=>l(h.scale),className:`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs transition-all cursor-pointer ${x?"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})]}),x&&r.jsx(ht,{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 zb(e){const t=nn(),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??[],l=e.isStudentLocked??t?.isNavigationLocked??t?.isStudentLocked??!1,c=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(l){u();return}d(!c)},disabled:l,className:`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 shadow-2xs ${l?"cursor-not-allowed":"cursor-pointer"} ${c?"bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800":"bg-surface text-muted border-theme hover:text-main"} ${l?"opacity-70":""}`,title:l?n==="zh"?"全班专注锁定中,已强制跟随教师步调":"Class focus is locked; following the teacher is enforced":n==="zh"?"开启后,教师端切换课节/环节/Tab时,学生端将自动同步跟随":"Follow teacher navigation",children:[r.jsx(Lr,{size:12,className:c?"animate-spin":""}),r.jsx("span",{children:n==="zh"?`跟随教师步调: ${c?"开":"关"}`:`Follow Teacher: ${c?"ON":"OFF"}`})]}),r.jsx(bd,{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(Do,{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 Lb(e){const t=nn(),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",l=e.session!==void 0?e.session:t?.session,c=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??[],x=e.readNotifications??t?.readNotifications??new Set;e.selectedNotificationForModal!==void 0?e.selectedNotificationForModal:t?.selectedNotificationForModal;const g=e.dbConnected??t?.dbConnected??!1,b=e.dbStatus??t?.dbStatus??"normal",w=e.siteInfo??t?.siteInfo,y=e.setActiveStudentId??t?.setActiveStudentId??(()=>{}),S=e.setReadNotifications??t?.setReadNotifications??(()=>{}),C=e.setIsSystemResourceLibraryOpen??t?.setIsSystemResourceLibraryOpen??(()=>{}),k=e.setProfileOpen??t?.setProfileOpen??(()=>{}),v=e.setTeacherTab??t?.setTeacherTab??(()=>{}),N=e.setStudentViewStatus??t?.setStudentViewStatus??(()=>{}),O=e.setIsNotificationsOpen??t?.setIsNotificationsOpen??(()=>{}),D=e.setSelectedNotificationForModal??t?.setSelectedNotificationForModal??(()=>{}),_=e.handleLogout??t?.handleLogout??t?.onLogout??(()=>{}),T=e.toggleLanguage??t?.toggleLanguage??(()=>{}),z=e.setActiveRole??t?.setActiveRole??(()=>{}),R=e.isStudentLocked??t?.isNavigationLocked??t?.isStudentLocked??!1,$=e.onBlockedNavigate??t?.notifyLockedNavigation,I=bb(U=>U.timetableOcrTask);if(t?.isStudentLiveMode)return r.jsx(zb,{});const B=n==="student"&&R,H=()=>{if(B){$?.();return}n==="teacher"?v("live_class"):n==="student"&&N("dashboard")},A=()=>{if(B){$?.();return}n==="teacher"?v("dashboard"):n==="student"&&N("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:H,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:B?i==="zh"?"全班专注锁定中,无法返回首页":"Class focus locked — cannot return to home":i==="zh"?"返回首页":"Back to Home",children:[w.logoUrl?r.jsx("img",{src:w.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:w.siteName||"OpenLearn Next"}),r.jsxs("span",{className:"text-xs font-medium text-subtle tracking-tight",children:["v","0.7.2"]}),w.slogan&&r.jsx("span",{className:"hidden md:inline text-xs text-subtle font-normal truncate max-w-[200px]",children:w.slogan})]})]}),r.jsx(Me,{slot:"header.status_pill",slotProps:{dbConnected:g,dbStatus:b,lang:i}}),I?.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($t,{size:13,className:"animate-spin text-violet-600"}),r.jsx("span",{children:i==="zh"?"后台识别课表中...":"Timetable OCR Running..."})]}),I?.status==="completed"&&o!=="timetable"&&r.jsxs("button",{type:"button",onClick:()=>{v("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(at,{size:13,className:"text-emerald-600"}),r.jsx("span",{children:i==="zh"?`课表识别已完成 (${I.result?.entries.length||0}节) · 查看`:`Timetable Ready (${I.result?.entries.length||0})`})]}),r.jsx(Me,{slot:"header.async_task.item",slotProps:{lang:i,activeRole:n,teacherTab:o,setTeacherTab:v}}),r.jsxs("button",{onClick:A,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"} ${B?"opacity-50":""}`,children:[B?r.jsx(Gi,{size:16}):r.jsx(td,{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(Jp,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),n==="student"&&l?.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(Ns,{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:c||"",onChange:U=>y(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}z?.("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(Oe,{size:12}):r.jsx(zr,{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"&&c&&u&&r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>O(!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($o,{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(c){try{const U=p.filter(j=>!x.has(j.id)).map(j=>fetch(`/api/students/${c}/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(V=>j.add(V.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=!x.has(U.id);return r.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${j?"bg-indigo-50/30":""}`,onClick:()=>{j&&(c&&fetch(`/api/students/${c}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:U.id})}).catch(console.error),S(G=>new Set(G).add(U.id)));const V=u?.assignments?.find(G=>G.id===U.relatedId);D({...U,assignment:V}),O(!1)},children:r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"mt-0.5",children:U.type==="new_assignment"?r.jsx(Ss,{size:16,className:"text-indigo-500"}):r.jsx(at,{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(Me,{slot:"header.action",lang:i,fallback:r.jsx(r.Fragment,{}),slotProps:{session:l,currentRole:n,lang:i}})}),r.jsxs("button",{onClick:()=>C(!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(Xi,{size:14,className:"text-emerald-500 animate-pulse"}),i==="zh"?"系统资源库":"System Resource Library"]}),r.jsx("button",{onClick:T,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(Xi,{size:16})}),r.jsx(bd,{lang:i}),r.jsx(Ab,{lang:i}),n!=="student"&&(()=>{const U=b==="error"||!g?{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"}:b==="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(Kp,{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(yb,{session:l,lang:i,onLogout:_,onProfile:()=>k(!0)})]})]})}function Rb(){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 _b(){const e=nn(),t=Rb(),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(Me,{slot:"statusbar.item",lang:n,fallback:r.jsx(r.Fragment,{}),slotProps:{session:i,currentRole:s,lang:n,isOnline:t}})})}function Ob({open:e,session:t,lang:n,onClose:s,onSaved:i,onAvatar:o}){const[a,l]=f.useState(t.name),[c,d]=f.useState(!1),[u,m]=f.useState(null),p=f.useRef(null),[h,x]=f.useState(!1),[g,b]=f.useState(null),[w,y]=f.useState(!1),[S,C]=f.useState(""),[k,v]=f.useState(""),[N,O]=f.useState(""),[D,_]=f.useState(!1),[T,z]=f.useState(null),[R,$]=f.useState(!1);if(!e)return null;const I=(W,Y)=>n==="zh"?W:Y,B=t.role==="teacher"?t.subRole==="administrator"?I("管理员","Administrator"):I("教师","Teacher"):I("学生","Student"),H=a.trim(),A=H.length>0&&H!==t.name,U=async()=>{if(!(!A||c)){d(!0),m(null);try{const W=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:H})}),Y=await W.json();if(!W.ok){m(Y.error||(n==="zh"?"保存失败":"Save failed"));return}i(Y.name??H)}catch{m(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{d(!1)}}},j=S.length>0&&k.length>=8&&/[a-zA-Z]/.test(k)&&/[0-9]/.test(k)&&k===N,V=async()=>{if(!(!j||D)){_(!0),z(null);try{const W=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:S,newPassword:k})}),Y=await W.json();if(!W.ok){z(Y.error||(n==="zh"?"修改失败":"Change failed"));return}$(!0),C(""),v(""),O(""),y(!1)}catch{z(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{_(!1)}}},G=async W=>{const Y=W.target.files?.[0];if(W.target.value="",!!Y){x(!0),b(null);try{const K=await new Promise((je,X)=>{const me=new FileReader;me.onload=()=>je(me.result),me.onerror=()=>X(me.error),me.readAsDataURL(Y)}),ne=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:Y.name,base64Data:K})}),fe=await ne.json();if(!ne.ok){b(fe.error||(n==="zh"?"上传失败":"Upload failed"));return}o?.(fe.avatar)}catch{b(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{x(!1)}}},E=async()=>{x(!0),b(null);try{const W=await fetch("/api/auth/avatar",{method:"DELETE"}),Y=await W.json().catch(()=>({}));if(!W.ok){b(Y.error||(n==="zh"?"移除失败":"Remove failed"));return}o?.(null)}catch{b(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{x(!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 max-w-md overflow-hidden",onClick:W=>W.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[r.jsx("h3",{className:"font-semibold text-gray-800",children:I("个人资料","Profile")}),r.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:r.jsx(Oe,{size:18})})]}),r.jsxs("div",{className:"p-5 space-y-5",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:t.avatar?r.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):r.jsx(vs,{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:B}),r.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:()=>p.current?.click(),disabled:h,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:h?I("上传中…","Uploading…"):t.avatar?I("更换头像","Change avatar"):I("上传头像","Upload avatar")}),t.avatar&&r.jsx("button",{type:"button",onClick:E,disabled:h,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:I("移除","Remove")})]}),r.jsx("input",{ref:p,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:G})]})]}),g&&r.jsx("p",{className:"text-xs text-rose-500",children:g}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:I("显示名称","Display Name")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{value:a,onChange:W=>l(W.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:U,disabled:!A||c,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer shrink-0",children:c?I("保存中…","Saving…"):I("保存","Save")})]}),u&&r.jsx("p",{className:"text-xs text-rose-500 mt-1",children:u})]}),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(Lo,{size:16,className:"text-gray-400"}),I("修改密码","Change Password")]}),!w&&!R&&r.jsx("button",{onClick:()=>{y(!0),z(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:I("修改","Edit")})]}),R&&r.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[r.jsx(at,{size:16}),I("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),w&&r.jsxs("div",{className:"mt-3 space-y-3",children:[r.jsx("input",{type:"password",value:S,onChange:W=>C(W.target.value),placeholder:I("当前密码","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:k,onChange:W=>v(W.target.value),placeholder:I("新密码(≥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:N,onChange:W=>O(W.target.value),placeholder:I("确认新密码","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"}),T&&r.jsx("p",{className:"text-xs text-rose-500",children:T}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx("button",{onClick:()=>{y(!1),C(""),v(""),O(""),z(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:I("取消","Cancel")}),r.jsx("button",{onClick:V,disabled:!j||D,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer",children:D?I("提交中…","Submitting…"):I("提交","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:I("用户名(登录账号)","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:I("角色","Role")}),r.jsx("span",{className:"text-sm font-medium text-gray-700",children:B})]})]})]})]})})}const Db=f.lazy(()=>Je(()=>import("./StudentView-PHKxIV9T.js").then(e=>e.S),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.StudentView}))),Mb=f.lazy(()=>Je(()=>import("./TeacherView-DscJtOJ9.js"),__vite__mapDeps([5,1,2,3,4])).then(e=>({default:e.TeacherView})));function $b(e){const{activeRole:t}=e;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($t,{className:"w-8 h-8 animate-spin text-indigo-500"}),r.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?r.jsx(Db,{}):r.jsx(Mb,{})})}const Fb=(e,t,n)=>e.replace(/\{\{\s*([\w-]+)\s*\}\}/g,(s,i)=>{const o=n[i];return o!==void 0&&o!==""?o:t?.find(l=>l.name===i)?.default??`{{${i}}}`});function Bb({setInput:e,currentInput:t,lang:n="zh"}){const s=Ne(x=>x.extensionPoints),[i,o]=f.useState(!1),[a,l]=f.useState(null),[c,d]=f.useState({}),u=f.useMemo(()=>s.get("ai.prompt.template")??[],[s]),m=n==="zh",p=u.find(x=>x.id===a);if(u.length===0)return null;const h=(x,g)=>{const b=x.slotProps?.prompt??"",w=Fb(b,x.slotProps?.parameters,g);e(t?`${t.trimEnd()}
|
|
11
|
+
|
|
12
|
+
${w}`:w),o(!1),l(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(Yp,{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),l(null)},className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:r.jsx(Oe,{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(x=>r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"text-[11px] text-gray-500",children:x.label||x.name}),r.jsx("input",{value:c[x.name]??"",onChange:g=>d(b=>({...b,[x.name]:g.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:x.default||x.name})]},x.name)),r.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[r.jsx("button",{type:"button",onClick:()=>h(p,c),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:()=>l(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(x=>{const g=x.slotProps?.title||x.id,b=x.slotProps?.description;return r.jsxs("button",{type:"button",onClick:()=>{const w=x.slotProps?.parameters??[];if(w.length>0){const y={};for(const S of w)S.default&&(y[S.name]=S.default);d(y),l(x.id)}else h(x,{})},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:g}),b&&r.jsx("div",{className:"text-[11px] text-gray-500 mt-0.5 line-clamp-2",children:b})]},x.id)})})]})]})}function Ub(e={}){const t=nn(),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 l=e.setAgentProviderId??t?.setAgentProviderId??(()=>{}),c=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,x=e.input??t?.input??"",g=e.setInput??t?.setInput??(()=>{}),b=e.handleSend??t?.handleSend??(async()=>{}),w=e.chatAttachments??t?.chatAttachments??[],y=e.setChatAttachments??t?.setChatAttachments??(()=>{}),S=e.handleChatFileChange??t?.handleChatFileChange??(()=>{}),C=e.handleChatDrop??t?.handleChatDrop??(()=>{}),k=e.onClearAgentMemory??t?.handleClearAgentMemory??(()=>{}),v=e.events??t?.events??[],N=e.lang??t?.lang??"zh",O=e.t??t?.t??{},D=f.useRef(null);f.useEffect(()=>{D.current?.scrollIntoView({behavior:"smooth"})},[p]);const[_,T]=f.useState([]);return f.useEffect(()=>{!n||_.length>0||fetch("/api/agent/personas").then(z=>z.ok?z.json():null).then(z=>{z?.success&&Array.isArray(z.personas)&&T(z.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(Yr,{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(Xs,{size:14})," Shell"]}),r.jsx(Me,{slot:"ai_sidebar.tab",slotProps:{renderType:"button",activeTab:i,setActiveTab:o,lang:N}}),r.jsx("button",{onClick:()=>s(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:r.jsx(Zp,{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(Yr,{size:16})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:O.agentTitle}),r.jsx("p",{className:"text-xs text-gray-500",children:O.agentSubtitle}),r.jsxs("button",{onClick:k,title:N==="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:["🧹 ",N==="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:N==="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:N==="zh"?"未配置 AI 提供商":"No AI Provider"})}):r.jsx("select",{value:a,onChange:z=>l(z.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(z=>r.jsx("option",{value:z.id,children:z.name},z.id))}),r.jsx(Nn,{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}`:N==="zh"?"未配置提供商":"No Provider"})]})]})}),d&&_.length>0&&r.jsx("div",{className:"mx-4 mb-3",children:r.jsxs("select",{value:c||"",onChange:z=>d(z.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:N==="zh"?"🤖 助教角色:默认":"🤖 Persona: Default"}),_.filter(z=>z.id!=="plain_assistant").map(z=>r.jsxs("option",{value:z.id,children:[z.icon||"🎯"," ",N==="zh"?z.nameZh:z.nameEn]},z.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(Mt,{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:N==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),r.jsx("p",{className:"mt-0.5 text-amber-700",children:N==="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((z,R)=>r.jsx("div",{className:`flex flex-col ${z.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 ${z.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:z.content})},R)),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:D})]}),r.jsxs("form",{onSubmit:b,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:z=>z.preventDefault(),onDrop:C,children:[w.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:w.map((z,R)=>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(Jc,{size:10,className:"shrink-0"}),r.jsx("span",{className:"truncate max-w-[100px]",title:z.name,children:z.name}),r.jsx("button",{type:"button",onClick:()=>y($=>$.filter((I,B)=>B!==R)),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(Oe,{size:10})})]},R))}),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(Xp,{size:14}),r.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:S,accept:".csv,.txt,.json,.md"})]}),r.jsx(Bb,{setInput:g,currentInput:x,lang:N}),r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"text",value:x,disabled:u.length===0,onChange:z=>g(z.target.value),placeholder:u.length===0?N==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":O.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||!x.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(Kc,{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(Xs,{size:14}),r.jsx("span",{className:"text-xs",children:O.eventStream})]})}),r.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:v.length===0?r.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):v.map((z,R)=>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(z.timestamp).toLocaleTimeString(),"]"]}),r.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:z.source,children:z.source})]}),r.jsx("div",{className:"text-green-300 font-bold",children:z.type}),r.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:z.payload})]},R))})]}):r.jsx("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-4",children:r.jsx(Me,{slot:"ai_sidebar.tab",slotProps:{renderType:"panel",activeTab:i,lang:N}})})]}):r.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-subtle w-full",onClick:()=>s(!0),children:[r.jsx(Yr,{size:18,className:"mb-6 hover:text-indigo-500"}),r.jsx(Xs,{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 Vb=f.lazy(()=>Je(()=>import("./ImportModal-DqjqNeH4.js"),__vite__mapDeps([6,1,2,3])).then(e=>({default:e.ImportModal}))),Hb=f.lazy(()=>Je(()=>import("./CourseWizardModal-Dbi6Caw2.js"),__vite__mapDeps([7,1,2,3,4])).then(e=>({default:e.CourseWizardModal}))),Wb=f.lazy(()=>Je(()=>import("./ImportLessonsModal-PhHtX31R.js"),__vite__mapDeps([8,1,2,3,4])).then(e=>({default:e.ImportLessonsModal}))),qb=f.lazy(()=>Je(()=>import("./QuizGeneratorModal-bUA002kP.js"),__vite__mapDeps([9,1,2,3,4])).then(e=>({default:e.QuizGeneratorModal}))),Gb=f.lazy(()=>Je(()=>import("./ProcessLogsModal-Cfr-T9Gd.js"),__vite__mapDeps([10,1,2,3])).then(e=>({default:e.ProcessLogsModal}))),Qb=f.lazy(()=>Je(()=>import("./CloudDriveModal-D2t3Uyzr.js"),__vite__mapDeps([11,1,2,12,3,4])).then(e=>({default:e.CloudDriveModal}))),Jb=f.lazy(()=>Je(()=>import("./SystemResourceLibraryModal-DgXYe6_x.js"),__vite__mapDeps([13,1,2,11,12,3,4])).then(e=>({default:e.SystemResourceLibraryModal}))),Kb=f.lazy(()=>Je(()=>import("./BatchPickerModal-CbmjInp7.js"),__vite__mapDeps([14,1,2,3,4])).then(e=>({default:e.BatchPickerModal}))),Yb=f.lazy(()=>Je(()=>import("./ExportWeightModal-BrmAh6VX.js"),__vite__mapDeps([15,1,2,3,4])).then(e=>({default:e.ExportWeightModal}))),Zb=f.lazy(()=>Je(()=>import("./NotificationDetailModal-tY5rxYCN.js"),__vite__mapDeps([16,1,2,3,4])).then(e=>({default:e.NotificationDetailModal}))),Xb=f.lazy(()=>Je(()=>import("./HelpTour-D_q1z_MI.js"),__vite__mapDeps([17,1,2,3])).then(e=>({default:e.HelpTour}))),e0=f.lazy(()=>Je(()=>import("./CoursewareHubPanel-CyxDIJAF.js"),__vite__mapDeps([18,1,2,3])).then(e=>({default:e.CoursewareHubPanel})));function t0(e={}){const t=nn(),{lang:n=t?.lang??"zh",t:s=t?.t??{},showImportModal:i=t?.showImportModal??!1,setShowImportModal:o=t?.setShowImportModal??(()=>{}),handleImportFile:a=t?.handleImportFile??(()=>{}),importError:l=t?.importError??null,importSuccess:c=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:x=t?.importStatus??"idle",setIsDraggingImport:g=t?.setIsDraggingImport??(()=>{}),handleCSVFileChange:b=t?.handleCSVFileChange??(()=>{}),handleImportFileChange:w=t?.handleImportFileChange??(()=>{}),downloadCsvTemplate:y=t?.downloadCsvTemplate??(()=>{}),downloadCourseTemplate:S=t?.downloadCourseTemplate??(()=>{}),packagePreview:C=t?.packagePreview??null,handlePackageImportSubmit:k=t?.handlePackageImportSubmit??(()=>{}),packageDuplicate:v=t?.packageDuplicate??null,handlePackageDuplicateDismiss:N=t?.handlePackageDuplicateDismiss??(()=>{}),isDraggingImport:O=t?.isDraggingImport??!1,previewImportData:D=t?.previewImportData??[],setPreviewImportData:_=t?.setPreviewImportData??(()=>{}),setImportStatus:T=t?.setImportStatus??(()=>{}),importProgress:z=t?.importProgress??0,importProgressTotal:R=t?.importProgressTotal??0,importErrorMsg:$=t?.importErrorMsg??"",setImportErrorMsg:I=t?.setImportErrorMsg??(()=>{}),handleCSVImportSubmit:B=t?.handleCSVImportSubmit??(()=>{}),lessons:H=t?.lessons??[],fetchClassDashboard:A=t?.fetchClassDashboard??(()=>{}),currentVfsParent:U=t?.currentVfsParent??null,setCurrentVfsParent:j=t?.setCurrentVfsParent??(()=>{}),vfsNodes:V=t?.vfsNodes??[],showProcessLogs:G=t?.showProcessLogs??null,setShowProcessLogs:E=t?.setShowProcessLogs??(()=>{}),processLogsContent:W=t?.processLogsContent??"",isCloudDriveOpen:Y=t?.isCloudDriveOpen??!1,setIsCloudDriveOpen:K=t?.setIsCloudDriveOpen??(()=>{}),cloudDrivePreviewNode:ne=t?.cloudDrivePreviewNode??null,setCloudDrivePreviewNode:fe=t?.setCloudDrivePreviewNode??(()=>{}),isSystemResourceLibraryOpen:je=t?.isSystemResourceLibraryOpen??!1,setIsSystemResourceLibraryOpen:X=t?.setIsSystemResourceLibraryOpen??(()=>{}),systemResourceTab:me=t?.systemResourceTab??"system",setSystemResourceTab:ke=t?.setSystemResourceTab??(()=>{}),selectedLibraryResourceId:Se=t?.selectedLibraryResourceId??null,setSelectedLibraryResourceId:M=t?.setSelectedLibraryResourceId??(()=>{}),loadingLibraryResources:Z=t?.loadingLibraryResources??!1,libraryResources:ee=t?.libraryResources??[],fetchLibraryResources:te=t?.fetchLibraryResources??(()=>{}),classes:ce=t?.classes??[],expandedClassId:oe=t?.expandedClassId??null,isExportWeightModalOpen:xe=t?.isExportWeightModalOpen??!1,setIsExportWeightModalOpen:ie=t?.setIsExportWeightModalOpen??(()=>{}),quizzesWeight:Pe=t?.quizzesWeight??40,setQuizzesWeight:ze=t?.setQuizzesWeight??(()=>{}),assignmentsWeight:ue=t?.assignmentsWeight??60,setAssignmentsWeight:re=t?.setAssignmentsWeight??(()=>{}),handleQuizzesWeightChange:P=t?.handleQuizzesWeightChange??(()=>{}),handleAssignmentsWeightChange:L=t?.handleAssignmentsWeightChange??(()=>{}),customCategoryOverrides:F=t?.customCategoryOverrides??{},setCustomCategoryOverrides:q=t?.setCustomCategoryOverrides??(()=>{}),classDashboardMap:J=t?.classDashboardMap??{},exportClassId:be=t?.exportClassId??"",exportClassName:se=t?.exportClassName??"",csvPreviewData:ye=t?.csvPreviewData??null,handleExportGrades:$e=t?.handleExportGrades??(()=>{}),setSelectedAssignment:Fe=t?.setSelectedAssignment??(()=>{}),setStudentViewStatus:Ce=t?.setStudentViewStatus??(()=>{}),setQuizStudentAnswers:We=t?.setQuizStudentAnswers??(()=>{}),setSubAssignmentTab:He=t?.setSubAssignmentTab??(()=>{}),isTourOpen:Et=t?.isTourOpen??!1,setIsTourOpen:et=t?.setIsTourOpen??(()=>{}),handleSeedSuccess:jt=t?.handleSeedSuccess??(()=>{}),setTeacherTab:Vt=t?.setTeacherTab??(()=>{}),showCoursewareHub:Ln=t?.showCoursewareHub??!1,setShowCoursewareHub:Ht=t?.setShowCoursewareHub??(()=>{})}=e,Re=e.courseWizard??t,rn=Re?.isCourseWizardOpen??e.isCourseWizardOpen??!1,Rn=Re?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),_n=Re?.wizardStep??e.wizardStep??1,On=Re?.setWizardStep??e.setWizardStep??(()=>{}),on=Re?.wizardIsSubmitting??e.wizardIsSubmitting??!1,Dn=Re?.wizardCourseTitle??e.wizardCourseTitle??"",an=Re?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),Mn=Re?.wizardCourseDescription??e.wizardCourseDescription??"",$n=Re?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Fn=Re?.wizardCourseCategory??e.wizardCourseCategory??"",Tt=Re?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),ln=Re?.wizardCourseTimeline??e.wizardCourseTimeline??[],Wt=Re?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),Bn=Re?.wizardCourseContent??e.wizardCourseContent??"",Un=Re?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),Pt=Re?.wizardIsGeneratingOutline??e.wizardIsGeneratingOutline??!1,cn=Re?.handleGenerateOutline??e.handleGenerateOutline??(async()=>{}),dn=Re?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),_e=e.quizGenerator??t,Vn=_e?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,Hn=_e?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),Wn=_e?.quizGenMode??e.quizGenMode??"scan_lesson",qn=_e?.setQuizGenMode??e.setQuizGenMode??(()=>{}),Gn=_e?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",Qn=_e?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),Jn=_e?.quizGenTopic??e.quizGenTopic??"",Kn=_e?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),Yn=_e?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,Zn=_e?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),Xn=_e?.suggestedObjectives??e.suggestedObjectives??[],es=_e?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),ts=_e?.suggestedQuestions??e.suggestedQuestions??[],ge=_e?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),Ke=_e?.quizGenTimeLimit??e.quizGenTimeLimit??0,qt=_e?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),pe=_e?.savingQuiz??e.savingQuiz??!1,qe=_e?.setSavingQuiz??e.setSavingQuiz??(()=>{}),Ze=_e?.quizGeneratorClassId??e.quizGeneratorClassId??null,Xe=e.classBatch??t,mt=Xe?.batchPicker??e.batchPicker??null,rt=Xe?.setBatchPicker??e.setBatchPicker??(()=>{}),It=Xe?.batchPickerLesson??e.batchPickerLesson??"",Gt=Xe?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),zs=Xe?.batchPickerDate??e.batchPickerDate??"",Wr=Xe?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),Ls=Xe?.batchPickerTargetClass??e.batchPickerTargetClass??"",qr=Xe?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Gr=Xe?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),Rs=e.studentNotificationsHook??t,Qr=Rs?.selectedNotificationForModal??e.selectedNotificationForModal??null,Jr=Rs?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return r.jsxs(f.Suspense,{fallback:null,children:[r.jsx(Vb,{show:i,onClose:()=>o(!1),lang:n,handleImportFile:a,importError:l,importSuccess:c,isImporting:d,downloadCSVTemplate:u}),r.jsx(Hb,{isCourseWizardOpen:rn,setIsCourseWizardOpen:Rn,lang:n,wizardStep:_n,setWizardStep:On,wizardIsSubmitting:on,wizardCourseTitle:Dn,setWizardCourseTitle:an,wizardCourseDescription:Mn,setWizardCourseDescription:$n,wizardCourseCategory:Fn,setWizardCourseCategory:Tt,wizardCourseTimeline:ln,setWizardCourseTimeline:Wt,wizardCourseContent:Bn,setWizardCourseContent:Un,addToast:m,wizardIsGeneratingOutline:Pt,handleGenerateOutline:cn,handleDeployWizardCourse:dn}),r.jsx(Wb,{isImportLessonsOpen:p,setIsImportLessonsOpen:h,lang:n,importStatus:x,setIsDraggingImport:g,handleCSVFileChange:b,handleImportFileChange:w,downloadCsvTemplate:y,downloadCourseTemplate:S,packagePreview:C,handlePackageImportSubmit:k,packageDuplicate:v,handlePackageDuplicateDismiss:N,isDraggingImport:O,previewImportData:D,setPreviewImportData:_,setImportStatus:T,importProgress:z,importProgressTotal:R,importErrorMsg:$,setImportErrorMsg:I,handleCSVImportSubmit:B}),r.jsx(qb,{isQuizGeneratorOpen:Vn,setIsQuizGeneratorOpen:Hn,lessons:H,quizGenMode:Wn,setQuizGenMode:qn,quizGenSelectedLessonId:Gn,setQuizGenSelectedLessonId:Qn,quizGenTopic:Jn,setQuizGenTopic:Kn,isGeneratingSuggestions:Yn,setIsGeneratingSuggestions:Zn,suggestedObjectives:Xn,setSuggestedObjectives:es,suggestedQuestions:ts,setSuggestedQuestions:ge,quizGenTimeLimit:Ke,setQuizGenTimeLimit:qt,savingQuiz:pe,setSavingQuiz:qe,quizGeneratorClassId:Ze,fetchClassDashboard:A}),r.jsx(Gb,{showProcessLogs:G,setShowProcessLogs:E,processLogsContent:W,t:s}),r.jsx(Qb,{isOpen:Y,onClose:()=>K(!1),vfsNodes:V,currentVfsParent:U,setCurrentVfsParent:j,cloudDrivePreviewNode:ne,setCloudDrivePreviewNode:fe}),r.jsx(Jb,{isSystemResourceLibraryOpen:je,setIsSystemResourceLibraryOpen:X,lang:n,systemResourceTab:me,setSystemResourceTab:ke,selectedLibraryResourceId:Se,setSelectedLibraryResourceId:M,vfsNodes:V,currentVfsParent:U,setCurrentVfsParent:j,cloudDrivePreviewNode:ne,setCloudDrivePreviewNode:fe,loadingLibraryResources:Z,libraryResources:ee,fetchLibraryResources:te}),r.jsx(Kb,{batchPicker:mt,setBatchPicker:rt,batchPickerLesson:It,setBatchPickerLesson:Ge=>Gt(typeof Ge=="function"?Ge(It):Ge),batchPickerDate:zs,setBatchPickerDate:Ge=>Wr(typeof Ge=="function"?Ge(zs):Ge),batchPickerTargetClass:Ls,setBatchPickerTargetClass:Ge=>qr(typeof Ge=="function"?Ge(Ls):Ge),lessons:H,classes:ce,expandedClassId:oe,confirmBatchPicker:Gr,lang:n}),r.jsx(Yb,{isExportWeightModalOpen:xe,setIsExportWeightModalOpen:ie,lang:n,quizzesWeight:Pe,setQuizzesWeight:ze,assignmentsWeight:ue,setAssignmentsWeight:re,handleQuizzesWeightChange:P,handleAssignmentsWeightChange:L,customCategoryOverrides:F,setCustomCategoryOverrides:q,classDashboardMap:J,exportClassId:be,exportClassName:se,csvPreviewData:ye,handleExportGrades:$e}),r.jsx(Zb,{notification:Qr,onClose:()=>Jr(null),lang:n,onOpenWorkspace:Ge=>{Fe(Ge),Ce("assignment"),We({}),He("quiz")}}),r.jsx(Xb,{isOpen:Et,onClose:()=>et(!1),lang:n,onSeedSuccess:jt,onJumpTab:Ge=>Vt(Ge)}),Ln&&r.jsx(e0,{onClose:()=>Ht(!1),lang:n})]})}const n0="openlearn_live_classroom_sync";class yd{constructor(t=n0,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=Yo(()=>this.ensureSocketBound())}ensureSocketBound(){if(this.isDestroyed)return;const t=lt();!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=lt();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=lt();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=lt();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=lt();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=lt();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=lt();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=lt();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=lt();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=lt();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 s0(e){const t=await fetch(`/api/students/${e}/read_notifications`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function r0(e,t){await fetch(`/api/students/${e}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:t})})}async function i0(e,t){await fetch(`/api/students/${e}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function o0(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 a0(e){const t=await fetch(`/api/students/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}function l0(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 c0(){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 d0({lessonId:e,lang:t="zh",syncChannel:n}){const[s,i]=f.useState(null),[o,a]=f.useState(!1),[l,c]=f.useState(!0),[d,u]=f.useState(!1),m=f.useRef(s);m.current=s,f.useEffect(()=>{if(!e)return;let y=null,S;try{y=n||new yd,S=y.onMessage(N=>{N.type==="TEACHER_BROADCAST_COUNTDOWN"?i(N.payload):N.type==="TEACHER_SYNC_TIMER"&&i(O=>O?{...O,timeRemaining:N.payload.timeRemaining,isRunning:N.payload.isRunning,endsAt:N.payload.isRunning?Date.now()+N.payload.timeRemaining*1e3:null}:{lessonId:e,totalDuration:Math.max(300,N.payload.timeRemaining),timeRemaining:N.payload.timeRemaining,isRunning:N.payload.isRunning,isPaused:!1,label:t==="zh"?"⏱️ 课堂限时任务":"⏱️ Timed Task",endsAt:N.payload.isRunning?Date.now()+N.payload.timeRemaining*1e3:null,updatedAt:Date.now()})})}catch{}(async()=>{try{const N=await fetch(`/api/classroom/sessions/${e}/countdown`);if(N.ok){const O=await N.json();O.success&&O.countdown&&i(O.countdown)}}catch{}})();let k=null;const v=Yo(N=>{const O=D=>{!D||D.lessonId&&D.lessonId!==e||i(D)};k?.(),N.on("classroom:countdown_updated",O),k=()=>N.off("classroom:countdown_updated",O)});return()=>{S?.(),v(),k?.(),!n&&typeof y?.destroy=="function"&&y.destroy()}},[e,t]),l0("openlearn:countdown:updated",y=>{y&&i(y)});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 y=setInterval(()=>{const S=m.current;if(!S||!S.isRunning||!S.endsAt)return;const C=Date.now(),k=Math.max(0,Math.round((S.endsAt-C)/1e3));if(k!==S.timeRemaining){const v={...S,timeRemaining:k,updatedAt:C};k<=0&&(v.isRunning=!1,v.isPaused=!1,v.endsAt=null,l&&!d&&(c0(),u(!0))),i(v);try{window.dispatchEvent(new CustomEvent("openlearn:student:countdown_tick",{detail:{timeRemaining:k,totalDuration:S.totalDuration,label:S.label}}))}catch{}}},500);return()=>clearInterval(y)},[s?.isRunning,s?.endsAt,l,d]),!s||s.timeRemaining===0&&!s.isRunning&&!d)return null;const h=y=>{const S=Math.floor(y/60),C=y%60,k=v=>v.toString().padStart(2,"0");return`${k(S)}:${k(C)}`},x=s.totalDuration>0?Math.min(100,Math.max(0,s.timeRemaining/s.totalDuration*100)):0,g=s.timeRemaining>0&&s.timeRemaining<=60,b=s.timeRemaining>60&&s.timeRemaining<=180,w=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 ${g?"border-rose-500/80 shadow-rose-500/20":b?"border-amber-500/80 shadow-amber-500/20":w?"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 ${g?"bg-rose-500 animate-pulse":b?"bg-amber-500":w?"bg-emerald-500":"bg-primary-theme"}`,children:r.jsx(Es,{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:()=>c(!l),className:"p-1 rounded-md text-muted hover:text-main text-xs transition-colors cursor-pointer",title:l?"提示音已开启":"提示音已静音",children:l?r.jsx(eg,{size:12}):r.jsx(tg,{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(Nn,{size:12}):r.jsx(ng,{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 ${g?"text-rose-500 animate-pulse":b?"text-amber-500":w?"text-emerald-500":"text-primary-theme"}`,children:h(s.timeRemaining)}),r.jsx("span",{className:"text-[11px] font-semibold text-muted",children:w?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 ${g?"bg-rose-500":b?"bg-amber-500":w?"bg-emerald-500":"bg-primary-theme"}`,style:{width:`${x}%`}})}),r.jsx(Me,{slot:"student.classroom.countdown",slotProps:{countdown:s,lang:t}})]})]})})}const u0=({isOpen:e,onClose:t,lessonId:n,studentName:s="我",lang:i="zh",coreQuestion:o,challengeQuestion:a,onSubmitSuccess:l})=>{const[c,d]=f.useState(null),[u,m]=f.useState(!1),[p,h]=f.useState(null),x=!!o,g=x&&!!a,[b,w]=f.useState(null),[y,S]=f.useState(5),[C,k]=f.useState(""),[v,N]=f.useState(""),[O,D]=f.useState(!1),[_,T]=f.useState(!1),z=()=>{if(!c||!o)return;const I=c===o.correctOption;h(I),m(!0)},R=async()=>{if(O)return;D(!0);const I=x?p?b?"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:y,puzzledConcept:C.trim(),feedback:v.trim(),...x?{coreAnswer:c,isCorrect:p,tierLevel:I,challengeAnswer:b}:{}})}),T(!0),l?.()}catch{T(!0),l?.()}finally{D(!1)}},$=()=>{l?.(),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(at,{size:20}),r.jsx("span",{children:i==="zh"?"60 秒自适应结课通票 (Adaptive Exit Ticket)":"60s Adaptive Exit Ticket"})]}),r.jsx("button",{onClick:$,className:"text-muted hover:text-main rounded-lg p-1 cursor-pointer","aria-label":"Close",children:r.jsx(Oe,{size:18})})]}),_?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(at,{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:$,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(I=>r.jsxs("button",{type:"button",disabled:u,onClick:()=>d(I.key),className:`w-full p-2.5 rounded-xl border text-left flex items-start gap-2.5 transition-all cursor-pointer ${c===I.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:I.key}),r.jsx("span",{className:"text-2xs leading-relaxed",children:I.text})]},I.key))}),!u&&r.jsxs("button",{type:"button",disabled:!c,onClick:z,className:`mt-1 py-1.5 px-3 rounded-xl font-bold text-2xs transition-colors flex items-center justify-center gap-1 ${c?"bg-indigo-600 hover:bg-indigo-700 text-white cursor-pointer shadow-xs":"bg-surface-secondary text-muted cursor-not-allowed"}`,children:[r.jsx("span",{children:"确认本题答案"}),r.jsx(Cn,{size:12})]}),u&&p&&g&&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(yt,{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(I=>r.jsxs("button",{type:"button",onClick:()=>w(I.key),className:`p-2 rounded-lg border text-left text-2xs transition-colors ${b===I.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:[I.key,"."]}),r.jsx("span",{children:I.text})]},I.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(Rr,{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(I=>r.jsx("button",{type:"button",onClick:()=>S(I),"aria-label":`${I} 星`,"aria-pressed":I===y,className:"p-0.5 text-xl transition-transform hover:scale-125 cursor-pointer",children:r.jsx(vr,{size:20,className:I<=y?"text-amber-400 fill-amber-400":"text-slate-300"})},I)),r.jsxs("span",{className:"text-2xs font-bold text-amber-700 dark:text-amber-400 font-mono ml-1",children:[y,".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:C,onChange:I=>k(I.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:v,onChange:I=>N(I.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:O,onClick:R,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:O?i==="zh"?"正在提交...":"Submitting...":i==="zh"?"提交自适应结课通票":"Submit Exit Ticket"})})]})]})}):null};class ro extends Error{constructor(t,n){super(n),this.name="ApiError",this.status=t}}async function Te(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 ro(n.status,i?.error||`HTTP ${n.status}`);return i}const Ot={listQuestionTypes:()=>Te("/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 Te(`/api/assessments${n?`?${n}`:""}`)},get:e=>Te(`/api/assessments/${encodeURIComponent(e)}`),create:e=>Te("/api/assessments",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>Te(`/api/assessments/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)}),remove:e=>Te(`/api/assessments/${encodeURIComponent(e)}`,{method:"DELETE"}),replaceItems:(e,t)=>Te(`/api/assessments/${encodeURIComponent(e)}/items`,{method:"PUT",body:JSON.stringify({items:t})}),listBank:e=>Te(`/api/question-bank${e?`?type=${encodeURIComponent(e)}`:""}`),createBankItem:e=>Te("/api/question-bank",{method:"POST",body:JSON.stringify(e)}),removeBankItem:e=>Te(`/api/question-bank/${encodeURIComponent(e)}`,{method:"DELETE"}),getAssignments:e=>Te(`/api/assessments/${encodeURIComponent(e)}/assignments`),getTeacherView:e=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/teacher-view`),publish:(e,t)=>Te(`/api/assessments/${encodeURIComponent(e)}/publish`,{method:"POST",body:JSON.stringify(t)}),closeAssignment:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/close`,{method:"POST"}),releaseScores:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/release`,{method:"POST"}),syncGradebook:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/sync-gradebook`,{method:"POST"}),getAssignmentProgress:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/progress`),listAttempts:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`),stats:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/stats`),gradeAnswer:(e,t,n)=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/grade`,{method:"PUT",body:JSON.stringify(n)}),aiSuggestGrade:(e,t)=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/ai-suggest`,{method:"POST"}),regrade:e=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/regrade`,{method:"POST"}),exportCsvUrl:e=>`/api/assessment-assignments/${encodeURIComponent(e)}/export?format=csv`,startClassroomAssessment:(e,t)=>Te(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment`,{method:"POST",body:JSON.stringify(t)}),getClassroomAssessmentProgress:(e,t)=>Te(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment-progress${t?`?assignmentId=${encodeURIComponent(t)}`:""}`),myAssessments:()=>Te("/api/me/assessments"),startAttempt:e=>Te(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`,{method:"POST"}),reportProctor:(e,t)=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/proctor`,{method:"PUT",body:JSON.stringify(t)}),saveAnswer:(e,t,n)=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({answer:n})}),submitAttempt:e=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/submit`,{method:"POST"}),attemptResult:e=>Te(`/api/assessment-attempts/${encodeURIComponent(e)}/result`)};class h0{constructor(){this.store=St(()=>({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 kt=new h0,ks="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 f0(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function Cr({htmlFor:e,children:t}){return r.jsx("label",{htmlFor:e,className:"block text-xs font-semibold text-muted mb-1",children:t})}function wd({config:e,answerKey:t,onChange:n,lang:s,disabled:i,multiple:o,idPrefix:a}){const l=f0(e),c=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 x=h?[...new Set([...c,p])].sort((g,b)=>g-b):c.filter(g=>g!==p);n({config:e,answerKey:x.length>0?{indexes:x}: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"}),l.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:c.includes(h),disabled:i,onChange:x=>u(h,x.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:x=>{const g=[...l];g[h]=x.target.value,d(g)},className:ks}),r.jsx("button",{type:"button",disabled:i||l.length<=2,onClick:()=>{const x=l.filter((g,b)=>b!==h);d(x),n({config:{...e,options:x},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(_r,{size:13})})]},h))]}),r.jsxs("button",{type:"button",disabled:i,onClick:()=>d([...l,s==="zh"?`选项 ${m(l.length)}`:`Option ${m(l.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(Bo,{size:12}),s==="zh"?"添加选项":"Add option"]}),c.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 m0=e=>r.jsx(wd,{...e,multiple:!1,idPrefix:`sc-${e.lang}`}),p0=e=>r.jsx(wd,{...e,multiple:!0,idPrefix:`mc-${e.lang}`}),g0=({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 x0(e){const t=e.blanks;return Array.isArray(t)?t:[]}function b0(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 y0=({config:e,answerKey:t,onChange:n,lang:s,disabled:i})=>{const o=x0(e),a=b0(t,o.length),l=(c,d)=>{const u=d.map(h=>h.split("|").map(x=>x.trim()).filter(Boolean)),m=u.some(h=>h.length>0),p=c.map((h,x)=>u[x]??[]);n({config:{...e,blanks:c},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((c,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(Cr,{htmlFor:`fb-accepted-${c.id}`,children:s==="zh"?`第 ${d+1} 空的可接受答案`:`Accepted answers for blank ${d+1}`}),r.jsx("input",{id:`fb-accepted-${c.id}`,type:"text",value:a[d]??"",disabled:i,onChange:u=>{const m=[...a];m[d]=u.target.value,l(o,m)},placeholder:s==="zh"?"光合作用 | photosynthesis":"photosynthesis",className:ks})]}),r.jsxs("div",{children:[r.jsx(Cr,{htmlFor:`fb-type-${c.id}`,children:s==="zh"?"作答类型":"Answer type"}),r.jsxs("select",{id:`fb-type-${c.id}`,value:c.inputType??"text",disabled:i,onChange:u=>{const m=o.map((p,h)=>h===d?{...p,inputType:u.target.value}:p);l(m,a)},className:ks,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);l(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(_r,{size:13})})]},c.id)),r.jsxs("button",{type:"button",disabled:i,onClick:()=>{const c=`b${o.length+1}-${Date.now().toString(36)}`;l([...o,{id:c,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(Bo,{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."})]})},w0=({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(Cr,{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:ks})]}),r.jsxs("div",{children:[r.jsx(Cr,{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:ks})]}),r.jsx("p",{className:"col-span-2 text-xs text-muted",children:n==="zh"?"简答题不自动判分,交卷后进入人工批改队列。":"Short answers are always graded manually."})]}),ea="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 v0(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function S0(e){return String.fromCharCode(65+e)}const vd=({config:e,value:t,onChange:n,lang:s,readOnly:i,multiple:o,name:a})=>{const l=v0(e),c=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"}),l.map((u,m)=>{const p=o?d.includes(m):c===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 x=h.target.checked?[...new Set([...d,m])].sort((g,b)=>g-b):d.filter(g=>g!==m);n(x)}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:[S0(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"})]})},j0=e=>r.jsx(vd,{...e,multiple:!1,name:"answer-single"}),k0=e=>r.jsx(vd,{...e,multiple:!0,name:"answer-multi"}),C0=({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)))]})},N0=({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((l,c)=>r.jsxs("div",{children:[r.jsx("label",{htmlFor:`blank-${l.id}`,className:"block text-2xs font-semibold text-muted mb-1",children:s==="zh"?`第 ${c+1} 空`:`Blank ${c+1}`}),r.jsx("input",{id:`blank-${l.id}`,type:l.inputType==="numeric"?"number":"text",value:String(a[c]??""),disabled:i,placeholder:l.placeholder,onChange:d=>{const u=o.map((m,p)=>p===c?d.target.value:String(a[p]??""));n(u)},className:ea})]},l.id))})},E0=({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:l=>n(l.target.value),className:`${ea} resize-y`}),r.jsxs("p",{className:"text-2xs text-muted mt-1 text-right",children:[a.length,"/",o]})]})},T0=({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:`${ea} resize-y font-mono`})]})},ll=["选项 A","选项 B","选项 C","选项 D"];let cl=!1;function P0(){cl||(cl=!0,kt.register({type:"single_choice",label:{zh:"单选题",en:"Single choice"},category:"objective",supports:["quiz","exam","survey"],Editor:m0,Answer:j0,createDefaultConfig:()=>({options:[...ll]}),createDefaultAnswerKey:()=>({index:0})}),kt.register({type:"multiple_choice",label:{zh:"多选题",en:"Multiple choice"},category:"objective",supports:["quiz","exam","survey"],Editor:p0,Answer:k0,createDefaultConfig:()=>({options:[...ll]}),createDefaultAnswerKey:()=>({indexes:[0]})}),kt.register({type:"true_false",label:{zh:"判断题",en:"True / false"},category:"objective",supports:["quiz","exam","survey"],Editor:g0,Answer:C0,createDefaultConfig:()=>({trueLabel:"正确",falseLabel:"错误"}),createDefaultAnswerKey:()=>({value:!0})}),kt.register({type:"fill_blank",label:{zh:"填空题",en:"Fill in the blank"},category:"objective",supports:["quiz","exam","survey"],Editor:y0,Answer:N0,createDefaultConfig:()=>({blanks:[{id:"b1",inputType:"text"}]}),createDefaultAnswerKey:()=>null}),kt.register({type:"short_answer",label:{zh:"简答/论述",en:"Short answer"},category:"subjective",supports:["quiz","exam","survey"],Editor:w0,Answer:E0,createDefaultConfig:()=>({placeholder:"请输入你的作答",maxLength:2e3}),createDefaultAnswerKey:()=>null}))}P0();const I0=1500;function A0(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 dl(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 z0({lang:e,onExit:t}){const n=e==="zh",[s,i]=f.useState({mode:"list"}),[o,a]=f.useState(null),[l,c]=f.useState(!1),[d,u]=f.useState(null),m=f.useCallback(async()=>{c(!0),u(null);try{const g=await Ot.myAssessments();a(g.items)}catch(g){u(g instanceof ro?g.message:String(g?.message??g))}finally{c(!1)}},[]);f.useEffect(()=>{s.mode==="list"&&m()},[s.mode,m]);const p=async g=>{u(null),c(!0);try{if(g.completed&&g.attempt){const b=await Ot.attemptResult(g.attempt.id);i({mode:"result",result:b})}else{const b=await Ot.startAttempt(g.assignmentId);i({mode:"answering",payload:b,answers:{...b.answers}})}}catch(b){u(b instanceof ro?b.message:String(b?.message??b))}finally{c(!1)}};if(s.mode==="answering")return r.jsx(ta,{lang:e,payload:s.payload,initialAnswers:s.answers,onSubmitted:g=>i({mode:"result",result:g}),onExit:()=>i({mode:"list"})});if(s.mode==="result")return r.jsx(na,{lang:e,result:s.result,onBack:()=>{i({mode:"list"}),m()}});const h=(o??[]).filter(g=>!g.completed),x=(o??[]).filter(g=>g.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(Uo,{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(Ss,{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:l,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(Lr,{size:13,className:l?"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&&l?r.jsxs("p",{className:"text-xs text-muted flex items-center gap-2",children:[r.jsx($t,{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(Ss,{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(g=>r.jsx("li",{children:r.jsx(ul,{entry:g,lang:e,disabled:l,onOpen:()=>void p(g)})},g.assignmentId))})]}),x.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","(",x.length,")"]}),r.jsx("ul",{"data-testid":"student-completed-list",className:"space-y-2",children:x.map(g=>r.jsx("li",{children:r.jsx(ul,{entry:g,lang:e,disabled:l,onOpen:()=>void p(g)})},g.assignmentId))})]})]})})]})}function ul({entry:e,lang:t,disabled:n,onOpen:s}){const i=t==="zh",o=e.windowState==="after_close",a=e.windowState==="before_open",l=!e.completed&&(o||a),c=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:c}),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(Es,{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||l,className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold shrink-0 ${l?"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:[!l&&!e.completed&&r.jsx(Ro,{size:12}),l?o?i?"已截止":"Closed":i?"未开始":"Not open":e.completed?i?"查看结果":"View result":i?"开始作答":"Start"]})]})}function ta({lang:e,payload:t,initialAnswers:n,onSubmitted:s,onExit:i}){const o=e==="zh",a=t.attempt.id,l=t.assignment.kind==="exam"||!!t.assignment.settings?.strictProctor,[c,d]=f.useState(n),[u,m]=f.useState(new Set),[p,h]=f.useState(t.attempt.remainingSeconds??null),[x,g]=f.useState(!1),[b,w]=f.useState(null),[y,S]=f.useState(null),[C,k]=f.useState(!!document.fullscreenElement),[v,N]=f.useState(0),[O,D]=f.useState(null),_=f.useRef({}),T=f.useRef(c),z=f.useRef(!1);T.current=c;const R=f.useCallback(async j=>{if(!(!l||z.current))try{N(G=>G+1),D({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 Ot.reportProctor(a,{type:j})}catch{}},[a,l,o]);f.useEffect(()=>{if(!l)return;const j=()=>{document.visibilityState==="hidden"&&R("visibility_hidden")},V=()=>{R("blur")},G=()=>{const Y=!!document.fullscreenElement;k(Y),!Y&&!z.current&&R("fullscreen_exit")},E=Y=>{Y.preventDefault()},W=Y=>{Y.preventDefault()};return document.addEventListener("visibilitychange",j),window.addEventListener("blur",V),document.addEventListener("fullscreenchange",G),document.addEventListener("contextmenu",E),document.addEventListener("copy",W),document.addEventListener("cut",W),document.addEventListener("paste",W),()=>{document.removeEventListener("visibilitychange",j),window.removeEventListener("blur",V),document.removeEventListener("fullscreenchange",G),document.removeEventListener("contextmenu",E),document.removeEventListener("copy",W),document.removeEventListener("cut",W),document.removeEventListener("paste",W)}},[l,R]);const $=async()=>{try{document.fullscreenElement||await document.documentElement.requestFullscreen()}catch{}},I=f.useCallback(async j=>{try{await Ot.saveAnswer(a,j,T.current[j]??null),S(Date.now()),m(V=>{const G=new Set(V);return G.delete(j),G})}catch(V){w(V?.message??String(V))}},[a]),B=(j,V)=>{d(G=>({...G,[j]:V})),m(G=>new Set(G).add(j)),_.current[j]&&clearTimeout(_.current[j]),_.current[j]=setTimeout(()=>void I(j),I0)},H=f.useCallback(async()=>{if(!z.current){z.current=!0,g(!0),w(null);try{for(const G of Object.keys(_.current))_.current[G]&&clearTimeout(_.current[G]);const j=[...u];await Promise.all(j.map(G=>Ot.saveAnswer(a,G,T.current[G]??null)));const V=await Ot.submitAttempt(a);document.fullscreenElement&&document.exitFullscreen().catch(()=>{}),s(V)}catch(j){z.current=!1,w(j?.message??String(j))}finally{g(!1)}}},[a,u,s]);f.useEffect(()=>{if(p===null)return;if(p<=0){H();return}const j=setTimeout(()=>h(V=>V===null?null:V-1),1e3);return()=>clearTimeout(j)},[p,H]),f.useEffect(()=>()=>{Object.values(_.current).forEach(j=>clearTimeout(j))},[]);const A=f.useMemo(()=>[...t.items].sort((j,V)=>j.sortOrder-V.sortOrder),[t.items]),U=A.filter(j=>{const V=c[j.id];return V==null||V===""?!1:Array.isArray(V)?V.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 ${l?"select-none":""}`,children:[l&&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,V)=>r.jsxs("div",{className:"transform -rotate-25 text-xs font-mono font-bold tracking-widest text-main",children:[t.assignment.title," · #",a.slice(-6)]},V))}),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:[!l&&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(Uo,{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}),l&&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,"/",A.length,y&&` · ${o?"已自动保存":"autosaved"}`,u.size>0&&` · ${o?"保存中…":"saving…"}`,l&&v>0&&r.jsx("span",{className:"text-rose-600 font-semibold ml-2",children:o?`异常记录 ${v} 次`:`Violations: ${v}`})]})]}),l&&!C&&r.jsx("button",{type:"button",onClick:()=>void $(),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(Es,{size:12}),A0(p)]}),r.jsxs("button",{type:"button",onClick:()=>void H(),disabled:x,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:[x?r.jsx($t,{size:13,className:"animate-spin"}):r.jsx(at,{size:13}),o?"提交交卷":"Submit"]}),r.jsx(Me,{slot:"assessment.attempt.toolbar",slotProps:{assignmentId:t.assignment.id,attemptId:a,lang:e},lang:e})]}),O&&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:["⚠️ ",O]}),r.jsx("button",{type:"button",onClick:()=>D(null),className:"text-2xs font-bold underline cursor-pointer",children:o?"知道了":"Dismiss"})]}),b&&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:b}),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:A.map((j,V)=>{const E=kt.get(j.type)?.Answer??T0;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:["#",V+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(E,{config:j.config,value:c[j.id],onChange:W=>B(j.id,W),lang:e})]},j.id)})})})]})}function na({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(Uo,{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,l)=>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:["#",l+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(at,{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:"}),dl(a.answer)]}),t.showAnalysis&&a.answerKey!==void 0&&a.answerKey!==null&&r.jsxs("p",{className:"text-2xs text-muted",children:[s?"参考答案:":"Reference answer:"," ",dl(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(Mt,{size:11}),s?"成绩尚未正式发布。":"Scores are not officially released yet."]})]})]})}const NN=Object.freeze(Object.defineProperty({__proto__:null,AssessmentRunner:ta,ResultView:na,StudentAssessmentsView:z0},Symbol.toStringTag,{value:"Module"}));function L0({lessonId:e,studentId:t,studentName:n="我",lang:s="zh"}){const[i,o]=f.useState(null),[a,l]=f.useState(null),[c,d]=f.useState("IN_CLASS_TEACHING"),[u,m]=f.useState(null),[p,h]=f.useState({}),[x,g]=f.useState(null),[b,w]=f.useState(null),[y,S]=f.useState(!1),[C,k]=f.useState("IDLE"),[v,N]=f.useState(null),[O,D]=f.useState(null),[_,T]=f.useState(!1),[z,R]=f.useState(!1),[$,I]=f.useState(null),[B,H]=f.useState(null),[A,U]=f.useState(5),[j,V]=f.useState(""),[G,E]=f.useState(""),[W,Y]=f.useState(null),[K,ne]=f.useState("closed"),[fe,je]=f.useState(null),[X,me]=f.useState(null),[ke,Se]=f.useState(!1),[M,Z]=f.useState(null),ee=f.useRef(Date.now()),te=f.useRef(null),ce=f.useRef(0),oe=f.useRef(0),xe=f.useRef(null),ie=f.useRef(null),Pe=f.useRef(!1);f.useEffect(()=>{if(!e)return;let L=!0;const F=async()=>{const J=++ce.current;try{const be=await fetch(`/api/classroom/sessions/${e}`);if(be.ok&&L){const se=await be.json();if(se.hasActiveSession){if(d(se.stage),se.session?.current_segment_id&&m(se.session.current_segment_id),se.stage==="WRAP_UP_EXIT_TICKET"&&!Pe.current&&T(!0),se.exitTicketCoreQuestion!==void 0&&I(se.exitTicketCoreQuestion),se.exitTicketChallengeQuestion!==void 0&&H(se.exitTicketChallengeQuestion),se.activeCountdown)try{window.dispatchEvent(new CustomEvent("openlearn:countdown:updated",{detail:se.activeCountdown}))}catch{}se.activePoll&&(!xe.current||xe.current.id!==se.activePoll.id)?(xe.current=se.activePoll,o(se.activePoll),w(null),S(!1)):!se.activePoll&&xe.current&&(xe.current=null,o(null));const ye=ie.current;if(se.activeBuzzer)if(!ye||ye.id!==se.activeBuzzer.id)ie.current=se.activeBuzzer,l(se.activeBuzzer),k("IDLE"),N(null),te.current=null,ee.current=Date.now();else if(se.activeBuzzer.status==="LOCKED"){const Fe=te.current,Ce=Fe&&Fe.buzzerId===se.activeBuzzer.id?Fe.status:t&&se.activeBuzzer.winner_student_id===t?"WINNER":"MISSED";te.current={buzzerId:se.activeBuzzer.id,status:Ce},ie.current=se.activeBuzzer,k(Ce),l(se.activeBuzzer)}else se.activeBuzzer.status==="READY"&&!(J<=oe.current)&&te.current?.buzzerId===se.activeBuzzer.id&&(te.current=null,ie.current=se.activeBuzzer,k("IDLE"),l(se.activeBuzzer),N(null),ee.current=Date.now());else ye&&(ie.current=null,l(null),k("IDLE"),te.current=null)}}}catch{}};F();const q=setInterval(F,2500);return()=>{L=!1,clearInterval(q)}},[e,t]),f.useEffect(()=>{const L=lt();if(!L||!e)return;const F=J=>{J?.lessonId===e&&J?.activeSegmentId&&m(J.activeSegmentId)},q=J=>{J?.lessonId===e&&J?.assignmentId&&(Y({assignmentId:J.assignmentId,title:J.title||(s==="zh"?"随堂测评":"Classroom Assessment"),kind:J.kind||"quiz",durationSec:J.durationSec??null,totalItems:J.totalItems??0,maxScore:J.maxScore??0}),ne("prompt"))};return L.on("student-active-segment-changed",F),L.on("classroom:assessment_started",q),()=>{typeof L.off=="function"&&(L.off("student-active-segment-changed",F),L.off("classroom:assessment_started",q))}},[e,s]);const ze=async()=>{if(W){Se(!0),Z(null);try{const L=await Ot.startAttempt(W.assignmentId);je(L),ne("answering")}catch(L){Z(L?.message||String(L))}finally{Se(!1)}}};if(f.useEffect(()=>{e&&fetch(`/api/lessons/${e}`).then(L=>L.ok?L.json():null).then(L=>{if(L?.timeline)try{const F=typeof L.timeline=="string"?JSON.parse(L.timeline):L.timeline;if(Array.isArray(F)){const q={};F.forEach(J=>{J?.id&&J?.title&&(q[J.id]=J.title)}),h(q)}}catch{}}).catch(()=>{})},[e]),f.useEffect(()=>{if(!e)return;fetch(`/api/classroom/sessions/${e}/pacing-summary?segmentId=${encodeURIComponent(u||"default")}`).then(F=>F.ok?F.json():null).then(F=>{F?.success&&g(F.mySignal||null)}).catch(()=>{})},[e,u]),!e)return null;const ue=async L=>{try{const F=x===L,q=await fetch(`/api/classroom/sessions/${e}/pacing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signal:F?null:L,action:F?"cancel":void 0,toggle:!0,segmentId:u||"default"})});if(q.ok){const J=await q.json();g(J.currentSignal??null),J.currentSignal?D(L==="TOO_FAST"?s==="zh"?"已反馈: 🐇 讲太快":"Pacing: Too Fast":L==="SLOW"?s==="zh"?"已反馈: 🐢 讲太慢":"Pacing: Too Slow":L==="CONFUSED"?s==="zh"?"已反馈: ❓ 有疑问":"Pacing: Confused":s==="zh"?"已反馈: 💡 听懂了":"Pacing: Clear"):D(s==="zh"?"已取消反馈":"Feedback cleared"),setTimeout(()=>D(null),2500)}}catch{}},re=async L=>{if(!(!i||y))try{w(L),S(!0),await fetch(`/api/classroom/sessions/${e}/quick-poll/${i.id}/vote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({option:L})})}catch{}},P=async()=>{if(!a||a.status!=="READY"||C!=="IDLE")return;const L=Date.now()-ee.current;oe.current=ce.current,k("BUZZED");try{const F=await fetch(`/api/classroom/sessions/${e}/buzzer/${a.id}/buzz`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentName:n,responseTimeMs:L})});if(F.ok){const q=await F.json(),J=q.won??q.winner===!0,be=J?"WINNER":"MISSED";if(te.current={buzzerId:a.id,status:be},k(be),!J&&q.winner){const se={...a,status:"LOCKED",winner_student_id:q.winner.studentId??null,winner_student_name:q.winner.studentName??null,winner_response_time_ms:q.winner.responseTimeMs??null};ie.current=se,l(se)}}else k("IDLE")}catch{k("IDLE")}};return r.jsxs(r.Fragment,{children:[r.jsx(d0,{lessonId:e,lang:s}),r.jsx(Me,{slot:"student.classroom.overlay",slotProps:{studentId:t,lessonId:e}}),r.jsx(Me,{slot:"student.fullscreen",slotProps:{studentId:t,lessonId:e}}),r.jsxs("aside",{"aria-label":s==="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:u&&p[u]?p[u]:s==="zh"?"当前环节":"Current Segment"})]}),O&&r.jsx("span",{className:"text-2xs font-bold text-primary-ink px-1.5 py-0.5 animate-fade-in whitespace-nowrap",children:O}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{type:"button",onClick:()=>ue("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:s==="zh"?"听懂了,节奏适宜(再次点击取消)":"Clear & Optimal (Click again to cancel)",children:[r.jsx("span",{children:"💡"}),r.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"听懂了":"Clear"}),x==="CLEAR"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",onClick:()=>ue("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:s==="zh"?"有点困惑,希望老师点拨(再次点击取消)":"Confused (Click again to cancel)",children:[r.jsx("span",{children:"❓"}),r.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"有疑问":"Confused"}),x==="CONFUSED"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",onClick:()=>ue("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:s==="zh"?"讲得太快了,希望能慢一点(再次点击取消)":"Too fast (Click again to cancel)",children:[r.jsx("span",{children:"🐇"}),r.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太快":"Too Fast"}),x==="TOO_FAST"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",onClick:()=>ue("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:s==="zh"?"讲太慢了,希望快一点(再次点击取消)":"Too slow (Click again to cancel)",children:[r.jsx("span",{children:"🐢"}),r.jsx("span",{className:"hidden sm:inline",children:s==="zh"?"讲太慢":"Too Slow"}),x==="SLOW"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]})]})]}),i&&i.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(yt,{size:14}),s==="zh"?"极速答题进行中":"Quick Poll Active"]}),y&&r.jsxs("span",{className:"text-[11px] text-emerald-700 dark:text-emerald-400 font-bold flex items-center gap-1",children:[r.jsx(at,{size:12}),s==="zh"?"已提交":"Submitted"]})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:i.title}),r.jsx("div",{className:"grid grid-cols-2 gap-2 mt-1",children:(i.options||["A","B","C","D"]).map(L=>{const F=b===L;return r.jsx("button",{disabled:y,onClick:()=>re(L),className:`p-3 rounded-xl font-bold text-center text-sm transition-all cursor-pointer ${F?"bg-primary-solid text-white ring-2 ring-primary-theme shadow-md scale-95":y?"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:L},L)})})]}),a&&v!==a.id&&r.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4",onClick:()=>N(a.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:L=>L.stopPropagation(),children:[r.jsx("button",{onClick:()=>N(a.id),"aria-label":s==="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(Oe,{size:18})}),r.jsxs("h3",{className:"text-xl font-black text-foreground flex items-center gap-2",children:[r.jsx($o,{size:22,className:"text-rose-700 dark:text-rose-400 animate-bounce"}),r.jsx("span",{children:a.title||"全班极速抢答"})]}),C==="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:"请稍候,马上公布结果"})]}),C==="IDLE"&&a.status==="READY"&&r.jsxs("div",{className:"my-4 flex flex-col items-center gap-3",children:[r.jsxs("button",{onClick:P,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(rg,{size:32,className:"mb-1"}),r.jsx("span",{children:"抢!"})]}),r.jsx("span",{className:"text-xs text-muted",children:"点击红色大按钮抢得首答权"})]}),C==="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:()=>N(a.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:s==="zh"?"知道了,返回课堂":"Got it, back to class"})]}),C==="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:["已被 ",a.winner_student_name||"其他同学"," 抢先一步!"]}),r.jsx("span",{className:"text-xs text-muted mt-1",children:"下次手速要更快哦"}),r.jsx("button",{onClick:()=>N(a.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:s==="zh"?"知道了,返回课堂":"Got it, back to class"})]})]})}),r.jsx(u0,{isOpen:_,onClose:()=>T(!1),lessonId:e,studentName:n,lang:s,coreQuestion:$,challengeQuestion:B,onSubmitSuccess:()=>{Pe.current=!0,R(!0)}}),W&&K==="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(Ss,{size:14}),s==="zh"?"随堂测评已发起":"Classroom Assessment"]}),r.jsx("button",{onClick:()=>ne("closed"),"aria-label":s==="zh"?"关闭":"Close",className:"p-1 rounded-lg text-muted hover:text-foreground cursor-pointer",children:r.jsx(Oe,{size:14})})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:W.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:W.kind==="exam"?s==="zh"?"考试":"Exam":W.kind==="survey"?s==="zh"?"问卷":"Survey":s==="zh"?"测试":"Quiz"}),r.jsxs("span",{children:[W.totalItems," ",s==="zh"?"道题":"items"]}),r.jsxs("span",{children:[s==="zh"?"满分":"Total"," ",W.maxScore]}),W.durationSec&&r.jsxs("span",{className:"inline-flex items-center gap-1",children:[r.jsx(Es,{size:11}),Math.round(W.durationSec/60)," ",s==="zh"?"分钟":"min"]})]}),M&&r.jsx("p",{className:"text-2xs text-rose-600 bg-rose-50 dark:bg-rose-950/40 p-1.5 rounded-lg",children:M}),r.jsxs("button",{type:"button",onClick:()=>void ze(),disabled:ke,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:[ke?r.jsx("span",{className:"animate-spin text-xs",children:"⏳"}):r.jsx(Ro,{size:13}),s==="zh"?"立即开始作答":"Start Assessment"]})]}),K==="answering"&&fe&&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(ta,{lang:s,payload:fe,initialAnswers:fe.answers,onSubmitted:L=>{me(L),ne("result")},onExit:()=>ne("closed")})})}),K==="result"&&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(na,{lang:s,result:X,onBack:()=>{ne("closed"),Y(null),je(null),me(null)}})})})]})}function R0(e){const t=nn(),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",l=e.selectedLesson!==void 0?e.selectedLesson:t?.selectedLesson??null,c=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,x=e.addToast??t?.addToast??(()=>{}),g=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(yt,{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(Oe,{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(yt,{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 yd(void 0,l,c);if(b.acknowledgePick(i.studentId),b.destroy(),i.rollcallId){const w=i.rollcallId;d&&r0(d,w).catch(console.error),g(y=>new Set(y).add(w))}o?.(null),x(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(at,{size:20}),r.jsx("span",{children:a==="zh"?"🙋♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋♂️ Ready / Acknowledge to Teacher"})]})})]})}),(m==="student"||p)&&r.jsx(L0,{lessonId:l,studentId:d||h||void 0,studentName:u.find(b=>b.id===(d||h))?.name||void 0,lang:a})]})}const sa=f.createContext({});function ra(e){const t=f.useRef(null);return t.current===null&&(t.current=e()),t.current}const _0=typeof window<"u",Sd=_0?f.useLayoutEffect:f.useEffect,Mr=f.createContext(null),ia=f.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function hl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function O0(...e){return t=>{let n=!1;const s=e.map(i=>{const o=hl(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():hl(e[i],null)}}}}function D0(...e){return f.useCallback(O0(...e),e)}class M0 extends f.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Zr(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,i=Zr(s)&&s.offsetWidth||0,o=Zr(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=i-l.width-l.left,l.bottom=o-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function $0({children:e,isPresent:t,anchorX:n,anchorY:s,root:i,pop:o}){const a=f.useId(),l=f.useRef(null),c=f.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:d}=f.useContext(ia),u=e.props?.ref??e?.ref,m=D0(l,u);return f.useInsertionEffect(()=>{const{width:p,height:h,top:x,left:g,right:b,bottom:w,direction:y}=c.current;if(t||o===!1||!l.current||!p||!h)return;const S=y==="rtl",C=n==="left"?S?`right: ${b}`:`left: ${g}`:S?`left: ${g}`:`right: ${b}`,k=s==="bottom"?`bottom: ${w}`:`top: ${x}`;l.current.dataset.motionPopId=a;const v=document.createElement("style");d&&(v.nonce=d);const N=i??document.head;return N.appendChild(v),v.sheet&&v.sheet.insertRule(`
|
|
13
|
+
[data-motion-pop-id="${a}"] {
|
|
14
|
+
position: absolute !important;
|
|
15
|
+
width: ${p}px !important;
|
|
16
|
+
height: ${h}px !important;
|
|
17
|
+
${C}px !important;
|
|
18
|
+
${k}px !important;
|
|
19
|
+
}
|
|
20
|
+
`),()=>{l.current?.removeAttribute("data-motion-pop-id"),N.contains(v)&&N.removeChild(v)}},[t]),r.jsx(M0,{isPresent:t,childRef:l,sizeRef:c,pop:o,children:o===!1?e:f.cloneElement(e,{ref:m})})}const F0=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:i,presenceAffectsLayout:o,mode:a,anchorX:l,anchorY:c,root:d})=>{const u=ra(B0),m=f.useId();let p=!0,h=f.useMemo(()=>(p=!1,{id:m,initial:t,isPresent:n,custom:i,onExitComplete:x=>{u.set(x,!0);for(const g of u.values())if(!g)return;s&&s()},register:x=>(u.set(x,!1),()=>u.delete(x))}),[n,u,s]);return o&&p&&(h={...h}),f.useMemo(()=>{u.forEach((x,g)=>u.set(g,!1))},[n]),f.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),e=r.jsx($0,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:d,children:e}),r.jsx(Mr.Provider,{value:h,children:e})};function B0(){return new Map}function jd(e=!0){const t=f.useContext(Mr);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 Fs=e=>e.key||"";function fl(e){const t=[];return f.Children.forEach(e,n=>{f.isValidElement(n)&&t.push(n)}),t}const kd=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:i=!0,mode:o="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:d})=>{const[u,m]=jd(a),p=f.useMemo(()=>fl(e),[e]),h=a&&!u?[]:p.map(Fs),x=f.useRef(!0),g=f.useRef(p),b=ra(()=>new Map),w=f.useRef(new Set),[y,S]=f.useState(p),[C,k]=f.useState(p);Sd(()=>{x.current=!1,g.current=p;for(let O=0;O<C.length;O++){const D=Fs(C[O]);h.includes(D)?(b.delete(D),w.current.delete(D)):b.get(D)!==!0&&b.set(D,!1)}},[C,h.length,h.join("-")]);const v=[];if(p!==y){let O=[...p];for(let D=0;D<C.length;D++){const _=C[D],T=Fs(_);h.includes(T)||(O.splice(D,0,_),v.push(_))}return o==="wait"&&v.length&&(O=v),k(fl(O)),S(p),null}const{forceRender:N}=f.useContext(sa);return r.jsx(r.Fragment,{children:C.map(O=>{const D=Fs(O),_=a&&!u?!1:p===C||h.includes(D),T=()=>{if(w.current.has(D))return;if(b.has(D))w.current.add(D),b.set(D,!0);else return;let z=!0;b.forEach(R=>{R||(z=!1)}),z&&(N?.(),k(g.current),a&&m?.(),s&&s())};return r.jsx(F0,{isPresent:_,initial:!x.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:d,onExitComplete:_?void 0:T,anchorX:l,anchorY:c,children:O},D)})})},Cd=f.createContext({strict:!1}),ml={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let pl=!1;function U0(){if(pl)return;const e={};for(const t in ml)e[t]={isEnabled:n=>ml[t].some(s=>!!n[s])};nd(e),pl=!0}function Nd(){return U0(),dg()}function V0(e){const t=Nd();for(const n in e)t[n]={...t[n],...e[n]};nd(t)}const H0=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 Nr(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||H0.has(e)}let Ed=e=>!Nr(e);function W0(e){typeof e=="function"&&(Ed=t=>t.startsWith("on")?!Nr(t):e(t))}try{W0(require("@emotion/is-prop-valid").default)}catch{}function q0(e,t,n){const s={};for(const i in e)i==="values"&&typeof e.values=="object"||Ho(e[i])||(Ed(i)||n===!0&&Nr(i)||!t&&!Nr(i)||e.draggable&&i.startsWith("onDrag"))&&(s[i]=e[i]);return s}const $r=f.createContext({});function G0(e,t){if(sd(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Wa(n)?n:void 0,animate:Wa(s)?s:void 0}}return e.inherit!==!1?t:{}}function Q0(e){const{initial:t,animate:n}=G0(e,f.useContext($r));return f.useMemo(()=>({initial:t,animate:n}),[gl(t),gl(n)])}function gl(e){return Array.isArray(e)?e.join(" "):e}const oa=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Td(e,t,n){for(const s in t)!Ho(t[s])&&!ug(s,n)&&(e[s]=t[s])}function J0({transformTemplate:e},t){return f.useMemo(()=>{const n=oa();return hg(n,t,e),Object.assign({},n.vars,n.style)},[t])}function K0(e,t){const n=e.style||{},s={};return Td(s,n,e),Object.assign(s,J0(e,t)),s}function Y0(e,t){const n={},s=K0(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 Pd=()=>({...oa(),attrs:{}});function Z0(e,t,n,s){const i=f.useMemo(()=>{const o=Pd();return fg(o,t,mg(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Td(o,e.style,e),i.style={...o,...i.style}}return i}const X0=["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 aa(e){return typeof e!="string"||e.includes("-")?!1:!!(X0.indexOf(e)>-1||/[A-Z]/u.test(e))}function ey(e,t,n,{latestValues:s},i,o=!1,a){const c=(a??aa(e)?Z0:Y0)(t,s,i,e),d=q0(t,typeof e=="string",o),u=e!==f.Fragment?{...d,...c,ref:n}:{},{children:m}=t,p=f.useMemo(()=>Ho(m)?m.get():m,[m]);return f.createElement(e,{...u,children:p})}function ty({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,i){return{latestValues:ny(n,s,i,e),renderState:t()}}function ny(e,t,n,s){const i={},o=s(e,{});for(const p in o)i[p]=pg(o[p]);let{initial:a,animate:l}=e;const c=sd(e),d=gg(e);t&&d&&!c&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let u=n?n.initial===!1:!1;u=u||a===!1;const m=u?l:a;if(m&&typeof m!="boolean"&&!rd(m)){const p=Array.isArray(m)?m:[m];for(let h=0;h<p.length;h++){const x=xg(e,p[h]);if(x){const{transitionEnd:g,transition:b,...w}=x;for(const y in w){let S=w[y];if(Array.isArray(S)){const C=u?S.length-1:0;S=S[C]}S!==null&&(i[y]=S)}for(const y in g)i[y]=g[y]}}}return i}const Id=e=>(t,n)=>{const s=f.useContext($r),i=f.useContext(Mr),o=()=>ty(e,t,s,i);return n?o():ra(o)},sy=Id({scrapeMotionValuesFromProps:bg,createRenderState:oa}),ry=Id({scrapeMotionValuesFromProps:yg,createRenderState:Pd}),iy=Symbol.for("motionComponentSymbol");function oy(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 l=a(o);typeof l=="function"&&(i.current=l)}else i.current?(i.current(),i.current=null):a(o);else a&&(a.current=o)},[t])}const Ad=f.createContext({});function bn(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ay(e,t,n,s,i,o){const{visualElement:a}=f.useContext($r),l=f.useContext(Cd),c=f.useContext(Mr),d=f.useContext(ia),u=d.reducedMotion,m=d.skipAnimations,p=f.useRef(null),h=f.useRef(!1);s=s||l.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:m,isSVG:o}),h.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const x=p.current,g=f.useContext(Ad);x&&!x.projection&&i&&(x.type==="html"||x.type==="svg")&&ly(p.current,n,i,g);const b=f.useRef(!1);f.useInsertionEffect(()=>{x&&b.current&&x.update(n,c)});const w=n[wg],y=f.useRef(!!w&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(w)&&window.MotionHasOptimisedAnimation?.(w));return Sd(()=>{h.current=!0,x&&(b.current=!0,window.MotionIsMounted=!0,x.updateFeatures(),x.scheduleRenderMicrotask(),y.current&&x.animationState&&x.animationState.animateChanges())}),f.useEffect(()=>{x&&(!y.current&&x.animationState&&x.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(w)}),y.current=!1),x.enteringChildren=void 0)}),x}function ly(e,t,n,s){const{layoutId:i,layout:o,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:m}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:zd(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!a||l&&bn(l),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:m,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function zd(e){if(e)return e.options.allowProjection!==!1?e.projection:zd(e.parent)}function xi(e,{forwardMotionProps:t=!1,type:n}={},s,i){s&&V0(s);const o=n?n==="svg":aa(e),a=o?ry:sy;function l(d,u){let m;const p={...f.useContext(ia),...d,layoutId:cy(d)},{isStatic:h}=p,x=Q0(d),g=a(d,h);if(!h&&typeof window<"u"){dy();const b=uy(p);m=b.MeasureLayout,x.visualElement=ay(e,g,p,i,b.ProjectionNode,o)}return r.jsxs($r.Provider,{value:x,children:[m&&x.visualElement?r.jsx(m,{visualElement:x.visualElement,...p}):null,ey(e,d,oy(g,x.visualElement,u),g,h,t,o)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=f.forwardRef(l);return c[iy]=e,c}function cy({layoutId:e}){const t=f.useContext(sa).id;return t&&e!==void 0?t+"-"+e:e}function dy(e,t){f.useContext(Cd).strict}function uy(e){const t=Nd(),{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 hy(e,t){if(typeof Proxy>"u")return xi;const n=new Map,s=(o,a)=>xi(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,xi(a,void 0,e,t)),n.get(a))})}const fy=(e,t)=>t.isSVG??aa(e)?new vg(t):new Sg(t,{allowProjection:e!==f.Fragment});class my extends Bt{constructor(t){super(t),t.animationState||(t.animationState=jg(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();rd(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 py=0;class gy extends Bt{constructor(){super(...arguments),this.id=py++,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 l=kg(this.node,o,a);if(l){const{transition:c,transitionEnd:d,...u}=l;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 xy={animation:{Feature:my},exit:{Feature:gy}};function Ts(e){return{point:{x:e.pageX,y:e.pageY}}}const by=e=>t=>id(t)&&e(t,Ts(t));function gs(e,t,n,s){return Sr(e,t,by(n),s)}const Ld=({current:e})=>e?e.ownerDocument.defaultView:null,xl=(e,t)=>Math.abs(e-t);function yy(e,t){const n=xl(e.x,t.x),s=xl(e.y,t.y);return Math.sqrt(n**2+s**2)}const bl=new Set(["auto","scroll"]);class Rd{constructor(t,n,{transformPagePoint:s,contextWindow:i=window,dragSnapToOrigin:o=!1,distanceThreshold:a=3,element:l}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=h=>{this.handleScroll(h.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Bs(this.lastRawMoveEventInfo,this.transformPagePoint));const h=bi(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,g=yy(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!g)return;const{point:b}=h,{timestamp:w}=qa;this.history.push({...b,timestamp:w});const{onStart:y,onMove:S}=this.handlers;x||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,h)},this.handlePointerMove=(h,x)=>{this.lastMoveEvent=h,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Bs(x,this.transformPagePoint),ft.update(this.updatePoint,!0)},this.handlePointerUp=(h,x)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:w}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=bi(h.type==="pointercancel"?this.lastMoveEventInfo:Bs(x,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,y),b&&b(h,y)},!id(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=i||window;const c=Ts(t),d=Bs(c,this.transformPagePoint),{point:u}=d,{timestamp:m}=qa;this.history=[{...u,timestamp:m}];const{onSessionStart:p}=n;p&&p(t,bi(d,this.history)),this.removeListeners=od(gs(this.contextWindow,"pointermove",this.handlePointerMove),gs(this.contextWindow,"pointerup",this.handlePointerUp),gs(this.contextWindow,"pointercancel",this.handlePointerUp)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(bl.has(s.overflowX)||bl.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(),Cg(this.updatePoint)}}function Bs(e,t){return t?{point:t(e.point)}:e}function yl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function bi({point:e},t){return{point:e,delta:yl(e,_d(t)),offset:yl(e,wy(t)),velocity:vy(t,.1)}}function wy(e){return e[0]}function _d(e){return e[e.length-1]}function vy(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const i=_d(e);for(;n>=0&&(s=e[n],!(i.timestamp-s.timestamp>Ga(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&i.timestamp-s.timestamp>Ga(t)*2&&(s=e[1]);const o=Ng(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 Sy(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?jr(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?jr(n,e,s.max):Math.min(e,n)),e}function wl(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 jy(e,{top:t,left:n,bottom:s,right:i}){return{x:wl(e.x,n,i),y:wl(e.y,t,s)}}function vl(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 ky(e,t){return{x:vl(e.x,t.x),y:vl(e.y,t.y)}}function Cy(e,t){let n=.5;const s=eo(e),i=eo(t);return i>s?n=Qa(t.min,t.max-s,e.min):s>i&&(n=Qa(e.min,e.max-i,t.min)),Eg(0,1,n)}function Ny(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 io=.35;function Ey(e=io){return e===!1?e=0:e===!0&&(e=io),{x:Sl(e,"left","right"),y:Sl(e,"top","bottom")}}function Sl(e,t,n){return{min:jl(e,t),max:jl(e,n)}}function jl(e,t){return typeof e=="number"?e:e[t]||0}const Ty=new WeakMap;class Py{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=Tg(),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(Ts(m).point),this.stopAnimation()},a=(m,p)=>{const{drag:h,dragPropagation:x,onDragStart:g}=this.getProps();if(h&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Lg(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),zt(w=>{let y=this.getAxisMotionValue(w).get()||0;if(Rg.test(y)){const{projection:S}=this.visualElement;if(S&&S.layout){const C=S.layout.layoutBox[w];C&&(y=eo(C)*(parseFloat(y)/100))}}this.originPoint[w]=y}),g&&ft.update(()=>g(m,p),!1,!0),Ja(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},l=(m,p)=>{this.latestPointerEvent=m,this.latestPanInfo=p;const{dragPropagation:h,dragDirectionLock:x,onDirectionLock:g,onDrag:b}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:w}=p;if(x&&this.currentDirection===null){this.currentDirection=Ay(w),this.currentDirection!==null&&g&&g(this.currentDirection);return}this.updateAxis("x",p.point,w),this.updateAxis("y",p.point,w),this.visualElement.render(),b&&ft.update(()=>b(m,p),!1,!0)},c=(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 Rd(t,{onSessionStart:o,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:Ld(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:l}=this.getProps();l&&ft.postRender(()=>l(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||!Us(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=Sy(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&&bn(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=jy(s.layoutBox,t):this.constraints=!1,this.elastic=Ey(n),i!==this.constraints&&!bn(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&zt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Ny(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!bn(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=Pg(s,i.root,this.visualElement.getTransformPagePoint());let a=ky(i.layout.layoutBox,o);if(n){const l=n(Ig(a));this.hasMutatedConstraints=!!l,l&&(a=Ag(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:i,dragTransition:o,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=zt(u=>{if(!Us(u,n,this.currentDirection))return;let m=c&&c[u]||{};(a===!0||a===u)&&(m={min:0,max:0});const p=i?200:1e6,h=i?40:1e7,x={type:"inertia",velocity:s?t[u]:0,bounceStiffness:p,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...o,...m};return this.startAxisValueAnimation(u,x)});return Promise.all(d).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Ja(this.visualElement,t),s.start(zg(t,s,0,n,this.visualElement,!1))}stopAnimation(){zt(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){zt(n=>{const{drag:s}=this.getProps();if(!Us(n,s,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(n);if(i&&i.layout){const{min:a,max:l}=i.layout.layoutBox[n],c=o.get()||0;o.set(t[n]-jr(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!bn(n)||!s||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};zt(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();i[a]=Cy({min:c,max:c},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(),zt(a=>{if(!Us(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:d}=this.constraints[a];l.set(jr(c,d,i[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Ty.set(this.visualElement,this);const t=this.visualElement.current,n=gs(t,"pointerdown",d=>{const{drag:u,dragListener:m=!0}=this.getProps(),p=d.target,h=p!==t&&_g(p);u&&m&&!h&&this.start(d)});let s;const i=()=>{const{dragConstraints:d}=this.getProps();bn(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),s||(s=Iy(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 l=Sr(window,"resize",()=>this.scalePositionWithinConstraints()),c=o.addEventListener("didUpdate",(({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(zt(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=d[m].translate,p.set(p.get()+d[m].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:i=!1,dragConstraints:o=!1,dragElastic:a=io,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:i,dragConstraints:o,dragElastic:a,dragMomentum:l}}}function kl(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Iy(e,t,n){const s=Ka(e,kl(n)),i=Ka(t,kl(n));return()=>{s(),i()}}function Us(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ay(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class zy extends Bt{constructor(t){super(t),this.removeGroupControls=er,this.removeListeners=er,this.controls=new Py(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||er}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 yi=e=>(t,n)=>{e&&ft.update(()=>e(t,n),!1,!0)};class Ly extends Bt{constructor(){super(...arguments),this.removePointerDownListener=er}onPointerDown(t){this.session=new Rd(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ld(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:i}=this.node.getProps();return{onSessionStart:yi(t),onStart:yi(n),onMove:yi(s),onEnd:(o,a)=>{delete this.session,i&&ft.postRender(()=>i(o,a))}}}mount(){this.removePointerDownListener=gs(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 wi=!1;class Ry 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),wi&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Dg.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}),wi=!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 l=a.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),Og.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:i}=t;wi=!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 Od(e){const[t,n]=jd(),s=f.useContext(sa);return r.jsx(Ry,{...e,layoutGroup:s,switchLayoutGroup:f.useContext(Ad),isPresent:t,safeToRemove:n})}const _y={pan:{Feature:Ly},drag:{Feature:zy,ProjectionNode:ad,MeasureLayout:Od}};function Cl(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,Ts(t)))}class Oy extends Bt{mount(){const{current:t}=this.node;t&&(this.unmount=Mg(t,(n,s)=>(Cl(this.node,s,"Start"),i=>Cl(this.node,i,"End"))))}unmount(){}}class Dy extends Bt{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=od(Sr(this.node.current,"focus",()=>this.onFocus()),Sr(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Nl(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,Ts(t)))}class My extends Bt{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=$g(t,(i,o)=>(Nl(this.node,o,"Start"),(a,{success:l})=>Nl(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const oo=new WeakMap,vi=new WeakMap,$y=e=>{const t=oo.get(e.target);t&&t(e)},Fy=e=>{e.forEach($y)};function By({root:e,...t}){const n=e||document;vi.has(n)||vi.set(n,{});const s=vi.get(n),i=JSON.stringify(t);return s[i]||(s[i]=new IntersectionObserver(Fy,{root:e,...t})),s[i]}function Uy(e,t,n){const s=By(t);return oo.set(e,n),s.observe(e),()=>{oo.delete(e),s.unobserve(e)}}const Vy={some:0,all:1};class Hy extends Bt{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:Vy[i]},l=c=>{const{isIntersecting:d}=c;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(c)};this.stopObserver=Uy(this.node.current,a,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Wy(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function Wy({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const qy={inView:{Feature:Hy},tap:{Feature:My},focus:{Feature:Dy},hover:{Feature:Oy}},Gy={layout:{ProjectionNode:ad,MeasureLayout:Od}},Qy={...xy,...qy,..._y,...Gy},ir=hy(Qy,fy);async function Er(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 Jy(){const e=mx(o=>o.toasts),[t,n]=f.useState(null),s=async(o,a)=>{o.stopPropagation();const l=`[${a.title}] ${a.message}`;await Er(l)&&(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(br,{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(Mt,{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(Yc,{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(at,{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(kd,{children:e.map(o=>{const a=i(o.type),l=t===o.id;return r.jsxs(ir.div,{initial:{opacity:0,y:50,x:50,scale:.9},animate:{opacity:1,y:0,x:0,scale:1},exit:{opacity:0,scale:.85,transition:{duration:.2}},transition:{type:"spring",stiffness:300,damping:24},className:`pointer-events-auto w-full bg-white dark:bg-slate-900 ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 ${a.border} overflow-hidden text-gray-900 dark:text-gray-100`,id:`toast-${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:c=>s(c,o),className:`text-xs font-bold px-1.5 py-0.5 rounded transition-all flex items-center gap-1 cursor-pointer shrink-0 ${l?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-gray-600 dark:text-gray-300"}`,title:"复制错误内容",children:[l?r.jsx(ht,{size:11}):r.jsx(vn,{size:11}),r.jsx("span",{children:l?"已复制":"复制"})]})]}),r.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 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(Oe,{size:14})})]},o.id)})})})}const ao=new Set;function Ky(e){return ao.add(e),()=>{ao.delete(e)}}const El=30,Tl=(e,t)=>Math.min(e,t.length);function la(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(`
|
|
21
|
+
`)}function Dd(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(`
|
|
22
|
+
`)}function Yy(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 系统诊断报告
|
|
23
|
+
- 生成时间: ${n}
|
|
24
|
+
- 暂无记录的系统异常。`;const o=e.length+t.length,a=["# 🛠️ OpenLearn 系统异常诊断报告",`- **生成时间**: ${n}`,`- **当前页面**: ${s}`,`- **异常总数**: ${o} 项`,`- **本机异常数**: ${e.length} 项`,`- **学生端异常数**: ${t.length} 项`,`- **运行环境**: ${i}`,"","---",""].join(`
|
|
25
|
+
`),l=e.length>0?`## 💻 本机异常记录 (${e.length})
|
|
26
|
+
|
|
27
|
+
`+e.map((d,u)=>`#### 错误 #${u+1} (${d.type.toUpperCase()})
|
|
28
|
+
`+la(d)).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`):"",c=t.length>0?`## 🎒 学生端异常记录 (${t.length})
|
|
33
|
+
|
|
34
|
+
`+t.map((d,u)=>`#### 学生异常 #${u+1}
|
|
35
|
+
`+Dd(d)).join(`
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
`):"";return[a,l,c].filter(Boolean).join(`
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
`)}const Xt=St((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(c=>c.type===n.type&&c.message===n.message&&s-c.timestamp<2e3);if(a>=0)return t().errors[a];const l={id:`err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:n.timestamp||s,url: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(c=>{const d=[l,...c.errors].slice(0,El);return{errors:d,unreadCount:Tl(c.unreadCount+1,d)}}),ao.forEach(c=>{try{c(l)}catch(d){console.error("[ErrorStore] Error in errorListener:",d)}}),l},removeError:n=>e(s=>{const i=s.errors.filter(o=>o.id!==n);return{errors:i,unreadCount:Tl(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,El)})},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 pt(e){return Ft(Xt,e||(t=>t))}function Zy(){const e=de(T=>T.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=pt(T=>T.errors),i=pt(T=>T.studentErrors),o=pt(T=>T.activeTab),a=pt(T=>T.setActiveTab),l=pt(T=>T.isErrorCenterOpen),c=pt(T=>T.setIsErrorCenterOpen),d=pt(T=>T.clearErrors),u=pt(T=>T.clearStudentErrors),m=pt(T=>T.removeError),p=pt(T=>T.removeStudentError),[h,x]=f.useState(!1),[g,b]=f.useState(null),[w,y]=f.useState(new Set),[S,C]=f.useState(!1),k=s.length+(n?0:i.length),v=s.length>0||!n&&i.length>0,N=T=>{y(z=>{const R=new Set(z);return R.has(T)?R.delete(T):R.add(T),R})},O=async()=>{const T=Yy(s,n?[]:i);await Er(T)&&(x(!0),setTimeout(()=>x(!1),2500))},D=async(T,z,R=!1)=>{T.stopPropagation();const $=R?Dd(z):la(z);await Er($)&&(b(z.id),setTimeout(()=>b(null),2500))},_=T=>{switch(T){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:[v&&!l&&!S&&(n?r.jsxs(ir.button,{type:"button",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},className:"fixed bottom-5 left-5 z-40 w-8 h-8 rounded-full bg-slate-900/80 hover:bg-slate-900 text-rose-400 border border-rose-500/40 shadow-lg flex items-center justify-center cursor-pointer transition-all hover:scale-105 select-none",onClick:()=>c(!0),id:"system-error-pill",title:`系统状态提示: ${s.length} 处异常`,children:[r.jsx(Mt,{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(ir.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"),c(!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(Mt,{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:T=>{T.stopPropagation(),C(!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(Oe,{size:13})})]})),r.jsx(kd,{children:l&&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(ir.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(ig,{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:O,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(ht,{size:13}):r.jsx(vn,{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(_r,{size:16})}),r.jsx("button",{type:"button",onClick:()=>c(!1),className:"p-1.5 text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors cursor-pointer",children:r.jsx(Oe,{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(og,{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(xr,{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(ht,{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((T,z)=>{const R=w.has(T.id),$=g===T.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:()=>N(T.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:R?r.jsx(Nn,{size:15}):r.jsx(Cn,{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(xr,{size:11}),r.jsx("span",{children:T.studentName||T.studentId})]}),_(T.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",i.length-z," ",T.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(T.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:T.message}),r.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[r.jsxs("span",{children:["学生学号/ID: ",T.studentId]}),T.lessonId&&r.jsxs("span",{children:["课节: ",T.lessonId]}),T.classId&&r.jsxs("span",{children:["班级: ",T.classId]}),T.endpoint&&r.jsxs("span",{children:["接口: ",T.endpoint]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:I=>D(I,T,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${$?"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:[$?r.jsx(ht,{size:11}):r.jsx(vn,{size:11}),r.jsx("span",{children:$?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),p(T.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(Oe,{size:13})})]})]}),R&&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:["学生: ",T.studentName||"未知"," (",T.studentId,")"]}),r.jsxs("span",{children:["页面地址: ",T.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(T.timestamp).toLocaleString()]})]}),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 leading-relaxed max-h-48 overflow-y-auto opacity-90",children:T.stack})]}),T.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:T.componentStack})]})]})]},T.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(ht,{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((T,z)=>{const R=w.has(T.id),$=g===T.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:()=>N(T.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:R?r.jsx(Nn,{size:15}):r.jsx(Cn,{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:[_(T.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-z," ",T.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(T.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:T.message}),T.endpoint&&r.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",T.endpoint]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:I=>D(I,T,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${$?"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:[$?r.jsx(ht,{size:11}):r.jsx(vn,{size:11}),r.jsx("span",{children:$?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),m(T.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(Oe,{size:13})})]})]}),R&&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:["页面地址: ",T.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(T.timestamp).toLocaleString()]})]}),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 leading-relaxed max-h-48 overflow-y-auto opacity-90",children:T.stack})]}),T.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:T.componentStack})]})]})]},T.id)})})]})})})]})}let Pl=!1;function Xy(){if(Pl)return;Pl=!0;const e=()=>Je(()=>import("./ActivityWorkspaceWidget-5PzyxF6a.js"),__vite__mapDeps([19,1,2,3,4])).then(t=>({default:()=>r.jsx(t.ActivityWorkspaceWidget,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,Ne.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}function ew(){return{addToast:f.useCallback((t,n,s="info")=>{const i=Math.random().toString(36).substring(2,9);ve.getState().addToast({id:i,title:t,message:n,type:s}),setTimeout(()=>{ve.getState().removeToast(i)},6e3)},[])}}function Il(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 tw(){f.useEffect(()=>{if(typeof window>"u")return;const e=o=>{const a=o.reason,l=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",c=a instanceof Error?a.stack:void 0;Xt.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:l,stack:c}),Il({source:"promise",message:l,stack:c}),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"),l=o.error?.stack;Xt.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:l}),Il({source:"runtime",message:a,stack:l}),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 c=await a.clone().text();let d="";try{const p=JSON.parse(c);d=p.error||p.message||p.details||c}catch{d=c.slice(0,300)}const u=o[0],m=typeof u=="string"?u:u instanceof Request?u.url:String(u);Xt.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 l=o[0],c=typeof l=="string"?l:l instanceof Request?l.url:String(l);throw c&&(c.startsWith("/api")||c.includes("/api/"))&&Xt.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:c,stack:a?.stack}),a}},i=Ky(o=>{try{const a=ve.getState(),l=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||l))return;const 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,x={studentId:u,studentName:m,lessonId:p,classId:h,error:o},g=lt();if(g&&g.connected)g.emit("student-client-error",x);else{const b="/api/diagnostics/report",w=JSON.stringify(x);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(b,new Blob([w],{type:"application/json"})):fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:w}).catch(()=>{})}}catch(a){console.warn("[GlobalErrorCapture] Failed to report student error:",a)}});return window.fetch=s,window.addEventListener("unhandledrejection",e),window.addEventListener("error",t),()=>{window.fetch=n,window.removeEventListener("unhandledrejection",e),window.removeEventListener("error",t),i()}},[])}function nw(e){const{fetchStudents:t}=e,n=de(S=>S.session),s=de(S=>S.setSession),i=de(S=>S.lang),o=de(S=>S.setLang),[a,l]=f.useState("teacher"),[c,d]=f.useState(!0),[u,m]=f.useState("normal"),[p,h]=f.useState(null),[x,g]=f.useState(!1);return f.useEffect(()=>{if(!n||n.role!=="teacher")return;const S=async()=>{try{const{ok:k,status:v,data:N}=await Bg();k?(N.status==="warning"||N.warning?m("warning"):m("normal"),d(!0)):v===429||v===503?(m("warning"),d(!0)):(m("error"),d(!1))}catch{m("error"),d(!1)}};S();const C=setInterval(S,5e3);return()=>clearInterval(C)},[n]),f.useEffect(()=>{(async()=>{try{const{ok:C,data:k}=await ld();C&&ve.getState().setSiteInfo({siteName:k.siteName||"",slogan:k.slogan||"",logoUrl:k.logoUrl||null})}catch(C){console.warn("Failed to fetch site settings:",C)}})()},[]),{session:n,setSession:s,lang:i,setLang:o,activeRole:a,setActiveRole:l,setActiveStudentId:h,activeStudentId:p,dbConnected:c,dbStatus:u,profileOpen:x,setProfileOpen:g,handleLoginSuccess:S=>{if(s(S),S.role==="teacher"){l("teacher");const C=typeof window<"u"?ms(window.location.hash):null;ve.getState().setTeacherTab(C||"live_class")}else l("student"),h(S.studentId),t()},handleLogout:async()=>{try{await Vg()}catch(S){console.error("Logout failed",S)}s(null)},toggleLanguage:()=>{o(i==="zh"?"en":"zh")}}}function sw(e){const{activeStudentId:t,activeRole:n,students:s,liveClassFocusLocked:i,setIsFollowingTeacher:o,lang:a,addToast:l}=e,[c,d]=f.useState("dashboard"),u=s.find(R=>R.id===t),m=n==="student"&&(!!t&&!!u?.locked_lesson_id||i),p=u?.lock_mode||"full",h=m,x=m&&p==="full",g=(()=>{if(!u?.lock_target)return null;try{return typeof u.lock_target=="string"?JSON.parse(u.lock_target):u.lock_target}catch{return null}})(),b=f.useRef(h),w=f.useRef(p),y=f.useRef(c);f.useEffect(()=>{b.current=h,w.current=p,y.current=c},[h,p,c]),f.useEffect(()=>{h&&(o(!0),d("lesson"))},[h,o]);const[S,C]=f.useState("whiteboard");f.useEffect(()=>{h&&g?.tab&&C(g.tab)},[h,g?.tab]);const k=R=>{const $=typeof R=="function"?R(y.current):R;if(b.current&&$!=="lesson"){v();return}d($)},v=()=>{const R=w.current==="navigation";l(a==="zh"?R?"🔒 答题锁定":"🔒 全班专注锁定":R?"🔒 Answer Locked":"🔒 Class Focus Locked",a==="zh"?R?"老师已开启答题锁定,请在当前页面完成作答并提交,暂时无法离开本页。":"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":R?"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")},[N,O]=f.useState(null),[D,_]=f.useState("none"),[T,z]=f.useState(!0);return f.useEffect(()=>{c!=="lesson"&&z(!0)},[c]),{studentViewStatus:c,setStudentViewStatus:k,isStudentLocked:m,isNavigationLocked:h,isInteractionLocked:x,studentLockMode:p,studentLockTarget:g,studentLessonTab:S,setStudentLessonTab:C,studentSelectedCourseware:N,setStudentSelectedCourseware:O,studentFullscreenPanel:D,setStudentFullscreenPanel:_,isStudentLessonContentCollapsed:T,setIsStudentLessonContentCollapsed:z,notifyLockedNavigation:v}}function rw({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,l=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null,c=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")),x=o||h,[g,b]=f.useState(!0),[w,y]=f.useState(!1);f.useEffect(()=>{Dr.getState().initTheme(),wn.getState().initFontSize();const L=F=>{(F.ctrlKey||F.metaKey)&&F.altKey&&(F.key==="+"||F.key==="="?(F.preventDefault(),wn.getState().increaseScale()):F.key==="-"||F.key==="_"?(F.preventDefault(),wn.getState().decreaseScale()):F.key==="0"&&(F.preventDefault(),wn.getState().resetScale()))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const S=de(L=>L.session),C=de(L=>L.setSession),[k,v]=f.useState(!0),N=nw({fetchStudents:n}),{activeRole:O,setActiveRole:D,activeStudentId:_,setActiveStudentId:T,dbConnected:z,dbStatus:R,profileOpen:$,setProfileOpen:I,handleLoginSuccess:B,handleLogout:H,toggleLanguage:A}=N,U=de(L=>L.students);de(L=>L.dataVersion);const j=de(L=>L.setSelectedLesson),V=sw({activeStudentId:_,activeRole:O,students:U,liveClassFocusLocked:w,setIsFollowingTeacher:b,lang:e,addToast:t}),{studentViewStatus:G,setStudentViewStatus:E,isStudentLocked:W,isNavigationLocked:Y,isInteractionLocked:K,studentLockMode:ne,studentLockTarget:fe,studentLessonTab:je,setStudentLessonTab:X,studentSelectedCourseware:me,setStudentSelectedCourseware:ke,studentFullscreenPanel:Se,setStudentFullscreenPanel:M,isStudentLessonContentCollapsed:Z,setIsStudentLessonContentCollapsed:ee,notifyLockedNavigation:te}=V;f.useEffect(()=>{(async()=>{try{const{ok:F,data:q}=await Ug();if(F&&q&&q.session)if(C(q.session),x){D("student"),E("lesson");const J=a||q.session.studentId;J&&T(J),l&&j(l),n()}else D(q.session.role),l&&j(l),q.session.role==="student"&&q.session.studentId&&(T(q.session.studentId),n())}catch(F){console.warn("Session check failed",F)}finally{v(!1)}})()},[]);const ce=de(L=>L.teacherTab),oe=de(L=>L.setTeacherTab),xe=f.useRef(!0);f.useEffect(()=>{if(x||d)return;const L=()=>{const q=ms(window.location.hash);q&&q!==ve.getState().teacherTab&&oe(q)};window.addEventListener("hashchange",L);const F=ms(window.location.hash);return F&&F!==ve.getState().teacherTab&&oe(F),()=>window.removeEventListener("hashchange",L)},[oe,x,d]),f.useEffect(()=>{if(x||d)return;if(xe.current){xe.current=!1;const F=ms(window.location.hash);if(F&&F!==ce)return}const L=dd(ce);window.location.hash!==L&&(window.location.hash=L)},[ce,oe,x,d]);const[ie,Pe]=f.useState(!1),[ze,ue]=f.useState(!1),[re,P]=f.useState(!1);return f.useEffect(()=>{S?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&Pe(!0)},[S]),f.useEffect(()=>{ce==="live_class"&&i(!0)},[ce]),{mainNavCollapsed:s,setMainNavCollapsed:i,isStudentLiveMode:o,liveStudentParam:a,liveLessonParam:l,liveClassParam:c,isStageDisplayMode:d,stageLessonParam:u,stageTitleParam:m,stageLangParam:p,isStudentPreviewMode:h,isStudentTabMode:x,isFollowingTeacher:g,setIsFollowingTeacher:b,liveClassFocusLocked:w,setLiveClassFocusLocked:y,session:S,setSession:C,sessionLoading:k,fetchStudents:n,sessionBootstrapData:N,activeRole:O,setActiveRole:D,activeStudentId:_,setActiveStudentId:T,dbConnected:z,dbStatus:R,profileOpen:$,setProfileOpen:I,handleLoginSuccess:B,handleLogout:H,toggleLanguage:A,students:U,setSelectedLesson:j,studentViewStateData:V,studentViewStatus:G,setStudentViewStatus:E,isStudentLocked:W,isNavigationLocked:Y,isInteractionLocked:K,studentLockMode:ne,studentLockTarget:fe,studentLessonTab:je,setStudentLessonTab:X,studentSelectedCourseware:me,setStudentSelectedCourseware:ke,studentFullscreenPanel:Se,setStudentFullscreenPanel:M,isStudentLessonContentCollapsed:Z,setIsStudentLessonContentCollapsed:ee,notifyLockedNavigation:te,teacherTab:ce,setTeacherTab:oe,isTourOpen:ie,setIsTourOpen:Pe,isApprovalsCollapsed:ze,setIsApprovalsCollapsed:ue,isProcessesCollapsed:re,setIsProcessesCollapsed:P}}function iw(e){const[t,n]=f.useState(""),[s,i]=f.useState("recent"),[o,a]=f.useState(!1),[l,c]=f.useState(!1),[d,u]=f.useState(!1),[m,p]=f.useState(null),h=f.useMemo(()=>{let x=[...e];if(t.trim()){const g=t.toLowerCase();x=x.filter(b=>b.title.toLowerCase().includes(g)||b.content.toLowerCase().includes(g))}if(o&&(x=x.filter(g=>(g.enrollment_count||0)>0)),l&&(x=x.filter(g=>g.content&&g.content.trim().length>0)),d){const g=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();x=x.filter(b=>(b.created_at||0)>=g)}return s==="recent"?x.sort((g,b)=>(b.created_at||0)-(g.created_at||0)):s==="alphabetical"?x.sort((g,b)=>g.title.localeCompare(b.title)):s==="enrollment"&&x.sort((g,b)=>(b.enrollment_count||0)-(g.enrollment_count||0)),x},[e,t,s,o,l,d]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:i,filterEnrollment:o,setFilterEnrollment:a,filterHasContent:l,setFilterHasContent:c,filterThisMonth:d,setFilterThisMonth:u,copyingLessonId:m,setCopyingLessonId:p,filteredAndSortedLessons:h}}function ow(){const e=Gg(),t=e?.academicYear==="all"?null:e?.academicYear??null,[n,s]=f.useState([]),[i,o]=f.useState(!1),[a,l]=f.useState({lab_id:null,seats:[]}),[c,d]=f.useState(!1),[u,m]=f.useState([]),[p,h]=f.useState({}),[x,g]=f.useState({}),[b,w]=f.useState(null),[y,S]=f.useState(""),[C,k]=f.useState(""),v=f.useCallback(async()=>{try{o(!0);const T=await fetch("/api/labs");T.ok&&s(await T.json())}catch(T){console.error(T)}finally{o(!1)}},[]),N=f.useCallback(async T=>{try{const z=await fetch(`/api/classes/${T}/seats`);if(z.ok){const R=await z.json();l(R)}}catch(z){console.error(z)}},[]),O=f.useCallback(async()=>{try{const T=new Date().toISOString().split("T")[0],z=await fetch(`/api/schedules/today?date=${T}`);if(z.ok){const R=await z.json();R.success&&R.schedules&&m(R.schedules)}}catch(T){console.warn("Failed to fetch today schedules",T)}},[]),D=f.useCallback(async T=>{try{const z=await fetch(`/api/classes/${T}/schedules${t?`?academicYear=${encodeURIComponent(t)}`:""}`);if(z.ok){const R=await z.json();h($=>({...$,[T]:R}))}}catch{}},[t]),_=f.useCallback(async T=>{try{const z=await fetch(`/api/schedules/${T}/attendance`);if(z.ok){const R=await z.json();g($=>({...$,[T]:R}))}}catch{}},[]);return{computerLabs:n,setComputerLabs:s,loadingLabs:i,setLoadingLabs:o,fetchLabs:v,classSeats:a,setClassSeats:l,savingSeats:c,setSavingSeats:d,fetchClassSeats:N,todaySchedules:u,setTodaySchedules:m,fetchTodaySchedules:O,classSchedulesMap:p,setClassSchedulesMap:h,fetchClassSchedules:D,scheduleAttendanceMap:x,setScheduleAttendanceMap:g,fetchScheduleAttendance:_,expandedScheduleId:b,setExpandedScheduleId:w,newScheduleDate:y,setNewScheduleDate:S,newScheduleLessonId:C,setNewScheduleLessonId:k}}function aw(e){const{lang:t,addToast:n,setCopyingLessonId:s}=e,i=de(h=>h.selectedLesson),o=de(h=>h.setSelectedLesson),a=de(h=>h.setElements),l=f.useRef(new Map),c=async()=>{await ve.getState().loadLessons()};return{fetchLessons:c,handleQuickCreateLesson:async(h,x)=>{try{const{ok:g,data:b}=await Yg({title:h,content:x});if(g)return await c(),b.id||"lesson-created"}catch(g){console.error("Quick create lesson failed",g)}return""},handleDeleteCourse:async h=>{const{ok:x,data:g}=await Zg(h);if(!x)throw new Error(g.error||"Failed to delete course");await c(),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:x,data:g}=await Xg(h);if(!x)throw new Error(g.error||"Failed to copy course");await c(),n(t==="zh"?"复制成功":"Course Copied",t==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(x){n(t==="zh"?"复制失败":"Copy Failed",x.message||(t==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{s(null)}},fetchElements:async h=>{try{const{ok:x,data:g}=await ex(h);if(!x)return;const b=JSON.stringify(g);b!==l.current.get(h)&&(l.current.set(h,b),a(g))}catch{}},lastElementsJsonByRoomRef:l}}async function lw(){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 cw(e){const t=await fetch(`/api/vfs${e?`?parentId=${e}`:""}`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function dw(){const e=await fetch("/api/processes");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function uw(e){const t=await fetch(`/api/processes/${e}/logs`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function hw(e,t){return{ok:(await fetch(`/api/classes/${e}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function fw(e,t){return{ok:(await fetch(`/api/assignments/${e}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function mw(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 pw(e){const t=await fetch(`/api/classes/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function gw(e){const t=await fetch(`/api/classes/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function xw(e){const t=await fetch(`/api/students/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function EN(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 bw(e){const{fetchClassSchedules:t}=e,[n,s]=f.useState({}),[i,o]=f.useState({}),[a,l]=f.useState({}),[c,d]=f.useState({}),[u,m]=f.useState({}),[p,h]=f.useState([]),x=async C=>{try{const{ok:k,data:v}=await ix(C);k&&s(N=>({...N,[C]:v}))}catch{}},g=async C=>{try{const{ok:k,data:v}=await pw(C);k&&o(N=>({...N,[C]:v}))}catch{}},b=async C=>{try{const{ok:k,data:v}=await gw(C);k&&l(N=>({...N,[C]:v}))}catch{}};return{classStudentsMap:n,setClassStudentsMap:s,classProgressMap:i,setClassProgressMap:o,classDashboardMap:a,setClassDashboardMap:l,classAssignmentsMap:c,setClassAssignmentsMap:d,assignmentSubmissionsMap:u,setAssignmentSubmissionsMap:m,liveClassStudentProgress:p,setLiveClassStudentProgress:h,fetchClassStudents:x,fetchClassProgress:g,fetchClassDashboard:b,fetchLiveClassStudentProgress:async(C,k)=>{try{const{ok:v,data:N}=await o0(C,k);v&&h(N)}catch{}},handleQuickScheduleClass:async(C,k,v)=>{try{const{ok:N}=await hw(C,{lessonId:k,scheduledDate:v});if(N)return await t(C),!0}catch(N){console.error("Quick schedule class failed",N)}return!1},handleQuickGenerateAssignment:async(C,k,v)=>{const N=k||v||"Assignment";try{const{ok:O,data:D}=await mw(C,N);if(O)return await b(C),D.id||"assignment-created"}catch(O){console.error("Quick generate assignment failed",O)}return null}}}function yw(e){const[t,n]=f.useState([]),[s,i]=f.useState([]),[o,a]=f.useState([]),[l,c]=f.useState(null),[d,u]=f.useState(""),[m,p]=f.useState(!1),[h,x]=f.useState(null);return{registeredCommands:t,setRegisteredCommands:n,vfsNodes:s,setVfsNodes:i,processes:o,setProcesses:a,showProcessLogs:l,setShowProcessLogs:c,processLogsContent:d,setProcessLogsContent:u,showLogs:m,setShowLogs:p,currentVfsParent:h,setCurrentVfsParent:x,fetchRegisteredCommands:async()=>{try{const{ok:S,data:C,contentType:k}=await lw();S&&k&&k.includes("application/json")&&Array.isArray(C)&&n(C)}catch(S){console.warn("Failed to fetch registered commands",S)}},fetchVfs:async S=>{if(e)try{const{ok:C,data:k}=await cw(S);C&&i(k)}catch(C){console.warn("Failed to fetch VFS nodes",C)}},fetchProcesses:async()=>{try{const{ok:S,data:C}=await dw();S&&a(C)}catch{}},fetchProcessLogs:async S=>{try{const{ok:C,data:k}=await uw(S);C&&(u(k.logs||""),c(S))}catch{}}}}function xs(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 ww(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+`
|
|
44
|
+
`+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 Kt(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(l=>l.includes(o));if(a!==-1)return a}return-1}function Al(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||""}}function zl(e,t){if(!e||e.length===0)return"";const n=e.map(s=>`${s.student_number||"-"} / ${s.name} / ${s.initial_password}`).join(`
|
|
45
|
+
`);return t==="zh"?`
|
|
46
|
+
|
|
47
|
+
🔑 以下 ${e.length} 名学生使用系统生成的初始密码(仅本次显示,请及时分发):
|
|
48
|
+
${n}`:`
|
|
49
|
+
|
|
50
|
+
🔑 Initial passwords for ${e.length} student(s) (shown once — distribute them now):
|
|
51
|
+
${n}`}const vw={zh:{className:"班级名称",classDesc:"班级描述",studentNumber:"学生学号",studentName:"学生姓名",studentEmail:"学生邮箱",password:"初始密码",notes:"学生备注"},en:{className:"Class Name",classDesc:"Class Desc",studentNumber:"Student Number",studentName:"Student Name",studentEmail:"Student Email",password:"Initial Password",notes:"Student Notes"}};function gt(e){return e.map(t=>{const n=t??"";return/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}).join(",")}function Ll(e,t){const n=vw[t==="zh"?"zh":"en"];let s,i,o;e==="class"?(s=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",i=gt([n.className,n.classDesc,n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes]),o=t==="zh"?[gt(["高一A班","基础英语课程","20260101","李明","liming@example.com","",""]),gt(["高一A班","基础英语课程","20260102","王华","wanghua@example.com","","数学较弱"])]:[gt(["Class 101","Introduction to English","20260101","John Doe","john@example.com","",""]),gt(["Class 101","Introduction to English","20260102","Jane Smith","jane@example.com","",""])]):(s=t==="zh"?"学生批量导入模板.csv":"student_import_template.csv",i=gt([n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes]),o=t==="zh"?[gt(["20260101","张三","zhangsan@example.com","",""]),gt(["20260102","李四","lisi@example.com","",""])]:[gt(["20260101","Alice Cooper","alice@example.com","",""]),gt(["20260102","Bob Dylan","bob@example.com","",""])]);const a=new Blob(["\uFEFF"+i+`
|
|
52
|
+
`+o.join(`
|
|
53
|
+
`)+`
|
|
54
|
+
`],{type:"text/csv;charset=utf-8;"}),l=URL.createObjectURL(a),c=document.createElement("a");c.href=l,c.setAttribute("download",s),document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l)}async function Sw(e,t){const{lang:n,fetchClasses:s,fetchStudents:i}=t;return new Promise((o,a)=>{const l=new FileReader;l.onload=async c=>{try{const d=c.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(g=>g.className||g.name&&(g.students||g.classDescription))?(p=!0,u=h.map(g=>{const b=g.name||g.className||g.class_name,w=g.description||g.classDescription||"",y=g.students||g.studentList||[],S=(Array.isArray(y)?y:[]).map(Al).filter(C=>C.name);return{name:b,description:w,students:S}}).filter(g=>g.name)):(p=!1,m=h.map(Al).filter(g=>g.name))}else{const h=d.split(/\r?\n/);if(h.length<2)throw new Error("CSV has empty or insufficient data");const x=xs(h[0]).map(N=>N.trim().toLowerCase()),g=Kt(x,["班级名称","class name","classname","class_name","班级"]),b=Kt(x,["班级描述","class desc","classdesc","class_desc","描述"]),w=Kt(x,["学生学号","student number","studentnumber","student_number","student no","学号","编号"]),y=Kt(x,["学生姓名","student name","studentname","student_name","姓名","学生"]),S=Kt(x,["学生邮箱","student email","studentemail","student_email","邮箱","email","mail"]),C=Kt(x,["初始密码","initial password","password","passwd","pwd","密码"]),k=Kt(x,["学生备注","student notes","private_notes","备注","note","remark"]);if(y===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');const v=N=>({name:N[y]||"",email:S!==-1&&N[S]||"",student_number:w!==-1&&N[w]||"",password:C!==-1&&N[C]||"",private_notes:k!==-1&&N[k]||""});if(g!==-1){p=!0;const N={};for(let O=1;O<h.length;O++){const D=h[O].trim();if(!D)continue;const _=xs(D),T=_[g];if(!T)continue;const z=b!==-1&&_[b]||"",R=v(_);N[T]||(N[T]={name:T,description:z,students:[]}),R.name&&N[T].students.push(R)}u=Object.values(N)}else{p=!1;for(let N=1;N<h.length;N++){const O=h[N].trim();if(!O)continue;const D=v(xs(O));D.name&&m.push(D)}}}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 y=await h.json();throw new Error(y.error||"Server importation failed")}const x=await h.json();await s(),await i();const g=x.imported.length,b=x.imported.reduce((y,S)=>y+(S.studentsCount||0),0),w=zl(x.credentials,n);o({success:!0,message:n==="zh"?`成功导入 ${g} 个班级、${b} 名学生。${w}`:`Imported ${g} class(es) and ${b} student(s).${w}`})}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 x=await h.json();await i();const g=x.created??x.imported.filter(S=>S.new).length,b=x.existing??x.imported.filter(S=>!S.new).length,w=(x.imported||[]).filter(S=>S.created&&S.initial_password).map(S=>({student_number:S.student_number,name:S.name,initial_password:S.initial_password})),y=zl(w,n);o({success:!0,message:n==="zh"?`成功导入 ${g} 名新学生${b?`,${b} 名已存在(按邮箱或学号匹配,已跳过重复创建)`:""}。${y}`:`Imported ${g} new student(s)${b?`, skipped ${b} existing one(s) matched by email or student number`:""}.${y}`})}}catch(d){a(d)}},l.onerror=()=>{a(new Error("Failed to read file from disk."))},l.readAsText(e)})}function jw(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 l=a.split(/\r?\n/);if(l.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const c=xs(l[0]).map(h=>h.trim().toLowerCase()),d=c.findIndex(h=>h.includes("title")||h.includes("标题")||h.includes("课程")),u=c.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=ww(l.slice(1)),p=[];for(const h of m){if(!h.trim())continue;const x=xs(h),g=x[d]?.trim(),b=x[u]?.trim();g&&b&&p.push({title:g,content:b})}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 kw(e,t){const{lang:n,setImportProgress:s,fetchLessons:i}=t;let o=0;for(let a=0;a<e.length;a++){const l=e[a];try{const c=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:l.title,content:l.content})});if(c.ok)o++;else{const d=await c.json();console.warn(`Failed to import item ${a+1}:`,d)}}catch(c){console.warn(`Error importing item ${a+1}:`,c)}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 Rl="openlearn.course-package",ca=20*1024*1024,lo=Math.round(ca/(1024*1024));function co(e){return`${(e/(1024*1024)).toFixed(1)}MB`}async function Cw(){try{const e=await fetch("/api/course-packages/template");if(!e.ok){let i="";try{i=(await e.json())?.error||""}catch{}return{ok:!1,error:i||`模板下载失败(HTTP ${e.status})`}}const t=await e.blob(),n=URL.createObjectURL(t),s=document.createElement("a");return s.href=n,s.setAttribute("download","openlearn-course-template.json"),document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n),{ok:!0}}catch(e){return{ok:!1,error:e?.message||String(e)}}}async function Nw(e){if(e.size>ca)return{ok:!1,error:`课程包文件 ${co(e.size)} 超过 ${lo}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!==Rl)return{ok:!1,error:`不是 OpenLearn 课程包文件(format 应为 "${Rl}")`};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 Ew(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 Tw=ca;function Pw(e){const{lang:t,fetchClasses:n,fetchStudents:s,fetchLessons:i,addToast:o}=e,[a,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(!1),[p,h]=f.useState("system"),[x,g]=f.useState(null),[b,w]=f.useState([]),[y,S]=f.useState(!1),[C,k]=f.useState(!1),v=async()=>{try{S(!0);const{ok:ue,data:re}=await Fg();ue&&w(re)}catch(ue){console.warn("Error fetching library resources:",ue)}finally{S(!1)}};f.useEffect(()=>{u&&v()},[u]);const[N,O]=f.useState(!1),[D,_]=f.useState("idle"),[T,z]=f.useState(0),[R,$]=f.useState(0),[I,B]=f.useState(""),[H,A]=f.useState([]),[U,j]=f.useState(!1),[V,G]=f.useState(null),[E,W]=f.useState(null),[Y,K]=f.useState(null),ne=()=>{Ll("class",t)},fe=async ue=>{if(ue){if(!ue.name.toLowerCase().endsWith(".csv")){_("error"),B(t==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}_("parsing"),B("");try{const re=await jw(ue,t);A(re)}catch(re){_("error"),B(re.message||String(re))}}},je=async ue=>{if(!ue)return;if(ue.size>Tw){_("error"),B(t==="zh"?`文件 ${co(ue.size)} 超过 ${lo}MB 上限,请精简后重试。`:`File is ${co(ue.size)}, over the ${lo}MB limit.`),G(null),W(null);return}if(ue.name.toLowerCase().endsWith(".json")){B("");try{const P=await Nw(ue);if(!P.ok){G(null),W(null),_("error"),B(P.error);return}W(P.package),G(P.preview),A([]),_("parsing")}catch(P){_("error"),B(P?.message||String(P))}return}G(null),W(null),await fe(ue)},X=async()=>{const ue=await Cw();if(!ue.ok){_("error"),B(ue.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")},me=async(ue=!1)=>{if(!E)return;_("importing"),B("");const re=await Ew(E,{allowDuplicate:ue});if(re.ok&&re.result){_("success"),K(null),await i(),o(t==="zh"?"课程包导入成功":"Course package imported",t==="zh"?`已导入「${re.result.title}」:${re.result.segments} 个教学环节、${re.result.elements} 个白板元素、${re.result.assets} 份课件附件。`:`Imported "${re.result.title}": ${re.result.segments} segments, ${re.result.elements} elements, ${re.result.assets} assets.`,"success");return}if(re.duplicate){K(re.duplicate),_("error"),B(re.error||"");return}_("error"),B(re.error||(t==="zh"?"课程包导入失败":"Course package import failed"))},ke=()=>{K(null),B(""),_("parsing")},Se=async()=>{if(H.length===0)return;_("importing"),z(0),$(H.length);const ue=await kw(H,{lang:t,setImportProgress:z,fetchLessons:i});ue.success?_("success"):(_("error"),B(ue.errorMsg||""))},[M,Z]=f.useState(!1),[ee,te]=f.useState(!1),[ce,oe]=f.useState(null),[xe,ie]=f.useState(null);return{isCloudDriveOpen:a,setIsCloudDriveOpen:l,cloudDrivePreviewNode:c,setCloudDrivePreviewNode:d,isSystemResourceLibraryOpen:u,setIsSystemResourceLibraryOpen:m,systemResourceTab:p,setSystemResourceTab:h,selectedLibraryResourceId:x,setSelectedLibraryResourceId:g,libraryResources:b,setLibraryResources:w,loadingLibraryResources:y,setLoadingLibraryResources:S,showCoursewareHub:C,setShowCoursewareHub:k,fetchLibraryResources:v,isImportLessonsOpen:N,setIsImportLessonsOpen:O,importStatus:D,setImportStatus:_,importProgress:T,setImportProgress:z,importProgressTotal:R,setImportProgressTotal:$,importErrorMsg:I,setImportErrorMsg:B,previewImportData:H,setPreviewImportData:A,isDraggingImport:U,setIsDraggingImport:j,downloadCsvTemplate:ne,handleCSVFileChange:fe,handleCSVImportSubmit:Se,packagePreview:V,setPackagePreview:G,pendingCoursePackage:E,packageDuplicate:Y,handlePackageDuplicateDismiss:ke,handleImportFileChange:je,handlePackageImportSubmit:me,downloadCourseTemplate:X,showImportModal:M,setShowImportModal:Z,isImporting:ee,setIsImporting:te,importError:ce,setImportError:oe,importSuccess:xe,setImportSuccess:ie,downloadCSVTemplate:ue=>{Ll(ue,t)},handleImportFile:async ue=>{te(!0),oe(null),ie(null);try{const re=await Sw(ue,{lang:t,fetchClasses:n,fetchStudents:s});ie(re.message)}catch(re){oe(re.message||String(re))}finally{te(!1)}}}}function Iw(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:i,setTeacherTab:o}=e,[a,l]=f.useState(!1),[c,d]=f.useState(1),[u,m]=f.useState(""),[p,h]=f.useState("Mathematics"),[x,g]=f.useState(""),[b,w]=f.useState(""),[y,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"}]),[C,k]=f.useState(!1),[v,N]=f.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:l,wizardStep:c,setWizardStep:d,wizardCourseTitle:u,setWizardCourseTitle:m,wizardCourseCategory:p,setWizardCourseCategory:h,wizardCourseDescription:x,setWizardCourseDescription:g,wizardCourseContent:b,setWizardCourseContent:w,wizardCourseTimeline:y,setWizardCourseTimeline:S,wizardIsSubmitting:C,setWizardIsSubmitting:k,wizardIsGeneratingOutline:v,handleGenerateOutline:async()=>{if(!v){if(!u.trim()){n(t==="zh"?"请先填写课程课题":"Course Title Required",t==="zh"?"AI 需要课题名称才能生成大纲。":"AI needs a course title to generate the outline.","warning");return}N(!0);try{const _=await fetch("/api/lessons/generate-outline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:u,category:p,description:x,timeline:y,lang:t})}),T=await _.json().catch(()=>null);if(!_.ok||!T?.success)throw new Error(T?.error||T?.message||`HTTP ${_.status}`);const z=(T.content||"").trim();if(!z)throw new Error(t==="zh"?"AI 返回了空内容":"AI returned empty content");w(z),n(t==="zh"?"✨ AI 大纲生成成功":"✨ AI Outline Generated",t==="zh"?`已根据《${u}》生成 ${z.length} 字的专家级教学大纲。`:`Generated a ${z.length}-character outline for "${u}".`,"success")}catch(_){console.error(_),n(t==="zh"?"AI 大纲生成失败":"AI Outline Generation Failed",_?.message||(t==="zh"?"请确认「系统管理 -> AI 提供商管理」中已配置可用的模型服务。":"Please configure a working AI Provider in System Management."),"error")}finally{N(!1)}}},handleDeployWizardCourse:async()=>{if(!u.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}k(!0);try{const _=b.trim()||`Course outline for ${u} (${p})`,T=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:u,content:_})});if(T.ok){const R=(await T.json()).result?.lessonId;R&&await fetch(`/api/lessons/${R}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:y})}),await s(),R&&(i(R),o("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${u}》已成功保存到核心SQLite并已自动激活!`:`Course "${u}" is now live in SQLite and auto-activated.`,"success"),l(!1),m(""),h("Mathematics"),g(""),w(""),d(1)}else n("Error","SQLite save failed","warning")}catch(_){console.error(_),n("Error","Launch Exception","warning")}finally{k(!1)}}}}const Aw=`exports.default = {
|
|
55
|
+
manifest: {
|
|
56
|
+
id: "@my-scope/hello-world",
|
|
57
|
+
name: "Hello World Plugin",
|
|
58
|
+
version: "1.0.0",
|
|
59
|
+
capabilitiesProposed: ["lesson:read"]
|
|
60
|
+
},
|
|
61
|
+
activate: async (ctx) => {
|
|
62
|
+
ctx.log.info('Hello World plugin activated');
|
|
63
|
+
}
|
|
64
|
+
};`;function zw(e){const{session:t,host:n,lang:s,addToast:i,setChatLog:o,setTeacherTab:a,fetchLessons:l}=e,[c,d]=f.useState([]),[u,m]=f.useState([]),[p,h]=f.useState(!1),[x,g]=f.useState(null),[b,w]=f.useState(""),[y,S]=f.useState(""),[C,k]=f.useState(""),[v,N]=f.useState(""),[O,D]=f.useState(null),[_,T]=f.useState(!1),[z,R]=f.useState("store"),[$,I]=f.useState(Aw),[B,H]=f.useState(!1),[A,U]=f.useState([]),[j,V]=f.useState([]),[G,E]=f.useState({}),[W,Y]=f.useState([]),[K,ne]=f.useState(!1),fe=f.useCallback(async()=>{ne(!0);try{const P=await fetch("/api/plugins/orphan-data");if(P.ok){const L=await P.json();Y(Array.isArray(L.items)?L.items:[])}}catch(P){console.warn("Failed to fetch plugin orphan data",P)}finally{ne(!1)}},[]),je=f.useCallback(async P=>{try{const L=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(P.pluginId)}/export`,{method:"POST"}),F=await L.json().catch(()=>({}));L.ok&&F?.success?(i(s==="zh"?"导出完成":"Export finished",s==="zh"?`已导出 ${F.tables?.length??0} 张表 / ${F.rowCount??0} 行到 ${F.file}`:`Exported ${F.tables?.length??0} tables / ${F.rowCount??0} rows to ${F.file}`,"success"),await fe()):i(s==="zh"?"导出失败":"Export failed",F?.error||"Unknown error","error")}catch(L){i(s==="zh"?"导出失败":"Export failed",String(L?.message??L),"error")}},[i,fe,s]),X=f.useCallback(async P=>{try{const L=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(P.pluginId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:P.pluginId})}),F=await L.json().catch(()=>({}));L.ok&&F?.success?(i(s==="zh"?"已清除插件数据":"Plugin data purged",s==="zh"?`删除 ${F.droppedTables?.length??0} 张表;归档:${F.exportFile??"(无)"}`:`Dropped ${F.droppedTables?.length??0} tables; archive: ${F.exportFile??"(none)"}`,"success"),await fe()):i(s==="zh"?"清除失败":"Purge failed",F?.error||"Unknown error","error")}catch(L){i(s==="zh"?"清除失败":"Purge failed",String(L?.message??L),"error")}},[i,fe,s]),me=f.useCallback(P=>{window.open(`/api/plugins/orphan-data/${encodeURIComponent(P.pluginId)}/archive`,"_blank")},[]),ke=f.useRef(new Set),Se=f.useCallback(async()=>{try{const P=await fetch("/api/plugins");if(P.ok){const L=await P.json();d(L)}}catch(P){console.warn("Failed to fetch plugins",P)}},[]),M=f.useCallback(async()=>{try{const P=await fetch("/api/ai-providers");if(P.ok){const L=await P.json();m(L)}}catch(P){console.warn("Failed to fetch AI Providers",P)}},[]);f.useEffect(()=>{Se(),t&&t.role!=="student"&&M()},[Se,M,t?.role]);const Z=f.useCallback(async()=>{try{const P=await fetch("/api/events");P.ok&&U(await P.json())}catch{}},[]),ee=f.useCallback(async()=>{try{const P=await fetch("/api/approvals");P.ok&&V(await P.json())}catch{}},[]);return{plugins:c,setPlugins:d,fetchPlugins:Se,aiProviders:u,setAiProviders:m,fetchAIProviders:M,isAIProviderModalOpen:p,setIsAIProviderModalOpen:h,editingAIProvider:x,setEditingAIProvider:g,providerName:b,setProviderName:w,providerApiUrl:y,setProviderApiUrl:S,providerApiKey:C,setProviderApiKey:k,providerModelName:v,setProviderModelName:N,testingProviderId:O,setTestingProviderId:D,showPluginModal:_,setShowPluginModal:T,storeTab:z,setStoreTab:R,pluginCode:$,setPluginCode:I,installingPlugin:B,setInstallingPlugin:H,events:A,setEvents:U,fetchEvents:Z,approvals:j,setApprovals:V,fetchApprovals:ee,scoreOverrides:G,setScoreOverrides:E,handleSaveAIProvider:async()=>{if(!b.trim()||!y.trim()||!v.trim()){i(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let P;if(x?P=await fetch(`/api/ai-providers/${x.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:b,api_url:y,api_key:C,model_name:v})}):P=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:b,api_url:y,api_key:C,model_name:v})}),P.ok)i(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${b}] 已保存。`:`AI Provider [${b}] has been updated.`,"success"),h(!1),g(null),w(""),S(""),k(""),N(""),M();else{const L=await P.json().catch(()=>({}));i(s==="zh"?"保存失败":"Failed to Save",L.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(P){console.error(P),i(s==="zh"?"保存异常":"Execution Error",P.message||"Error occurred","warning")}},handleDeleteAIProvider:async(P,L)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${L}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${L}]?`))try{(await fetch(`/api/ai-providers/${P}`,{method:"DELETE"})).ok?(i(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${L}] 已经被清除。`:`AI Provider [${L}] has been removed.`,"success"),M()):i(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(F){console.error(F),i(s==="zh"?"操作异常":"Execution Error",F.message||"Error occurred","warning")}},handleTestAIProvider:async P=>{D(P.id);try{const L=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:P.api_url,api_key:P.api_key,model_name:P.model_name})}),F=await L.json();L.ok&&F.success?i(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${P.name}]。${F.message}`:`Successfully connected to [${P.name}]. ${F.message}`,"success"):i(s==="zh"?"测试失败":"Test Failed",F.error||"Connection error","warning")}catch(L){console.error(L),i(s==="zh"?"连接异常":"Connection Exception",L.message||"Error occurred","warning")}finally{D(null)}},handleInstallPlugin:async()=>{if($.trim()){H(!0);try{const L=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:$})})).json();L.success?(await Se(),T(!1),o(F=>[...F,{role:"agent",content:`[System] Plugin "${L.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+L.error)}catch(P){alert("Error: "+P.message)}finally{H(!1)}}},handleZipPluginUpload:async(P,L,F)=>{H(!0);const q=F?.mode==="update";try{const J={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(P.name),"X-Execution-Mode":L,"X-Install-Mode":q?"update":"install","X-Allow-Downgrade":F?.allowDowngrade?"true":"false"};F?.approvePublicRoutes&&(J["X-Approve-Public-Routes"]="true"),F?.approveCapabilities&&(J["X-Approve-Capabilities"]="true"),F?.approveNetworkHosts&&(J["X-Approve-Network-Hosts"]="true"),q&&(J["X-Acknowledge-Risk"]="true"),F?.targetPluginId&&(J["X-Target-Plugin-Id"]=encodeURIComponent(F.targetPluginId));const be=q&&F?.targetPluginId?`/api/plugins/${encodeURIComponent(F.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",se=await fetch(be,{method:"POST",headers:J,body:P}),ye=await se.json().catch(()=>({}));if(!se.ok||!ye.success){const et=ye.error||"Unknown error";throw i(s==="zh"?q?"更新失败":"安装失败":q?"Update Failed":"Installation Failed",et,"error"),new Error(et)}const $e=ye.pluginId||ye.manifest?.pluginId||ye.manifest?.id,Fe=!!(ye.updated||q);if(!Fe&&$e)await fetch(`/api/plugins/${encodeURIComponent($e)}/toggle`,{method:"POST"}).catch(()=>{});else if(Fe&&ye.wasActive&&$e)try{await n.deactivatePlugin($e)}catch{}a("plugins"),R("store"),await Se(),setTimeout(()=>{Se()},1e3);const Ce=ye.manifest?.name||$e||P.name,We=typeof ye.executionMode=="string"?ye.executionMode:L,He=We==="process"?s==="zh"?"子进程隔离":"process isolation":We==="worker"?s==="zh"?"Worker 线程":"worker thread":We==="inline"?s==="zh"?"主进程":"in-process":We,Et=ye.executionModeCoerced===!0?s==="zh"?"(未受信任插件已强制改为子进程,清单里的 inline/worker 不会生效)":" (untrusted plugin was forced into a child process)":"";if(Fe){const et=ye.oldVersion||"?",jt=ye.newVersion||ye.manifest?.version||"?";i(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${Ce}" 已从 v${et} 更新到 v${jt}(配置与数据已保留)`:`"${Ce}" updated v${et} → v${jt} (config & data preserved)`,"success"),o(Vt=>[...Vt,{role:"agent",content:`[System] Plugin "${Ce}" updated ${et} → ${jt}.`}])}else i(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${Ce}" 已上传,实际运行模式为 [${He}]${Et}`:`Plugin "${Ce}" installed in [${He}] mode${Et}`,"success"),o(et=>[...et,{role:"agent",content:`[System] Plugin "${Ce}" installed successfully from ZIP file.`}])}catch(J){const be=J?.message?String(J.message):"";throw be&&be!=="Failed to fetch"&&be!=="Network error"||i(s==="zh"?"网络错误":"Network Error",be||"Network error","error"),J}finally{H(!1)}},handleTogglePlugin:async P=>{if(!ke.current.has(P)){ke.current.add(P);try{const L=await fetch(`/api/plugins/${encodeURIComponent(P)}/toggle`,{method:"POST"}),F=await L.json().catch(()=>({}));if(L.ok)await Se();else{const q=F.error||"Unknown error";q.includes("requires human approval")||q.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await ee()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+q)}}catch(L){console.error("Failed to toggle plugin:",L),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{ke.current.delete(P)}}},handleDeletePlugin:async(P,L="keep")=>{try{const F=L==="purge"?`/api/plugins/${encodeURIComponent(P)}?dataPolicy=purge&confirm=purge`:`/api/plugins/${encodeURIComponent(P)}`,q=await fetch(F,{method:"DELETE"});if(q.ok){const J=await q.json().catch(()=>({}));a("plugins"),R("store"),await Se();const be=L==="purge"?s==="zh"?`插件已卸载,数据已清除(归档:${J.exportFile??"无数据需归档"})。`:`Plugin uninstalled and data purged (archive: ${J.exportFile??"nothing to archive"}).`:s==="zh"?`插件已卸载,数据已保留(${J.keptTables?.length??0} 张表),可在「插件数据」中管理。`:`Plugin uninstalled with data kept (${J.keptTables?.length??0} tables). Manage it under Plugin Data.`;o(se=>[...se,{role:"agent",content:`[System] ${be}`}]),i(s==="zh"?"卸载完成":"Uninstalled",be,"success")}else{const J=await q.json().catch(()=>({}));alert(J.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(F){console.error("Failed to delete plugin:",F),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},orphanData:W,orphanDataLoading:K,fetchOrphanData:fe,handleExportOrphanData:je,handlePurgeOrphanData:X,handleDownloadOrphanArchive:me,handleApprove:async(P,L)=>{try{const q=await(await fetch(`/api/approvals/${P}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:L})})).json();q.success?(await ee(),await l(),await Se()):alert("Action failed: "+q.error)}catch(F){console.error(F)}},handleReject:async P=>{try{await fetch(`/api/approvals/${P}/reject`,{method:"POST"}),await ee(),await Se()}catch(L){console.error(L)}}}}function Lw(){const[e,t]=f.useState(!1),[n,s]=f.useState(null),[i,o]=f.useState("scan_lesson"),[a,l]=f.useState(""),[c,d]=f.useState(""),[u,m]=f.useState(!1),[p,h]=f.useState([]),[x,g]=f.useState([]),[b,w]=f.useState(!1),[y,S]=f.useState({}),[C,k]=f.useState(10),[v,N]=f.useState("quiz"),O=f.useRef(y);return f.useEffect(()=>{O.current=y},[y]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:i,setQuizGenMode:o,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:l,quizGenTopic:c,setQuizGenTopic:d,isGeneratingSuggestions:u,setIsGeneratingSuggestions:m,suggestedObjectives:p,setSuggestedObjectives:h,suggestedQuestions:x,setSuggestedQuestions:g,savingQuiz:b,setSavingQuiz:w,quizStudentAnswers:y,setQuizStudentAnswers:S,quizGenTimeLimit:C,setQuizGenTimeLimit:k,quizStudentAnswersRef:O,subAssignmentTab:v,setSubAssignmentTab:N}}function Rw(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:i,fetchClassStudents:o,handleExportAllClassesCombined:a}=e,[l,c]=f.useState(!1),[d,u]=f.useState(new Set),[m,p]=f.useState(new Set),[h,x]=f.useState(null),[g,b]=f.useState(""),[w,y]=f.useState(""),[S,C]=f.useState("");return{batchMode:l,setBatchMode:c,selectedClassIds:d,setSelectedClassIds:u,selectedStudentIds:m,setSelectedStudentIds:p,batchPicker:h,setBatchPicker:x,batchPickerLesson:g,setBatchPickerLesson:b,batchPickerDate:w,setBatchPickerDate:y,batchPickerTargetClass:S,setBatchPickerTargetClass:C,toggleClassSelection:A=>{u(U=>{const j=new Set(U);return j.has(A)?j.delete(A):j.add(A),j})},toggleSelectAllClasses:()=>{u(A=>A.size===n.length&&n.length>0?new Set:new Set(n.map(U=>U.id)))},toggleStudentSelection:A=>{p(U=>{const j=new Set(U);return j.has(A)?j.delete(A):j.add(A),j})},toggleSelectAllStudents:A=>{p(U=>U.size===A.length&&A.length>0?new Set:new Set(A.map(j=>j.id)))},handleBatchDeleteClasses:async()=>{if(d.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${d.size} 个班级吗?该操作不可恢复。`:`Delete ${d.size} selected classes permanently?`)){for(const A of d)await fetch(`/api/classes/${A}`,{method:"DELETE"});u(new Set),await i()}},handleBatchExportClasses:async()=>{d.size!==0&&await a(n.filter(A=>d.has(A.id)))},handleBatchSetPasscode:async()=>{if(d.size===0)return;const A=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(A!==null){for(const U of d)await fetch(`/api/classes/${U}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:A===""?null:A})});u(new Set),await i()}},handleBatchScheduleClasses:()=>{d.size!==0&&(b(""),y(new Date().toISOString().split("T")[0]),x("schedule"))},handleBatchDeleteStudents:async()=>{if(!(m.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${m.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${m.size} selected student accounts?`)){for(const A of m)await fetch(`/api/students/${A}`,{method:"DELETE"});p(new Set),await o(s)}},handleBatchResetPassword:async()=>{if(m.size===0||!s)return;const A=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(A===null||A.trim()==="")){for(const U of m)await fetch(`/api/students/${U}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:A})});p(new Set),await o(s)}},handleBatchTransferStudents:()=>{m.size===0||!s||(C(""),x("transfer"))},handleBatchSetLockedLesson:()=>{m.size===0||!s||(b(""),x("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(h==="schedule"){if(!g){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const A of d)await fetch(`/api/classes/${A}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:g,scheduledDate:w+" 09:00:00",status:"scheduled"})});u(new Set)}else if(h==="lockedLesson"){if(!g){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const A of m)await fetch(`/api/students/${A}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:g})});p(new Set)}else if(h==="transfer"){if(!S||S===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const A of m)await fetch(`/api/classes/${s}/students/${A}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:A})});p(new Set)}x(null),s&&await o(s)}}}}function _w(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[i,o]=f.useState([]),[a,l]=f.useState("seg-1"),[c,d]=f.useState(null),[u,m]=f.useState(null),[p,h]=f.useState("none"),[x,g]=f.useState(null),[b,w]=f.useState(!1),y=f.useRef(null),S=async(C,k)=>{h("saving");try{(await fetch(`/api/lessons/${C}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:k})})).ok?(s(N=>N.map(O=>O.id===C?{...O,timeline:JSON.stringify(k)}:O)),o(k),h("saved"),g(new Date)):h("error")}catch(v){console.error("Failed to save timeline:",v),h("error")}};return f.useEffect(()=>{if(t){const C=n.find(k=>k.id===t);if(C){let k=[];if(C.timeline)try{k=typeof C.timeline=="string"?JSON.parse(C.timeline):C.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 v=y.current!==t;y.current=t,k.length>0?(v||!k.some(N=>N.id===a))&&l(k[0].id):l(null)}}},[t,n]),{timelineSegments:i,setTimelineSegments:o,activeSegmentId:a,setActiveSegmentId:l,segmentToEdit:c,setSegmentToEdit:d,draggedSegmentIdx:u,setDraggedSegmentIdx:m,editorSaveStatus:p,setEditorSaveStatus:h,editorLastSavedTime:x,setEditorLastSavedTime:g,editorPanelsExpanded:b,setEditorPanelsExpanded:w,saveTimeline:S}}function Md(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
|
|
65
|
+
`)?`"${t.replace(/"/g,'""')}"`:t}async function Ow(e){const{classId:t,className:n,students:s,dashData:i,lang:o,addToast:a,setIsGeneratingPDFReport:l}=e;l(c=>({...c,[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 c=i.performance||[],d=i.assignments||[],u={};s.forEach(A=>{u[A.id]={id:A.id,name:A.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(A=>{const U=A.student_id;u[U]&&(u[U].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&u[U].submittedCount++,A.score!==null&&A.score!==void 0&&(u[U].totalGradesSum+=A.score,u[U].gradedCount++))});const m=Object.values(u).map(A=>{const U=A.gradedCount>0?A.totalGradesSum/A.gradedCount:0,j=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avgScore:U,submissionRate:j}});m.sort((A,U)=>U.avgScore-A.avgScore);let p=0,h=0,x=0,g=0;c.forEach(A=>{g++,(A.submission_status==="submitted"||A.submission_status==="graded")&&x++,A.score!==null&&A.score!==void 0&&(p+=A.score,h++)});const b=h>0?p/h:0,w=g>0?x/g*100:0,y={};d.forEach(A=>{y[A.id]={id:A.id,title:A.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(A=>{const U=A.assignment_id;y[U]&&(y[U].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&y[U].submittedCount++,A.score!==null&&A.score!==void 0&&y[U].scores.push(A.score))});const S=Object.values(y).map(A=>{const U=A.scores.length,j=A.scores.reduce((Y,K)=>Y+K,0),V=U>0?j/U:0,G=U>0?Math.max(...A.scores):0,E=U>0?Math.min(...A.scores):0,W=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avg:V,max:G,min:E,subRate:W}}),{jsPDF:C}=await Je(async()=>{const{jsPDF:A}=await import("./vendor-pdf-C1Vh2Aqq.js").then(U=>U.j);return{jsPDF:A}},[]),{applyPlugin:k}=await Je(async()=>{const{applyPlugin:A}=await import("./vendor-pdf-C1Vh2Aqq.js").then(U=>U.b);return{applyPlugin:A}},[]);k(C);const v=new C({orientation:"p",unit:"mm",format:"a4"}),N=[15,23,42],O=[79,70,229],D=[51,65,85],_=[226,232,240],T=A=>{v.setDrawColor(_[0],_[1],_[2]),v.setLineWidth(.3),v.line(14,A,196,A)};v.setFillColor(N[0],N[1],N[2]),v.rect(0,0,210,42,"F"),v.setTextColor(255,255,255),v.setFont("helvetica","bold"),v.setFontSize(20),v.text("CLASS PERFORMANCE REPORT",14,18),v.setFont("helvetica","normal"),v.setFontSize(10),v.setTextColor(194,205,225),v.text("Academic Insights • Generative Report Summary",14,25),v.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),v.setFillColor(O[0],O[1],O[2]),v.rect(172,10,24,24,"F"),v.setFont("helvetica","bold"),v.setFontSize(14),v.setTextColor(255,255,255),v.text("OS",180,26);let z=52;v.setTextColor(N[0],N[1],N[2]),v.setFont("helvetica","bold"),v.setFontSize(12),v.text("I. EXECUTIVE OVERVIEW",14,z),z+=6;const R=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${d.length} items`],["Global Assignment Submission Rate",`${w.toFixed(1)}%`],["Class Average Performance Score",`${b.toFixed(1)}%`]];v.autoTable({startY:z,head:[["Metric Indicator","Class-wide Metric Value"]],body:R,theme:"striped",headStyles:{fillColor:N,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:D,fontSize:9.5},margin:{left:14,right:14}}),z=v.lastAutoTable.finalY+12,v.setTextColor(N[0],N[1],N[2]),v.setFont("helvetica","bold"),v.setFontSize(12),v.text("II. STUDENT RANKING DISTRIBUTION",14,z),z+=6;const $=m.map((A,U)=>{let j="Excellent";return A.avgScore>=90?j="Excellent (A)":A.avgScore>=75?j="Good (B)":A.avgScore>=60?j="Satisfactory (C)":j="Needs Improvement (D)",[`${U+1}`,A.name,`${A.submittedCount}/${A.totalCount} (${A.submissionRate.toFixed(0)}%)`,`${A.avgScore.toFixed(1)}%`,j]});v.autoTable({startY:z,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:$,theme:"grid",headStyles:{fillColor:O,textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:D,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}}),z=v.lastAutoTable.finalY+12,z>210&&(v.addPage(),z=20),v.setTextColor(N[0],N[1],N[2]),v.setFont("helvetica","bold"),v.setFontSize(12),v.text("III. ASSIGNMENT PERFORMANCE METRICS",14,z),z+=6;const I=S.map(A=>[A.title,`${A.subRate.toFixed(0)}%`,`${A.avg.toFixed(1)}%`,`${A.min.toFixed(0)}% - ${A.max.toFixed(0)}%`]);v.autoTable({startY:z,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:I.length>0?I:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:D,fontSize:9.5},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),z=v.lastAutoTable.finalY+15,T(275),v.setFontSize(8),v.setTextColor(148,163,184),v.text("Generated by OpenLearn Next • Educational Operating System",14,282),v.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const B=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),H=new Date().toISOString().split("T")[0];v.save(`Class_Report_${B}_${H}.pdf`),a(o==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",o==="zh"?`班级【${n}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${n} saved to your device.`,"success")}catch(c){console.error("PDF Generation Failed:",c),a(o==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",c.message||"Error occurred during PDF generation","warning")}finally{l(c=>({...c,[t]:!1}))}}function Dw(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 l=s.assignments||[],c=s.performance||[],d=l.map(S=>{let C="assignment";if(a[S.id])C=a[S.id];else{const k=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),v=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));C=k||v?"quiz":"assignment"}return{...S,category:C}}),u=["Student Name","Student Email"];d.forEach(S=>{const C=S.category==="quiz"?"Quiz":"Assignment";u.push(`${C}: ${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 C=[S.name,S.email];let k=0,v=0,N=0,O=0,D=0,_=0,T=0;d.forEach(A=>{const U=c.find(j=>j.assignment_id===A.id&&j.student_id===S.id);if(U&&U.score!==null&&U.score!==void 0){C.push(`${U.score}%`);const j=Number(U.score);A.category==="quiz"?(k+=j,v++):(N+=j,O++),D+=j,_++,T++}else U&&U.submission_status==="submitted"?(C.push("Pending Grade"),T++):C.push("Not Submitted")});const z=v>0?Math.round(k/v):null,R=O>0?Math.round(N/O):null;let $="N/A";if(z!==null&&R!==null){const A=z*(i/100)+R*(o/100);$=`${Math.round(A)}%`}else z!==null?$=`${z}%`:R!==null&&($=`${R}%`);const I=z!==null?`${z}%`:"N/A",B=R!==null?`${R}%`:"N/A",H=_>0?`${Math.round(D/_)}%`:"N/A";C.push(I,B,$,H,`${T}`,`${l.length}`),m.push(C.map(Md))});const p=m.map(S=>S.join(",")).join(`
|
|
66
|
+
`),h=new Blob(["\uFEFF"+p],{type:"text/csv;charset=utf-8;"}),x=URL.createObjectURL(h),g=document.createElement("a"),b=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),w=new Date().toISOString().split("T")[0],y=`${b}_grades_report_${w}.csv`;g.setAttribute("href",x),g.setAttribute("download",y),g.style.visibility="hidden",document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(x)}function Mw(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:i,assignmentsWeight:o,customCategoryOverrides:a,lang:l}=e;if(!t)return null;const c=n[t]||[],d=s[t];if(!d||!d.assignments||c.length===0)return null;const u=d.assignments||[],m=d.performance||[],p=u.map(b=>{let w="assignment";if(a[b.id])w=a[b.id];else{const y=b.content&&b.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=b.title&&(b.title.toLowerCase().includes("quiz")||b.title.toLowerCase().includes("test")||b.title.includes("测验")||b.title.includes("测试"));w=y||S?"quiz":"assignment"}return{...b,category:w}}),h=["Student Name","Student Email"];p.forEach(b=>{const w=b.category==="quiz"?"Quiz":"Assignment";h.push(`${w}: ${b.title}`)}),h.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${o}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const x=[];return c.slice(0,5).forEach(b=>{const w=[b.name,b.email];let y=0,S=0,C=0,k=0,v=0,N=0,O=0;p.forEach(I=>{const B=m.find(H=>H.assignment_id===I.id&&H.student_id===b.id);if(B&&B.score!==null&&B.score!==void 0){w.push(`${B.score}%`);const H=Number(B.score);I.category==="quiz"?(y+=H,S++):(C+=H,k++),v+=H,N++,O++}else B&&B.submission_status==="submitted"?(w.push(l==="zh"?"待评分":"Pending Grade"),O++):w.push(l==="zh"?"未提交":"Not Submitted")});const D=S>0?Math.round(y/S):null,_=k>0?Math.round(C/k):null;let T="N/A";if(D!==null&&_!==null){const I=D*(i/100)+_*(o/100);T=`${Math.round(I)}%`}else D!==null?T=`${D}%`:_!==null&&(T=`${_}%`);const z=D!==null?`${D}%`:"N/A",R=_!==null?`${_}%`:"N/A",$=N>0?`${Math.round(v/N)}%`:"N/A";w.push(z,R,T,$,`${O}`,`${u.length}`),x.push(w)}),{headers:h,rows:x,totalStudents:c.length}}function $w(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||[],x=h.map(g=>{const b=g.content&&g.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=g.title&&(g.title.toLowerCase().includes("quiz")||g.title.toLowerCase().includes("test")||g.title.includes("测验")||g.title.includes("测试"));return{...g,category:b||w?"quiz":"assignment"}});m.forEach(g=>{let b=0,w=0,y=0,S=0,C=0,k=0;x.forEach(T=>{const z=p.performance?.find(R=>R.student_id===g.id&&R.assignment_id===T.id&&R.submission_status==="graded"&&R.score!==null);if(z){const R=Number(z.score);C+=R,k++,T.category==="quiz"?(b+=R,w++):(y+=R,S++)}});const v=w>0?Math.round(b/w):null,N=S>0?Math.round(y/S):null;let O=0;v!==null&&N!==null?O=Math.round(v*.4+N*.6):v!==null?O=Math.round(v):N!==null&&(O=Math.round(N));const D=k>0?Math.round(C/k):0,_=[u.name,g.name,g.email,v!==null?`${v}%`:"N/A",N!==null?`${N}%`:"N/A",`${O}%`,`${D}%`,`${k}`,`${h.length}`];a.push(_)})}),a.length<=1){alert(i==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const l="data:text/csv;charset=utf-8,\uFEFF"+a.map(u=>u.map(Md).join(",")).join(`
|
|
67
|
+
`),c=encodeURI(l),d=document.createElement("a");d.setAttribute("href",c),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 Fw(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:i,fetchClassStudents:o,fetchClassDashboard:a,fetchClassProgress:l,addToast:c=()=>{}}=e,[d,u]=f.useState(!1),[m,p]=f.useState(""),[h,x]=f.useState(""),[g,b]=f.useState(40),[w,y]=f.useState(60),[S,C]=f.useState({}),[k,v]=f.useState(!1),[N,O]=f.useState(!1),[D,_]=f.useState(null),[T,z]=f.useState(!1),[R,$]=f.useState({}),I=f.useCallback(E=>{const W=Math.min(100,Math.max(0,E));b(W),y(100-W)},[]),B=f.useCallback(E=>{const W=Math.min(100,Math.max(0,E));y(W),b(100-W)},[]),H=f.useMemo(()=>Mw({exportClassId:m,classStudentsMap:s,classDashboardMap:i,quizzesWeight:g,assignmentsWeight:w,customCategoryOverrides:S,lang:t}),[m,g,w,S,s,i,t]),A=f.useCallback(async(E,W)=>{_(E);try{await o(E),await a(E),await l(E),p(E),x(W),b(40),y(60),C({}),u(!0)}catch(Y){console.error(Y)}finally{_(null),v(!1)}},[o,a,l]),U=f.useCallback((E,W,Y=40,K=60,ne={})=>{Dw({className:W,students:s[E]||[],dashData:i[E],qWeight:Y,aWeight:K,overrides:ne})},[s,i]),j=f.useCallback(async(E,W)=>{await o(E),await a(E),await l(E),await Ow({classId:E,className:W,students:s[E]||[],dashData:i[E],lang:t,addToast:c,setIsGeneratingPDFReport:$})},[s,i,t,c,o,a,l]),V=f.useCallback(async()=>{z(!0);try{await $w({classes:n,classStudentsMap:s,classDashboardMap:i,lang:t})}catch(E){console.error("Export all classes error:",E)}finally{z(!1),v(!1)}},[n,s,i,t]),G=f.useCallback((E,W)=>{const Y=i[W];if(!Y||!Y.performance)return null;const K=Date.now()-2592e6,fe=Y.performance.filter(me=>me.student_id===E).filter(me=>me.submitted_at&&me.submitted_at>=K&&me.score!==null&&me.score!==void 0);if(fe.length===0)return null;const X=fe.reduce((me,ke)=>me+Number(ke.score),0)/fe.length;return X<60?Math.round(X):null},[i]);return{isExportWeightModalOpen:d,setIsExportWeightModalOpen:u,exportClassId:m,setExportClassId:p,exportClassName:h,setExportClassName:x,quizzesWeight:g,setQuizzesWeight:b,assignmentsWeight:w,setAssignmentsWeight:y,customCategoryOverrides:S,setCustomCategoryOverrides:C,exportDropdownOpen:k,setExportDropdownOpen:v,exportTooltipOpen:N,setExportTooltipOpen:O,loadingExportClassId:D,setLoadingExportClassId:_,isExportingAllCombined:T,setIsExportingAllCombined:z,isGeneratingPDFReport:R,setIsGeneratingPDFReport:$,handleQuizzesWeightChange:I,handleAssignmentsWeightChange:B,csvPreviewData:H,triggerExportForClass:A,handleExportGrades:U,handleGeneratePDFReport:j,handleExportAllClassesCombined:V,get30DayAverageWarning:G}}class Bw{constructor(){this.store=St(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId;this.store.setState(i=>{const o=new Map(i.items);return o.set(t.type,{config:{...t,pluginId:s},pluginId:s}),{items:o}})}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 Sn=new Bw;function TN(){return Ft(Sn.getStore(),Fc(e=>Array.from(e.items.values()).map(t=>t.config)))}const PN={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"}},IN=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],Uw=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:Fo,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
|
|
68
|
+
---
|
|
69
|
+
## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
|
|
70
|
+
---
|
|
71
|
+
## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:Xs,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:Mo,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:Xi,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
|
|
72
|
+
<div style='padding:20px; text-align:center;'>
|
|
73
|
+
<h2>Interactive Web Courseware</h2>
|
|
74
|
+
<p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
|
|
75
|
+
</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:Hc,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:Ss,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:Gc,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:yt,color:"pink",group:"manage",defaultData:{},editFields:[]}],Vw=Uw.reduce((e,t)=>(e[t.type]=t,e),{});function Hw(e){return Vw[e]||Sn.get(e)}const _l="openlearnv2.agentProviderId";function Ww({lang:e,addToast:t,host:n,session:s,fetchStudents:i,fetchClasses:o,chatLogRef:a}){const l=de(ae=>ae.lessons),c=de(ae=>ae.setLessons),d=iw(l),{lessonsSearchQuery:u,setLessonsSearchQuery:m,lessonsSortOrder:p,setLessonsSortOrder:h,filterEnrollment:x,setFilterEnrollment:g,filterHasContent:b,setFilterHasContent:w,filterThisMonth:y,setFilterThisMonth:S,copyingLessonId:C,setCopyingLessonId:k,filteredAndSortedLessons:v}=d,N=de(ae=>ae.selectedLesson),O=de(ae=>ae.setSelectedLesson),D=de(ae=>ae.elements),_=de(ae=>ae.setElements),[T,z]=f.useState(!1),[R,$]=f.useState("agent"),I=de(ae=>ae.classes),B=de(ae=>ae.setClasses),H=de(ae=>ae.students),A=de(ae=>ae.setStudents);de(ae=>ae.dataVersion);const U=ow(),{computerLabs:j,setComputerLabs:V,loadingLabs:G,setLoadingLabs:E,fetchLabs:W,classSeats:Y,setClassSeats:K,savingSeats:ne,setSavingSeats:fe,fetchClassSeats:je,todaySchedules:X,setTodaySchedules:me,fetchTodaySchedules:ke,classSchedulesMap:Se,setClassSchedulesMap:M,fetchClassSchedules:Z,scheduleAttendanceMap:ee,setScheduleAttendanceMap:te,fetchScheduleAttendance:ce,expandedScheduleId:oe,setExpandedScheduleId:xe,newScheduleDate:ie,setNewScheduleDate:Pe,newScheduleLessonId:ze,setNewScheduleLessonId:ue}=U,re=aw({lang:e,addToast:t,setCopyingLessonId:k}),{fetchLessons:P,handleQuickCreateLesson:L,handleDeleteCourse:F,handleCopyCourse:q,fetchElements:J}=re,be=bw({fetchClassSchedules:Z}),{classStudentsMap:se,setClassStudentsMap:ye,classProgressMap:$e,setClassProgressMap:Fe,classDashboardMap:Ce,setClassDashboardMap:We,classAssignmentsMap:He,setClassAssignmentsMap:Et,assignmentSubmissionsMap:et,setAssignmentSubmissionsMap:jt,liveClassStudentProgress:Vt,setLiveClassStudentProgress:Ln,fetchClassStudents:Ht,fetchClassProgress:Re,fetchClassDashboard:rn,fetchLiveClassStudentProgress:Rn,handleQuickScheduleClass:_n,handleQuickGenerateAssignment:On}=be,[on,Dn]=f.useState(null),an=ae=>{Dn(ae)},[Mn,$n]=f.useState(null),Fn=ae=>{$n(ae)},Tt=f.useRef(null),[ln,Wt]=f.useState(null),Bn=ae=>{const ns=Hw(ae);ns&&Wt({type:ae,data:{...ns.defaultData}})},Un=async ae=>{const ns=ln;if(Wt(null),!ns)return;const Sp=Date.now()+15e3;for(;Date.now()<Sp;){const Fa=Tt.current?.addElementAtCenter;if(typeof Fa=="function"){await Fa(ns.type,ae);return}await new Promise(jp=>setTimeout(jp,50))}},Pt=de(ae=>ae.siteInfo),cn=de(ae=>ae.setSiteInfo),dn=_w({selectedLesson:N,lessons:l,setLessons:c}),{timelineSegments:_e,setTimelineSegments:Vn,activeSegmentId:Hn,setActiveSegmentId:Wn,segmentToEdit:qn,setSegmentToEdit:Gn,draggedSegmentIdx:Qn,setDraggedSegmentIdx:Jn,editorSaveStatus:Kn,setEditorSaveStatus:Yn,editorLastSavedTime:Zn,setEditorLastSavedTime:Xn,editorPanelsExpanded:es,setEditorPanelsExpanded:ts,saveTimeline:ge}=dn,Ke=yw(s),{registeredCommands:qt,setRegisteredCommands:pe,vfsNodes:qe,setVfsNodes:Ze,processes:Xe,setProcesses:mt,showProcessLogs:rt,setShowProcessLogs:It,processLogsContent:Gt,setProcessLogsContent:zs,showLogs:Wr,setShowLogs:Ls,currentVfsParent:qr,setCurrentVfsParent:Gr,fetchRegisteredCommands:Rs,fetchVfs:Qr,fetchProcesses:Jr,fetchProcessLogs:Ge}=Ke,Ia=Pw({lang:e,fetchClasses:o,fetchStudents:i,fetchLessons:P,addToast:t}),{isCloudDriveOpen:Vu,setIsCloudDriveOpen:Hu,cloudDrivePreviewNode:Wu,setCloudDrivePreviewNode:qu,isSystemResourceLibraryOpen:Gu,setIsSystemResourceLibraryOpen:Qu,systemResourceTab:Ju,setSystemResourceTab:Ku,selectedLibraryResourceId:Yu,setSelectedLibraryResourceId:Zu,libraryResources:Xu,setLibraryResources:eh,loadingLibraryResources:th,setLoadingLibraryResources:nh,showCoursewareHub:sh,setShowCoursewareHub:rh,fetchLibraryResources:ih,isImportLessonsOpen:oh,setIsImportLessonsOpen:ah,importStatus:lh,setImportStatus:ch,importProgress:dh,setImportProgress:uh,importProgressTotal:hh,setImportProgressTotal:fh,importErrorMsg:mh,setImportErrorMsg:ph,previewImportData:gh,setPreviewImportData:xh,isDraggingImport:bh,setIsDraggingImport:yh,downloadCsvTemplate:wh,handleCSVFileChange:vh,handleCSVImportSubmit:Sh,showImportModal:jh,setShowImportModal:kh,isImporting:Ch,setIsImporting:Nh,importError:Eh,setImportError:Th,importSuccess:Ph,setImportSuccess:Ih,downloadCSVTemplate:Ah,handleImportFile:zh}=Ia,Aa=de(ae=>ae.setTeacherTab),za=Iw({lang:e,addToast:t,fetchLessons:P,setSelectedLesson:O,setTeacherTab:Aa}),{isCourseWizardOpen:Lh,setIsCourseWizardOpen:Rh,wizardStep:_h,setWizardStep:Oh,wizardCourseTitle:Dh,setWizardCourseTitle:Mh,wizardCourseCategory:$h,setWizardCourseCategory:Fh,wizardCourseDescription:Bh,setWizardCourseDescription:Uh,wizardCourseContent:Vh,setWizardCourseContent:Hh,wizardCourseTimeline:Wh,setWizardCourseTimeline:qh,wizardIsSubmitting:Gh,wizardIsGeneratingOutline:Qh,handleGenerateOutline:Jh,handleDeployWizardCourse:Kh}=za,La=zw({session:s,host:n,lang:e,addToast:t,setChatLog:ae=>a.current(ae),setTeacherTab:Aa,fetchLessons:P}),{plugins:Yh,setPlugins:Zh,fetchPlugins:Xh,aiProviders:At,setAiProviders:ef,fetchAIProviders:tf,isAIProviderModalOpen:nf,setIsAIProviderModalOpen:sf,editingAIProvider:rf,setEditingAIProvider:of,providerName:af,setProviderName:lf,providerApiUrl:cf,setProviderApiUrl:df,providerApiKey:uf,setProviderApiKey:hf,providerModelName:ff,setProviderModelName:mf,testingProviderId:pf,setTestingProviderId:gf,showPluginModal:xf,setShowPluginModal:bf,storeTab:yf,setStoreTab:wf,pluginCode:vf,setPluginCode:Sf,installingPlugin:jf,setInstallingPlugin:kf,events:Cf,setEvents:Nf,fetchEvents:Ef,approvals:Tf,setApprovals:Pf,fetchApprovals:If,scoreOverrides:Af,setScoreOverrides:zf,handleSaveAIProvider:Lf,handleDeleteAIProvider:Rf,handleTestAIProvider:_f,handleInstallPlugin:Of,handleZipPluginUpload:Df,handleTogglePlugin:Mf,handleDeletePlugin:$f,handleApprove:Ff,handleReject:Bf}=La,[Qt,Ra]=f.useState(()=>typeof window>"u"?"":window.localStorage.getItem(_l)||""),_a=At.some(ae=>ae.id===Qt)?Qt:At[0]?.id||"",Uf=At.find(ae=>ae.id===_a)||null;f.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(_l,Qt)},[Qt]),f.useEffect(()=>{At.length>0&&!At.some(ae=>ae.id===Qt)&&Ra(At[0].id)},[At,Qt]);const Oa=Lw(),{isQuizGeneratorOpen:Vf,setIsQuizGeneratorOpen:Hf,quizGeneratorClassId:Wf,setQuizGeneratorClassId:qf,quizGenMode:Gf,setQuizGenMode:Qf,quizGenSelectedLessonId:Jf,setQuizGenSelectedLessonId:Kf,quizGenTopic:Yf,setQuizGenTopic:Zf,isGeneratingSuggestions:Xf,setIsGeneratingSuggestions:em,suggestedObjectives:tm,setSuggestedObjectives:nm,suggestedQuestions:sm,setSuggestedQuestions:rm,savingQuiz:im,setSavingQuiz:om,quizStudentAnswers:am,setQuizStudentAnswers:lm,quizGenTimeLimit:cm,setQuizGenTimeLimit:dm,quizStudentAnswersRef:um,subAssignmentTab:hm,setSubAssignmentTab:fm}=Oa,[mm,pm]=f.useState(null),[gm,xm]=f.useState("dueDate"),[bm,ym]=f.useState({}),Da=Fw({lang:e,classes:I,classStudentsMap:se,classDashboardMap:Ce,fetchClassStudents:Ht,fetchClassDashboard:rn,fetchClassProgress:Re}),{isExportWeightModalOpen:wm,setIsExportWeightModalOpen:vm,exportClassId:Sm,setExportClassId:jm,exportClassName:km,setExportClassName:Cm,quizzesWeight:Nm,setQuizzesWeight:Em,assignmentsWeight:Tm,setAssignmentsWeight:Pm,customCategoryOverrides:Im,setCustomCategoryOverrides:Am,exportDropdownOpen:zm,setExportDropdownOpen:Lm,exportTooltipOpen:Rm,setExportTooltipOpen:_m,loadingExportClassId:Om,setLoadingExportClassId:Dm,isExportingAllCombined:Mm,setIsExportingAllCombined:$m,isGeneratingPDFReport:Fm,setIsGeneratingPDFReport:Bm,handleQuizzesWeightChange:Um,handleAssignmentsWeightChange:Vm,csvPreviewData:Hm,triggerExportForClass:Wm,handleExportGrades:qm,handleGeneratePDFReport:Gm,handleExportAllClassesCombined:Ma,get30DayAverageWarning:Qm}=Da,$a=Rw({lang:e,classes:I,expandedClassId:on,fetchClasses:o,fetchClassStudents:Ht,handleExportAllClassesCombined:Ma}),{batchMode:Jm,setBatchMode:Km,selectedClassIds:Ym,setSelectedClassIds:Zm,selectedStudentIds:Xm,setSelectedStudentIds:ep,batchPicker:tp,setBatchPicker:np,batchPickerLesson:sp,setBatchPickerLesson:rp,batchPickerDate:ip,setBatchPickerDate:op,batchPickerTargetClass:ap,setBatchPickerTargetClass:lp,toggleClassSelection:cp,toggleSelectAllClasses:dp,toggleStudentSelection:up,toggleSelectAllStudents:hp,handleBatchDeleteClasses:fp,handleBatchExportClasses:mp,handleBatchSetPasscode:pp,handleBatchScheduleClasses:gp,handleBatchDeleteStudents:xp,handleBatchResetPassword:bp,handleBatchTransferStudents:yp,handleBatchSetLockedLesson:wp,confirmBatchPicker:vp}=$a;return{lessons:l,setLessons:c,lessonFilteringData:d,lessonsSearchQuery:u,setLessonsSearchQuery:m,lessonsSortOrder:p,setLessonsSortOrder:h,filterEnrollment:x,setFilterEnrollment:g,filterHasContent:b,setFilterHasContent:w,filterThisMonth:y,setFilterThisMonth:S,copyingLessonId:C,setCopyingLessonId:k,filteredAndSortedLessons:v,selectedLesson:N,setSelectedLesson:O,elements:D,setElements:_,showRightSidebar:T,setShowRightSidebar:z,rightSidebarTab:R,setRightSidebarTab:$,classes:I,setClasses:B,students:H,setStudents:A,labAndScheduleData:U,computerLabs:j,setComputerLabs:V,loadingLabs:G,setLoadingLabs:E,fetchLabs:W,classSeats:Y,setClassSeats:K,savingSeats:ne,setSavingSeats:fe,fetchClassSeats:je,todaySchedules:X,setTodaySchedules:me,fetchTodaySchedules:ke,classSchedulesMap:Se,setClassSchedulesMap:M,fetchClassSchedules:Z,scheduleAttendanceMap:ee,setScheduleAttendanceMap:te,fetchScheduleAttendance:ce,expandedScheduleId:oe,setExpandedScheduleId:xe,newScheduleDate:ie,setNewScheduleDate:Pe,newScheduleLessonId:ze,setNewScheduleLessonId:ue,lessonCrudData:re,fetchLessons:P,handleQuickCreateLesson:L,handleDeleteCourse:F,handleCopyCourse:q,fetchElements:J,classOpsData:be,classStudentsMap:se,setClassStudentsMap:ye,classProgressMap:$e,setClassProgressMap:Fe,classDashboardMap:Ce,setClassDashboardMap:We,classAssignmentsMap:He,setClassAssignmentsMap:Et,assignmentSubmissionsMap:et,setAssignmentSubmissionsMap:jt,liveClassStudentProgress:Vt,setLiveClassStudentProgress:Ln,fetchClassStudents:Ht,fetchClassProgress:Re,fetchClassDashboard:rn,fetchLiveClassStudentProgress:Rn,handleQuickScheduleClass:_n,handleQuickGenerateAssignment:On,expandedClassId:on,setExpandedClassId:an,expandedStudentId:Mn,setExpandedStudentId:Fn,whiteboardRef:Tt,paletteEdit:ln,setPaletteEdit:Wt,handlePaletteActivate:Bn,handlePaletteConfirm:Un,siteInfo:Pt,setSiteInfo:cn,lessonTimelineData:dn,timelineSegments:_e,setTimelineSegments:Vn,activeSegmentId:Hn,setActiveSegmentId:Wn,segmentToEdit:qn,setSegmentToEdit:Gn,draggedSegmentIdx:Qn,setDraggedSegmentIdx:Jn,editorSaveStatus:Kn,setEditorSaveStatus:Yn,editorLastSavedTime:Zn,setEditorLastSavedTime:Xn,editorPanelsExpanded:es,setEditorPanelsExpanded:ts,saveTimeline:ge,systemData:Ke,registeredCommands:qt,setRegisteredCommands:pe,vfsNodes:qe,setVfsNodes:Ze,processes:Xe,setProcesses:mt,showProcessLogs:rt,setShowProcessLogs:It,processLogsContent:Gt,setProcessLogsContent:zs,showLogs:Wr,setShowLogs:Ls,currentVfsParent:qr,setCurrentVfsParent:Gr,fetchRegisteredCommands:Rs,fetchVfs:Qr,fetchProcesses:Jr,fetchProcessLogs:Ge,resourceLibraryData:Ia,isCloudDriveOpen:Vu,setIsCloudDriveOpen:Hu,cloudDrivePreviewNode:Wu,setCloudDrivePreviewNode:qu,isSystemResourceLibraryOpen:Gu,setIsSystemResourceLibraryOpen:Qu,systemResourceTab:Ju,setSystemResourceTab:Ku,selectedLibraryResourceId:Yu,setSelectedLibraryResourceId:Zu,libraryResources:Xu,setLibraryResources:eh,loadingLibraryResources:th,setLoadingLibraryResources:nh,showCoursewareHub:sh,setShowCoursewareHub:rh,fetchLibraryResources:ih,isImportLessonsOpen:oh,setIsImportLessonsOpen:ah,importStatus:lh,setImportStatus:ch,importProgress:dh,setImportProgress:uh,importProgressTotal:hh,setImportProgressTotal:fh,importErrorMsg:mh,setImportErrorMsg:ph,previewImportData:gh,setPreviewImportData:xh,isDraggingImport:bh,setIsDraggingImport:yh,downloadCsvTemplate:wh,handleCSVFileChange:vh,handleCSVImportSubmit:Sh,showImportModal:jh,setShowImportModal:kh,isImporting:Ch,setIsImporting:Nh,importError:Eh,setImportError:Th,importSuccess:Ph,setImportSuccess:Ih,downloadCSVTemplate:Ah,handleImportFile:zh,courseWizard:za,isCourseWizardOpen:Lh,setIsCourseWizardOpen:Rh,wizardStep:_h,setWizardStep:Oh,wizardCourseTitle:Dh,setWizardCourseTitle:Mh,wizardCourseCategory:$h,setWizardCourseCategory:Fh,wizardCourseDescription:Bh,setWizardCourseDescription:Uh,wizardCourseContent:Vh,setWizardCourseContent:Hh,wizardCourseTimeline:Wh,setWizardCourseTimeline:qh,wizardIsSubmitting:Gh,wizardIsGeneratingOutline:Qh,handleGenerateOutline:Jh,handleDeployWizardCourse:Kh,pluginManagementData:La,plugins:Yh,setPlugins:Zh,fetchPlugins:Xh,aiProviders:At,setAiProviders:ef,fetchAIProviders:tf,isAIProviderModalOpen:nf,setIsAIProviderModalOpen:sf,editingAIProvider:rf,setEditingAIProvider:of,providerName:af,setProviderName:lf,providerApiUrl:cf,setProviderApiUrl:df,providerApiKey:uf,setProviderApiKey:hf,providerModelName:ff,setProviderModelName:mf,testingProviderId:pf,setTestingProviderId:gf,showPluginModal:xf,setShowPluginModal:bf,storeTab:yf,setStoreTab:wf,pluginCode:vf,setPluginCode:Sf,installingPlugin:jf,setInstallingPlugin:kf,events:Cf,setEvents:Nf,fetchEvents:Ef,approvals:Tf,setApprovals:Pf,fetchApprovals:If,scoreOverrides:Af,setScoreOverrides:zf,handleSaveAIProvider:Lf,handleDeleteAIProvider:Rf,handleTestAIProvider:_f,handleInstallPlugin:Of,handleZipPluginUpload:Df,handleTogglePlugin:Mf,handleDeletePlugin:$f,handleApprove:Ff,handleReject:Bf,agentProviderId:Qt,setAgentProviderId:Ra,effectiveAgentProviderId:_a,selectedAgentProvider:Uf,quizGenerator:Oa,isQuizGeneratorOpen:Vf,setIsQuizGeneratorOpen:Hf,quizGeneratorClassId:Wf,setQuizGeneratorClassId:qf,quizGenMode:Gf,setQuizGenMode:Qf,quizGenSelectedLessonId:Jf,setQuizGenSelectedLessonId:Kf,quizGenTopic:Yf,setQuizGenTopic:Zf,isGeneratingSuggestions:Xf,setIsGeneratingSuggestions:em,suggestedObjectives:tm,setSuggestedObjectives:nm,suggestedQuestions:sm,setSuggestedQuestions:rm,savingQuiz:im,setSavingQuiz:om,quizStudentAnswers:am,setQuizStudentAnswers:lm,quizGenTimeLimit:cm,setQuizGenTimeLimit:dm,quizStudentAnswersRef:um,subAssignmentTab:hm,setSubAssignmentTab:fm,isGeneratingAssignment:mm,setIsGeneratingAssignment:pm,assignmentSortOrder:gm,setAssignmentSortOrder:xm,isGrading:bm,setIsGrading:ym,gradeExport:Da,isExportWeightModalOpen:wm,setIsExportWeightModalOpen:vm,exportClassId:Sm,setExportClassId:jm,exportClassName:km,setExportClassName:Cm,quizzesWeight:Nm,setQuizzesWeight:Em,assignmentsWeight:Tm,setAssignmentsWeight:Pm,customCategoryOverrides:Im,setCustomCategoryOverrides:Am,exportDropdownOpen:zm,setExportDropdownOpen:Lm,exportTooltipOpen:Rm,setExportTooltipOpen:_m,loadingExportClassId:Om,setLoadingExportClassId:Dm,isExportingAllCombined:Mm,setIsExportingAllCombined:$m,isGeneratingPDFReport:Fm,setIsGeneratingPDFReport:Bm,handleQuizzesWeightChange:Um,handleAssignmentsWeightChange:Vm,csvPreviewData:Hm,triggerExportForClass:Wm,handleExportGrades:qm,handleGeneratePDFReport:Gm,handleExportAllClassesCombined:Ma,get30DayAverageWarning:Qm,classBatch:$a,batchMode:Jm,setBatchMode:Km,selectedClassIds:Ym,setSelectedClassIds:Zm,selectedStudentIds:Xm,setSelectedStudentIds:ep,batchPicker:tp,setBatchPicker:np,batchPickerLesson:sp,setBatchPickerLesson:rp,batchPickerDate:ip,setBatchPickerDate:op,batchPickerTargetClass:ap,setBatchPickerTargetClass:lp,toggleClassSelection:cp,toggleSelectAllClasses:dp,toggleStudentSelection:up,toggleSelectAllStudents:hp,handleBatchDeleteClasses:fp,handleBatchExportClasses:mp,handleBatchSetPasscode:pp,handleBatchScheduleClasses:gp,handleBatchDeleteStudents:xp,handleBatchResetPassword:bp,handleBatchTransferStudents:yp,handleBatchSetLockedLesson:wp,confirmBatchPicker:vp,handleSeedSuccess:async ae=>{await o(),await P(),await ke().catch(()=>{}),ve.getState().setLiveClassSelectedClassId(ae.classId),O(ae.lessonId),ve.getState().setLiveClassIsActive(!0),t(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")}}}function qw(){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 x=new h,g=x.currentTime,b=x.createOscillator(),w=x.createGain();b.type="sine",b.frequency.setValueAtTime(587.33,g),b.frequency.exponentialRampToValueAtTime(880,g+.25),w.gain.setValueAtTime(.25,g),w.gain.exponentialRampToValueAtTime(.001,g+.8),b.connect(w),w.connect(x.destination),b.start(g),b.stop(g+.8)}}catch{}},[e]);const[i,o]=f.useState([]),a=h=>{o(x=>{const g=typeof h=="function"?h(x):h;return Array.isArray(g)&&g.length>200?g.slice(0,200):g})},[l,c]=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:l,setLiveClassAcknowledgedMap:c,onlineStudentIds:d,setOnlineStudentIds:u,activeStudentLessons:m,setActiveStudentLessons:p}}function Gw(e){const{activeStudentId:t,activeRole:n,selectedLesson:s,quizStudentAnswersRef:i,setStudentViewStatus:o}=e,a=de(y=>y.session),l=de(y=>y.setSelectedLesson),[c,d]=f.useState(null),[u,m]=f.useState({}),[p,h]=f.useState(null),x=async y=>{try{const{ok:S,data:C}=await xw(y);if(S){if(d(C),C.profile){const k=C.profile,v=ve.getState().students,N=v.findIndex(_=>_.id===C.profile.id),O=N>=0?v[N]:null;if(!O||O.locked_lesson_id!==k.locked_lesson_id||O.lock_mode!==k.lock_mode||JSON.stringify(O.lock_target)!==JSON.stringify(k.lock_target)||O.name!==k.name)if(N>=0){const _=[...v];_[N]={..._[N],...k},ve.getState().setStudents(_)}else ve.getState().setStudents([k])}C.profile&&C.profile.locked_lesson_id&&(l(C.profile.locked_lesson_id),o("lesson"))}}catch{}},g=async(y=!1)=>{if(!p||!t)return;const C=p?.content&&p.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(i.current):"Submitted via Whiteboard";try{const{ok:k}=await fw(p.id,{studentId:t,content:C});k&&(y&&alert("Time is up! Your assessment was successfully submitted automatically."),await x(t),o("dashboard"),h(null))}catch(k){console.error(k)}};return f.useEffect(()=>{a&&n==="student"&&t&&x(t)},[a,n,t]),{studentDashboardData:c,setStudentDashboardData:d,studentProgressMap:u,setStudentProgressMap:m,selectedAssignment:p,setSelectedAssignment:h,fetchStudentDashboard:x,fetchStudentProgress:async y=>{try{const{ok:S,data:C}=await a0(y);S&&m(k=>({...k,[y]:C}))}catch{}},updateStudentProgress:async y=>{if(n==="student"&&t&&s)try{await i0(t,{lessonId:s,completed:y===100,progressPercent:y})}catch(S){console.error("Failed to update student progress:",S)}},submitQuizAssignment:g}}function Qw(e,t,n){const[s,i]=f.useState(new Set),[o,a]=f.useState(null),[l,c]=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 x=!!h.feedback;m.push({id:`graded-${h.id}`,type:"graded",title:x?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:x?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,x)=>x.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:l,setIsNotificationsOpen:c}}function Jw(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:i,expandedClassId:o,fetchLessons:a,fetchClasses:l,fetchStudents:c,fetchClassStudents:d,fetchClassProgress:u,fetchClassDashboard:m,fetchElements:p}=e,[h,x]=f.useState([{role:"agent",content:n.agentIntro||""}]),[g,b]=f.useState(""),[w,y]=f.useState(!1),[S,C]=f.useState([]),[k,v]=f.useState("");f.useEffect(()=>{h.length===1&&h[0].role==="agent"&&x([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const N=f.useCallback(async z=>{try{const R=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(z||"")}`);if(!R.ok)return;const $=await R.json(),I=Array.isArray($.messages)?$.messages:[];I.length>0?x(I.map(B=>({role:B.role==="assistant"?"agent":"user",content:B.content}))):x([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),O=f.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(s||"")}`,{method:"DELETE"})}catch{}x([{role:"agent",content:n.agentIntro}])},[s,n.agentIntro]);return f.useEffect(()=>{N(s)},[s,N]),{personaId:k,setPersonaId:v,chatLog:h,setChatLog:x,input:g,setInput:b,loading:w,setLoading:y,chatAttachments:S,setChatAttachments:C,handleChatFileChange:z=>{z.target.files&&Array.from(z.target.files).forEach(R=>{const $=new FileReader;$.onload=I=>{I.target?.result&&C(B=>[...B,{name:R.name,content:I.target.result}])},R.name.endsWith(".zip")?$.readAsDataURL(R):$.readAsText(R)})},handleChatDrop:z=>{z.preventDefault(),z.dataTransfer.files&&Array.from(z.dataTransfer.files).forEach(R=>{const $=new FileReader;$.onload=I=>{I.target?.result&&C(B=>[...B,{name:R.name,content:I.target.result}])},R.name.endsWith(".zip")?$.readAsDataURL(R):$.readAsText(R)})},handleSend:async z=>{if(z.preventDefault(),!g.trim()||w)return;const R=[...S];let $=g;R.length>0&&($+=`
|
|
76
|
+
(📁 ${t==="zh"?"附件":"Attachments"}: ${R.map(I=>I.name).join(", ")})`),x(I=>[...I,{role:"user",content:$}]),b(""),C([]),y(!0);try{const I=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:g,lang:t,currentLessonId:s,attachments:R,providerId:i||null,personaId:k||null})}),B=await I.json();let H="";!I.ok||B.success===!1?H=`⚠️ ${B.message||B.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(H=B.agentText||"",B.toolResults&&B.toolResults.length>0&&(H+=`
|
|
77
|
+
|
|
78
|
+
${n.executedCommands}`+B.toolResults.map(A=>A.callName).join(", "))),x(A=>[...A,{role:"agent",content:H}]),await a(),await l(),await c(),o&&(await d(o),await u(o),await m(o)),s&&await p(s)}catch{x(I=>[...I,{role:"agent",content:n.simulationError}])}finally{y(!1)}},handleClearAgentMemory:O,restoreAgentMemory:N}}function Kw(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:i,selectedLesson:o,selectedAssignment:a,expandedClassId:l,fetchLessons:c,fetchPlugins:d,fetchRegisteredCommands:u,fetchEvents:m,fetchApprovals:p,fetchProcesses:h,fetchClasses:x,fetchTodaySchedules:g,fetchStudents:b,fetchLabs:w,fetchVfs:y,fetchProcessLogs:S,fetchClassStudents:C,fetchElements:k}=e,v=f.useRef(i),N=f.useRef(o),O=f.useRef(a),D=f.useRef(l);f.useEffect(()=>{v.current=i},[i]),f.useEffect(()=>{N.current=o},[o]),f.useEffect(()=>{O.current=a},[a]),f.useEffect(()=>{D.current=l},[l]),f.useEffect(()=>{if(!t)return;const _=t.role==="teacher",T=_&&(t.subRole==="administrator"||t.username==="admin"||t.userId==="usr_admin");c(),d(),u(),g().catch(()=>{}),T&&(m(),p(),h()),_&&(x(),b(),w(),y(v.current));let z=!1;const R=setInterval(async()=>{if(!z){z=!0;try{if(T&&(await m(),await p(),await h(),n&&await S(n)),await c(),await u(),await g().catch(()=>{}),_&&(await x(),await b(),await w(),await y(v.current),D.current&&await C(D.current)),O.current){const $=s||O.current.student_id;await k(`assignment-${O.current.id}-student-${$}`)}else N.current&&await k(N.current)}finally{z=!1}}},2e3);return()=>clearInterval(R)},[t,n,s]),f.useEffect(()=>{t&&t.role==="teacher"&&y(i)},[i,t]),f.useEffect(()=>{o&&k(o)},[o])}const wt=Object.create(null);wt.open="0";wt.close="1";wt.ping="2";wt.pong="3";wt.message="4";wt.upgrade="5";wt.noop="6";const or=Object.create(null);Object.keys(wt).forEach(e=>{or[wt[e]]=e});const uo={type:"error",data:"parser error"},$d=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Fd=typeof ArrayBuffer=="function",Bd=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,da=({type:e,data:t},n,s)=>$d&&t instanceof Blob?n?s(t):Ol(t,s):Fd&&(t instanceof ArrayBuffer||Bd(t))?n?s(t):Ol(new Blob([t]),s):s(wt[e]+(t||"")),Ol=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function Dl(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Si;function Yw(e,t){if($d&&e.data instanceof Blob)return e.data.arrayBuffer().then(Dl).then(t);if(Fd&&(e.data instanceof ArrayBuffer||Bd(e.data)))return t(Dl(e.data));da(e,!1,n=>{Si||(Si=new TextEncoder),t(Si.encode(n))})}const Ml="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",us=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Ml.length;e++)us[Ml.charCodeAt(e)]=e;const Zw=e=>{let t=e.length*.75,n=e.length,s,i=0,o,a,l,c;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=us[e.charCodeAt(s)],a=us[e.charCodeAt(s+1)],l=us[e.charCodeAt(s+2)],c=us[e.charCodeAt(s+3)],u[i++]=o<<2|a>>4,u[i++]=(a&15)<<4|l>>2,u[i++]=(l&3)<<6|c&63;return d},Xw=typeof ArrayBuffer=="function",ua=(e,t)=>{if(typeof e!="string")return{type:"message",data:Ud(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:ev(e.substring(1),t)}:or[n]?e.length>1?{type:or[n],data:e.substring(1)}:{type:or[n]}:uo},ev=(e,t)=>{if(Xw){const n=Zw(e);return Ud(n,t)}else return{base64:!0,data:e}},Ud=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Vd="",tv=(e,t)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((o,a)=>{da(o,!1,l=>{s[a]=l,++i===n&&t(s.join(Vd))})})},nv=(e,t)=>{const n=e.split(Vd),s=[];for(let i=0;i<n.length;i++){const o=ua(n[i],t);if(s.push(o),o.type==="error")break}return s};function sv(){return new TransformStream({transform(e,t){Yw(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 ji;function Vs(e){return e.reduce((t,n)=>t+n.length,0)}function Hs(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 rv(e,t){ji||(ji=new TextDecoder);const n=[];let s=0,i=-1,o=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(s===0){if(Vs(n)<1)break;const c=Hs(n,1);o=(c[0]&128)===128,i=c[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(Vs(n)<2)break;const c=Hs(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Vs(n)<8)break;const c=Hs(n,8),d=new DataView(c.buffer,c.byteOffset,c.length),u=d.getUint32(0);if(u>Math.pow(2,21)-1){l.enqueue(uo);break}i=u*Math.pow(2,32)+d.getUint32(4),s=3}else{if(Vs(n)<i)break;const c=Hs(n,i);l.enqueue(ua(o?c:ji.decode(c),t)),s=0}if(i===0||i>e){l.enqueue(uo);break}}}})}const Hd=4;function Ue(e){if(e)return iv(e)}function iv(e){for(var t in Ue.prototype)e[t]=Ue.prototype[t];return e}Ue.prototype.on=Ue.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Ue.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Ue.prototype.off=Ue.prototype.removeListener=Ue.prototype.removeAllListeners=Ue.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};Ue.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};Ue.prototype.emitReserved=Ue.prototype.emit;Ue.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Ue.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Fr=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),ct=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ov="arraybuffer";function Wd(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const av=ct.setTimeout,lv=ct.clearTimeout;function Br(e,t){t.useNativeTimers?(e.setTimeoutFn=av.bind(ct),e.clearTimeoutFn=lv.bind(ct)):(e.setTimeoutFn=ct.setTimeout.bind(ct),e.clearTimeoutFn=ct.clearTimeout.bind(ct))}const cv=1.33;function dv(e){return typeof e=="string"?uv(e):Math.ceil((e.byteLength||e.size)*cv)}function uv(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 qd(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function hv(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function fv(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 mv extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class ha extends Ue{constructor(t){super(),this.writable=!1,Br(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 mv(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=ua(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=hv(t);return n.length?"?"+n:""}}class pv extends ha{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)};nv(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,tv(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]=qd()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let Gd=!1;try{Gd=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const gv=Gd;function xv(){}class bv extends pv{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 jn=class ar extends Ue{constructor(t,n,s){super(),this.createRequest=t,Br(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=Wd(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=ar.requestsCount++,ar.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=xv,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ar.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()}};jn.requestsCount=0;jn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",$l);else if(typeof addEventListener=="function"){const e="onpagehide"in ct?"pagehide":"unload";addEventListener(e,$l,!1)}}function $l(){for(let e in jn.requests)jn.requests.hasOwnProperty(e)&&jn.requests[e].abort()}const yv=(function(){const e=Qd({xdomain:!1});return e&&e.responseType!==null})();class wv extends bv{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=yv&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new jn(Qd,this.uri(),t)}}function Qd(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||gv))return new XMLHttpRequest}catch{}if(!t)try{return new ct[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Jd=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class vv extends ha{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=Jd?{}:Wd(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;da(s,this.supportsBinary,o=>{try{this.doWrite(s,o)}catch{}i&&Fr(()=>{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]=qd()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const ki=ct.WebSocket||ct.MozWebSocket;class Sv extends vv{createSocket(t,n,s){return Jd?new ki(t,n,s):n?new ki(t,n):new ki(t)}doWrite(t,n){this.ws.send(n)}}class jv extends ha{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=rv(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),i=sv();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{s.read().then(({done:l,value:c})=>{l||(this.onPacket(c),o())}).catch(l=>{})};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&&Fr(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const kv={websocket:Sv,webtransport:jv,polling:wv},Cv=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Nv=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ho(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=Cv.exec(e||""),o={},a=14;for(;a--;)o[Nv[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=Ev(o,o.path),o.queryKey=Tv(o,o.query),o}function Ev(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 Tv(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,o){i&&(n[i]=o)}),n}const fo=typeof addEventListener=="function"&&typeof removeEventListener=="function",lr=[];fo&&addEventListener("offline",()=>{lr.forEach(e=>e())},!1);class Dt extends Ue{constructor(t,n){if(super(),this.binaryType=ov,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=ho(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=ho(n.host).host);Br(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=fv(this.opts.query)),fo&&(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"})},lr.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=Hd,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&&Dt.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",Dt.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+=dv(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,Fr(()=>{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(Dt.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(),fo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=lr.indexOf(this._offlineEventListener);s!==-1&&lr.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Dt.protocol=Hd;class Pv extends Dt{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;Dt.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;Dt.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 l(){a("transport closed")}function c(){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",l),this.off("close",c),this.off("upgrading",d)};n.once("open",i),n.once("error",a),n.once("close",l),this.once("close",c),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 Iv=class extends Pv{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=>kv[i]).filter(i=>!!i)),super(t,s)}};function Av(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=ho(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 zv=typeof ArrayBuffer=="function",Lv=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Kd=Object.prototype.toString,Rv=typeof Blob=="function"||typeof Blob<"u"&&Kd.call(Blob)==="[object BlobConstructor]",_v=typeof File=="function"||typeof File<"u"&&Kd.call(File)==="[object FileConstructor]";function fa(e){return zv&&(e instanceof ArrayBuffer||Lv(e))||Rv&&e instanceof Blob||_v&&e instanceof File}function cr(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(cr(e[n]))return!0;return!1}if(fa(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return cr(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&cr(e[n]))return!0;return!1}function Ov(e){const t=[],n=e.data,s=e;return s.data=dr(n,t),s.attachments=t.length,{packet:s,buffers:t}}function dr(e,t,n){if(!e)return e;if(fa(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]=dr(e[i],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return dr(e.toJSON(),t,!0);const s={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=dr(e[i],t));return s}return e}function Dv(e,t){return e.data=mo(e.data,t),delete e.attachments,e}function mo(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]=mo(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=mo(e[n],t));return e}const Mv=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var we;(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"})(we||(we={}));class $v{constructor(t){this.replacer=t}encode(t){return(t.type===we.EVENT||t.type===we.ACK)&&cr(t)?this.encodeAsBinary({type:t.type===we.EVENT?we.BINARY_EVENT:we.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===we.BINARY_EVENT||t.type===we.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=Ov(t),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}class ma extends Ue{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===we.BINARY_EVENT;s||n.type===we.BINARY_ACK?(n.type=s?we.EVENT:we.ACK,this.reconstructor=new Fv(n)):super.emitReserved("decoded",n)}else if(fa(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(we[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===we.BINARY_EVENT||s.type===we.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 l=Number(a);if(!Bv(l)||l<1)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}if(t.charAt(n+1)==="/"){const 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(ma.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 we.CONNECT:return Fl(n);case we.DISCONNECT:return n===void 0;case we.CONNECT_ERROR:return typeof n=="string"||Fl(n);case we.EVENT:case we.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Mv.indexOf(n[0])===-1);case we.ACK:case we.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Fv{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=Dv(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Bv=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Fl(e){return Object.prototype.toString.call(e)==="[object Object]"}const Uv=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ma,Encoder:$v,get PacketType(){return we}},Symbol.toStringTag,{value:"Module"}));function ut(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Vv=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Yd extends Ue{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=[ut(t,"open",this.onopen.bind(this)),ut(t,"packet",this.onpacket.bind(this)),ut(t,"error",this.onerror.bind(this)),ut(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(Vv.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:we.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 l=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!l||(c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,n){var s;const 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 l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},i),a=(...l)=>{this.io.clearTimeoutFn(o),n.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((s,i)=>{const o=(a,l)=>a?i(a):s(l);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:we.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 we.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 we.EVENT:case we.BINARY_EVENT:this.onevent(t);break;case we.ACK:case we.BINARY_ACK:this.onack(t);break;case we.DISCONNECT:this.ondisconnect();break;case we.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:we.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:we.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 In(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}In.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};In.prototype.reset=function(){this.attempts=0};In.prototype.setMin=function(e){this.ms=e};In.prototype.setMax=function(e){this.max=e};In.prototype.setJitter=function(e){this.jitter=e};class po extends Ue{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,Br(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 In({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||Uv;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 Iv(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=ut(n,"open",function(){s.onopen(),t&&t()}),o=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=ut(n,"error",o);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}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(ut(t,"ping",this.onping.bind(this)),ut(t,"data",this.ondata.bind(this)),ut(t,"error",this.onerror.bind(this)),ut(t,"close",this.onclose.bind(this)),ut(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){Fr(()=>{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 Yd(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 os={};function ur(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=Av(e,t.path||"/socket.io"),s=n.source,i=n.id,o=n.path,a=os[i]&&o in os[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let c;return l?c=new po(s,t):(os[i]||(os[i]=new po(s,t)),c=os[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(ur,{Manager:po,Socket:Yd,io:ur,connect:ur});class Hv{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"}}}}class Wv{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 qv{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 go=St(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null}),remoteBrowserFullscreenElementId:null,setRemoteBrowserFullscreenElementId:t=>e({remoteBrowserFullscreenElementId:t})})),zN=e=>Ft(go,e),Ci=new Set,Zd=St((e,t)=>({lastEvent:null,version:0,subscribe:n=>(Ci.add(n),()=>{Ci.delete(n)}),record:n=>{e({lastEvent:n,version:t().version+1});for(const s of Ci)try{s(n)}catch(i){console.error("[pointsLedgerStore] listener error:",i)}},reset:()=>{e({lastEvent:null,version:0})}})),LN=e=>Ft(Zd,e),Xd=200;function Gv(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 Qv{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??Xd,this.persist=t.persist??!1}ingest(t,n){const s={id:Or(),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=Gv(s);tn.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(l){console.error("[WhiteboardEventSlot] replay handler error:",l)}})}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 l=this.buffer[a];if(l.timestamp<i||Bl(l,t)&&(o.push(l),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(Bl(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 Jv(),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 Bl(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 Ws=null;function Jv(){return Ws||(Ws=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)}),Ws)}const _t=new Qv({capacity:Xd,persist:!1});typeof window<"u"&&tn.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);_t.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})});const Kv={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 Ul(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 RN(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 _N(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 ON(e,t=Math.random){if(!e||e.length===0)return null;if(e.length===1)return{student:e[0],weight:Ul(e[0])};const n=e.map(a=>Ul(a)),s=n.reduce((a,l)=>a+l,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 Yv(e){const{session:t,host:n,activeRole:s,activeStudentId:i,selectedLesson:o,activeSegmentId:a,studentViewStatus:l,lang:c,students:d,addToast:u,setOnlineStudentIds:m,setActiveStudentLessons:p,setLessons:h,setActiveSegmentId:x,setLiveClassStudentProgress:g,setLiveClassAcknowledgedMap:b,setLiveClassFeed:w,setSelectedLesson:y,setStudentViewStatus:S,studentLessonTab:C,setStudentLessonTab:k,selectedAssignment:v,setSelectedAssignment:N,setLocalProgressPercent:O,fetchStudentDashboard:D,fetchStudents:_,fetchElements:T,setPickedAlertData:z,setPickedAnnouncement:R,onStudentProgressUpdated:$}=e,I=f.useRef(null),B=f.useRef(s),H=f.useRef(i),A=f.useRef(c),U=f.useRef(d),j=f.useRef(u),V=f.useRef(o),G=f.useRef(null),E=f.useRef(l),W=f.useRef(new Map),Y=f.useRef(C),K=f.useRef(z),ne=f.useRef(R),fe=f.useRef($),je=f.useRef(null);return f.useEffect(()=>{B.current=s},[s]),f.useEffect(()=>{H.current=i},[i]),f.useEffect(()=>{A.current=c},[c]),f.useEffect(()=>{U.current=d},[d]),f.useEffect(()=>{j.current=u},[u]),f.useEffect(()=>{V.current=o},[o]),f.useEffect(()=>{E.current=l},[l]),f.useEffect(()=>{Y.current=C},[C]),f.useEffect(()=>{G.current=v},[v]),f.useEffect(()=>{K.current=z},[z]),f.useEffect(()=>{ne.current=R},[R]),f.useEffect(()=>{fe.current=$},[$]),f.useEffect(()=>{if(!t)return;const X=ur();I.current=X,xd(X),n.isInitialized()||n.initialize(new Hv,new Ux(X),new Wv(j.current),new qv("__app__"));const me=()=>{X.emit("join-room","whiteboard-broadcast");const M=ve.getState().liveClassSelectedClassId;B.current==="teacher"&&M&&X.emit("join-room",`class-${M}`),B.current==="student"&&H.current?(X.emit("register-student",{studentId:H.current,name:U.current.find(Z=>Z.id===H.current)?.name||H.current}),E.current==="lesson"&&V.current&&X.emit("enter-lesson",{studentId:H.current,lessonId:V.current})):X.emit("request-presence")};me(),X.on("presence-update",M=>{m(M.onlineStudentIds),p(M.activeStudentLessons)}),X.on("lesson-progress-mode-changed",M=>{const{lessonId:Z,progressMode:ee,progressConditions:te}=M;h(ce=>ce.map(oe=>oe.id===Z?{...oe,progress_mode:ee,progress_conditions:te}:oe))}),X.on("student-active-segment-changed",M=>{const{activeSegmentId:Z}=M;x(Z)}),X.on("segment-gate-changed",M=>{window.dispatchEvent(new CustomEvent("openlearn:segment-gate-changed",{detail:M}))}),X.on("student-pinged",M=>{const Z=M.message||(A.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");u(A.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",Z,"warning")}),X.on("student-progress-updated",M=>{const{studentId:Z,lessonId:ee,progressPercent:te,completed:ce}=M;g(oe=>{const xe=oe.findIndex(ie=>ie.student_id===Z);if(xe!==-1){const ie=[...oe];return ie[xe]={...ie[xe],progress_percent:te,completed:ce?1:0},ie}else return[...oe,{student_id:Z,progress_percent:te,completed:ce?1:0}]}),fe.current?.({studentId:Z,lessonId:ee,progressPercent:te,completed:!!ce,verified:M.verified===!0})}),X.on("student-error-alert",M=>{if(!(!M||!M.error)&&(B.current==="teacher"||t?.role==="administrator")){Xt.getState().addStudentError({...M.error,studentId:M.studentId,studentName:M.studentName||M.studentId,lessonId:M.lessonId,classId:M.classId});const Z=M.studentName?`${M.studentName} (${M.studentId})`:M.studentId;u(A.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${Z}: ${M.error.title||M.error.message}`,"warning")}}),X.on("assignment-graded-toast",M=>{if(B.current==="student"&&H.current&&M.studentId===H.current){const Z=M.assignmentTitle||M.assignmentId,ee=A.current==="zh"?`您的作业"${Z}"已完成评分!得分:${M.score}%。建议反馈已收到,快去查看。`:`Your assignment "${Z}" was graded. Score: ${M.score}%. Tutoring feedback has been posted.`;u(A.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",ee,"success"),D(H.current)}}),X.on("student-picked",M=>{const Z=`${M.studentId}:${M.pickedTime??""}`,ee=Date.now(),te=W.current.get(Z),ce=te!==void 0&&ee-te<1e4;if(!ce){W.current.set(Z,ee);for(const[ie,Pe]of W.current)ee-Pe>=1e4&&W.current.delete(ie)}const oe=H.current,xe=B.current==="student"&&oe&&M.studentId===oe;if(xe&&oe&&!ce){K.current?.({studentId:M.studentId,studentName:M.studentName,rollcallId:M.rollcallId});const ie=A.current==="zh"?"闪电警报!您已被老师在课程随机抽问中抽中!请立即集中注意力参与课堂回答。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";u(A.current==="zh"?"⚡️ 闪电抽问:老师抽中了你!":"⚡️ Classroom Pick Alert",ie,"warning"),D(oe)}else if(B.current==="student"&&!xe&&!ce){const ie=M.studentName||"同学";ne.current?.({studentName:ie,studentId:M.studentId});const Pe=A.current==="zh"?`老师在课堂中随机抽中了【${ie}】同学回答问题!`:`Teacher randomly selected [${ie}] to answer!`;u(A.current==="zh"?"🎯 课堂随机抽问":"🎯 Classroom Random Pick",Pe,"info")}w(ie=>[{id:`feed-pick-${M.studentId}-${M.pickedTime||Date.now()}`,time:new Date(M.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:A.current==="zh"?`点名互动:随机抽中学生【${M.studentName}】。`:`Classroom Pick: Randomly selected student "${M.studentName}".`},...ie])}),X.on("rollcall:evaluated",M=>{if(B.current!=="student"||M?.lessonId&&V.current&&M.lessonId!==V.current)return;const Z=!!H.current&&M?.studentId===H.current,ee=A.current==="zh",te=Kv[M?.rating];te&&(Z?(u(ee?`${te.badge} ${te.label} +${M.rewardCoins} 金币`:`${te.badge} ${te.labelEn} +${M.rewardCoins} coins`,ee?`老师在随机抽问中给了你「${te.label}」的评价,成长金币 +${M.rewardCoins} 已到账!`:`The teacher rated you "${te.labelEn}" in the random pick. +${M.rewardCoins} growth coins credited!`,"success"),H.current&&D(H.current)):u(ee?`${te.badge} 课堂表现评定`:`${te.badge} Classroom Evaluation`,ee?`老师给【${M.studentName||"某位同学"}】评了「${te.label}」。`:`The teacher rated "${M.studentName||"a student"}" as "${te.labelEn}".`,"info"),w(ce=>[{id:`feed-eval-${M.rollcallId||M.studentId}-${M.timestamp||Date.now()}`,time:new Date(M.timestamp||Date.now()).toLocaleTimeString(),type:"picked",message:ee?`点名评价:${M.studentName||"学生"} 获评「${te.label}」+${M.rewardCoins}金币。`:`Roll-call evaluation: "${M.studentName||"a student"}" rated ${te.labelEn} +${M.rewardCoins} coins.`},...ce]))}),X.on("classroom:points_awarded",M=>{if(!M?.studentId)return;const Z=A.current==="zh",ee=Number(M.deltaPoints)||0;Zd.getState().record({studentId:M.studentId,classId:M.classId??"",deltaPoints:ee,reason:M.reason??"",dimensionId:M.dimensionId,createdAt:M.createdAt}),!!H.current&&M.studentId===H.current&&(u(Z?ee>=0?"🎁 获得成长积分":"📉 积分调整":ee>=0?"Points earned":"Points adjusted",Z?`${ee>=0?"+":""}${ee} 积分${M.reason?`:${M.reason}`:""}`:`${ee>=0?"+":""}${ee} points${M.reason?`: ${M.reason}`:""}`,ee>=0?"success":"warning"),H.current&&D(H.current))}),X.on("student-acknowledged",M=>{const{studentId:Z}=M;b(ee=>{const te=new Map(ee);return te.set(Z,!0),te}),w(ee=>[{id:`feed-ack-${Z}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:A.current==="zh"?`学生已确认收到提问点名(学生 ID: ${Z})。`:`Student acknowledged the classroom call (Student ID: ${Z}).`},...ee]),_()}),X.on("class-lock-status-changed",M=>{const{lessonId:Z,locked:ee,mode:te,target:ce}=M||{};if(B.current==="student"&&H.current){const oe=H.current,xe=ve.getState().students,ie=xe.findIndex(ze=>ze.id===oe),Pe=ie>=0?{...xe[ie]}:{id:oe,name:""};if(Pe.locked_lesson_id=ee?Z:null,Pe.lock_mode=ee&&te||"full",Pe.lock_target=ee?ce:null,ie>=0){const ze=[...xe];ze[ie]=Pe,ve.getState().setStudents(ze)}else ve.getState().setStudents([Pe]);if(ee&&Z){y(Z),S("lesson"),ce?.tab&&k(ce.tab);const ze=te==="navigation";u(A.current==="zh"?ze?"🔒 答题锁定已开启":"🔒 课程已被锁定":ze?"🔒 Answer Lock Active":"🔒 Lesson Locked",A.current==="zh"?ze?"老师已开启答题锁定,请完成作答后提交,暂时无法离开本页。":"老师已锁定当前授课,您将无法切换到其他页面。":ze?"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")}D(oe)}else _()}),X.on("student-lesson-tab-changed",M=>{B.current==="student"&&M?.tab&&(!M.lessonId||M.lessonId===V.current)&&k(M.tab)}),X.on("teacher-switched-lesson",M=>{B.current==="student"&&M?.lessonId&&(y(M.lessonId),S("lesson"))}),X.on("whiteboard-sync",M=>{const{roomId:Z,type:ee}=M||{};if(ee!=="refresh"||!Z)return;const te=V.current;te&&te!==Z||(T(Z),!te&&B.current==="student"&&(y(Z),S("lesson")),X.emit("join-room",Z))});const ke=()=>{go.getState().clearRemoteFullscreen();const M=je.current;je.current=null,M&&(k(M.lessonTab),M.viewStatus==="assignment"&&(N(M.assignment??null),M.lessonId&&y(M.lessonId),S("assignment")))};X.on("whiteboard-fullscreen-changed",M=>{if(B.current!=="student")return;const Z=M?.lessonId,ee=M?.elementId??null,te=M?.mode==="browser",ce=go.getState();if(!ee){if(te){ce.setRemoteBrowserFullscreenElementId(null),ce.remoteFullscreenElementId||ke();return}ke();return}if(!Z)return;const oe=E.current;(oe==="lesson"?V.current===Z:oe==="assignment")&&(!ce.remoteFullscreenElementId&&!ce.remoteBrowserFullscreenElementId&&(je.current={viewStatus:oe,lessonTab:Y.current,lessonId:V.current,assignment:oe==="assignment"?G.current:null}),te?ce.setRemoteBrowserFullscreenElementId(ee):ce.setRemoteFullscreenElementId(ee),oe==="assignment"&&N(null),y(Z),T(Z),S("lesson"),k("whiteboard"))}),X.on("connect",()=>{me(),ke(),Promise.resolve(_()).catch(()=>{}),B.current==="student"&&H.current&&Promise.resolve(D(H.current)).catch(()=>{})}),X.io?.on("reconnect",()=>{me()});const Se=M=>{try{if(!M)return;_t.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(Z){console.error("[useClassroomSocket] quiz.answered ingest failed",Z)}};return X.on("whiteboard-quiz-answered-staff",M=>{B.current!=="teacher"&&t?.role!=="administrator"||Se(M)}),X.on("whiteboard-quiz-answered",M=>{B.current==="teacher"||t?.role==="administrator"||Se(M)}),X.on("courseware-attempt-updated",M=>{try{if(!M||typeof M.attemptId!="string")return;const Z=M.type==="log"?"courseware.event_logged":M.type==="submit"?"courseware.submitted":M.type==="promote"?"courseware.finished":"courseware.event_logged";_t.ingest({source:"iframe.bridge",type:Z,attemptId:M.attemptId,payload:{attemptId:M.attemptId,attemptType:M.type},raw:M})}catch(Z){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",Z)}}),()=>{X.disconnect(),I.current=null}},[t,s,i]),f.useEffect(()=>{I.current&&s==="student"&&i&&(l==="lesson"&&o?(I.current.emit("enter-lesson",{studentId:i,lessonId:o}),fetch(`/api/students/${i}/progress`).then(X=>X.json()).then(X=>{if(Array.isArray(X)){const me=X.find(ke=>ke.lesson_id===o);O(me?me.progress_percent:0)}}).catch(console.error)):I.current.emit("leave-lesson",{studentId:i}))},[l,o,s,i]),f.useEffect(()=>{s==="teacher"&&o&&a&&I.current&&I.current.emit("teacher-broadcast-segment",{lessonId:o,activeSegmentId:a})},[a,o,s]),{socketRef:I}}const Vl=new Map,Ni=new Map;async function Zv(e){const t=Vl.get(e);if(t)return t;const n=Ni.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?(Vl.set(e,o.attemptId),o.attemptId):e}catch(i){return console.warn("[LMS Bridge] Attempt adopt request failed:",i),e}finally{Ni.delete(e)}})();return Ni.set(e,s),s}const Tr=new Set;function Xv(e){return Tr.add(e),()=>{Tr.delete(e)}}function eu(e){if(!e)return null;for(const t of Tr)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 Hl(e){return typeof document>"u"||!e?!1:eu(e)!==null}function xo(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 bo=-1,yn=-2,eS=4;function tS(e){if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:typeof e.toJSON!="function"}function yo(e,t,n){if(e===null)return 4;const s=typeof e;if(s==="boolean")return e===!0?4:5;if(s==="number"){const c=e;return Number.isFinite(c)?String(c).length:4}if(s==="string")return xo(e);if(typeof e!="object")return 0;if(t>=eS||!tS(e))return bo;let i=2,o=!0;const a=c=>(i+=c,n.total+=c,n.total>n.limit),l=c=>(i+=c,n.total>n.limit?yn:null);if(Array.isArray(e)){for(let c=0;c<e.length;c++){if(!o&&a(1))return yn;o=!1;const d=e[c];if(d===void 0||typeof d=="function"||typeof d=="symbol"){if(a(4))return yn;continue}const u=yo(d,t+1,n);if(u<0)return u;const m=l(u);if(m!==null)return m}return i}for(const c of Object.keys(e)){let d;try{d=e[c]}catch{return bo}if(d===void 0||typeof d=="function"||typeof d=="symbol")continue;if(!o&&a(1)||(o=!1,a(xo(c)+1)))return yn;const u=yo(d,t+1,n);if(u<0)return u;const m=l(u);if(m!==null)return m}return i}function nS(e,t=512*1024){if(!e||typeof e=="number"||typeof e=="boolean")return!1;if(typeof e=="string")return xo(e)>t;const s=yo(e,0,{total:0,limit:t});if(s===yn)return!0;if(s===bo)try{return JSON.stringify(e).length>t}catch{return!1}return s>t}async function sS(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(nS(t,512*1024)){console.warn("[LMS Bridge] Dropped oversized postMessage (>512KB)");return}if(typeof window<"u"&&e.source&&e.source!==window&&!Hl(e.source))return;let i=t.attempt_id;const o=t.payload||t;if(!i&&e.source)try{const c=eu(e.source);if(c&&c.contentWindow){const d=c.contentWindow;d.__LMS_STUDENT__?.attempt_id&&(i=d.__LMS_STUDENT__.attempt_id)}}catch{}if(!i||typeof i!="string")return;if(i=await Zv(i),n==="LMS_CONFIG"){qs("courseware.config_reported",i,t.config??o);return}if(n==="LMS_GET_PROGRESS"){const c=t.requestId,d=e.source;if(c&&d&&typeof d.postMessage=="function"){if(d!==window&&!Hl(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:c,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),l=n==="LMS_SAVE_PROGRESS"||n==="saveProgress";if(a){qs("courseware.submitted",i,o);try{const c=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(!c.ok){const d=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${c.status}`,d)}}catch(c){console.error("[LMS Bridge] Failed to submit attempt data to backend:",c)}}else if(l){qs("courseware.progress_saved",i,o);try{const c=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(!c.ok){const d=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${c.status}`,d)}}catch(c){console.error("[LMS Bridge] Failed to save progress to backend:",c)}}else{qs("courseware.event_logged",i,o);try{const c=await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:n||"log",payload:o})});if(!c.ok){const d=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${c.status}`,d)}}catch(c){console.error("[LMS Bridge] Failed to log event to backend:",c)}}}function qs(e,t,n){tn.publish({id:Or(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t})}function rS(e){f.useEffect(()=>{if(!e)return;const t=n=>{sS(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function tu(){const e=[],t=new Set;for(const n of Tr)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 Pr(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 nu(e,t={}){if(!(typeof document>"u"))try{tu().forEach(s=>{Pr(s,{type:"LMS_HOST_COMMAND",event:"theme:changed",payload:{theme:e,tokens:t}}),Pr(s,{type:"LMS_THEME_CHANGED",theme:e,tokens:t})})}catch{}}function su(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));tu().forEach(s=>{Pr(s,{type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}}),Pr(s,{type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)})})}catch{}}let Ei=null,Ti=null;typeof window<"u"&&(tn.subscribe("theme.changed",e=>{Ei&&clearTimeout(Ei),Ei=setTimeout(()=>{const t=e.payload;t&&typeof t.theme=="string"&&nu(t.theme,t.tokens??{})},50)}),tn.subscribe("font-scale.changed",e=>{Ti&&clearTimeout(Ti),Ti=setTimeout(()=>{const t=e.payload;t&&typeof t.scale=="number"&&su(t.scale)},50)}));function Pi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Wl(e){if(!e||typeof e!="object")return[];const t=Pi(e.capabilitiesProposed);if(t.length>0)return t;const n=e.manifest;if(typeof n=="string"&&n.length>0)try{return Pi(JSON.parse(n)?.capabilitiesProposed)}catch{return[]}return n&&typeof n=="object"?Pi(n.capabilitiesProposed):[]}const hs="@openlearn/frontend:IFrontendAPI",wo="@openlearn/frontend:ISocketService",hr="@openlearn/frontend:IUIService",fr="@openlearn/frontend:IStorageService",ru="@openlearn/frontend:ISemesterGradeService",iS="@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||{});function oS(e){const{lang:t,t:n,addToast:s,host:i,session:o,activeStudentId:a,activeRole:l,setStudentViewStatus:c,studentViewStatus:d,studentLessonTab:u,setStudentLessonTab:m,setLiveClassFocusLocked:p,isStudentLiveMode:h,isFollowingTeacher:x,liveStudentParam:g,fetchStudents:b,fetchLessons:w,fetchElements:y,fetchClasses:S,fetchClassStudents:C,fetchClassProgress:k,fetchClassDashboard:v,fetchLiveClassStudentProgress:N,setLiveClassStudentProgress:O,fetchRegisteredCommands:D,fetchVfs:_,fetchProcesses:T,fetchProcessLogs:z,fetchTodaySchedules:R,fetchLabs:$,fetchPlugins:I,fetchEvents:B,fetchApprovals:H,showProcessLogs:A,currentVfsParent:U,expandedClassId:j,activeSegmentId:V,setActiveSegmentId:G,quizStudentAnswersRef:E,effectiveAgentProviderId:W,plugins:Y}=e,[K,ne]=f.useState(0),fe=qw(),{pickedAlertData:je,setPickedAlertData:X,pickedAnnouncement:me,setPickedAnnouncement:ke,liveClassFeed:Se,setLiveClassFeed:M,liveClassAcknowledgedMap:Z,setLiveClassAcknowledgedMap:ee,onlineStudentIds:te,setOnlineStudentIds:ce,activeStudentLessons:oe,setActiveStudentLessons:xe}=fe,ie=de(ge=>ge.liveClassSelectedClassId),Pe=de(ge=>ge.setLiveClassSelectedClassId),ze=de(ge=>ge.liveClassIsActive),ue=de(ge=>ge.setLiveClassIsActive),re=de(ge=>ge.selectedLesson),P=de(ge=>ge.setSelectedLesson),L=de(ge=>ge.setLessons),F=de(ge=>ge.students);de(ge=>ge.dataVersion);const q=Gw({activeStudentId:a,activeRole:l,selectedLesson:re,quizStudentAnswersRef:E,setStudentViewStatus:c}),{studentDashboardData:J,setStudentDashboardData:be,studentProgressMap:se,setStudentProgressMap:ye,selectedAssignment:$e,setSelectedAssignment:Fe,fetchStudentDashboard:Ce,fetchStudentProgress:We,updateStudentProgress:He,submitQuizAssignment:Et}=q,[et,jt]=f.useState(""),[Vt,Ln]=f.useState("all"),[Ht,Re]=f.useState("grid"),[rn,Rn]=f.useState({}),[_n,On]=f.useState({}),[on,Dn]=f.useState({}),an=Qw(l,J,t),{studentNotifications:Mn,unreadNotifications:$n,readNotifications:Fn,setReadNotifications:Tt,selectedNotificationForModal:ln,setSelectedNotificationForModal:Wt,isNotificationsOpen:Bn,setIsNotificationsOpen:Un}=an;f.useEffect(()=>{a&&s0(a).then(({ok:ge,data:Ke})=>{Tt(ge&&Array.isArray(Ke)?new Set(Ke):new Set)}).catch(ge=>{console.warn("Failed to load read notifications from DB",ge),Tt(new Set)})},[a]);const Pt=f.useRef(new Set);f.useEffect(()=>{if(!i.isInitialized()||Y.length===0)return;const ge=Ne.getState(),Ke=Y.filter(pe=>pe.status==="active");for(const pe of Ke){if(!pe.has_frontend||Pt.current.has(pe.id))continue;const qe=ge.activePlugins.find(rt=>rt.id===pe.id),Ze=!!(qe&&pe.version&&qe.version!==pe.version);if(!(!qe||Ze||qe.state!==Le.ACTIVE&&qe.state!==Le.ACTIVATING))continue;Pt.current.add(pe.id);const mt=()=>{if(!ge.activePlugins.find(rt=>rt.id===pe.id))ge.addPlugin({id:pe.id,name:pe.name,version:pe.version??"",state:Le.INSTALLED,executionMode:"process",capabilitiesProposed:Wl(pe)});else if(Ze)try{const rt=Wl(pe);Ne.setState(It=>({activePlugins:It.activePlugins.map(Gt=>Gt.id===pe.id?{...Gt,version:pe.version??"",name:pe.name,capabilitiesProposed:rt}:Gt)}))}catch{}try{const rt=JSON.parse(pe.manifest);i.activateRemotePlugin(pe.id,rt).catch(It=>{console.error(`[App] Failed to activate remote plugin "${pe.name}":`,It)}).finally(()=>{Pt.current.delete(pe.id)})}catch(rt){Pt.current.delete(pe.id),console.error(`[App] Failed to parse manifest for plugin "${pe.name}":`,rt)}};qe&&qe.state===Le.ACTIVE&&Ze?i.deactivatePlugin(pe.id).catch(()=>{}).finally(mt):mt()}const qt=Y.filter(pe=>pe.status!=="active");for(const pe of qt){if(!pe.has_frontend)continue;const qe=ge.activePlugins.find(Ze=>Ze.id===pe.id);qe&&qe.state===Le.ACTIVE&&i.deactivatePlugin(pe.id).catch(Ze=>{console.error(`[App] Failed to deactivate remote plugin "${pe.name}":`,Ze)})}},[Y,i]),f.useEffect(()=>{if(!i.isInitialized()||Y.length===0)return;const ge=Ne.getState();for(const Ke of Y)Ke.status==="active"&&(ge.dashboardVisibility.has(Ke.id)||ge.setDashboardVisibility(Ke.id,!0))},[Y,i]),f.useEffect(()=>{ie&&re?N(ie,re):O([])},[ie,re]),f.useEffect(()=>{ie&&C(ie)},[ie]),rS(o);const cn=Jw({lang:t,t:n,selectedLesson:re,effectiveAgentProviderId:W,expandedClassId:j,fetchLessons:w,fetchClasses:S,fetchStudents:b,fetchClassStudents:C,fetchClassProgress:k,fetchClassDashboard:v,fetchElements:y}),{personaId:dn,setPersonaId:_e,chatLog:Vn,setChatLog:Hn,input:Wn,setInput:qn,loading:Gn,setLoading:Qn,chatAttachments:Jn,setChatAttachments:Kn,handleChatFileChange:Yn,handleChatDrop:Zn,handleSend:Xn,handleClearAgentMemory:es}=cn;Kw({session:o,showProcessLogs:A,activeStudentId:a,currentVfsParent:U,selectedLesson:re,selectedAssignment:$e,expandedClassId:j,fetchLessons:w,fetchPlugins:I,fetchRegisteredCommands:D,fetchEvents:B,fetchApprovals:H,fetchProcesses:T,fetchClasses:S,fetchTodaySchedules:R,fetchStudents:b,fetchLabs:$,fetchVfs:_,fetchProcessLogs:z,fetchClassStudents:C,fetchElements:y});const{socketRef:ts}=Yv({session:o,host:i,activeRole:l,activeStudentId:a,selectedLesson:re,activeSegmentId:V,studentViewStatus:d,lang:t,students:F,addToast:s,setOnlineStudentIds:ce,setActiveStudentLessons:xe,setLessons:L,setActiveSegmentId:G,setLiveClassStudentProgress:O,setLiveClassAcknowledgedMap:ee,setLiveClassFeed:M,setSelectedLesson:P,setStudentViewStatus:c,studentLessonTab:u,setStudentLessonTab:m,selectedAssignment:$e,setSelectedAssignment:Fe,setLocalProgressPercent:ne,fetchStudentDashboard:Ce,fetchStudents:b,fetchElements:y,setPickedAlertData:X,setPickedAnnouncement:ke,onStudentProgressUpdated:({studentId:ge,lessonId:Ke,progressPercent:qt,completed:pe,verified:qe})=>{ye(Ze=>{const Xe=Ze[ge];return Xe?{...Ze,[ge]:Xe.map(mt=>Ke&&mt.lesson_id!==Ke?mt:{...mt,progress_percent:qt,completed:pe?1:0,...qe!==void 0?{verified:qe?1:0}:{}})}:Ze})}});return{localProgressPercent:K,setLocalProgressPercent:ne,classroomLiveData:fe,pickedAlertData:je,setPickedAlertData:X,pickedAnnouncement:me,setPickedAnnouncement:ke,liveClassFeed:Se,setLiveClassFeed:M,liveClassAcknowledgedMap:Z,setLiveClassAcknowledgedMap:ee,onlineStudentIds:te,setOnlineStudentIds:ce,activeStudentLessons:oe,setActiveStudentLessons:xe,liveClassSelectedClassId:ie,setLiveClassSelectedClassId:Pe,liveClassIsActive:ze,setLiveClassIsActive:ue,studentOpsData:q,studentDashboardData:J,setStudentDashboardData:be,studentProgressMap:se,setStudentProgressMap:ye,selectedAssignment:$e,setSelectedAssignment:Fe,fetchStudentDashboard:Ce,fetchStudentProgress:We,updateStudentProgress:He,submitQuizAssignment:Et,rosterSearchQuery:et,setRosterSearchQuery:jt,rosterTagFilter:Vt,setRosterTagFilter:Ln,rosterViewMode:Ht,setRosterViewMode:Re,classSubmissionFilters:rn,setClassSubmissionFilters:Rn,classActiveTabs:_n,setClassActiveTabs:On,studentActiveTabs:on,setStudentActiveTabs:Dn,studentNotificationsHook:an,studentNotifications:Mn,unreadNotifications:$n,readNotifications:Fn,setReadNotifications:Tt,selectedNotificationForModal:ln,setSelectedNotificationForModal:Wt,isNotificationsOpen:Bn,setIsNotificationsOpen:Un,agentChatData:cn,personaId:dn,setPersonaId:_e,chatLog:Vn,setChatLog:Hn,input:Wn,setInput:qn,loading:Gn,setLoading:Qn,chatAttachments:Jn,setChatAttachments:Kn,handleChatFileChange:Yn,handleChatDrop:Zn,handleSend:Xn,handleClearAgentMemory:es,socketRef:ts}}Xy();function aS(){tw();const e=de(h=>h.lang),t=no[e]??no.zh,{addToast:n}=ew(),s=yx(),i=async()=>{await ve.getState().loadStudents()},o=async()=>{await ve.getState().loadClasses()},a=f.useRef(()=>{}),l=rw({lang:e,addToast:n,fetchStudents:i}),c=Ww({lang:e,addToast:n,host:s,session:l.session,fetchStudents:i,fetchClasses:o,chatLogRef:a}),d=oS({lang:e,t,addToast:n,host:s,session:l.session,activeStudentId:l.activeStudentId,activeRole:l.activeRole,setStudentViewStatus:l.setStudentViewStatus,studentViewStatus:l.studentViewStatus,studentLessonTab:l.studentLessonTab,setStudentLessonTab:l.setStudentLessonTab,setLiveClassFocusLocked:l.setLiveClassFocusLocked,isStudentLiveMode:l.isStudentLiveMode,isFollowingTeacher:l.isFollowingTeacher,liveStudentParam:l.liveStudentParam,fetchStudents:i,fetchLessons:c.fetchLessons,fetchElements:c.fetchElements,fetchClasses:o,fetchClassStudents:c.fetchClassStudents,fetchClassProgress:c.fetchClassProgress,fetchClassDashboard:c.fetchClassDashboard,fetchLiveClassStudentProgress:c.fetchLiveClassStudentProgress,setLiveClassStudentProgress:c.setLiveClassStudentProgress,fetchRegisteredCommands:c.fetchRegisteredCommands,fetchVfs:c.fetchVfs,fetchProcesses:c.fetchProcesses,fetchProcessLogs:c.fetchProcessLogs,fetchTodaySchedules:c.fetchTodaySchedules,fetchLabs:c.fetchLabs,fetchPlugins:c.fetchPlugins,fetchEvents:c.fetchEvents,fetchApprovals:c.fetchApprovals,showProcessLogs:c.showProcessLogs,currentVfsParent:c.currentVfsParent,expandedClassId:c.expandedClassId,activeSegmentId:c.activeSegmentId,setActiveSegmentId:c.setActiveSegmentId,quizStudentAnswersRef:c.quizStudentAnswersRef,effectiveAgentProviderId:c.effectiveAgentProviderId,plugins:c.plugins});a.current=d.setChatLog;const u=de(h=>h.setSelectedLesson),m=de(h=>h.setTeacherTab);return{appData:{addToast:n,...c.systemData,...c.resourceLibraryData,...c.lessonCrudData,...c.classOpsData,...l.studentViewStateData,...d.studentOpsData,...l.sessionBootstrapData,...d.classroomLiveData,...c.labAndScheduleData,...c.pluginManagementData,...d.agentChatData,...c.quizGenerator,...c.courseWizard,...c.classBatch,...c.lessonTimelineData,...d.studentNotificationsHook,...c.gradeExport,...c.lessonFilteringData,mainNavCollapsed:l.mainNavCollapsed,setMainNavCollapsed:l.setMainNavCollapsed,batchMode:c.batchMode,setBatchMode:c.setBatchMode,selectedClassIds:c.selectedClassIds,setSelectedClassIds:c.setSelectedClassIds,setSelectedStudentIds:c.setSelectedStudentIds,expandedClassId:c.expandedClassId,setExpandedClassId:c.setExpandedClassId,exportTooltipOpen:c.exportTooltipOpen,setExportTooltipOpen:c.setExportTooltipOpen,exportDropdownOpen:c.exportDropdownOpen,setExportDropdownOpen:c.setExportDropdownOpen,expandedStudentId:c.expandedStudentId,setExpandedStudentId:c.setExpandedStudentId,selectedStudentIds:c.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:c.assignmentSortOrder,setAssignmentSortOrder:c.setAssignmentSortOrder,isGeneratingAssignment:c.isGeneratingAssignment,isGrading:c.isGrading,setIsGrading:c.setIsGrading,setStudents:c.setStudents,setImportError:c.setImportError,setImportSuccess:c.setImportSuccess,setShowImportModal:c.setShowImportModal,studentActiveTabs:d.studentActiveTabs,setStudentActiveTabs:d.setStudentActiveTabs,fetchStudents:i,fetchClasses:o,onLogout:l.handleLogout,onAIProvidersChanged:c.fetchAIProviders,onDeleteCourse:c.handleDeleteCourse,onCopyCourse:c.handleCopyCourse,socketRef:d.socketRef,liveClassSelectedClassId:d.liveClassSelectedClassId,setLiveClassSelectedClassId:d.setLiveClassSelectedClassId,liveClassIsActive:d.liveClassIsActive,setLiveClassIsActive:d.setLiveClassIsActive,setSelectedLesson:u,setTeacherTab:m,teacherTab:l.teacherTab,onViewCourse:h=>{m("lesson_editor"),u(h)},t,readNotifications:d.readNotifications,setReadNotifications:d.setReadNotifications,localProgressPercent:d.localProgressPercent,setLocalProgressPercent:d.setLocalProgressPercent,lessons:c.lessons,selectedLesson:c.selectedLesson,elements:c.elements,classes:c.classes,students:c.students,isApprovalsCollapsed:l.isApprovalsCollapsed,setIsApprovalsCollapsed:l.setIsApprovalsCollapsed,isProcessesCollapsed:l.isProcessesCollapsed,setIsProcessesCollapsed:l.setIsProcessesCollapsed,whiteboardRef:c.whiteboardRef,paletteEdit:c.paletteEdit,handlePaletteActivate:c.handlePaletteActivate,handlePaletteConfirm:c.handlePaletteConfirm,setPaletteEdit:c.setPaletteEdit,session:l.session,showRightSidebar:c.showRightSidebar,setShowRightSidebar:c.setShowRightSidebar,rightSidebarTab:c.rightSidebarTab,setRightSidebarTab:c.setRightSidebarTab,agentProviderId:c.agentProviderId,setAgentProviderId:c.setAgentProviderId,effectiveAgentProviderId:c.effectiveAgentProviderId,selectedAgentProvider:c.selectedAgentProvider,isTourOpen:l.isTourOpen,setIsTourOpen:l.setIsTourOpen,handleSeedSuccess:c.handleSeedSuccess,wizardIsGeneratingOutline:c.wizardIsGeneratingOutline,handleGenerateOutline:c.handleGenerateOutline,activeRole:l.activeRole,setActiveRole:l.setActiveRole,isStudentPreviewMode:l.isStudentPreviewMode,isNotificationsOpen:d.isNotificationsOpen,setIsNotificationsOpen:d.setIsNotificationsOpen,selectedNotificationForModal:d.selectedNotificationForModal,setSelectedNotificationForModal:d.setSelectedNotificationForModal,setProfileOpen:l.setProfileOpen,notifyLockedNavigation:l.notifyLockedNavigation,handleLogout:l.handleLogout,toggleLanguage:l.toggleLanguage,setIsSystemResourceLibraryOpen:c.setIsSystemResourceLibraryOpen,siteInfo:c.siteInfo,isStudentLiveMode:l.isStudentLiveMode,liveStudentParam:l.liveStudentParam,isFollowingTeacher:l.isFollowingTeacher,setIsFollowingTeacher:l.setIsFollowingTeacher},sessionLoading:l.sessionLoading,session:l.session,setSession:l.setSession,handleLoginSuccess:l.handleLoginSuccess,handleLogout:l.handleLogout,isStageDisplayMode:l.isStageDisplayMode,stageLessonParam:l.stageLessonParam,stageTitleParam:l.stageTitleParam,stageLangParam:l.stageLangParam,activeRole:l.activeRole,selectedLesson:c.selectedLesson,lessons:c.lessons,profileOpen:l.profileOpen,setProfileOpen:l.setProfileOpen,lang:e}}function lS(){const{appData:e,sessionLoading:t,session:n,setSession:s,handleLoginSuccess:i,handleLogout:o,isStageDisplayMode:a,stageLessonParam:l,stageTitleParam:c,stageLangParam:d,activeRole:u,selectedLesson:m,lessons:p,profileOpen:h,setProfileOpen:x,lang:g}=aS();return t?r.jsx(Os,{children:r.jsx(_s,{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($t,{size:48,className:"text-indigo-500 animate-spin"}),r.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:g==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]})})}):n?n.mustChangePassword?r.jsx(Os,{children:r.jsx(_s,{value:e,children:r.jsx(Jg,{lang:g,username:n.username,onDone:()=>s({...n,mustChangePassword:!1}),onLogout:o})})}):r.jsx(Os,{children:r.jsx(_s,{value:e,children:r.jsxs(r.Fragment,{children:[a&&r.jsx(mb,{lessonId:l||m,lessonTitle:c||p.find(b=>b.id===(l||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(pb,{}),n.role==="student"&&n.usedDefaultPassword&&r.jsx(gb,{userId:n.studentId||n.userId,lang:g,onOpenProfile:()=>x(!0)}),r.jsx(Lb,{}),r.jsx(Ob,{open:h,session:n,lang:g,onClose:()=>x(!1),onSaved:b=>{n&&s({...n,name:b}),x(!1)},onAvatar:b=>{n&&s({...n,avatar:b??void 0})}}),r.jsx($b,{activeRole:u}),r.jsx(_b,{})]}),r.jsx(Ub,{}),r.jsx(t0,{}),r.jsx(R0,{}),r.jsx(Jy,{}),r.jsx(Zy,{})]})]})})}):r.jsx(Os,{children:r.jsx(_s,{value:e,children:r.jsx(Qg,{onLoginSuccess:i,lang:g})})})}class cS{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 dS=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function iu(e,t){const n=t+".";return e.startsWith(n)||dS.test(e)?e:n+e}const ql="api:write",Gl="api:admin",Ql="grades:write",Jl="agent:tool",Kl="ai:invoke",Gs="task:register",uS=Object.freeze(["/api/plugins","/api/users","/api/auth","/api/ai-providers","/api/agent","/api/grade-sync","/api/site-settings","/api/approvals"]),hS=Object.freeze(["/gdpr-delete"]),fS=/^\/api\/[^/]+\/[^/]+$/;function mS(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 pS(e){return!Array.isArray(e)||e.length===0?"":mS(e[0])}function Yt(e,t){return e.some(n=>typeof n=="string"&&(n===t||n.startsWith(`${t}:`)))}function gS(e){return e==="get"||e.startsWith("get")}function xS(e){const{token:t,method:n,args:s,tokens:i}=e,o=e.caps??[];if(i.frontendApi&&t===i.frontendApi){if(gS(n)||n==="request"&&!Array.isArray(s))return null;const a=pS(s),l=uS.some(u=>a===u||a.startsWith(`${u}/`)),c=hS.some(u=>a.endsWith(u)),d=n==="del"&&fS.test(a);return l||c||d?Yt(o,Gl)?null:`${c?`不可逆操作 '${a}'`:d?`实体级删除 '${a}'`:`写入高危路径 '${a||"<未提供路径>"}'`} 需要 manifest 声明 '${Gl}' 能力`:Yt(o,ql)?null:`写操作(${n})需要 manifest 声明 '${ql}' 能力(普通只读调用请用 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")?Yt(o,Ql)?null:`写入学期成绩需要 manifest 声明 '${Ql}' 能力('grades' 或 'grades:read' 不足以解锁写入)`:null;if(i.processService&&t===i.processService)return n==="registerHandler"||n==="registerInterval"?Yt(o,Gs)?null:`注册后台任务(${n})需要 manifest 声明 '${Gs}' 能力`:n==="restore"?Yt(o,Gs)?null:`恢复后台任务(restore)会重放全部插件的 running 进程,需要 manifest 声明 '${Gs}' 能力`:null;if(i.aiService&&t===i.aiService)return n==="generateText"||n==="chat"||n==="complete"?Yt(o,Kl)?null:`调用 AI 生成(${n})需要 manifest 声明 '${Kl}' 能力`:null;if(i.actionRegistry&&t===i.actionRegistry){if(n==="register"){const l=(Array.isArray(s)?s[0]:void 0)?.exposeToAgent;if(l===void 0||l!==!1)return Yt(o,Jl)?null:`注册对外暴露的 action 需要 manifest 声明 '${Jl}' 能力(如不希望进入 AI Agent 工具列表,请设置 exposeToAgent: false)`}return null}return i.storageService&&t===i.storageService||i.uiService&&t===i.uiService,null}const bS=Object.freeze({frontendApi:hs,socketService:wo,uiService:hr,storageService:fr,semesterGradeService:ru});function yS(e,t,n,s=[]){return xS({token:e,method:t,args:n,caps:s,tokens:bS})}const fs="ol-plugin-frame",wS="allow-scripts",vS="/plugin-sandbox/frame";function Yl(e){return!!e&&typeof e=="object"&&e.channel===fs}function SS(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const jS=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,kS=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,CS={};function Zl(e,t){return(CS.jsx?kS:jS).test(e)}const NS=/[ \t\n\f\r]/g;function ES(e){return typeof e=="object"?e.type==="text"?Xl(e.value):!1:Xl(e)}function Xl(e){return e.replace(NS,"")===""}class Ps{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}Ps.prototype.normal={};Ps.prototype.property={};Ps.prototype.space=void 0;function ou(e,t){const n={},s={};for(const i of e)Object.assign(n,i.property),Object.assign(s,i.normal);return new Ps(n,s,t)}function vo(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 TS=0;const he=sn(),Be=sn(),So=sn(),Q=sn(),Ie=sn(),en=sn(),it=sn();function sn(){return 2**++TS}const jo=Object.freeze(Object.defineProperty({__proto__:null,boolean:he,booleanish:Be,commaOrSpaceSeparated:it,commaSeparated:en,number:Q,overloadedBoolean:So,spaceSeparated:Ie},Symbol.toStringTag,{value:"Module"})),Ii=Object.keys(jo);class pa extends st{constructor(t,n,s,i){let o=-1;if(super(t,n),ec(this,"space",i),typeof s=="number")for(;++o<Ii.length;){const a=Ii[o];ec(this,Ii[o],(s&jo[a])===jo[a])}}}pa.prototype.defined=!0;function ec(e,t,n){n&&(e[t]=n)}function An(e){const t={},n={};for(const[s,i]of Object.entries(e.properties)){const o=new pa(s,e.transform(e.attributes||{},s),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(o.mustUseProperty=!0),t[s]=o,n[vo(s)]=s,n[vo(o.attribute)]=s}return new Ps(t,n,e.space)}const au=An({properties:{ariaActiveDescendant:null,ariaAtomic:Be,ariaAutoComplete:null,ariaBusy:Be,ariaChecked:Be,ariaColCount:Q,ariaColIndex:Q,ariaColSpan:Q,ariaControls:Ie,ariaCurrent:null,ariaDescribedBy:Ie,ariaDetails:null,ariaDisabled:Be,ariaDropEffect:Ie,ariaErrorMessage:null,ariaExpanded:Be,ariaFlowTo:Ie,ariaGrabbed:Be,ariaHasPopup:null,ariaHidden:Be,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Ie,ariaLevel:Q,ariaLive:null,ariaModal:Be,ariaMultiLine:Be,ariaMultiSelectable:Be,ariaOrientation:null,ariaOwns:Ie,ariaPlaceholder:null,ariaPosInSet:Q,ariaPressed:Be,ariaReadOnly:Be,ariaRelevant:null,ariaRequired:Be,ariaRoleDescription:Ie,ariaRowCount:Q,ariaRowIndex:Q,ariaRowSpan:Q,ariaSelected:Be,ariaSetSize:Q,ariaSort:null,ariaValueMax:Q,ariaValueMin:Q,ariaValueNow:Q,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function lu(e,t){return t in e?e[t]:t}function cu(e,t){return lu(e,t.toLowerCase())}const PS=An({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:en,acceptCharset:Ie,accessKey:Ie,action:null,allow:null,allowFullScreen:he,allowPaymentRequest:he,allowUserMedia:he,alpha:he,alt:null,as:null,async:he,autoCapitalize:null,autoComplete:Ie,autoFocus:he,autoPlay:he,blocking:Ie,capture:null,charSet:null,checked:he,cite:null,className:Ie,closedBy:null,colorSpace:null,cols:Q,colSpan:Q,command:null,commandFor:null,content:null,contentEditable:Be,controls:he,controlsList:Ie,coords:Q|en,crossOrigin:null,data:null,dateTime:null,decoding:null,default:he,defer:he,dir:null,dirName:null,disabled:he,download:So,draggable:Be,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:he,formTarget:null,headers:Ie,height:Q,hidden:So,high:Q,href:null,hrefLang:null,htmlFor:Ie,httpEquiv:Ie,id:null,imageSizes:null,imageSrcSet:null,inert:he,inputMode:null,integrity:null,is:null,isMap:he,itemId:null,itemProp:Ie,itemRef:Ie,itemScope:he,itemType:Ie,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:he,low:Q,manifest:null,max:null,maxLength:Q,media:null,method:null,min:null,minLength:Q,multiple:he,muted:he,name:null,nonce:null,noModule:he,noValidate:he,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:he,optimum:Q,pattern:null,ping:Ie,placeholder:null,playsInline:he,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:he,referrerPolicy:null,rel:Ie,required:he,reversed:he,rows:Q,rowSpan:Q,sandbox:Ie,scope:null,scoped:he,seamless:he,selected:he,shadowRootClonable:he,shadowRootCustomElementRegistry:he,shadowRootDelegatesFocus:he,shadowRootMode:null,shadowRootSerializable:he,shape:null,size:Q,sizes:null,slot:null,span:Q,spellCheck:Be,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Q,step:null,style:null,tabIndex:Q,target:null,title:null,translate:null,type:null,typeMustMatch:he,useMap:null,value:Be,width:Q,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Ie,axis:null,background:null,bgColor:null,border:Q,borderColor:null,bottomMargin:Q,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:he,declare:he,event:null,face:null,frame:null,frameBorder:null,hSpace:Q,leftMargin:Q,link:null,longDesc:null,lowSrc:null,marginHeight:Q,marginWidth:Q,noResize:he,noHref:he,noShade:he,noWrap:he,object:null,profile:null,prompt:null,rev:null,rightMargin:Q,rules:null,scheme:null,scrolling:Be,standby:null,summary:null,text:null,topMargin:Q,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Q,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:he,disablePictureInPicture:he,disableRemotePlayback:he,exportParts:en,part:Ie,prefix:null,property:null,results:Q,security:null,unselectable:null},space:"html",transform:cu}),IS=An({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:Q,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Q,amplitude:Q,arabicForm:null,ascent:Q,attributeName:null,attributeType:null,azimuth:Q,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Q,by:null,calcMode:null,capHeight:Q,className:Ie,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:Q,diffuseConstant:Q,direction:null,display:null,dur:null,divisor:Q,dominantBaseline:null,download:he,dx:null,dy:null,edgeMode:null,editable:null,elevation:Q,enableBackground:null,end:null,event:null,exponent:Q,externalResourcesRequired:null,fill:null,fillOpacity:Q,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:en,g2:en,glyphName:en,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Q,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Q,horizOriginX:Q,horizOriginY:Q,id:null,ideographic:Q,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Q,k:Q,k1:Q,k2:Q,k3:Q,k4:Q,kernelMatrix:it,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Q,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:Q,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:Q,overlineThickness:Q,paintOrder:null,panose1:null,path:null,pathLength:Q,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Ie,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Q,pointsAtY:Q,pointsAtZ:Q,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:Q,specularExponent:Q,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Q,strikethroughThickness:Q,string:null,stroke:null,strokeDashArray:it,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Q,strokeOpacity:Q,strokeWidth:null,style:null,surfaceScale:Q,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:it,tabIndex:Q,tableValues:null,target:null,targetX:Q,targetY:Q,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:Q,underlineThickness:Q,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Q,values:null,vAlphabetic:Q,vMathematical:Q,vectorEffect:null,vHanging:Q,vIdeographic:Q,version:null,vertAdvY:Q,vertOriginX:Q,vertOriginY:Q,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Q,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:lu}),du=An({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()}}),uu=An({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:cu}),hu=An({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),AS={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"},zS=/[A-Z]/g,tc=/-[a-z]/g,LS=/^data[-\w.:]+$/i;function RS(e,t){const n=vo(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"&&LS.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(tc,OS);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!tc.test(o)){let a=o.replace(zS,_S);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=pa}return new i(s,t)}function _S(e){return"-"+e.toLowerCase()}function OS(e){return e.charAt(1).toUpperCase()}const DS=ou([au,PS,du,uu,hu],"html"),ga=ou([au,IS,du,uu,hu],"svg");function MS(e){return e.join(" ").trim()}var mn={},Ai,nc;function $S(){if(nc)return Ai;nc=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,l=/^\s+|\s+$/g,c=`
|
|
79
|
+
`,d="/",u="*",m="",p="comment",h="declaration";function x(b,w){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];w=w||{};var y=1,S=1;function C($){var I=$.match(t);I&&(y+=I.length);var B=$.lastIndexOf(c);S=~B?$.length-B:S+$.length}function k(){var $={line:y,column:S};return function(I){return I.position=new v($),D(),I}}function v($){this.start=$,this.end={line:y,column:S},this.source=w.source}v.prototype.content=b;function N($){var I=new Error(w.source+":"+y+":"+S+": "+$);if(I.reason=$,I.filename=w.source,I.line=y,I.column=S,I.source=b,!w.silent)throw I}function O($){var I=$.exec(b);if(I){var B=I[0];return C(B),b=b.slice(B.length),I}}function D(){O(n)}function _($){var I;for($=$||[];I=T();)I!==!1&&$.push(I);return $}function T(){var $=k();if(!(d!=b.charAt(0)||u!=b.charAt(1))){for(var I=2;m!=b.charAt(I)&&(u!=b.charAt(I)||d!=b.charAt(I+1));)++I;if(I+=2,m===b.charAt(I-1))return N("End of comment missing");var B=b.slice(2,I-2);return S+=2,C(B),b=b.slice(I),S+=2,$({type:p,comment:B})}}function z(){var $=k(),I=O(s);if(I){if(T(),!O(i))return N("property missing ':'");var B=O(o),H=$({type:h,property:g(I[0].replace(e,m)),value:B?g(B[0].replace(e,m)):m});return O(a),H}}function R(){var $=[];_($);for(var I;I=z();)I!==!1&&($.push(I),_($));return $}return D(),R()}function g(b){return b?b.replace(l,m):m}return Ai=x,Ai}var sc;function FS(){if(sc)return mn;sc=1;var e=mn&&mn.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mn,"__esModule",{value:!0}),mn.default=n;const t=e($S());function n(s,i){let o=null;if(!s||typeof s!="string")return o;const a=(0,t.default)(s),l=typeof i=="function";return a.forEach(c=>{if(c.type!=="declaration")return;const{property:d,value:u}=c;l?i(d,u,c):u&&(o=o||{},o[d]=u)}),o}return mn}var as={},rc;function BS(){if(rc)return as;rc=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()},l=function(d,u){return"".concat(u,"-")},c=function(d,u){return u===void 0&&(u={}),o(d)?d:(d=d.toLowerCase(),u.reactCompat?d=d.replace(i,l):d=d.replace(s,l),d.replace(t,a))};return as.camelCase=c,as}var ls,ic;function US(){if(ic)return ls;ic=1;var e=ls&&ls.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(FS()),n=BS();function s(i,o){var a={};return!i||typeof i!="string"||(0,t.default)(i,function(l,c){l&&c&&(a[(0,n.camelCase)(l,o)]=c)}),a}return s.default=s,ls=s,ls}var VS=US();const HS=Bc(VS),fu=mu("end"),xa=mu("start");function mu(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 WS(e){const t=xa(e),n=fu(e);if(t&&n)return{start:t,end:n}}function bs(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?oc(e.position):"start"in e||"end"in e?oc(e):"line"in e||"column"in e?ko(e):""}function ko(e){return ac(e&&e.line)+":"+ac(e&&e.column)}function oc(e){return ko(e&&e.start)+"-"+ko(e&&e.end)}function ac(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 c=s.indexOf(":");c===-1?o.ruleId=s:(o.source=s.slice(0,c),o.ruleId=s.slice(c+1))}if(!o.place&&o.ancestors&&o.ancestors){const c=o.ancestors[o.ancestors.length-1];c&&(o.place=c.position)}const l=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=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=l?l.line:void 0,this.name=bs(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 ba={}.hasOwnProperty,qS=new Map,GS=/[A-Z]/g,QS=new Set(["table","tbody","thead","tfoot","tr"]),JS=new Set(["td","th"]),pu="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function KS(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=rj(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=sj(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"?ga:DS,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=gu(i,e,void 0);return o&&typeof o!="string"?o:i.create(e,i.Fragment,{children:o||void 0},void 0)}function gu(e,t,n){if(t.type==="element")return YS(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return ZS(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return ej(e,t,n);if(t.type==="mdxjsEsm")return XS(e,t);if(t.type==="root")return tj(e,t,n);if(t.type==="text")return nj(e,t)}function YS(e,t,n){const s=e.schema;let i=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(i=ga,e.schema=i),e.ancestors.push(t);const o=bu(e,t.tagName,!1),a=ij(e,t);let l=wa(e,t);return QS.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!ES(c):!0})),xu(e,a,o,t),ya(a,l),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function ZS(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)}Cs(e,t.position)}function XS(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Cs(e,t.position)}function ej(e,t,n){const s=e.schema;let i=s;t.name==="svg"&&s.space==="html"&&(i=ga,e.schema=i),e.ancestors.push(t);const o=t.name===null?e.Fragment:bu(e,t.name,!0),a=oj(e,t),l=wa(e,t);return xu(e,a,o,t),ya(a,l),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function tj(e,t,n){const s={};return ya(s,wa(e,t)),e.create(t,e.Fragment,s,n)}function nj(e,t){return t.value}function xu(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function ya(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function sj(e,t,n){return s;function s(i,o,a,l){const d=Array.isArray(a.children)?n:t;return l?d(o,a,l):d(o,a)}}function rj(e,t){return n;function n(s,i,o,a){const l=Array.isArray(o.children),c=xa(s);return t(i,o,a,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function ij(e,t){const n={};let s,i;for(i in t.properties)if(i!=="children"&&ba.call(t.properties,i)){const o=aj(e,i,t.properties[i]);if(o){const[a,l]=o;e.tableCellAlignToStyle&&a==="align"&&typeof l=="string"&&JS.has(t.tagName)?s=l:n[a]=l}}if(s){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function oj(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 l=a.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else Cs(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 l=s.value.data.estree.body[0];l.type,o=e.evaluater.evaluateExpression(l.expression)}else Cs(e,t.position);else o=s.value===null?!0:s.value;n[i]=o}return n}function wa(e,t){const n=[];let s=-1;const i=e.passKeys?new Map:qS;for(;++s<t.children.length;){const o=t.children[s];let a;if(e.passKeys){const c=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(c){const d=i.get(c)||0;a=c+"-"+d,i.set(c,d+1)}}const l=gu(e,o,a);l!==void 0&&n.push(l)}return n}function aj(e,t,n){const s=RS(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?SS(n):MS(n)),s.property==="style"){let i=typeof n=="object"?n:lj(e,String(n));return e.stylePropertyNameCase==="css"&&(i=cj(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&s.space?AS[s.property]||s.property:s.attribute,n]}}function lj(e,t){try{return HS(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=pu+"#cannot-parse-style-attribute",i}}function bu(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 l=Zl(i[o])?{type:"Identifier",name:i[o]}:{type:"Literal",value:i[o]};a=a?{type:"MemberExpression",object:a,property:l,computed:!!(o&&l.type==="Literal"),optional:!1}:l}s=a}else s=Zl(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const i=s.value;return ba.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(s);Cs(e)}function Cs(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=pu+"#cannot-handle-mdx-estrees-without-createevaluater",n}function cj(e){const t={};let n;for(n in e)ba.call(e,n)&&(t[dj(n)]=e[n]);return t}function dj(e){let t=e.replace(GS,uj);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function uj(e){return"-"+e.toLowerCase()}const zi={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"]},hj={};function fj(e,t){const n=hj,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return yu(e,s,i)}function yu(e,t,n){if(mj(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 lc(e.children,t,n)}return Array.isArray(e)?lc(e,t,n):""}function lc(e,t,n){const s=[];let i=-1;for(;++i<e.length;)s[i]=yu(e[i],t,n);return s.join("")}function mj(e){return!!(e&&typeof e=="object")}const cc=document.createElement("i");function va(e){const t="&"+e+";";cc.innerHTML=t;const n=cc.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 dc={}.hasOwnProperty;function pj(e){const t={};let n=-1;for(;++n<e.length;)gj(t,e[n]);return t}function gj(e,t){let n;for(n in t){const i=(dc.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let a;if(o)for(a in o){dc.call(i,a)||(i[a]=[]);const l=o[a];xj(i[a],Array.isArray(l)?l:l?[l]:[])}}}function xj(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 wu(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 bt=Ut(/[A-Za-z]/),ot=Ut(/[\dA-Za-z]/),bj=Ut(/[#-'*+\--9=?A-Z^-~]/);function Co(e){return e!==null&&(e<32||e===127)}const No=Ut(/\d/),yj=Ut(/[\dA-Fa-f]/),wj=Ut(/[!-/:-@[-`{-~]/);function le(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 vj=Ut(/\p{P}|\p{S}/u),Sj=Ut(/\s/);function Ut(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function zn(e){const t=[];let n=-1,s=0,i=0;for(;++n<e.length;){const o=e.charCodeAt(n);let a="";if(o===37&&ot(e.charCodeAt(n+1))&&ot(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 l=e.charCodeAt(n+1);o<56320&&l>56319&&l<57344?(a=String.fromCharCode(o,l),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 Ae(e,t,n,s){const i=s?s-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(c){return Ee(c)?(e.enter(n),l(c)):t(c)}function l(c){return Ee(c)&&o++<i?(e.consume(c),l):(e.exit(n),t(c))}}const jj={tokenize:kj};function kj(e){const t=e.attempt(this.parser.constructs.contentInitial,s,i);let n;return t;function s(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Ae(e,t,"linePrefix")}function i(l){return e.enter("paragraph"),o(l)}function o(l){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(l)}function a(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return le(l)?(e.consume(l),e.exit("chunkText"),o):(e.consume(l),a)}}const Cj={tokenize:Nj},uc={tokenize:Ej};function Nj(e){const t=this,n=[];let s=0,i,o,a;return l;function l(S){if(s<n.length){const C=n[s];return t.containerState=C[1],e.attempt(C[0].continuation,c,d)(S)}return d(S)}function c(S){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&y();const C=t.events.length;let k=C,v;for(;k--;)if(t.events[k][0]==="exit"&&t.events[k][1].type==="chunkFlow"){v=t.events[k][1].end;break}w(s);let N=C;for(;N<t.events.length;)t.events[N][1].end={...v},N++;return vt(t.events,k+1,0,t.events.slice(C)),t.events.length=N,d(S)}return l(S)}function d(S){if(s===n.length){if(!i)return p(S);if(i.currentConstruct&&i.currentConstruct.concrete)return x(S);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(uc,u,m)(S)}function u(S){return i&&y(),w(s),p(S)}function m(S){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,x(S)}function p(S){return t.containerState={},e.attempt(uc,h,x)(S)}function h(S){return s++,n.push([t.currentConstruct,t.containerState]),p(S)}function x(S){if(S===null){i&&y(),w(0),e.consume(S);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),g(S)}function g(S){if(S===null){b(e.exit("chunkFlow"),!0),w(0),e.consume(S);return}return le(S)?(e.consume(S),b(e.exit("chunkFlow")),s=0,t.interrupt=void 0,l):(e.consume(S),g)}function b(S,C){const k=t.sliceStream(S);if(C&&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 v=i.events.length;for(;v--;)if(i.events[v][1].start.offset<a&&(!i.events[v][1].end||i.events[v][1].end.offset>a))return;const N=t.events.length;let O=N,D,_;for(;O--;)if(t.events[O][0]==="exit"&&t.events[O][1].type==="chunkFlow"){if(D){_=t.events[O][1].end;break}D=!0}for(w(s),v=N;v<t.events.length;)t.events[v][1].end={..._},v++;vt(t.events,O+1,0,t.events.slice(N)),t.events.length=v}}function w(S){let C=n.length;for(;C-- >S;){const k=n[C];t.containerState=k[1],k[0].exit.call(t,e)}n.length=S}function y(){i.write([null]),o=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Ej(e,t,n){return Ae(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function hc(e){if(e===null||nt(e)||Sj(e))return 1;if(vj(e))return 2}function Sa(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 Eo={name:"attention",resolveAll:Tj,tokenize:Pj};function Tj(e,t){let n=-1,s,i,o,a,l,c,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;c=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const m={...e[s][1].end},p={...e[n][1].start};fc(m,-c),fc(p,c),a={type:c>1?"strongSequence":"emphasisSequence",start:m,end:{...e[s][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:p},o={type:c>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},i={type:c>1?"strong":"emphasis",start:{...a.start},end:{...l.end}},e[s][1].end={...a.start},e[n][1].start={...l.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,Sa(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),d=dt(d,[["exit",o,t],["enter",l,t],["exit",l,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 Pj(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,i=hc(s);let o;return a;function a(c){return o=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===o)return e.consume(c),l;const d=e.exit("attentionSequence"),u=hc(c),m=!u||u===2&&i||n.includes(c),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(c)}}function fc(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Ij={name:"autolink",tokenize:Aj};function Aj(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 bt(h)?(e.consume(h),a):h===64?n(h):d(h)}function a(h){return h===43||h===45||h===46||ot(h)?(s=1,l(h)):d(h)}function l(h){return h===58?(e.consume(h),s=0,c):(h===43||h===45||h===46||ot(h))&&s++<32?(e.consume(h),l):(s=0,d(h))}function c(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||Co(h)?n(h):(e.consume(h),c)}function d(h){return h===64?(e.consume(h),u):bj(h)?(e.consume(h),d):n(h)}function u(h){return ot(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||ot(h))&&s++<63){const x=h===45?p:m;return e.consume(h),x}return n(h)}}const Ur={partial:!0,tokenize:zj};function zj(e,t,n){return s;function s(o){return Ee(o)?Ae(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||le(o)?t(o):n(o)}}const vu={continuation:{tokenize:Rj},exit:_j,name:"blockQuote",tokenize:Lj};function Lj(e,t,n){const s=this;return i;function i(a){if(a===62){const l=s.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),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 Rj(e,t,n){const s=this;return i;function i(a){return Ee(a)?Ae(e,o,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):o(a)}function o(a){return e.attempt(vu,t,n)(a)}}function _j(e){e.exit("blockQuote")}const Su={name:"characterEscape",tokenize:Oj};function Oj(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 wj(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const ju={name:"characterReference",tokenize:Dj};function Dj(e,t,n){const s=this;let i=0,o,a;return l;function l(m){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),c}function c(m){return m===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(m),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,a=ot,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=yj,u):(e.enter("characterReferenceValue"),o=7,a=No,u(m))}function u(m){if(m===59&&i){const p=e.exit("characterReferenceValue");return a===ot&&!va(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 mc={partial:!0,tokenize:$j},pc={concrete:!0,name:"codeFenced",tokenize:Mj};function Mj(e,t,n){const s=this,i={partial:!0,tokenize:k};let o=0,a=0,l;return c;function c(v){return d(v)}function d(v){const N=s.events[s.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,l=v,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),u(v)}function u(v){return v===l?(a++,e.consume(v),u):a<3?n(v):(e.exit("codeFencedFenceSequence"),Ee(v)?Ae(e,m,"whitespace")(v):m(v))}function m(v){return v===null||le(v)?(e.exit("codeFencedFence"),s.interrupt?t(v):e.check(mc,g,C)(v)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===null||le(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),m(v)):Ee(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Ae(e,h,"whitespace")(v)):v===96&&v===l?n(v):(e.consume(v),p)}function h(v){return v===null||le(v)?m(v):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||le(v)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),m(v)):v===96&&v===l?n(v):(e.consume(v),x)}function g(v){return e.attempt(i,C,b)(v)}function b(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),w}function w(v){return o>0&&Ee(v)?Ae(e,y,"linePrefix",o+1)(v):y(v)}function y(v){return v===null||le(v)?e.check(mc,g,C)(v):(e.enter("codeFlowValue"),S(v))}function S(v){return v===null||le(v)?(e.exit("codeFlowValue"),y(v)):(e.consume(v),S)}function C(v){return e.exit("codeFenced"),t(v)}function k(v,N,O){let D=0;return _;function _(I){return v.enter("lineEnding"),v.consume(I),v.exit("lineEnding"),T}function T(I){return v.enter("codeFencedFence"),Ee(I)?Ae(v,z,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):z(I)}function z(I){return I===l?(v.enter("codeFencedFenceSequence"),R(I)):O(I)}function R(I){return I===l?(D++,v.consume(I),R):D>=a?(v.exit("codeFencedFenceSequence"),Ee(I)?Ae(v,$,"whitespace")(I):$(I)):O(I)}function $(I){return I===null||le(I)?(v.exit("codeFencedFence"),N(I)):O(I)}}}function $j(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 Li={name:"codeIndented",tokenize:Bj},Fj={partial:!0,tokenize:Uj};function Bj(e,t,n){const s=this;return i;function i(d){return e.enter("codeIndented"),Ae(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?c(d):le(d)?e.attempt(Fj,a,c)(d):(e.enter("codeFlowValue"),l(d))}function l(d){return d===null||le(d)?(e.exit("codeFlowValue"),a(d)):(e.consume(d),l)}function c(d){return e.exit("codeIndented"),t(d)}}function Uj(e,t,n){const s=this;return i;function i(a){return s.parser.lazy[s.now().line]?n(a):le(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):Ae(e,o,"linePrefix",5)(a)}function o(a){const l=s.events[s.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):le(a)?i(a):n(a)}}const Vj={name:"codeText",previous:Wj,resolve:Hj,tokenize:qj};function Hj(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 Wj(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function qj(e,t,n){let s=0,i,o;return a;function a(m){return e.enter("codeText"),e.enter("codeTextSequence"),l(m)}function l(m){return m===96?(e.consume(m),s++,l):(e.exit("codeTextSequence"),c(m))}function c(m){return m===null?n(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),c):m===96?(o=e.enter("codeTextSequence"),i=0,u(m)):le(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),c):(e.enter("codeTextData"),d(m))}function d(m){return m===null||m===32||m===96||le(m)?(e.exit("codeTextData"),c(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 Gj{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 ku(e){const t={};let n=-1,s,i,o,a,l,c,d;const u=new Gj(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"&&(c=s[1]._tokenizer.events,o=0,o<c.length&&c[o][1].type==="lineEndingBlank"&&(o+=2),o<c.length&&c[o][1].type==="content"))for(;++o<c.length&&c[o][1].type!=="content";)c[o][1].type==="chunkText"&&(c[o][1]._isInFirstContentOfListItem=!0,o++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,Qj(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},l=u.slice(i,n),l.unshift(s),u.splice(i,n-i+1,l))}}return vt(e,0,Number.POSITIVE_INFINITY,u.slice(0)),!d}function Qj(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 l=a.events,c=[],d={};let u,m,p=-1,h=n,x=0,g=0;const b=[g];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<l.length;)l[p][0]==="exit"&&l[p-1][0]==="enter"&&l[p][1].type===l[p-1][1].type&&l[p][1].start.line!==l[p][1].end.line&&(g=p+1,b.push(g),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(a.events=[],h?(h._tokenizer=void 0,h.previous=void 0):b.pop(),p=b.length;p--;){const w=l.slice(b[p],b[p+1]),y=o.pop();c.push([y,y+w.length-1]),e.splice(y,2,w)}for(c.reverse(),p=-1;++p<c.length;)d[x+c[p][0]]=x+c[p][1],x+=c[p][1]-c[p][0]-1;return d}const Jj={resolve:Yj,tokenize:Zj},Kj={partial:!0,tokenize:Xj};function Yj(e){return ku(e),e}function Zj(e,t){let n;return s;function s(l){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(l)}function i(l){return l===null?o(l):le(l)?e.check(Kj,a,o)(l):(e.consume(l),i)}function o(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function a(l){return e.consume(l),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function Xj(e,t,n){const s=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Ae(e,o,"linePrefix")}function o(a){if(a===null||le(a))return n(a);const l=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):e.interrupt(s.parser.constructs.flow,n,t)(a)}}function Cu(e,t,n,s,i,o,a,l,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return m;function m(w){return w===60?(e.enter(s),e.enter(i),e.enter(o),e.consume(w),e.exit(o),p):w===null||w===32||w===41||Co(w)?n(w):(e.enter(s),e.enter(a),e.enter(l),e.enter("chunkString",{contentType:"string"}),g(w))}function p(w){return w===62?(e.enter(o),e.consume(w),e.exit(o),e.exit(i),e.exit(s),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===62?(e.exit("chunkString"),e.exit(l),p(w)):w===null||w===60||le(w)?n(w):(e.consume(w),w===92?x:h)}function x(w){return w===60||w===62||w===92?(e.consume(w),h):h(w)}function g(w){return!u&&(w===null||w===41||nt(w))?(e.exit("chunkString"),e.exit(l),e.exit(a),e.exit(s),t(w)):u<d&&w===40?(e.consume(w),u++,g):w===41?(e.consume(w),u--,g):w===null||w===32||w===40||Co(w)?n(w):(e.consume(w),w===92?b:g)}function b(w){return w===40||w===41||w===92?(e.consume(w),g):g(w)}}function Nu(e,t,n,s,i,o){const a=this;let l=0,c;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 l>999||h===null||h===91||h===93&&!c||h===94&&!l&&"_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):le(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||le(h)||l++>999?(e.exit("chunkString"),u(h)):(e.consume(h),c||(c=!Ee(h)),h===92?p:m)}function p(h){return h===91||h===92||h===93?(e.consume(h),l++,m):m(h)}}function Eu(e,t,n,s,i,o){let a;return l;function l(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,c):n(p)}function c(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),c(a)):p===null?n(p):le(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),Ae(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(p))}function u(p){return p===a||p===null||le(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 ys(e,t){let n;return s;function s(i){return le(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,s):Ee(i)?Ae(e,s,n?"linePrefix":"lineSuffix")(i):t(i)}}const ek={name:"definition",tokenize:nk},tk={partial:!0,tokenize:sk};function nk(e,t,n){const s=this;let i;return o;function o(h){return e.enter("definition"),a(h)}function a(h){return Nu.call(s,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function l(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"),c):n(h)}function c(h){return nt(h)?ys(e,d)(h):d(h)}function d(h){return Cu(e,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function u(h){return e.attempt(tk,m,m)(h)}function m(h){return Ee(h)?Ae(e,p,"whitespace")(h):p(h)}function p(h){return h===null||le(h)?(e.exit("definition"),s.parser.defined.push(i),t(h)):n(h)}}function sk(e,t,n){return s;function s(l){return nt(l)?ys(e,i)(l):n(l)}function i(l){return Eu(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function o(l){return Ee(l)?Ae(e,a,"whitespace")(l):a(l)}function a(l){return l===null||le(l)?t(l):n(l)}}const rk={name:"hardBreakEscape",tokenize:ik};function ik(e,t,n){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),i}function i(o){return le(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const ok={name:"headingAtx",resolve:ak,tokenize:lk};function ak(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 lk(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"),l(u)):n(u)}function l(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||le(u)?(e.exit("atxHeading"),t(u)):Ee(u)?Ae(e,l,"whitespace")(u):(e.enter("atxHeadingText"),d(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),l(u))}function d(u){return u===null||u===35||nt(u)?(e.exit("atxHeadingText"),l(u)):(e.consume(u),d)}}const ck=["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"],gc=["pre","script","style","textarea"],dk={concrete:!0,name:"htmlFlow",resolveTo:fk,tokenize:mk},uk={partial:!0,tokenize:gk},hk={partial:!0,tokenize:pk};function fk(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 mk(e,t,n){const s=this;let i,o,a,l,c;return d;function d(E){return u(E)}function u(E){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(E),m}function m(E){return E===33?(e.consume(E),p):E===47?(e.consume(E),o=!0,g):E===63?(e.consume(E),i=3,s.interrupt?t:j):bt(E)?(e.consume(E),a=String.fromCharCode(E),b):n(E)}function p(E){return E===45?(e.consume(E),i=2,h):E===91?(e.consume(E),i=5,l=0,x):bt(E)?(e.consume(E),i=4,s.interrupt?t:j):n(E)}function h(E){return E===45?(e.consume(E),s.interrupt?t:j):n(E)}function x(E){const W="CDATA[";return E===W.charCodeAt(l++)?(e.consume(E),l===W.length?s.interrupt?t:z:x):n(E)}function g(E){return bt(E)?(e.consume(E),a=String.fromCharCode(E),b):n(E)}function b(E){if(E===null||E===47||E===62||nt(E)){const W=E===47,Y=a.toLowerCase();return!W&&!o&&gc.includes(Y)?(i=1,s.interrupt?t(E):z(E)):ck.includes(a.toLowerCase())?(i=6,W?(e.consume(E),w):s.interrupt?t(E):z(E)):(i=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(E):o?y(E):S(E))}return E===45||ot(E)?(e.consume(E),a+=String.fromCharCode(E),b):n(E)}function w(E){return E===62?(e.consume(E),s.interrupt?t:z):n(E)}function y(E){return Ee(E)?(e.consume(E),y):_(E)}function S(E){return E===47?(e.consume(E),_):E===58||E===95||bt(E)?(e.consume(E),C):Ee(E)?(e.consume(E),S):_(E)}function C(E){return E===45||E===46||E===58||E===95||ot(E)?(e.consume(E),C):k(E)}function k(E){return E===61?(e.consume(E),v):Ee(E)?(e.consume(E),k):S(E)}function v(E){return E===null||E===60||E===61||E===62||E===96?n(E):E===34||E===39?(e.consume(E),c=E,N):Ee(E)?(e.consume(E),v):O(E)}function N(E){return E===c?(e.consume(E),c=null,D):E===null||le(E)?n(E):(e.consume(E),N)}function O(E){return E===null||E===34||E===39||E===47||E===60||E===61||E===62||E===96||nt(E)?k(E):(e.consume(E),O)}function D(E){return E===47||E===62||Ee(E)?S(E):n(E)}function _(E){return E===62?(e.consume(E),T):n(E)}function T(E){return E===null||le(E)?z(E):Ee(E)?(e.consume(E),T):n(E)}function z(E){return E===45&&i===2?(e.consume(E),B):E===60&&i===1?(e.consume(E),H):E===62&&i===4?(e.consume(E),V):E===63&&i===3?(e.consume(E),j):E===93&&i===5?(e.consume(E),U):le(E)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(uk,G,R)(E)):E===null||le(E)?(e.exit("htmlFlowData"),R(E)):(e.consume(E),z)}function R(E){return e.check(hk,$,G)(E)}function $(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),I}function I(E){return E===null||le(E)?R(E):(e.enter("htmlFlowData"),z(E))}function B(E){return E===45?(e.consume(E),j):z(E)}function H(E){return E===47?(e.consume(E),a="",A):z(E)}function A(E){if(E===62){const W=a.toLowerCase();return gc.includes(W)?(e.consume(E),V):z(E)}return bt(E)&&a.length<8?(e.consume(E),a+=String.fromCharCode(E),A):z(E)}function U(E){return E===93?(e.consume(E),j):z(E)}function j(E){return E===62?(e.consume(E),V):E===45&&i===2?(e.consume(E),j):z(E)}function V(E){return E===null||le(E)?(e.exit("htmlFlowData"),G(E)):(e.consume(E),V)}function G(E){return e.exit("htmlFlow"),t(E)}}function pk(e,t,n){const s=this;return i;function i(a){return le(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 gk(e,t,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Ur,t,n)}}const xk={name:"htmlText",tokenize:bk};function bk(e,t,n){const s=this;let i,o,a;return l;function l(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),c}function c(j){return j===33?(e.consume(j),d):j===47?(e.consume(j),k):j===63?(e.consume(j),S):bt(j)?(e.consume(j),O):n(j)}function d(j){return j===45?(e.consume(j),u):j===91?(e.consume(j),o=0,x):bt(j)?(e.consume(j),y):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):le(j)?(a=m,H(j)):(e.consume(j),m)}function p(j){return j===45?(e.consume(j),h):m(j)}function h(j){return j===62?B(j):j===45?p(j):m(j)}function x(j){const V="CDATA[";return j===V.charCodeAt(o++)?(e.consume(j),o===V.length?g:x):n(j)}function g(j){return j===null?n(j):j===93?(e.consume(j),b):le(j)?(a=g,H(j)):(e.consume(j),g)}function b(j){return j===93?(e.consume(j),w):g(j)}function w(j){return j===62?B(j):j===93?(e.consume(j),w):g(j)}function y(j){return j===null||j===62?B(j):le(j)?(a=y,H(j)):(e.consume(j),y)}function S(j){return j===null?n(j):j===63?(e.consume(j),C):le(j)?(a=S,H(j)):(e.consume(j),S)}function C(j){return j===62?B(j):S(j)}function k(j){return bt(j)?(e.consume(j),v):n(j)}function v(j){return j===45||ot(j)?(e.consume(j),v):N(j)}function N(j){return le(j)?(a=N,H(j)):Ee(j)?(e.consume(j),N):B(j)}function O(j){return j===45||ot(j)?(e.consume(j),O):j===47||j===62||nt(j)?D(j):n(j)}function D(j){return j===47?(e.consume(j),B):j===58||j===95||bt(j)?(e.consume(j),_):le(j)?(a=D,H(j)):Ee(j)?(e.consume(j),D):B(j)}function _(j){return j===45||j===46||j===58||j===95||ot(j)?(e.consume(j),_):T(j)}function T(j){return j===61?(e.consume(j),z):le(j)?(a=T,H(j)):Ee(j)?(e.consume(j),T):D(j)}function z(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),i=j,R):le(j)?(a=z,H(j)):Ee(j)?(e.consume(j),z):(e.consume(j),$)}function R(j){return j===i?(e.consume(j),i=void 0,I):j===null?n(j):le(j)?(a=R,H(j)):(e.consume(j),R)}function $(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||nt(j)?D(j):(e.consume(j),$)}function I(j){return j===47||j===62||nt(j)?D(j):n(j)}function B(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function H(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),A}function A(j){return Ee(j)?Ae(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 ja={name:"labelEnd",resolveAll:Sk,resolveTo:jk,tokenize:kk},yk={tokenize:Ck},wk={tokenize:Nk},vk={tokenize:Ek};function Sk(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 jk(e,t){let n=e.length,s=0,i,o,a,l;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 c={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 l=[["enter",c,t],["enter",d,t]],l=dt(l,e.slice(o+1,o+s+3)),l=dt(l,[["enter",u,t]]),l=dt(l,Sa(t.parser.constructs.insideSpan.null,e.slice(o+s+4,a-3),t)),l=dt(l,[["exit",u,t],e[a-2],e[a-1],["exit",d,t]]),l=dt(l,e.slice(a+1)),l=dt(l,[["exit",c,t]]),vt(e,o,e.length,l),e}function kk(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 l;function l(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"),c):n(p)}function c(p){return p===40?e.attempt(yk,u,a?u:m)(p):p===91?e.attempt(wk,u,a?d:m)(p):a?u(p):m(p)}function d(p){return e.attempt(vk,u,m)(p)}function u(p){return t(p)}function m(p){return o._balanced=!0,n(p)}}function Ck(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)?ys(e,o)(m):o(m)}function o(m){return m===41?u(m):Cu(e,a,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(m)}function a(m){return nt(m)?ys(e,c)(m):u(m)}function l(m){return n(m)}function c(m){return m===34||m===39||m===40?Eu(e,d,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(m):u(m)}function d(m){return nt(m)?ys(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 Nk(e,t,n){const s=this;return i;function i(l){return Nu.call(s,e,o,a,"reference","referenceMarker","referenceString")(l)}function o(l){return s.parser.defined.includes(kn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function a(l){return n(l)}}function Ek(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 Tk={name:"labelStartImage",resolveAll:ja.resolveAll,tokenize:Pk};function Pk(e,t,n){const s=this;return i;function i(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),o}function o(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),a):n(l)}function a(l){return l===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(l):t(l)}}const Ik={name:"labelStartLink",resolveAll:ja.resolveAll,tokenize:Ak};function Ak(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 Ri={name:"lineEnding",tokenize:zk};function zk(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Ae(e,t,"linePrefix")}}const mr={name:"thematicBreak",tokenize:Lk};function Lk(e,t,n){let s=0,i;return o;function o(d){return e.enter("thematicBreak"),a(d)}function a(d){return i=d,l(d)}function l(d){return d===i?(e.enter("thematicBreakSequence"),c(d)):s>=3&&(d===null||le(d))?(e.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===i?(e.consume(d),s++,c):(e.exit("thematicBreakSequence"),Ee(d)?Ae(e,l,"whitespace")(d):l(d))}}const tt={continuation:{tokenize:Dk},exit:$k,name:"list",tokenize:Ok},Rk={partial:!0,tokenize:Fk},_k={partial:!0,tokenize:Mk};function Ok(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 l;function l(h){const x=s.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!s.containerState.marker||h===s.containerState.marker:No(h)){if(s.containerState.type||(s.containerState.type=x,e.enter(x,{_container:!0})),x==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(mr,n,d)(h):d(h);if(!s.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(h)}return n(h)}function c(h){return No(h)&&++a<10?(e.consume(h),c):(!s.interrupt||a<2)&&(s.containerState.marker?h===s.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),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(Ur,s.interrupt?n:u,e.attempt(Rk,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 Dk(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Ur,i,o);function i(l){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Ae(e,t,"listItemIndent",s.containerState.size+1)(l)}function o(l){return s.containerState.furtherBlankLines||!Ee(l)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,a(l)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(_k,t,a)(l))}function a(l){return s.containerState._closeFlow=!0,s.interrupt=void 0,Ae(e,e.attempt(tt,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Mk(e,t,n){const s=this;return Ae(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 $k(e){e.exit(this.containerState.type)}function Fk(e,t,n){const s=this;return Ae(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 xc={name:"setextUnderline",resolveTo:Bk,tokenize:Uk};function Bk(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 Uk(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"),l(d)}function l(d){return d===i?(e.consume(d),l):(e.exit("setextHeadingLineSequence"),Ee(d)?Ae(e,c,"lineSuffix")(d):c(d))}function c(d){return d===null||le(d)?(e.exit("setextHeadingLine"),t(d)):n(d)}}const Vk={tokenize:Hk};function Hk(e){const t=this,n=e.attempt(Ur,s,e.attempt(this.parser.constructs.flowInitial,i,Ae(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Jj,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 Wk={resolveAll:Pu()},qk=Tu("string"),Gk=Tu("text");function Tu(e){return{resolveAll:Pu(e==="text"?Qk:void 0),tokenize:t};function t(n){const s=this,i=this.parser.constructs[e],o=n.attempt(i,a,l);return a;function a(u){return d(u)?o(u):l(u)}function l(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),c}function c(u){return d(u)?(n.exit("data"),o(u)):(n.consume(u),c)}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 Pu(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 Qk(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,l=0,c;for(;o--;){const d=i[o];if(typeof d=="string"){for(a=d.length;d.charCodeAt(a-1)===32;)l++,a--;if(a)break;a=-1}else if(d===-2)c=!0,l++;else if(d!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const d={type:n===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:s.start._bufferIndex+a,_index:s.start._index+o,line:s.end.line,column:s.end.column-l,offset:s.end.offset-l},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 Jk={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:vu},Kk={91:ek},Yk={[-2]:Li,[-1]:Li,32:Li},Zk={35:ok,42:mr,45:[xc,mr],60:dk,61:xc,95:mr,96:pc,126:pc},Xk={38:ju,92:Su},eC={[-5]:Ri,[-4]:Ri,[-3]:Ri,33:Tk,38:ju,42:Eo,60:[Ij,xk],91:Ik,92:[rk,Su],93:ja,95:Eo,96:Vj},tC={null:[Eo,Wk]},nC={null:[42,95]},sC={null:[]},rC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:nC,contentInitial:Kk,disable:sC,document:Jk,flow:Zk,flowInitial:Yk,insideSpan:tC,string:Xk,text:eC},Symbol.toStringTag,{value:"Module"}));function iC(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=[],l=[];const c={attempt:N(k),check:N(v),consume:y,enter:S,exit:C,interrupt:N(v,{interrupt:!0})},d={code:null,containerState:{},defineSkip:g,events:[],now:x,parser:e,previous:null,sliceSerialize:p,sliceStream:h,write:m};let u=t.tokenize.call(d,c);return t.resolveAll&&o.push(t),d;function m(T){return a=dt(a,T),b(),a[a.length-1]!==null?[]:(O(t,0),d.events=Sa(o,d.events,d),d.events)}function p(T,z){return aC(h(T),z)}function h(T){return oC(a,T)}function x(){const{_bufferIndex:T,_index:z,line:R,column:$,offset:I}=s;return{_bufferIndex:T,_index:z,line:R,column:$,offset:I}}function g(T){i[T.line]=T.column,_()}function b(){let T;for(;s._index<a.length;){const z=a[s._index];if(typeof z=="string")for(T=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===T&&s._bufferIndex<z.length;)w(z.charCodeAt(s._bufferIndex));else w(z)}}function w(T){u=u(T)}function y(T){le(T)?(s.line++,s.column=1,s.offset+=T===-3?2:1,_()):T!==-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=T}function S(T,z){const R=z||{};return R.type=T,R.start=x(),d.events.push(["enter",R,d]),l.push(R),R}function C(T){const z=l.pop();return z.end=x(),d.events.push(["exit",z,d]),z}function k(T,z){O(T,z.from)}function v(T,z){z.restore()}function N(T,z){return R;function R($,I,B){let H,A,U,j;return Array.isArray($)?G($):"tokenize"in $?G([$]):V($);function V(K){return ne;function ne(fe){const je=fe!==null&&K[fe],X=fe!==null&&K.null,me=[...Array.isArray(je)?je:je?[je]:[],...Array.isArray(X)?X:X?[X]:[]];return G(me)(fe)}}function G(K){return H=K,A=0,K.length===0?B:E(K[A])}function E(K){return ne;function ne(fe){return j=D(),U=K,K.partial||(d.currentConstruct=K),K.name&&d.parser.constructs.disable.null.includes(K.name)?Y():K.tokenize.call(z?Object.assign(Object.create(d),z):d,c,W,Y)(fe)}}function W(K){return T(U,j),I}function Y(K){return j.restore(),++A<H.length?E(H[A]):B}}}function O(T,z){T.resolveAll&&!o.includes(T)&&o.push(T),T.resolve&&vt(d.events,z,d.events.length-z,T.resolve(d.events.slice(z),d)),T.resolveTo&&(d.events=T.resolveTo(d.events,d))}function D(){const T=x(),z=d.previous,R=d.currentConstruct,$=d.events.length,I=Array.from(l);return{from:$,restore:B};function B(){s=T,d.previous=z,d.currentConstruct=R,d.events.length=$,l=I,_()}}function _(){s.line in i&&s.column<2&&(s.column=i[s.line],s.offset+=i[s.line]-1)}}function oC(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 l=a[0];typeof l=="string"?a[0]=l.slice(s):a.shift()}o>0&&a.push(e[i].slice(0,o))}return a}function aC(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=`
|
|
80
|
+
`;break}case-3:{a=`\r
|
|
81
|
+
`;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 lC(e){const s={constructs:pj([rC,...(e||{}).extensions||[]]),content:i(jj),defined:[],document:i(Cj),flow:i(Vk),lazy:{},string:i(qk),text:i(Gk)};return s;function i(o){return a;function a(l){return iC(s,o,l)}}}function cC(e){for(;!ku(e););return e}const bc=/[\0\t\n\r]/g;function dC(){let e=1,t="",n=!0,s;return i;function i(o,a,l){const c=[];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(bc.lastIndex=m,d=bc.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)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),m<p&&(c.push(o.slice(m,p)),e+=p-m),h){case 0:{c.push(65533),e++;break}case 9:{for(u=Math.ceil(e/4)*4,c.push(-2);e++<u;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:s=!0,e=1}m=p+1}return l&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const uC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function hC(e){return e.replace(uC,fC)}function fC(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),o=i===120||i===88;return wu(n.slice(o?2:1),o?16:10)}return va(n)||e}const Iu={}.hasOwnProperty;function mC(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),pC(n)(cC(lC(n).document().write(dC()(e,t,!0))))}function pC(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(oe),autolinkProtocol:D,autolinkEmail:D,atxHeading:o(Z),blockQuote:o(X),characterEscape:D,characterReference:D,codeFenced:o(me),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(me,a),codeText:o(ke,a),codeTextData:D,data:D,codeFlowValue:D,definition:o(Se),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(M),hardBreakEscape:o(ee),hardBreakTrailing:o(ee),htmlFlow:o(te,a),htmlFlowData:D,htmlText:o(te,a),htmlTextData:D,image:o(ce),label:a,link:o(oe),listItem:o(ie),listItemValue:p,listOrdered:o(xe,m),listUnordered:o(xe),paragraph:o(Pe),reference:E,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Z),strong:o(ze),thematicBreak:o(re)},exit:{atxHeading:c(),atxHeadingSequence:k,autolink:c(),autolinkEmail:je,autolinkProtocol:fe,blockQuote:c(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:Y,characterReferenceMarkerNumeric:Y,characterReferenceValue:K,characterReference:ne,codeFenced:c(b),codeFencedFence:g,codeFencedFenceInfo:h,codeFencedFenceMeta:x,codeFlowValue:_,codeIndented:c(w),codeText:c(I),codeTextData:_,data:_,definition:c(),definitionDestinationString:C,definitionLabelString:y,definitionTitleString:S,emphasis:c(),hardBreakEscape:c(z),hardBreakTrailing:c(z),htmlFlow:c(R),htmlFlowData:_,htmlText:c($),htmlTextData:_,image:c(H),label:U,labelText:A,lineEnding:T,link:c(B),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:W,resourceDestinationString:j,resourceTitleString:V,resource:G,setextHeading:c(O),setextHeadingLineSequence:N,setextHeadingText:v,strong:c(),thematicBreak:c()}};Au(t,(e||{}).mdastExtensions||[]);const n={};return s;function s(P){let L={type:"root",children:[]};const F={stack:[L],tokenStack:[],config:t,enter:l,exit:d,buffer:a,resume:u,data:n},q=[];let J=-1;for(;++J<P.length;)if(P[J][1].type==="listOrdered"||P[J][1].type==="listUnordered")if(P[J][0]==="enter")q.push(J);else{const be=q.pop();J=i(P,be,J)}for(J=-1;++J<P.length;){const be=t[P[J][0]];Iu.call(be,P[J][1].type)&&be[P[J][1].type].call(Object.assign({sliceSerialize:P[J][2].sliceSerialize},F),P[J][1])}if(F.tokenStack.length>0){const be=F.tokenStack[F.tokenStack.length-1];(be[1]||yc).call(F,void 0,be[0])}for(L.position={start:Lt(P.length>0?P[0][1].start:{line:1,column:1,offset:0}),end:Lt(P.length>0?P[P.length-2][1].end:{line:1,column:1,offset:0})},J=-1;++J<t.transforms.length;)L=t.transforms[J](L)||L;return L}function i(P,L,F){let q=L-1,J=-1,be=!1,se,ye,$e,Fe;for(;++q<=F;){const Ce=P[q];switch(Ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ce[0]==="enter"?J++:J--,Fe=void 0;break}case"lineEndingBlank":{Ce[0]==="enter"&&(se&&!Fe&&!J&&!$e&&($e=q),Fe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Fe=void 0}if(!J&&Ce[0]==="enter"&&Ce[1].type==="listItemPrefix"||J===-1&&Ce[0]==="exit"&&(Ce[1].type==="listUnordered"||Ce[1].type==="listOrdered")){if(se){let We=q;for(ye=void 0;We--;){const He=P[We];if(He[1].type==="lineEnding"||He[1].type==="lineEndingBlank"){if(He[0]==="exit")continue;ye&&(P[ye][1].type="lineEndingBlank",be=!0),He[1].type="lineEnding",ye=We}else if(!(He[1].type==="linePrefix"||He[1].type==="blockQuotePrefix"||He[1].type==="blockQuotePrefixWhitespace"||He[1].type==="blockQuoteMarker"||He[1].type==="listItemIndent"))break}$e&&(!ye||$e<ye)&&(se._spread=!0),se.end=Object.assign({},ye?P[ye][1].start:Ce[1].end),P.splice(ye||q,0,["exit",se,Ce[2]]),q++,F++}if(Ce[1].type==="listItemPrefix"){const We={type:"listItem",_spread:!1,start:Object.assign({},Ce[1].start),end:void 0};se=We,P.splice(q,0,["enter",We,Ce[2]]),q++,F++,$e=void 0,Fe=!0}}}return P[L][1]._spread=be,F}function o(P,L){return F;function F(q){l.call(this,P(q),q),L&&L.call(this,q)}}function a(){this.stack.push({type:"fragment",children:[]})}function l(P,L,F){this.stack[this.stack.length-1].children.push(P),this.stack.push(P),this.tokenStack.push([L,F||void 0]),P.position={start:Lt(L.start),end:void 0}}function c(P){return L;function L(F){P&&P.call(this,F),d.call(this,F)}}function d(P,L){const F=this.stack.pop(),q=this.tokenStack.pop();if(q)q[0].type!==P.type&&(L?L.call(this,P,q[0]):(q[1]||yc).call(this,P,q[0]));else throw new Error("Cannot close `"+P.type+"` ("+bs({start:P.start,end:P.end})+"): it’s not open");F.position.end=Lt(P.end)}function u(){return fj(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function p(P){if(this.data.expectingFirstListItemValue){const L=this.stack[this.stack.length-2];L.start=Number.parseInt(this.sliceSerialize(P),10),this.data.expectingFirstListItemValue=void 0}}function h(){const P=this.resume(),L=this.stack[this.stack.length-1];L.lang=P}function x(){const P=this.resume(),L=this.stack[this.stack.length-1];L.meta=P}function g(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const P=this.resume(),L=this.stack[this.stack.length-1];L.value=P.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const P=this.resume(),L=this.stack[this.stack.length-1];L.value=P.replace(/(\r?\n|\r)$/g,"")}function y(P){const L=this.resume(),F=this.stack[this.stack.length-1];F.label=L,F.identifier=kn(this.sliceSerialize(P)).toLowerCase()}function S(){const P=this.resume(),L=this.stack[this.stack.length-1];L.title=P}function C(){const P=this.resume(),L=this.stack[this.stack.length-1];L.url=P}function k(P){const L=this.stack[this.stack.length-1];if(!L.depth){const F=this.sliceSerialize(P).length;L.depth=F}}function v(){this.data.setextHeadingSlurpLineEnding=!0}function N(P){const L=this.stack[this.stack.length-1];L.depth=this.sliceSerialize(P).codePointAt(0)===61?1:2}function O(){this.data.setextHeadingSlurpLineEnding=void 0}function D(P){const F=this.stack[this.stack.length-1].children;let q=F[F.length-1];(!q||q.type!=="text")&&(q=ue(),q.position={start:Lt(P.start),end:void 0},F.push(q)),this.stack.push(q)}function _(P){const L=this.stack.pop();L.value+=this.sliceSerialize(P),L.position.end=Lt(P.end)}function T(P){const L=this.stack[this.stack.length-1];if(this.data.atHardBreak){const F=L.children[L.children.length-1];F.position.end=Lt(P.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(L.type)&&(D.call(this,P),_.call(this,P))}function z(){this.data.atHardBreak=!0}function R(){const P=this.resume(),L=this.stack[this.stack.length-1];L.value=P}function $(){const P=this.resume(),L=this.stack[this.stack.length-1];L.value=P}function I(){const P=this.resume(),L=this.stack[this.stack.length-1];L.value=P}function B(){const P=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";P.type+="Reference",P.referenceType=L,delete P.url,delete P.title}else delete P.identifier,delete P.label;this.data.referenceType=void 0}function H(){const P=this.stack[this.stack.length-1];if(this.data.inReference){const L=this.data.referenceType||"shortcut";P.type+="Reference",P.referenceType=L,delete P.url,delete P.title}else delete P.identifier,delete P.label;this.data.referenceType=void 0}function A(P){const L=this.sliceSerialize(P),F=this.stack[this.stack.length-2];F.label=hC(L),F.identifier=kn(L).toLowerCase()}function U(){const P=this.stack[this.stack.length-1],L=this.resume(),F=this.stack[this.stack.length-1];if(this.data.inReference=!0,F.type==="link"){const q=P.children;F.children=q}else F.alt=L}function j(){const P=this.resume(),L=this.stack[this.stack.length-1];L.url=P}function V(){const P=this.resume(),L=this.stack[this.stack.length-1];L.title=P}function G(){this.data.inReference=void 0}function E(){this.data.referenceType="collapsed"}function W(P){const L=this.resume(),F=this.stack[this.stack.length-1];F.label=L,F.identifier=kn(this.sliceSerialize(P)).toLowerCase(),this.data.referenceType="full"}function Y(P){this.data.characterReferenceType=P.type}function K(P){const L=this.sliceSerialize(P),F=this.data.characterReferenceType;let q;F?(q=wu(L,F==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):q=va(L);const J=this.stack[this.stack.length-1];J.value+=q}function ne(P){const L=this.stack.pop();L.position.end=Lt(P.end)}function fe(P){_.call(this,P);const L=this.stack[this.stack.length-1];L.url=this.sliceSerialize(P)}function je(P){_.call(this,P);const L=this.stack[this.stack.length-1];L.url="mailto:"+this.sliceSerialize(P)}function X(){return{type:"blockquote",children:[]}}function me(){return{type:"code",lang:null,meta:null,value:""}}function ke(){return{type:"inlineCode",value:""}}function Se(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function M(){return{type:"emphasis",children:[]}}function Z(){return{type:"heading",depth:0,children:[]}}function ee(){return{type:"break"}}function te(){return{type:"html",value:""}}function ce(){return{type:"image",title:null,url:"",alt:null}}function oe(){return{type:"link",title:null,url:"",children:[]}}function xe(P){return{type:"list",ordered:P.type==="listOrdered",start:null,spread:P._spread,children:[]}}function ie(P){return{type:"listItem",spread:P._spread,checked:null,children:[]}}function Pe(){return{type:"paragraph",children:[]}}function ze(){return{type:"strong",children:[]}}function ue(){return{type:"text",value:""}}function re(){return{type:"thematicBreak"}}}function Lt(e){return{line:e.line,column:e.column,offset:e.offset}}function Au(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Au(e,s):gC(e,s)}}function gC(e,t){let n;for(n in t)if(Iu.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 yc(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+bs({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+bs({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+bs({start:t.start,end:t.end})+") is still open")}function xC(e){const t=this;t.parser=n;function n(s){return mC(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function bC(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 yC(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
82
|
+
`}]}function wC(e,t){const n=t.value?t.value+`
|
|
83
|
+
`:"",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 vC(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function SC(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function jC(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),i=zn(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let a,l=e.footnoteCounts.get(s);l===void 0?(l=0,e.footnoteOrder.push(s),a=e.footnoteOrder.length):a=o+1,l+=1,e.footnoteCounts.set(s,l);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,c);const d={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,d),e.applyData(t,d)}function kC(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 CC(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function zu(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 NC(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return zu(e,t);const i={src:zn(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 EC(e,t){const n={src:zn(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 TC(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 PC(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return zu(e,t);const i={href:zn(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 IC(e,t){const n={href:zn(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 AC(e,t,n){const s=e.all(t),i=n?zC(n):Lu(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 l=-1;for(;++l<s.length;){const u=s[l];(i||l!==0||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
|
|
84
|
+
`}),u.type==="element"&&u.tagName==="p"&&!i?a.push(...u.children):a.push(u)}const c=s[s.length-1];c&&(i||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
|
|
85
|
+
`});const d={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,d),e.applyData(t,d)}function zC(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=Lu(n[s])}return t}function Lu(e){const t=e.spread;return t??e.children.length>1}function LC(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 RC(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function _C(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function OC(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function DC(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)},l=xa(t.children[1]),c=fu(t.children[t.children.length-1]);l&&c&&(a.position={start:l,end:c}),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 MC(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,l=a?a.length:t.children.length;let c=-1;const d=[];for(;++c<l;){const m=t.children[c],p={},h=a?a[c]:void 0;h&&(p.align=h);let x={type:"element",tagName:o,properties:p,children:[]};m&&(x.children=e.all(m),e.patch(m,x),x=e.applyData(m,x)),d.push(x)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(t,u),e.applyData(t,u)}function $C(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const wc=9,vc=32;function FC(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),i=0;const o=[];for(;s;)o.push(Sc(t.slice(i,s.index),i>0,!0),s[0]),i=s.index+s[0].length,s=n.exec(t);return o.push(Sc(t.slice(i),i>0,!1)),o.join("")}function Sc(e,t,n){let s=0,i=e.length;if(t){let o=e.codePointAt(s);for(;o===wc||o===vc;)s++,o=e.codePointAt(s)}if(n){let o=e.codePointAt(i-1);for(;o===wc||o===vc;)i--,o=e.codePointAt(i-1)}return i>s?e.slice(s,i):""}function BC(e,t){const n={type:"text",value:FC(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function UC(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const VC={blockquote:bC,break:yC,code:wC,delete:vC,emphasis:SC,footnoteReference:jC,heading:kC,html:CC,imageReference:NC,image:EC,inlineCode:TC,linkReference:PC,link:IC,listItem:AC,list:LC,paragraph:RC,root:_C,strong:OC,table:DC,tableCell:$C,tableRow:MC,text:BC,thematicBreak:UC,toml:Qs,yaml:Qs,definition:Qs,footnoteDefinition:Qs};function Qs(){}const Ru=-1,Vr=0,ws=1,Ir=2,ka=3,Ca=4,Na=5,Ea=6,_u=7,Ou=8,HC=typeof self=="object"?self:globalThis,jc=(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 HC[e](t)},WC=(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 Vr:case Ru:return n(a,i);case ws:{const l=n([],i);for(const c of a)l.push(s(c));return l}case Ir:{const l=n({},i);for(const[c,d]of a)l[s(c)]=s(d);return l}case ka:return n(new Date(a),i);case Ca:{const{source:l,flags:c}=a;return n(new RegExp(l,c),i)}case Na:{const l=n(new Map,i);for(const[c,d]of a)l.set(s(c),s(d));return l}case Ea:{const l=n(new Set,i);for(const c of a)l.add(s(c));return l}case _u:{const{name:l,message:c}=a;return n(jc(l,c),i)}case Ou: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:l}=new Uint8Array(a);return n(new DataView(l),a)}}return n(jc(o,a),i)};return s},kc=e=>WC(new Map,e)(0),pn="",{toString:qC}={},{keys:GC}=Object,ds=e=>{const t=typeof e;if(t!=="object"||!e)return[Vr,t];const n=qC.call(e).slice(8,-1);switch(n){case"Array":return[ws,pn];case"Object":return[Ir,pn];case"Date":return[ka,pn];case"RegExp":return[Ca,pn];case"Map":return[Na,pn];case"Set":return[Ea,pn];case"DataView":return[ws,n]}return n.includes("Array")?[ws,n]:n.includes("Error")?[_u,n]:[Ir,n]},Js=([e,t])=>e===Vr&&(t==="function"||t==="symbol"),QC=(e,t,n,s)=>{const i=(a,l)=>{const c=s.push(a)-1;return n.set(l,c),c},o=a=>{if(n.has(a))return n.get(a);let[l,c]=ds(a);switch(l){case Vr:{let u=a;switch(c){case"bigint":l=Ou,u=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return i([Ru],a)}return i([l,u],a)}case ws:{if(c){let p=a;return c==="DataView"?p=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(p=new Uint8Array(a)),i([c,[...p]],a)}const u=[],m=i([l,u],a);for(const p of a)u.push(o(p));return m}case Ir:{if(c)switch(c){case"BigInt":return i([c,a.toString()],a);case"Boolean":case"Number":case"String":return i([c,a.valueOf()],a)}if(t&&"toJSON"in a)return o(a.toJSON());const u=[],m=i([l,u],a);for(const p of GC(a))(e||!Js(ds(a[p])))&&u.push([o(p),o(a[p])]);return m}case ka:return i([l,a.toISOString()],a);case Ca:{const{source:u,flags:m}=a;return i([l,{source:u,flags:m}],a)}case Na:{const u=[],m=i([l,u],a);for(const[p,h]of a)(e||!(Js(ds(p))||Js(ds(h))))&&u.push([o(p),o(h)]);return m}case Ea:{const u=[],m=i([l,u],a);for(const p of a)(e||!Js(ds(p)))&&u.push(o(p));return m}}const{message:d}=a;return i([l,{name:c,message:d}],a)};return o},Cc=(e,{json:t,lossy:n}={})=>{const s=[];return QC(!(t||n),!!t,new Map,s)(e),s},Ar=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?kc(Cc(e,t)):structuredClone(e):(e,t)=>kc(Cc(e,t));function JC(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 KC(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function YC(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||JC,s=e.options.footnoteBackLabel||KC,i=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[c]);if(!d)continue;const u=e.all(d),m=String(d.identifier).toUpperCase(),p=zn(m.toLowerCase());let h=0;const x=[],g=e.footnoteCounts.get(m);for(;g!==void 0&&++h<=g;){x.length>0&&x.push({type:"text",value:" "});let y=typeof n=="string"?n:n(c,h);typeof y=="string"&&(y={type:"text",value:y}),x.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+p+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,h),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const b=u[u.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const y=b.children[b.children.length-1];y&&y.type==="text"?y.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...x)}else u.push(...x);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+p},children:e.wrap(u,!0)};e.patch(d,w),l.push(w)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Ar(a),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
|
|
86
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:`
|
|
87
|
+
`}]}}const Du=(function(e){if(e==null)return t1;if(typeof e=="function")return Hr(e);if(typeof e=="object")return Array.isArray(e)?ZC(e):XC(e);if(typeof e=="string")return e1(e);throw new Error("Expected function, string, or object as test")});function ZC(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Du(e[n]);return Hr(s);function s(...i){let o=-1;for(;++o<t.length;)if(t[o].apply(this,i))return!0;return!1}}function XC(e){const t=e;return Hr(n);function n(s){const i=s;let o;for(o in e)if(i[o]!==t[o])return!1;return!0}}function e1(e){return Hr(t);function t(n){return n&&n.type===e}}function Hr(e){return t;function t(n,s,i){return!!(n1(n)&&e.call(this,n,typeof s=="number"?s:void 0,i||void 0))}}function t1(){return!0}function n1(e){return e!==null&&typeof e=="object"&&"type"in e}const Mu=[],s1=!0,Nc=!1,r1="skip";function i1(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;l(e,void 0,[])();function l(c,d,u){const m=c&&typeof c=="object"?c:{};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 ("+(c.type+(h?"<"+h+">":""))+")"})}return p;function p(){let h=Mu,x,g,b;if((!t||o(c,d,u[u.length-1]||void 0))&&(h=o1(n(c,u)),h[0]===Nc))return h;if("children"in c&&c.children){const w=c;if(w.children&&h[0]!==r1)for(g=(s?w.children.length:-1)+a,b=u.concat(w);g>-1&&g<w.children.length;){const y=w.children[g];if(x=l(y,g,b)(),x[0]===Nc)return x;g=typeof x[1]=="number"?x[1]:g+a}}return h}}}function o1(e){return Array.isArray(e)?e:typeof e=="number"?[s1,e]:e==null?Mu:[e]}function $u(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),i1(e,o,l,i);function l(c,d){const u=d[d.length-1],m=u?u.children.indexOf(c):void 0;return a(c,m,u)}}const To={}.hasOwnProperty,a1={};function l1(e,t){const n=t||a1,s=new Map,i=new Map,o=new Map,a={...VC,...n.handlers},l={all:d,applyData:d1,definitionById:s,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:a,one:c,options:n,patch:c1,wrap:h1};return $u(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)}}),l;function c(u,m){const p=u.type,h=l.handlers[p];if(To.call(l.handlers,p)&&h)return h(l,u,m);if(l.options.passThrough&&l.options.passThrough.includes(p)){if("children"in u){const{children:g,...b}=u,w=Ar(b);return w.children=l.all(u),w}return Ar(u)}return(l.options.unknownHandler||u1)(l,u,m)}function d(u){const m=[];if("children"in u){const p=u.children;let h=-1;for(;++h<p.length;){const x=l.one(p[h],u);if(x){if(h&&p[h-1].type==="break"&&(!Array.isArray(x)&&x.type==="text"&&(x.value=Ec(x.value)),!Array.isArray(x)&&x.type==="element")){const g=x.children[0];g&&g.type==="text"&&(g.value=Ec(g.value))}Array.isArray(x)?m.push(...x):m.push(x)}}}return m}}function c1(e,t){e.position&&(t.position=WS(e))}function d1(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,Ar(o)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function u1(e,t){const n=t.data||{},s="value"in t&&!(To.call(n,"hProperties")||To.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 h1(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
|
|
88
|
+
`});++s<e.length;)s&&n.push({type:"text",value:`
|
|
89
|
+
`}),n.push(e[s]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
90
|
+
`}),n}function Ec(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Tc(e,t){const n=l1(e,t),s=n.one(e,void 0),i=YC(n),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return i&&o.children.push({type:"text",value:`
|
|
91
|
+
`},i),o}function f1(e,t){return e&&"run"in e?async function(n,s){const i=Tc(n,{file:s,...t});await e.run(i,s)}:function(n,s){return Tc(n,{file:s,...e||t})}}function Pc(e){if(e)throw e}var _i,Ic;function m1(){if(Ic)return _i;Ic=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},l=function(d,u){if(u==="__proto__")if(e.call(d,u)){if(s)return s(d,u).value}else return;return d[u]};return _i=function c(){var d,u,m,p,h,x,g=arguments[0],b=1,w=arguments.length,y=!1;for(typeof g=="boolean"&&(y=g,g=arguments[1]||{},b=2),(g==null||typeof g!="object"&&typeof g!="function")&&(g={});b<w;++b)if(d=arguments[b],d!=null)for(u in d)m=l(g,u),p=l(d,u),g!==p&&(y&&p&&(o(p)||(h=i(p)))?(h?(h=!1,x=m&&i(m)?m:[]):x=m&&o(m)?m:{},a(g,{name:u,newValue:c(y,x,p)})):typeof p<"u"&&a(g,{name:u,newValue:p}));return g},_i}var p1=m1();const Oi=Bc(p1);function Po(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 g1(){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);l(null,...i);function l(c,...d){const u=e[++o];let m=-1;if(c){a(c);return}for(;++m<i.length;)(d[m]===null||d[m]===void 0)&&(d[m]=i[m]);i=d,u?x1(u,l)(...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 x1(e,t){let n;return s;function s(...a){const l=e.length>a.length;let c;l&&a.push(i);try{c=e.apply(this,a)}catch(d){const u=d;if(l&&n)throw u;return i(u)}l||(c&&c.then&&typeof c.then=="function"?c.then(o,i):c instanceof Error?i(c):o(c))}function i(a,...l){n||(n=!0,t(a,...l))}function o(a){i(null,a)}}const xt={basename:b1,dirname:y1,extname:w1,join:v1,sep:"/"};function b1(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Is(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,l=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(o){n=i+1;break}}else a<0&&(o=!0,a=i+1),l>-1&&(e.codePointAt(i)===t.codePointAt(l--)?l<0&&(s=i):(l=-1,s=a));return n===s?s=a:s<0&&(s=e.length),e.slice(n,s)}function y1(e){if(Is(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 w1(e){Is(e);let t=e.length,n=-1,s=0,i=-1,o=0,a;for(;t--;){const l=e.codePointAt(t);if(l===47){if(a){s=t+1;break}continue}n<0&&(a=!0,n=t+1),l===46?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 v1(...e){let t=-1,n;for(;++t<e.length;)Is(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":S1(n)}function S1(e){Is(e);const t=e.codePointAt(0)===47;let n=j1(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function j1(e,t){let n="",s=0,i=-1,o=0,a=-1,l,c;for(;++a<=e.length;){if(a<e.length)l=e.codePointAt(a);else{if(l===47)break;l=47}if(l===47){if(!(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(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",s=0):(n=n.slice(0,c),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 l===46&&o>-1?o++:o=-1}return n}function Is(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const k1={cwd:C1};function C1(){return"/"}function Io(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function N1(e){if(typeof e=="string")e=new URL(e);else if(!Io(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 E1(e)}function E1(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 Di=["history","path","basename","stem","extname","dirname"];class Fu{constructor(t){let n;t?Io(t)?n={path:t}:typeof t=="string"||T1(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":k1.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<Di.length;){const o=Di[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)Di.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?xt.basename(this.path):void 0}set basename(t){$i(t,"basename"),Mi(t,"basename"),this.path=xt.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?xt.dirname(this.path):void 0}set dirname(t){Ac(this.basename,"dirname"),this.path=xt.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?xt.extname(this.path):void 0}set extname(t){if(Mi(t,"extname"),Ac(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=xt.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Io(t)&&(t=N1(t)),$i(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?xt.basename(this.path,this.extname):void 0}set stem(t){$i(t,"stem"),Mi(t,"stem"),this.path=xt.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 Mi(e,t){if(e&&e.includes(xt.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+xt.sep+"`")}function $i(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Ac(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function T1(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const P1=(function(e){const s=this.constructor.prototype,i=s[e],o=function(){return i.apply(o,arguments)};return Object.setPrototypeOf(o,s),o}),I1={}.hasOwnProperty;class Ta extends P1{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=g1()}copy(){const t=new Ta;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(Oi(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Ui("data",this.frozen),this.namespace[t]=n,this):I1.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ui("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=Ks(t),s=this.parser||this.Parser;return Fi("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),Fi("process",this.parser||this.Parser),Bi("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(o,a){const l=Ks(t),c=s.parse(l);s.run(c,l,function(u,m,p){if(u||!m||!p)return d(u);const h=m,x=s.stringify(h,p);L1(x)?p.value=x:p.result=x,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(),Fi("processSync",this.parser||this.Parser),Bi("processSync",this.compiler||this.Compiler),this.process(t,i),Lc("processSync","process",n),s;function i(o,a){n=!0,Pc(o),s=a}}run(t,n,s){zc(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,l){const c=Ks(n);i.run(t,c,d);function d(u,m,p){const h=m||t;u?l(u):a?a(h):s(void 0,h,p)}}}runSync(t,n){let s=!1,i;return this.run(t,n,o),Lc("runSync","run",s),i;function o(a,l){Pc(a),i=l,s=!0}}stringify(t,n){this.freeze();const s=Ks(n),i=this.compiler||this.Compiler;return Bi("stringify",i),zc(t),i(t,s)}use(t,...n){const s=this.attachers,i=this.namespace;if(Ui("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(d){if(typeof d=="function")c(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[u,...m]=d;c(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");l(d.plugins),d.settings&&(i.settings=Oi(!0,i.settings,d.settings))}function l(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 c(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,...x]=u;const g=s[p][1];Po(g)&&Po(h)&&(h=Oi(!0,g,h)),s[p]=[d,h,...x]}}}}const A1=new Ta().freeze();function Fi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Bi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ui(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 zc(e){if(!Po(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Lc(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Ks(e){return z1(e)?e:new Fu(e)}function z1(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function L1(e){return typeof e=="string"||R1(e)}function R1(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const _1="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Rc=[],_c={allowDangerousHtml:!0},O1=/^(https?|ircs?|mailto|xmpp)$/i,D1=[{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 M1(e){const t=$1(e),n=F1(e);return B1(t.runSync(t.parse(n),n),e)}function $1(e){const t=e.rehypePlugins||Rc,n=e.remarkPlugins||Rc,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._c}:_c;return A1().use(xC).use(n).use(f1,s).use(t)}function F1(e){const t=e.children||"",n=new Fu;return typeof t=="string"&&(n.value=t),n}function B1(e,t){const n=t.allowedElements,s=t.allowElement,i=t.components,o=t.disallowedElements,a=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||U1;for(const u of D1)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+_1+u.id,void 0);return $u(e,d),KS(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 zi)if(Object.hasOwn(zi,h)&&Object.hasOwn(u.properties,h)){const x=u.properties[h],g=zi[h];(g===null||g.includes(u.tagName))&&(u.properties[h]=c(String(x||""),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 l&&u.children?p.children.splice(m,1,...u.children):p.children.splice(m,1),m}}}function U1(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||O1.test(e.slice(0,t))?e:""}let V1=0;function H1(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++V1}`},i={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
|
|
92
|
+
<html><head>
|
|
93
|
+
<script>
|
|
94
|
+
window.__LMS_STUDENT__ = ${JSON.stringify(s)};
|
|
95
|
+
window.__LMS_COURSEWARE__ = ${JSON.stringify(i)};
|
|
96
|
+
(function() {
|
|
97
|
+
try {
|
|
98
|
+
// Override window.postMessage (self-targeting, always works)
|
|
99
|
+
var origPM = window.postMessage;
|
|
100
|
+
window.postMessage = function(msg, targetOrigin, transfer) {
|
|
101
|
+
var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
|
|
102
|
+
try { return origPM.call(this, msg, origin, transfer); }
|
|
103
|
+
catch(err) { if (err.name === 'SyntaxError') return origPM.call(this, msg, '*', transfer); throw err; }
|
|
104
|
+
};
|
|
105
|
+
// Shadow window.parent / window.top with Proxy to intercept .postMessage()
|
|
106
|
+
// Direct assignment (window.parent.postMessage = ...) silently fails on cross-origin WindowProxy
|
|
107
|
+
function proxyWin(realRef, propName) {
|
|
108
|
+
try {
|
|
109
|
+
var safePost = function(msg, targetOrigin, transfer) {
|
|
110
|
+
var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
|
|
111
|
+
try { return realRef.postMessage.call(realRef, msg, origin, transfer); }
|
|
112
|
+
catch(err) { if (err.name === 'SyntaxError') return realRef.postMessage.call(realRef, msg, '*', transfer); throw err; }
|
|
113
|
+
};
|
|
114
|
+
var px = new Proxy(realRef, {
|
|
115
|
+
get: function(t, p) {
|
|
116
|
+
if (p === 'postMessage') return safePost;
|
|
117
|
+
try { var v = t[p]; return typeof v === 'function' ? v.bind(t) : v; } catch(e) { return undefined; }
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
Object.defineProperty(window, propName, { get: function() { return px; }, configurable: true });
|
|
121
|
+
} catch(e) {}
|
|
122
|
+
}
|
|
123
|
+
if (window.parent && window.parent !== window) proxyWin(window.parent, 'parent');
|
|
124
|
+
try { if (window.top && window.top !== window) proxyWin(window.top, 'top'); } catch(e) {}
|
|
125
|
+
} catch(e) {}
|
|
126
|
+
})();
|
|
127
|
+
<\/script>
|
|
128
|
+
<script src="/bridge.js?cw=${encodeURIComponent(t||"")}"><\/script>
|
|
129
|
+
</head><body>
|
|
130
|
+
${e||""}
|
|
131
|
+
</body></html>`}class W1{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 pr=new W1,q1=4;let Ys=0;const Ao=new Set;function Oc(){return Ys>=q1?null:(Ys+=1,()=>{Ys=Math.max(0,Ys-1);for(const e of Ao)e()})}function G1(e){return Ao.add(e),()=>{Ao.delete(e)}}function Q1(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 l=t.current;if(!l)return;if(typeof IntersectionObserver>"u"){s(!0);return}const c=new IntersectionObserver(d=>{d.some(u=>u.isIntersecting)&&(s(!0),c.disconnect())},{rootMargin:"200px"});return c.observe(l),()=>c.disconnect()},[e,n,t]),f.useEffect(()=>{if(!n){a.current?.(),a.current=null,o(!1);return}const l=Oc();if(l)a.current=l,o(!0);else{const c=G1(()=>{const d=Oc();d&&(c(),a.current=d,o(!0))});return()=>c()}},[n]),f.useEffect(()=>()=>{a.current?.()},[]),i}function Zt(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 J1=new Set(["guest","teacher","teacher_preview"]);function K1(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 l=o.score;(i===null||l<i)&&(s=a+1,i=l),n.set(o.attemptId,s)}),n}function Y1(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 Z1({data:e,lessonId:t,elementId:n,className:s,title:i,lazy:o=!0}){const a=De.useRef(null),l=De.useRef(null),c=Q1(o,a),{theme:d}=Dr(),{scale:u}=wn(),m=de(V=>V.session),[p,h]=f.useState([]),[x,g]=f.useState(!1),[b,w]=f.useState(null),[y,S]=f.useState(null),C=pr.resolve(e,{lessonId:t}),k=!!e.code&&!e.coursewareUuid&&!e.resourceId&&!C,v=e.coursewareUuid??(k?y:null);f.useEffect(()=>{if(!k||!e.code){S(null);return}let V=!1;return fetch("/api/courseware/inline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e.code})}).then(G=>G.ok?G.json():Promise.reject(new Error(`HTTP ${G.status}`))).then(G=>{!V&&typeof G?.uuid=="string"&&G.uuid&&S(G.uuid)}).catch(()=>{}),()=>{V=!0}},[k,e.code]),f.useEffect(()=>{if(!v){w(null);return}let V=!1;return fetch(`/api/courseware/${encodeURIComponent(v)}/access-token`).then(G=>G.ok?G.json():Promise.reject(new Error(`HTTP ${G.status}`))).then(G=>{!V&&typeof G?.token=="string"&&G.token&&w(G.token)}).catch(()=>{}),()=>{V=!0}},[v]),f.useEffect(()=>{const V=e.coursewareUuid;if(!V)return;let G=!1;const E=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(V)}&pageSize=all`).then(ne=>ne.ok?ne.json():{data:[]}).then(ne=>{G||h(En(ne))}).catch(()=>{})};E();let W=null,Y=null;const K=()=>E();try{W=Bx(),W.on("courseware-attempt-updated",K)}catch{Y=setInterval(E,5e3)}return()=>{G=!0,W&&W.off("courseware-attempt-updated",K),Y&&clearInterval(Y)}},[e.coursewareUuid]);const N=()=>{nu(d,Xo(d)),su(u)};f.useEffect(()=>{const V=n??e.title??void 0,G=e.coursewareUuid;if(!V&&!G||!c)return;const E=a.current?.querySelector("iframe");if(!E||!(E instanceof HTMLIFrameElement)||!E.contentWindow)return;const W=Y=>{if(Y.source!==E.contentWindow)return;const K=Y.data;if(!(!K||typeof K!="object"))if(K.type==="LMS_SUBMIT"){const ne=K.payload??{};_t.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:V,coursewareUuid:G,attemptId:typeof K.attempt_id=="string"?K.attempt_id:void 0,payload:{score:Zt(ne.score??ne.grade),total:Zt(ne.total??ne.fullScore),completion:Zt(ne.completion??ne.progress),comment:typeof ne.comment=="string"?ne.comment:void 0},raw:K})}else if(K.type==="LMS_SAVE_PROGRESS"){const ne=K.payload??{};_t.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:V,coursewareUuid:G,attemptId:typeof K.attempt_id=="string"?K.attempt_id:void 0,payload:{score:Zt(ne.score),completion:Zt(ne.completion??ne.progress)},raw:K})}else if(K.type==="LMS_FINISH")_t.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:V,coursewareUuid:G,attemptId:typeof K.attempt_id=="string"?K.attempt_id:void 0,payload:{},raw:K});else if(K.type==="courseware:score"||K.type==="openlearn-cw-sdk:score"){const ne=K.payload??K;_t.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:V,coursewareUuid:G,payload:{score:Zt(ne.score),total:Zt(ne.total),detail:ne.detail,source:typeof K.source=="string"?K.source:"openlearn-cw-sdk"},raw:K})}else typeof K.type=="string"&&K.type.startsWith("LMS_")&&_t.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:V,coursewareUuid:G,payload:{originalType:K.type},raw:K})};return window.addEventListener("message",W),()=>window.removeEventListener("message",W)},[c,n,e.title,e.coursewareUuid,t]);const O=e.coursewareUuid?`/runtime/${e.coursewareUuid}/${b?`?ct=${encodeURIComponent(b)}`:""}`:e.resourceId?`/api/resources/${e.resourceId}/`:C??(y?`/runtime/${y}/${b?`?ct=${encodeURIComponent(b)}`:""}`:void 0);f.useEffect(()=>{if(!c)return;const V=l.current??a.current?.querySelector("iframe");if(V&&V instanceof HTMLIFrameElement)return Xv(V)},[c,O]);const D=p.filter(V=>V.finished_at!==null&&V.finished_at!==void 0),_=D.filter(V=>V.score!==null&&V.score!==void 0),T=_.length>0?_.reduce((V,G)=>V+(G.score||0),0)/_.length:null,z=60,R=m?.role==="student"&&(m.studentId||m.userId)||null,$=K1(p),I=D.filter(V=>!J1.has(V.studentId)||V.studentId===R),B=Y1(I,$),H=R?I.find(V=>V.studentId===R)??null:null,A=H?$.get(H.attemptId)??null:null,U=$.size,j=!!e.coursewareUuid&&p.length>0;return r.jsxs("div",{ref:a,className:(s??"w-full h-full")+" relative",children:[c?r.jsx("iframe",{ref:l,className:"w-full h-full border-none",src:O,srcDoc:O?void 0:H1(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:N}):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:()=>g(V=>!V),"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:x?"隐藏成绩":`查看成绩 (${B.length})`}),x&&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:[B.length," 人已提交",T!==null&&` · 均分 ${T.toFixed(1)}`]})}),R&&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:H?`我的成绩 ${typeof H.score=="number"?H.score:"—"}${A!==null?` · 全班第 ${A}/${U} 名`:""}`:"我还没有提交"}),B.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:B.map(V=>{const G=typeof V.score=="number"?V.score:null,E=typeof V.completion=="number"?Math.round(V.completion*100):null,W=$.get(V.attemptId),Y=!!R&&V.studentId===R;return r.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${Y?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${V.attemptId}`,children:[r.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:W??"-"}),r.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[V.studentName||V.studentId,Y&&r.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),r.jsxs("span",{className:`font-mono font-bold ${G!==null&&G>=z?"text-green-600":"text-red-500"}`,children:[G!==null?G:"-",E!==null&&r.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[E,"%"]})]})]},V.attemptId)})})]})]})]})}class X1{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 gr=new X1,DN=({type:e,title:t,data:n,containerSize:s,onClose:i,lessonId:o,elementId:a,dismissible:l=!0,readOnly:c=!1,renderContent:d})=>{De.useEffect(()=>{if(!l)return;const k=v=>{v.key==="Escape"&&i()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[i,l]);const u=l?i:()=>{},m=gr.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 x=De.useRef(null),[g,b]=f.useState({width:0,height:0}),w=De.useRef(null),y=De.useCallback(()=>{const k=x.current;if(!k)return;const v=window.getComputedStyle(k),N=k.clientWidth-(parseFloat(v.paddingLeft)||0)-(parseFloat(v.paddingRight)||0),O=k.clientHeight-(parseFloat(v.paddingTop)||0)-(parseFloat(v.paddingBottom)||0);b({width:Math.max(0,N),height:Math.max(0,O)})},[]),S=De.useCallback(k=>{x.current=k,w.current?.disconnect(),w.current=null,k&&typeof ResizeObserver<"u"&&(w.current=new ResizeObserver(y),w.current.observe(k))},[y]);f.useLayoutEffect(()=>{y()},[y]);const C=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}),l?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(Qi,{size:14})," 退出全屏"]}):r.jsx("span",{className:`px-2 py-1 rounded-md text-xs font-bold flex items-center gap-1 select-none ${c?"bg-amber-100 text-amber-800 border border-amber-300":"bg-indigo-100 text-indigo-600"}`,title:c?"教师已开启全班专注锁定,当前为只读演示视图":"由教师端控制,无法在本地退出",children:c?"🔒 全班专注锁定中 · 演示视图":r.jsxs(r.Fragment,{children:[r.jsx(Qi,{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:c&&!k?"none":"auto"},children:[m?r.jsx(m,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:o,elementId:a}):d?d(g):r.jsx(tN,{elementType:e,data:n,onClose:u,containerSize:p,lessonId:o}),c&&!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:v=>{v.stopPropagation(),v.preventDefault()},onPointerDown:v=>{v.stopPropagation(),v.preventDefault()}})]})})()]})});return kp.createPortal(C,document.body)},eN=[{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 tN({data:e,lessonId:t}){const n=eN.find(l=>e[l.field]!==void 0&&e[l.field]!==null&&e[l.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(Rr,{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(M1,{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 l=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:l.map((c,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],"."]}),c]},d))})]})}if(s==="url"){const l=tr(e.url);return l?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx("a",{href:l,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(Z1,{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 nN{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 Vi=new nN,Pa=[{id:"intro",labelZh:"准备环节",labelEn:"Intro",icon:ag},{id:"lecture",labelZh:"讲授新课",labelEn:"Lecture",icon:Fo},{id:"practice",labelZh:"互动练习",labelEn:"Practice",icon:lg},{id:"quiz",labelZh:"随堂测试",labelEn:"Quiz",icon:Vc},{id:"summary",labelZh:"要点总结",labelEn:"Summary",icon:at}],As=St(()=>({items:new Map}));function Bu(e){if(e&&typeof e!="string")return e;if(typeof e=="string"&&e.trim()){const t=wr;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 Xc}function Uu(e,t){const n=t||e.pluginId;As.setState(s=>{const i=new Map(s.items);return i.set(e.id,{meta:{...e,icon:Bu(e.icon),pluginId:n},pluginId:n}),{items:i}})}function sN(e,t){As.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 rN(e){As.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 iN(){return[...Pa,...Array.from(As.getState().items.values()).map(e=>e.meta)]}function MN(){return Ft(As,Fc(e=>[...Pa,...Array.from(e.items.values()).map(t=>t.meta)]))}const zo=[{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"}],$N=zo[1].color;function FN(e){return iN().find(t=>t.id===e)||Pa[1]}function BN(e){return zo.find(t=>t.color===e)||zo[1]}class oN{constructor(){this.store=St(()=>({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 Hi=new oN,aN=new Set(["slate","blue","violet","amber","rose","emerald","cyan","pink","indigo"]);function lN(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=aN.has(o)?o:"violet",l=String(e.group??e.category??"custom"),c=e.defaultData&&typeof e.defaultData=="object"&&!Array.isArray(e.defaultData)?e.defaultData:{},d=Array.isArray(e.editFields)?e.editFields:[];Sn.register({type:n,labelZh:s,labelEn:i,descriptionZh:String(e.descriptionZh??e.description??""),descriptionEn:String(e.descriptionEn??e.description??""),color:a,group:l,defaultData:c,editFields:d,pluginId:t},t)}function cN(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&&Uu({id:i,labelZh:n,labelEn:s,icon:Bu(typeof e.icon=="string"?e.icon:null),pluginId:t},t)}const Dc=()=>null;function Zs(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 dN(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:Dc,pluginId:t,origin:"manifest"});const i=s.contributes;if(i&&i.locales&&typeof i.locales=="object"&&jx(t,i.locales),i){for(const[o,a]of Object.entries(i))if(Array.isArray(a)&&!(o==="classroom.tool"&&s.classroomTools))for(const l of a){if(!l||typeof l!="object")continue;const c=l,d=String(c.id??"");d&&(e.registerExtensionPoint(o,{id:d,label:String(c.title??c.label??c.name??d),icon:typeof c.icon=="string"?c.icon:void 0,slotProps:c.commandType?{...c,commandType:iu(String(c.commandType),n)}:c,component:Dc,pluginId:t,origin:"manifest"}),o==="editor.palette_item"?lN(c,t):o==="editor.timeline_segment"&&cN(c,t))}}}const uN=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class hN{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.dispatcher=ud,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 cS;await a.register(hs,t),await a.register(wo,n),await a.register(hr,s),await a.register(fr,i),await a.register(ru,new fN(t)),await a.register(iS,this.dispatcher),this.registry=a,this.initialized=!0,Ne.getState().initialize(a)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),Ne.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){dN(Ne.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:fs,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",wS),i.setAttribute("src",vS),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),Ne.getState().updatePluginState(t,Le.ERROR))};i.addEventListener("load",a),document.body.appendChild(i),this.sandboxFrames.set(t,i);const l=this.registry?await this.registry.resolve(hs):null,c=this.registry?await this.registry.resolve(fr):null,d=this.registry?await this.registry.resolve(hr):null,u=Array.isArray(n.capabilitiesProposed)?n.capabilitiesProposed:[],m=p=>{if(p.source!==i.contentWindow||!Yl(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:l,storageService:c,uiService:d}).catch(x=>{i.contentWindow?.postMessage({channel:fs,type:"reply",callId:h.callId,ok:!1,error:x instanceof Error?x.message:String(x)},"*")})};window.addEventListener("message",m),this.sandboxCleanups.set(t,()=>{i.removeEventListener("load",a),window.removeEventListener("message",m)}),await new Promise((p,h)=>{let x=!1;const g=window.setTimeout(()=>{x||(window.removeEventListener("message",w),h(new Error("Activation timeout (5000ms)")))},5e3),b=y=>{x||(x=!0,window.clearTimeout(g),window.removeEventListener("message",w),y?h(y):p())},w=y=>{if(y.source!==i.contentWindow||!Yl(y.data))return;const S=y.data;if(S.type==="ready"){i.contentWindow?.postMessage({channel:fs,type:"load",id:t,pluginId:t,manifest:n,source:s},"*");return}if(S.type==="activated"&&S.id===t){b();return}if(S.type==="activate-error"&&S.id===t){b(new Error(S.error||"sandbox activation failed"));return}};window.addEventListener("message",w)})}async answerSandboxCall(t,n,s,i,o){const a=(l,c,d)=>{t.contentWindow?.postMessage({channel:fs,type:"reply",callId:n,ok:l,value:c,error:d},"*")};try{let l;if(s==="api.get"||s==="api.post"||s==="api.del"){const c=s.slice(4),d=yS(hs,c,i,o.caps);if(d)throw new Error(d);if(!o.frontendApi)throw new Error("frontendApi is not available");c==="get"?l=await o.frontendApi.get(String(i[0]??"")):c==="post"?l=await o.frontendApi.post(String(i[0]??""),i[1]):l=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 c=`${o.manifest.id}:${String(i[0]??"")}`;if(s==="storage.get")l=o.storageService.get(c);else if(s==="storage.set"){const d=i[1];o.storageService.set(c,typeof d=="string"?d:JSON.stringify(d??null)),l=!0}else o.storageService.delete(c),l=!0}else if(s==="command.invoke"){if(!o.frontendApi)throw new Error("frontendApi is not available");const c=String(i[0]??"");l=await o.frontendApi.post(`/api/plugins/${encodeURIComponent(o.pluginId)}/sandbox-command`,{type:c,payload:i[1]})}else if(s==="ui.register"){const c=String(i[0]??""),d=i[1]&&typeof i[1]=="object"?i[1]:{};Ne.getState().registerExtensionPoint(c,{...d,pluginId:o.pluginId,origin:"runtime"}),l=!0}else if(s==="ui.toast"){const c=String(i[0]??"");o.uiService?.showToast(c,c,"info"),l=!0}else if(s==="context.get"){const c=ve.getState();l={lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId}}else throw new Error(`Unsupported sandbox bridge op "${s}"`);a(!0,l)}catch(l){a(!1,void 0,l instanceof Error?l.message:String(l))}}async activateRemotePlugin(t,n){const s=Ne.getState();if(!n||typeof n.id!="string"||!n.id)throw new Error(`Invalid remote plugin manifest for "${t}": missing manifest.id`);const i=s.activePlugins.find(o=>o.id===t);if(!(i&&(i.state===Le.ACTIVE||i.state===Le.ACTIVATING))){s.updatePluginState(t,Le.ACTIVATING),this.manifests.set(t,n);try{const o=`/plugins/${t}/frontend.js`,a=await fetch(o,{credentials:"same-origin"});if(!a.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${a.status}`);let l=await a.text();window.HostSharedDeps&&(l=pN(l)),this.registerManifestContributions(t,n),await this.mountSandboxFrame(t,n,l),this.pluginModules.set(t,{manifest:n,activate:async()=>{},deactivate:async()=>{this.destroySandboxFrame(t)}}),s.updatePluginState(t,Le.ACTIVE),ei(t),s.clearPluginError(t)}catch(o){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,o),s.updatePluginState(t,Le.ERROR),this.destroySandboxFrame(t),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),s.setPluginError(t,Zs(o)),o}}}async activatePlugin(t){const n=Ne.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,l=a.manifest??o.manifest,c=a.activate??o.activate,d=a.deactivate??o.deactivate;if(!l||typeof c!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(l.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${l.id}"`);this.registerManifestContributions(t,l);const u=await this.buildContext(t,l);await Promise.race([c(u),new Promise((m,p)=>setTimeout(()=>p(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:l,activate:c,deactivate:typeof d=="function"?d:void 0}),n.updatePluginState(t,Le.ACTIVE),ei(t),n.clearPluginError(t),this.manifests.set(t,l)}catch(i){throw n.updatePluginState(t,Le.ERROR),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),n.setPluginError(t,Zs(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=Ne.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:l}=await this.workerManager.createWorker(t,o,i,uN,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,Zs(a)),a}}async deactivatePlugin(t){const n=Ne.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=Ne.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),Ne.getState().pluginErrors.get(t)||n.setPluginError(t,"插件前端连续崩溃,已自动降级")}}async retryPlugin(t){const n=Ne.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==="inline"||s.executionMode==="worker")await this.activatePlugin(t);else if(i)await this.activateRemotePlugin(t,i);else throw new Error(`无法重试插件 "${t}":缺少 manifest 缓存`);return!0}catch(i){return console.error(`[FrontendPluginHost] Retry failed for plugin "${t}":`,i),n.setPluginError(t,Zs(i)),!1}}async uninstallPlugin(t){const n=Ne.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 Ne.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?Ne.getState().unregisterPluginRuntimeExtensionPoints(t):Ne.getState().unregisterPluginExtensionPoints(t),gr.unregisterPlugin(t),Vi.unregisterPlugin(t),pr.unregisterPlugin(t),Sn.unregisterPlugin(t),rN(t),Hi.clearOwned(t),kt.clearOwned(t),kx(t),n?.keepBreakerState||ei(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(hs),i=await this.registry.resolve(wo),o=await this.registry.resolve(hr),a=await this.registry.resolve(fr),l=this.dispatcher.createScopedDispatcher?this.dispatcher.createScopedDispatcher(t):{dispatch:(c,d)=>this.dispatcher.dispatch(c,{sourcePluginId:t,...d}),registerHandler:(c,d)=>this.dispatcher.registerHandler(c,d),subscribe:(c,d)=>this.dispatcher.subscribe(c,d),use:c=>this.dispatcher.use(c)};return{services:{frontendApi:s,socketService:i,uiService:o,storageService:a},pluginId:t,manifest:n,dispatcher:l,ui:{registerExtensionPoint:(c,d)=>{Ne.getState().registerExtensionPoint(c,{...d,pluginId:t,origin:"runtime"})},unregisterExtensionPoint:(c,d)=>{Ne.getState().unregisterExtensionPoint(c,d,t)},registerFullscreenRenderer:(c,d)=>{gr.register(c,d,t)},unregisterFullscreenRenderer:c=>{gr.unregister(c,t)},registerPropertyEditor:(c,d)=>{Vi.register(c,d,t)},unregisterPropertyEditor:c=>{Vi.unregister(c,t)},registerCoursewareSource:c=>{pr.register(c,t)},unregisterCoursewareSource:c=>{pr.unregister(c,t)},registerPaletteItem:c=>{Sn.register(c,t)},unregisterPaletteItem:c=>{Sn.unregister(c,t)},registerSegmentType:c=>{Uu(c,t)},unregisterSegmentType:c=>{sN(c,t)},registerAssignmentQuestionRenderer:c=>{Hi.register(c,t)},unregisterAssignmentQuestionRenderer:c=>{Hi.unregister(c,t)},registerAssessmentQuestionType:c=>{kt.register(c,t)},unregisterAssessmentQuestionType:c=>{kt.unregister(c,t)}},navigation:{getTeacherTab:()=>ve.getState().teacherTab,setTeacherTab:c=>ve.getState().setTeacherTab(c),setSelectedLesson:c=>ve.getState().setSelectedLesson(c),subscribeTeacherTab:c=>{let d=ve.getState().teacherTab;return this.trackDisposer(t,ve.subscribe(u=>{const m=u.teacherTab;m!==d&&(d=m,c(m))}))}},context:{get:()=>{const c=ve.getState();return{lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId}},subscribe:c=>{const d=ve.getState();let u={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};return this.trackDisposer(t,ve.subscribe(m=>{const p={lessonId:m.selectedLesson,classId:m.liveClassSelectedClassId};(p.lessonId!==u.lessonId||p.classId!==u.classId)&&(u=p,c(p))}))}},i18n:{t:(c,d,u)=>{const m=c.includes(":")?c:`${t}:${c}`;return pd(m,d,u)},getLanguage:()=>Cx()},invokeCommand:async(c,d)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=iu(c,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:c=>{const d=c.slot||"teacher.dashboard.widget";Ne.getState().registerExtensionPoint(d,{...c,pluginId:t,origin:"runtime"})},registerMenu:c=>{const d=c.slot||"teacher.panel";Ne.getState().registerExtensionPoint(d,{...c,pluginId:t,origin:"runtime"})},registerToolbarButton:c=>{Ne.getState().registerExtensionPoint("classroom.tool",{...c,pluginId:t,origin:"runtime"})}}}}class fN{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 Mc={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 $c(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 mN(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 c=i[1],d=$c(i[2]);return n.push(`const ${c} = ${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 { ${$c(a[1])} } = ${t};`;const l=e.match(/^([a-zA-Z_$][\w$]*)$/);return l?`const ${l[1]} = ${t}?.default ?? ${t};`:null}function pN(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>Mc[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,i)=>{const o=Mc[i];if(!o)return n;const a=mN(s,o);return a||n}),t}class gN 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=la({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 Er(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}),Xt.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(cg,{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(Nn,{size:14}):r.jsx(Cn,{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(ht,{size:14}):r.jsx(vn,{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(Lr,{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(td,{size:14}),r.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}window.React=Wi;window.ReactDOM=qi;window.HostSharedDeps={React:Wi,ReactDOM:qi,ReactDOMClient:Ua,Recharts:Ya,LucideReact:wr,jsxRuntime:Ba,react:Wi,"react-dom":qi,"react-dom/client":Ua,"react/jsx-runtime":Ba,recharts:Ya,"lucide-react":wr};const xN=new hN;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())});Cp.createRoot(document.getElementById("root")).render(r.jsx(f.StrictMode,{children:r.jsx(gN,{children:r.jsx(bx,{host:xN,children:r.jsx(lS,{})})})}));export{ro as $,kd as A,ve as B,ca as C,ii as D,Me as E,lt as F,Wx as G,ob as H,LN as I,Md as J,pt as K,Fx as L,M1 as M,Ve as N,fb as O,fn as P,En as Q,n0 as R,zo as S,Xt as T,iu as U,Gg as V,xs as W,Kt as X,xb as Y,bb as Z,mx as _,Ot as a,kt as a0,Dr as a1,Xv as a2,nu as a3,Xo as a4,_t as a5,RN as a6,_N as a7,Kv as a8,ON as a9,Sn as aa,Vi as ab,DN as ac,wn as ad,zN as ae,go as af,Bx as ag,Z1 as ah,gr as ai,NN as aj,CN as b,nn as c,Ne as d,de as e,tn as f,EN as g,Hi as h,Yo as i,PN as j,TN as k,Uw as l,ir as m,IN as n,hx as o,BN as p,FN as q,$N as r,tr as s,no as t,l0 as u,MN as v,Or as w,hd as x,yd as y,Hw as z};
|