openlearn-next 0.7.12 → 0.7.16
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 +1 -1
- package/cli-data.mjs +2 -2
- package/cli-doctor.mjs +2 -1
- package/dist/assets/{AcademicYearFilter-Dm3no4Nb.js → AcademicYearFilter-pCzZgimU.js} +1 -1
- package/dist/assets/ActivityWorkspaceWidget-KJQdLnvf.js +1 -0
- package/dist/assets/AdminDirectoryView-DDxX8RO2.js +5 -0
- package/dist/assets/AssessmentCenter-D5cVUqvy.js +1 -0
- package/dist/assets/{AssignmentFilePreview-dVhnTYmq.js → AssignmentFilePreview-DK29gdpQ.js} +2 -2
- package/dist/assets/BatchPickerModal-Cw4OZqOJ.js +1 -0
- package/dist/assets/ClassesView-Czx7hU2V.js +32 -0
- package/dist/assets/ClassroomCountdownWidget-BeAM37Cq.js +2 -0
- package/dist/assets/CloudDriveModal-GNZzWVCP.js +1 -0
- package/dist/assets/ComputerLabView-C_0c7sjz.js +1 -0
- package/dist/assets/CourseManagement-DzLB0Xmp.js +1 -0
- package/dist/assets/CourseWizardModal-DmQu237c.js +3 -0
- package/dist/assets/CoursewareHubPanel-Xn5WbXg9.js +1 -0
- package/dist/assets/Dashboard-CX83FUeF.js +8 -0
- package/dist/assets/ExportWeightModal-C0SuUhHM.js +1 -0
- package/dist/assets/HelpTour-D8hVFA6N.js +1 -0
- package/dist/assets/HelpView-C0PP_51D.js +204 -0
- package/dist/assets/ImportLessonsModal-p8Uc1U_h.js +1 -0
- package/dist/assets/{ImportModal-Ct0I5cAL.js → ImportModal-DNaPHV0I.js} +2 -2
- package/dist/assets/InteractiveCoursewareViewer-D9YTgasv.js +1 -0
- package/dist/assets/InteractiveWhiteboard-CHYQfRjR.js +19 -0
- package/dist/assets/LazyCourseware-dtuOSiyR.js +2 -0
- package/dist/assets/LazyWhiteboard-DuBKAh4-.js +2 -0
- package/dist/assets/LessonEditorView-BgI7C_FK.js +1 -0
- package/dist/assets/LiveClassroomView-CJK_WMqD.js +67 -0
- package/dist/assets/NotificationDetailModal-BVYuS4uR.js +1 -0
- package/dist/assets/PluginView-CpWjy0Xf.js +66 -0
- package/dist/assets/ProcessLogsModal-D-Ez_YZA.js +1 -0
- package/dist/assets/QuizGeneratorModal-Lf5QMvkq.js +1 -0
- package/dist/assets/RevealPresentationWrapper-Dnf4v72i.js +48 -0
- package/dist/assets/StudentAssignmentEvalPanel-C-7YSfEQ.js +1 -0
- package/dist/assets/StudentAssignmentView-LuMaNpq8.js +1 -0
- package/dist/assets/StudentLessonView-DUG8I1Zy.js +1 -0
- package/dist/assets/StudentView-mMwGPiiF.js +2 -0
- package/dist/assets/SystemResourceLibraryModal-LUDNOwgW.js +1 -0
- package/dist/assets/TeacherView-ofB-3SEJ.js +2 -0
- package/dist/assets/TimetableView-DrZbyCOQ.js +6 -0
- package/dist/assets/{UTIF-BtQhea94.js → UTIF-DbcUtUKZ.js} +1 -1
- package/dist/assets/index-CG-g_9my.css +1 -0
- package/dist/assets/index-CLtQGl25.js +169 -0
- package/dist/assets/{index.es-CijVATXs.js → index.es-D1mLdmCj.js} +1 -1
- package/dist/assets/keyboard-Rs007iOv.js +1 -0
- package/dist/assets/{pluginParsers-DD3QL1Xl.js → pluginParsers-C46aCYkl.js} +1 -1
- package/dist/assets/student-workspace-BFPfR77J.js +1 -0
- package/dist/assets/{vendor-charts-skggaP9D.js → vendor-charts-CK-CU_m7.js} +1 -1
- package/dist/assets/{vendor-icons-CaXLq01o.js → vendor-icons-__JLt-CP.js} +2 -2
- package/dist/assets/{vendor-konva-BOuJWFuE.js → vendor-konva-DGELdczq.js} +1 -1
- package/dist/assets/{vendor-motion-BFAPOs-b.js → vendor-motion-DtyD8eRQ.js} +1 -1
- package/dist/assets/{vendor-pdf-DVWGghIL.js → vendor-pdf-DNexfcCO.js} +3 -3
- package/dist/assets/{vendor-pptx-BqU7v5zS.js → vendor-pptx-ByQkJ0Xi.js} +178 -178
- package/dist/assets/{vendor-react-DHoBZpn2.js → vendor-react-lfWn1oGs.js} +1 -1
- package/dist/assets/{vendor-utils-BxOuk3id.js → vendor-utils-CsoI4M9x.js} +1 -1
- package/dist/cli-migrator.cjs +23 -7
- package/dist/index.html +10 -6
- package/dist/server.cjs +16125 -9457
- package/docs_plugin_guide.md +1023 -0
- package/migrations/046_logout_clear_site_data.sql +9 -0
- package/migrations/047_third_party_theme_system.sql +55 -0
- package/migrations/048_file_storage_extension.sql +63 -0
- package/migrations/049_ai_personas.sql +25 -0
- package/migrations/050_ai_persona_governance.sql +11 -0
- package/migrations/051_community_registry_url.sql +9 -0
- package/migrations/052_community_install_enabled.sql +12 -0
- package/migrations/053_runtime_admin_policies.sql +28 -0
- package/migrations/054_user_onboarding_tour_status.sql +10 -0
- package/migrations/055_classroom_collab_whiteboard.sql +27 -0
- package/migrations/056_public_student_lookup.sql +9 -0
- package/migrations/README.md +59 -48
- package/migrations/schema-golden.json +98 -2
- package/package.json +8 -6
- package/scripts/assert-node-runtime.mjs +4 -3
- package/dist/assets/ActivityWorkspaceWidget-TtBuNORs.js +0 -1
- package/dist/assets/AdminDirectoryView-D03WOMc-.js +0 -5
- package/dist/assets/AssessmentCenter-MUvoJySb.js +0 -1
- package/dist/assets/BatchPickerModal-QALdhrX6.js +0 -1
- package/dist/assets/ClassesView-CKwlRz-A.js +0 -32
- package/dist/assets/ClassroomCountdownWidget-DyWyForY.js +0 -2
- package/dist/assets/CloudDriveModal-C8UAn3MO.js +0 -1
- package/dist/assets/ComputerLabView-E5b3XTkk.js +0 -1
- package/dist/assets/CourseManagement-3jSlq7lV.js +0 -1
- package/dist/assets/CourseWizardModal-BAkW5VJX.js +0 -3
- package/dist/assets/CoursewareHubPanel-BkjcusjZ.js +0 -1
- package/dist/assets/Dashboard-Ha2fZAqD.js +0 -8
- package/dist/assets/ExportWeightModal-D2Y13384.js +0 -1
- package/dist/assets/HelpTour-DBq2otcV.js +0 -1
- package/dist/assets/HelpView-BVLRnMxl.js +0 -204
- package/dist/assets/ImportLessonsModal-CQlq4b81.js +0 -1
- package/dist/assets/InteractiveCoursewareViewer-DGKh1gO8.js +0 -1
- package/dist/assets/InteractiveWhiteboard-BbZlYpRu.js +0 -65
- package/dist/assets/LazyCourseware-zONqinCM.js +0 -2
- package/dist/assets/LazyWhiteboard-BV98LEZ8.js +0 -2
- package/dist/assets/LessonEditorView-LXRkKxdY.js +0 -1
- package/dist/assets/LiveClassroomView-TaHtHWkY.js +0 -63
- package/dist/assets/NotificationDetailModal-BF_-pn0c.js +0 -1
- package/dist/assets/PluginView-sVMPXae9.js +0 -77
- package/dist/assets/ProcessLogsModal-D97xLgnL.js +0 -1
- package/dist/assets/QuizGeneratorModal-CNY8ISjR.js +0 -1
- package/dist/assets/StudentAssignmentEvalPanel-CUmM5DbT.js +0 -1
- package/dist/assets/StudentAssignmentView-B-1MtwKj.js +0 -1
- package/dist/assets/StudentLessonView-CqrcvVND.js +0 -1
- package/dist/assets/StudentView-Bi9kgSrN.js +0 -2
- package/dist/assets/SystemResourceLibraryModal-DDALKrJC.js +0 -1
- package/dist/assets/TeacherView-C5JmoKHk.js +0 -2
- package/dist/assets/TimetableView-BOLB-kZC.js +0 -6
- package/dist/assets/index-Bc9003lB.js +0 -131
- package/dist/assets/index-D4aq9poS.css +0 -1
- package/dist/assets/student-workspace-C4UgD58C.js +0 -1
- package/dist/assets/vendor-reveal-DcQQzuI9.css +0 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/student-workspace-BFPfR77J.js","assets/vendor-react-lfWn1oGs.js","assets/vendor-utils-CsoI4M9x.js","assets/LazyWhiteboard-DuBKAh4-.js","assets/StudentAssignmentEvalPanel-C-7YSfEQ.js","assets/AssignmentFilePreview-DK29gdpQ.js","assets/vendor-icons-__JLt-CP.js","assets/ActivityWorkspaceWidget-KJQdLnvf.js","assets/vendor-motion-DtyD8eRQ.js","assets/vendor-pptx-DIWdXF1L.css","assets/StudentView-mMwGPiiF.js","assets/TeacherView-ofB-3SEJ.js","assets/ImportModal-DNaPHV0I.js","assets/CourseWizardModal-DmQu237c.js","assets/ImportLessonsModal-p8Uc1U_h.js","assets/QuizGeneratorModal-Lf5QMvkq.js","assets/ProcessLogsModal-D-Ez_YZA.js","assets/CloudDriveModal-GNZzWVCP.js","assets/LazyCourseware-dtuOSiyR.js","assets/SystemResourceLibraryModal-LUDNOwgW.js","assets/BatchPickerModal-Cw4OZqOJ.js","assets/ExportWeightModal-C0SuUhHM.js","assets/NotificationDetailModal-BVYuS4uR.js","assets/HelpTour-D8hVFA6N.js","assets/CoursewareHubPanel-Xn5WbXg9.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as b,j as r,R as Ue,g as Rl,b as Yb,u as Gh,c as fr,d as Ra,h as La,J as Kc,i as Yc,k as Qb}from"./vendor-react-lfWn1oGs.js";import{f as Ll,h as Lt,j as tn}from"./vendor-utils-CsoI4M9x.js";import{G as Oa,K as Si,S as qi,X as De,C as Pt,a as Xe,b as Zh,U as Ol,c as wn,L as Da,A as li,E as Jb,d as kn,e as Kh,f as dt,g as ki,h as Dl,T as Bt,P as ji,I as ci,M as $a,B as Xs,i as Xb,j as Ni,W as e0,k as bt,l as Yh,m as Qh,n as Jh,R as Ci,o as qn,p as Xh,q as t0,r as $l,s as n0,H as s0,F as Ml,t as r0,u as Fl,v as Bl,w as ef,x as di,y as Ul,z as tf,D as i0,J as o0,N as Gi,O as nf,Q as $s,V as a0,Y as Ma,Z as l0,_ as ut,$ as Fa,a0 as c0,a1 as sf,a2 as Qc,a3 as rf,a4 as d0,a5 as u0,a6 as of,a7 as er,a8 as h0,a9 as f0,aa as ui,ab as m0,ac as p0,ad as Gn,ae as Ba,af as Ua,ag as g0,ah as Jn,ai as Vl,aj as x0,ak as Un,al as af,am as lf,an as b0,ao as cf,ap as y0,aq as w0,ar as tr,as as df,at as uf,au as Zn,av as hi,aw as v0,ax as Jc,ay as S0,az as k0,aA as hf,aB as Xc,aC as j0,aD as N0,aE as Zi,aF as Wr,aG as C0,aH as E0,aI as I0,aJ as A0,aK as Wl,aL as T0,aM as _0,aN as P0,aO as z0,aP as R0,aQ as L0}from"./vendor-icons-__JLt-CP.js";import{c as mr}from"./vendor-pptx-ByQkJ0Xi.js";import{_ as Ye}from"./vendor-pdf-DNexfcCO.js";import{i as Ki,g as O0,s as ff,a as Hl,r as D0,b as mf,c as ed,d as $0,e as M0,f as F0,h as B0,j as U0,k as V0,l as pf,m as W0,n as H0,o as q0,p as G0,S as Z0,H as K0,F as nn,q as Y0,t as Q0,u as gf,v as fi,w as td,x as kt,y as xf,z as J0,A as nd,B as X0,C as mi,D as Va,E as sd,G as ey,I as ty,J as qt,K as ny,L as sy,M as ry,N as rd,O as iy,P as oy,Q as id,R as ay,T as ly,U as Hr,V as cy,W as dy,X as bf,Y as uy,Z as hy}from"./vendor-motion-DtyD8eRQ.js";import{R as od}from"./vendor-charts-CK-CU_m7.js";const ql=b.createContext({});function Ei(e){const t=b.useRef(null);return t.current===null&&(t.current=e()),t.current}const fy=typeof window<"u",yf=fy?b.useLayoutEffect:b.useEffect,Ii=b.createContext(null),qs=b.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ad(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function my(...e){return t=>{let n=!1;const s=e.map(i=>{const o=ad(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():ad(e[i],null)}}}}function py(...e){return b.useCallback(my(...e),e)}class gy extends b.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Ki(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,i=Ki(s)&&s.offsetWidth||0,o=Ki(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 xy({children:e,isPresent:t,anchorX:n,anchorY:s,root:i,pop:o}){const a=b.useId(),l=b.useRef(null),c=b.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:u}=b.useContext(qs),d=e.props?.ref??e?.ref,f=py(l,d);return b.useInsertionEffect(()=>{const{width:m,height:h,top:y,left:p,right:x,bottom:g,direction:v}=c.current;if(t||o===!1||!l.current||!m||!h)return;const w=v==="rtl",E=n==="left"?w?`right: ${x}`:`left: ${p}`:w?`left: ${p}`:`right: ${x}`,N=s==="bottom"?`bottom: ${g}`:`top: ${y}`;l.current.dataset.motionPopId=a;const j=document.createElement("style");u&&(j.nonce=u);const I=i??document.head;return I.appendChild(j),j.sheet&&j.sheet.insertRule(`
|
|
3
|
+
[data-motion-pop-id="${a}"] {
|
|
4
|
+
position: absolute !important;
|
|
5
|
+
width: ${m}px !important;
|
|
6
|
+
height: ${h}px !important;
|
|
7
|
+
${E}px !important;
|
|
8
|
+
${N}px !important;
|
|
9
|
+
}
|
|
10
|
+
`),()=>{l.current?.removeAttribute("data-motion-pop-id"),I.contains(j)&&I.removeChild(j)}},[t]),r.jsx(gy,{isPresent:t,childRef:l,sizeRef:c,pop:o,children:o===!1?e:b.cloneElement(e,{ref:f})})}const by=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:i,presenceAffectsLayout:o,mode:a,anchorX:l,anchorY:c,root:u})=>{const d=Ei(yy),f=b.useId();let m=!0,h=b.useMemo(()=>(m=!1,{id:f,initial:t,isPresent:n,custom:i,onExitComplete:y=>{d.set(y,!0);for(const p of d.values())if(!p)return;s&&s()},register:y=>(d.set(y,!1),()=>d.delete(y))}),[n,d,s]);return o&&m&&(h={...h}),b.useMemo(()=>{d.forEach((y,p)=>d.set(p,!1))},[n]),b.useEffect(()=>{!n&&!d.size&&s&&s()},[n]),e=r.jsx(xy,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:u,children:e}),r.jsx(Ii.Provider,{value:h,children:e})};function yy(){return new Map}function wf(e=!0){const t=b.useContext(Ii);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:i}=t,o=b.useId();b.useEffect(()=>{if(e)return i(o)},[e]);const a=b.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,a]:[!0]}const pr=e=>e.key||"";function ld(e){const t=[];return b.Children.forEach(e,n=>{b.isValidElement(n)&&t.push(n)}),t}const wy=({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:u})=>{const[d,f]=wf(a),m=b.useMemo(()=>ld(e),[e]),h=a&&!d?[]:m.map(pr),y=b.useRef(!0),p=b.useRef(m),x=Ei(()=>new Map),g=b.useRef(new Set),[v,w]=b.useState(m),[E,N]=b.useState(m);yf(()=>{y.current=!1,p.current=m;for(let z=0;z<E.length;z++){const $=pr(E[z]);h.includes($)?(x.delete($),g.current.delete($)):x.get($)!==!0&&x.set($,!1)}},[E,h.length,h.join("-")]);const j=[];if(m!==v){let z=[...m];for(let $=0;$<E.length;$++){const V=E[$],B=pr(V);h.includes(B)||(z.splice($,0,V),j.push(V))}return o==="wait"&&j.length&&(z=j),N(ld(z)),w(m),null}const{forceRender:I}=b.useContext(ql);return r.jsx(r.Fragment,{children:E.map(z=>{const $=pr(z),V=a&&!d?!1:m===E||h.includes($),B=()=>{if(g.current.has($))return;if(x.has($))g.current.add($),x.set($,!0);else return;let _=!0;x.forEach(U=>{U||(_=!1)}),_&&(I?.(),N(p.current),a&&f?.(),s&&s())};return r.jsx(by,{isPresent:V,initial:!y.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:u,onExitComplete:V?void 0:B,anchorX:l,anchorY:c,children:z},$)})})},vf=b.createContext({strict:!1}),cd={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 dd=!1;function vy(){if(dd)return;const e={};for(const t in cd)e[t]={isEnabled:n=>cd[t].some(s=>!!n[s])};ff(e),dd=!0}function Sf(){return vy(),O0()}function Sy(e){const t=Sf();for(const n in e)t[n]={...t[n],...e[n]};ff(t)}const ky=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 pi(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||ky.has(e)}let kf=e=>!pi(e);function jf(e){typeof e=="function"&&(kf=t=>t.startsWith("on")?!pi(t):e(t))}try{jf(require("@emotion/is-prop-valid").default)}catch{}function jy(e,t,n){const s={};for(const i in e)i==="values"&&typeof e.values=="object"||Hl(e[i])||(kf(i)||n===!0&&pi(i)||!t&&!pi(i)||e.draggable&&i.startsWith("onDrag"))&&(s[i]=e[i]);return s}function Ny({children:e,isValidProp:t,...n}){t&&jf(t);const s=b.useContext(qs);n={...s,...n},n.transition=D0(n.transition,s.transition),n.isStatic=Ei(()=>n.isStatic);const i=b.useMemo(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion,n.skipAnimations]);return r.jsx(qs.Provider,{value:i,children:e})}const Ai=b.createContext({});function Cy(e,t){if(mf(e)){const{initial:n,animate:s}=e;return{initial:n===!1||ed(n)?n:void 0,animate:ed(s)?s:void 0}}return e.inherit!==!1?t:{}}function Ey(e){const{initial:t,animate:n}=Cy(e,b.useContext(Ai));return b.useMemo(()=>({initial:t,animate:n}),[ud(t),ud(n)])}function ud(e){return Array.isArray(e)?e.join(" "):e}const Gl=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Nf(e,t,n){for(const s in t)!Hl(t[s])&&!$0(s,n)&&(e[s]=t[s])}function Iy({transformTemplate:e},t){return b.useMemo(()=>{const n=Gl();return M0(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ay(e,t){const n=e.style||{},s={};return Nf(s,n,e),Object.assign(s,Iy(e,t)),s}function Ty(e,t){const n={},s=Ay(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 Cf=()=>({...Gl(),attrs:{}});function _y(e,t,n,s){const i=b.useMemo(()=>{const o=Cf();return F0(o,t,B0(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Nf(o,e.style,e),i.style={...o,...i.style}}return i}const Py=["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 Zl(e){return typeof e!="string"||e.includes("-")?!1:!!(Py.indexOf(e)>-1||/[A-Z]/u.test(e))}function zy(e,t,n,{latestValues:s},i,o=!1,a){const c=(a??Zl(e)?_y:Ty)(t,s,i,e),u=jy(t,typeof e=="string",o),d=e!==b.Fragment?{...u,...c,ref:n}:{},{children:f}=t,m=b.useMemo(()=>Hl(f)?f.get():f,[f]);return b.createElement(e,{...d,children:m})}function Ry({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,i){return{latestValues:Ly(n,s,i,e),renderState:t()}}function Ly(e,t,n,s){const i={},o=s(e,{});for(const m in o)i[m]=U0(o[m]);let{initial:a,animate:l}=e;const c=mf(e),u=V0(e);t&&u&&!c&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let d=n?n.initial===!1:!1;d=d||a===!1;const f=d?l:a;if(f&&typeof f!="boolean"&&!pf(f)){const m=Array.isArray(f)?f:[f];for(let h=0;h<m.length;h++){const y=W0(e,m[h]);if(y){const{transitionEnd:p,transition:x,...g}=y;for(const v in g){let w=g[v];if(Array.isArray(w)){const E=d?w.length-1:0;w=w[E]}w!==null&&(i[v]=w)}for(const v in p)i[v]=p[v]}}}return i}const Ef=e=>(t,n)=>{const s=b.useContext(Ai),i=b.useContext(Ii),o=()=>Ry(e,t,s,i);return n?o():Ei(o)},Oy=Ef({scrapeMotionValuesFromProps:H0,createRenderState:Gl}),Dy=Ef({scrapeMotionValuesFromProps:q0,createRenderState:Cf}),$y=Symbol.for("motionComponentSymbol");function My(e,t,n){const s=b.useRef(n);b.useInsertionEffect(()=>{s.current=n});const i=b.useRef(null);return b.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 If=b.createContext({});function On(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Fy(e,t,n,s,i,o){const{visualElement:a}=b.useContext(Ai),l=b.useContext(vf),c=b.useContext(Ii),u=b.useContext(qs),d=u.reducedMotion,f=u.skipAnimations,m=b.useRef(null),h=b.useRef(!1);s=s||l.renderer,!m.current&&s&&(m.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:d,skipAnimations:f,isSVG:o}),h.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const y=m.current,p=b.useContext(If);y&&!y.projection&&i&&(y.type==="html"||y.type==="svg")&&By(m.current,n,i,p);const x=b.useRef(!1);b.useInsertionEffect(()=>{y&&x.current&&y.update(n,c)});const g=n[G0],v=b.useRef(!!g&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return yf(()=>{h.current=!0,y&&(x.current=!0,window.MotionIsMounted=!0,y.updateFeatures(),y.scheduleRenderMicrotask(),v.current&&y.animationState&&y.animationState.animateChanges())}),b.useEffect(()=>{y&&(!v.current&&y.animationState&&y.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),v.current=!1),y.enteringChildren=void 0)}),y}function By(e,t,n,s){const{layoutId:i,layout:o,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:u,layoutAnchor:d,layoutCrossfade:f}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Af(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!a||l&&On(l),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:f,layoutScroll:c,layoutRoot:u,layoutAnchor:d})}function Af(e){if(e)return e.options.allowProjection!==!1?e.projection:Af(e.parent)}function Yi(e,{forwardMotionProps:t=!1,type:n}={},s,i){s&&Sy(s);const o=n?n==="svg":Zl(e),a=o?Dy:Oy;function l(u,d){let f;const m={...b.useContext(qs),...u,layoutId:Uy(u)},{isStatic:h}=m,y=Ey(u),p=a(u,h);if(!h&&typeof window<"u"){Vy();const x=Wy(m);f=x.MeasureLayout,y.visualElement=Fy(e,p,m,i,x.ProjectionNode,o)}return r.jsxs(Ai.Provider,{value:y,children:[f&&y.visualElement?r.jsx(f,{visualElement:y.visualElement,...m}):null,zy(e,u,My(p,y.visualElement,d),p,h,t,o)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=b.forwardRef(l);return c[$y]=e,c}function Uy({layoutId:e}){const t=b.useContext(ql).id;return t&&e!==void 0?t+"-"+e:e}function Vy(e,t){b.useContext(vf).strict}function Wy(e){const t=Sf(),{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 Yi;const n=new Map,s=(o,a)=>Yi(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,Yi(a,void 0,e,t)),n.get(a))})}const qy=(e,t)=>t.isSVG??Zl(e)?new Z0(t):new K0(t,{allowProjection:e!==b.Fragment});class Gy extends nn{constructor(t){super(t),t.animationState||(t.animationState=Y0(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();pf(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 Zy=0;class Ky extends nn{constructor(){super(...arguments),this.id=Zy++,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=Q0(this.node,o,a);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const f in d)this.node.getValue(f)?.jump(d[f])}}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 Yy={animation:{Feature:Gy},exit:{Feature:Ky}};function nr(e){return{point:{x:e.pageX,y:e.pageY}}}const Qy=e=>t=>gf(t)&&e(t,nr(t));function Ms(e,t,n,s){return fi(e,t,Qy(n),s)}const Tf=({current:e})=>e?e.ownerDocument.defaultView:null,hd=(e,t)=>Math.abs(e-t);function Jy(e,t){const n=hd(e.x,t.x),s=hd(e.y,t.y);return Math.sqrt(n**2+s**2)}const fd=new Set(["auto","scroll"]);class _f{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=gr(this.lastRawMoveEventInfo,this.transformPagePoint));const h=Qi(this.lastMoveEventInfo,this.history),y=this.startEvent!==null,p=Jy(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!y&&!p)return;const{point:x}=h,{timestamp:g}=td;this.history.push({...x,timestamp:g});const{onStart:v,onMove:w}=this.handlers;y||(v&&v(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,h)},this.handlePointerMove=(h,y)=>{this.lastMoveEvent=h,this.lastRawMoveEventInfo=y,this.lastMoveEventInfo=gr(y,this.transformPagePoint),kt.update(this.updatePoint,!0)},this.handlePointerUp=(h,y)=>{this.end();const{onEnd:p,onSessionEnd:x,resumeAnimation:g}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&g&&g(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=Qi(h.type==="pointercancel"?this.lastMoveEventInfo:gr(y,this.transformPagePoint),this.history);this.startEvent&&p&&p(h,v),x&&x(h,v)},!gf(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=i||window;const c=nr(t),u=gr(c,this.transformPagePoint),{point:d}=u,{timestamp:f}=td;this.history=[{...d,timestamp:f}];const{onSessionStart:m}=n;m&&m(t,Qi(u,this.history)),this.removeListeners=xf(Ms(this.contextWindow,"pointermove",this.handlePointerMove),Ms(this.contextWindow,"pointerup",this.handlePointerUp),Ms(this.contextWindow,"pointercancel",this.handlePointerUp)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(fd.has(s.overflowX)||fd.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),kt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),J0(this.updatePoint)}}function gr(e,t){return t?{point:t(e.point)}:e}function md(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Qi({point:e},t){return{point:e,delta:md(e,Pf(t)),offset:md(e,Xy(t)),velocity:ew(t,.1)}}function Xy(e){return e[0]}function Pf(e){return e[e.length-1]}function ew(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const i=Pf(e);for(;n>=0&&(s=e[n],!(i.timestamp-s.timestamp>nd(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&i.timestamp-s.timestamp>nd(t)*2&&(s=e[1]);const o=X0(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 tw(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?mi(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?mi(n,e,s.max):Math.min(e,n)),e}function pd(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 nw(e,{top:t,left:n,bottom:s,right:i}){return{x:pd(e.x,n,i),y:pd(e.y,t,s)}}function gd(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 sw(e,t){return{x:gd(e.x,t.x),y:gd(e.y,t.y)}}function rw(e,t){let n=.5;const s=Va(e),i=Va(t);return i>s?n=sd(t.min,t.max-s,e.min):s>i&&(n=sd(e.min,e.max-i,t.min)),ey(0,1,n)}function iw(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 Wa=.35;function ow(e=Wa){return e===!1?e=0:e===!0&&(e=Wa),{x:xd(e,"left","right"),y:xd(e,"top","bottom")}}function xd(e,t,n){return{min:bd(e,t),max:bd(e,n)}}function bd(e,t){return typeof e=="number"?e:e[t]||0}const aw=new WeakMap;class lw{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=ty(),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=f=>{n&&this.snapToCursor(nr(f).point),this.stopAnimation()},a=(f,m)=>{const{drag:h,dragPropagation:y,onDragStart:p}=this.getProps();if(h&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=oy(h),!this.openDragLock))return;this.latestPointerEvent=f,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),qt(g=>{let v=this.getAxisMotionValue(g).get()||0;if(ay.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const E=w.layout.layoutBox[g];E&&(v=Va(E)*(parseFloat(v)/100))}}this.originPoint[g]=v}),p&&kt.update(()=>p(f,m),!1,!0),rd(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},l=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m;const{dragPropagation:h,dragDirectionLock:y,onDirectionLock:p,onDrag:x}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:g}=m;if(y&&this.currentDirection===null){this.currentDirection=dw(g),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",m.point,g),this.updateAxis("y",m.point,g),this.visualElement.render(),x&&kt.update(()=>x(f,m),!1,!0)},c=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m,this.stop(f,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>{const{dragSnapToOrigin:f}=this.getProps();(f||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:d}=this.getProps();this.panSession=new _f(t,{onSessionStart:o,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Tf(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&&kt.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||!xr(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=tw(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&&On(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=nw(s.layoutBox,t):this.constraints=!1,this.elastic=ow(n),i!==this.constraints&&!On(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&qt(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=iw(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!On(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=ny(s,i.root,this.visualElement.getTransformPagePoint());let a=sw(i.layout.layoutBox,o);if(n){const l=n(sy(a));this.hasMutatedConstraints=!!l,l&&(a=ry(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:i,dragTransition:o,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},u=qt(d=>{if(!xr(d,n,this.currentDirection))return;let f=c&&c[d]||{};(a===!0||a===d)&&(f={min:0,max:0});const m=i?200:1e6,h=i?40:1e7,y={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...o,...f};return this.startAxisValueAnimation(d,y)});return Promise.all(u).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return rd(this.visualElement,t),s.start(iy(t,s,0,n,this.visualElement,!1))}stopAnimation(){qt(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){qt(n=>{const{drag:s}=this.getProps();if(!xr(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]-mi(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!On(n)||!s||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};qt(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();i[a]=rw({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(),qt(a=>{if(!xr(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:u}=this.constraints[a];l.set(mi(c,u,i[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;aw.set(this.visualElement,this);const t=this.visualElement.current,n=Ms(t,"pointerdown",u=>{const{drag:d,dragListener:f=!0}=this.getProps(),m=u.target,h=m!==t&&ly(m);d&&f&&!h&&this.start(u)});let s;const i=()=>{const{dragConstraints:u}=this.getProps();On(u)&&u.current&&(this.constraints=this.resolveRefConstraints(),s||(s=cw(t,u.current,()=>this.scalePositionWithinConstraints())))},{projection:o}=this.visualElement,a=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),kt.read(i);const l=fi(window,"resize",()=>this.scalePositionWithinConstraints()),c=o.addEventListener("didUpdate",(({delta:u,hasLayoutChanged:d})=>{this.isDragging&&d&&(qt(f=>{const m=this.getAxisMotionValue(f);m&&(this.originPoint[f]+=u[f].translate,m.set(m.get()+u[f].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=Wa,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:i,dragConstraints:o,dragElastic:a,dragMomentum:l}}}function yd(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function cw(e,t,n){const s=id(e,yd(n)),i=id(t,yd(n));return()=>{s(),i()}}function xr(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function dw(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class uw extends nn{constructor(t){super(t),this.removeGroupControls=Hr,this.removeListeners=Hr,this.controls=new lw(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Hr}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 Ji=e=>(t,n)=>{e&&kt.update(()=>e(t,n),!1,!0)};class hw extends nn{constructor(){super(...arguments),this.removePointerDownListener=Hr}onPointerDown(t){this.session=new _f(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Tf(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:i}=this.node.getProps();return{onSessionStart:Ji(t),onStart:Ji(n),onMove:Ji(s),onEnd:(o,a)=>{delete this.session,i&&kt.postRender(()=>i(o,a))}}}mount(){this.removePointerDownListener=Ms(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 Xi=!1;class fw extends b.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),Xi&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),dy.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}),Xi=!0,i||t.layoutDependency!==n||n===void 0||t.isPresent!==o?a.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?a.promote():a.relegate()||kt.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(),cy.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:i}=t;Xi=!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 zf(e){const[t,n]=wf(),s=b.useContext(ql);return r.jsx(fw,{...e,layoutGroup:s,switchLayoutGroup:b.useContext(If),isPresent:t,safeToRemove:n})}const mw={pan:{Feature:hw},drag:{Feature:uw,ProjectionNode:bf,MeasureLayout:zf}};function wd(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&&kt.postRender(()=>o(t,nr(t)))}class pw extends nn{mount(){const{current:t}=this.node;t&&(this.unmount=uy(t,(n,s)=>(wd(this.node,s,"Start"),i=>wd(this.node,i,"End"))))}unmount(){}}class gw extends nn{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=xf(fi(this.node.current,"focus",()=>this.onFocus()),fi(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function vd(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&&kt.postRender(()=>o(t,nr(t)))}class xw extends nn{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=hy(t,(i,o)=>(vd(this.node,o,"Start"),(a,{success:l})=>vd(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Ha=new WeakMap,eo=new WeakMap,bw=e=>{const t=Ha.get(e.target);t&&t(e)},yw=e=>{e.forEach(bw)};function ww({root:e,...t}){const n=e||document;eo.has(n)||eo.set(n,{});const s=eo.get(n),i=JSON.stringify(t);return s[i]||(s[i]=new IntersectionObserver(yw,{root:e,...t})),s[i]}function vw(e,t,n){const s=ww(t);return Ha.set(e,n),s.observe(e),()=>{Ha.delete(e),s.unobserve(e)}}const Sw={some:0,all:1};class kw extends nn{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:Sw[i]},l=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),m=u?d:f;m&&m(c)};this.stopObserver=vw(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(jw(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function jw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Nw={inView:{Feature:kw},tap:{Feature:xw},focus:{Feature:gw},hover:{Feature:pw}},Cw={layout:{ProjectionNode:bf,MeasureLayout:zf}},Ew={...Yy,...Nw,...mw,...Cw},qa=Hy(Ew,qy),Kl=b.createContext(null);function br({value:e,children:t}){return r.jsx(Kl.Provider,{value:e,children:t})}function qT(){const e=b.useContext(Kl);if(!e)throw new Error("useAppData must be used within <AppDataProvider>");return e}function Ot(){return b.useContext(Kl)}async function Iw(){const e=await fetch("/api/resources");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Aw(){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 Tw(){const e=await fetch("/api/auth/session");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function Rf(){const e=await fetch("/api/site-settings");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function _w(){await fetch("/api/auth/logout",{method:"POST"})}async function Pw(e){const t=await fetch("/api/auth/onboarding",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:e})});let n;try{n=await t.json()}catch{n={}}return{ok:t.ok,status:t.status,data:n}}const Lf=b.createContext(null),Ga="openlearn_academic_year";function zw(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get("academicYear");return t||null}function Rw(){if(typeof window>"u")return null;try{return window.localStorage.getItem(Ga)}catch{return null}}function Lw(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Ga,e):window.localStorage.removeItem(Ga)}catch{}}function yr({children:e}){const[t,n]=b.useState(()=>zw()||Rw()||null),[s,i]=b.useState(null),[o,a]=b.useState(!0);b.useEffect(()=>{let d=!0;return(async()=>{try{const f=await Rf();if(!d)return;if(f.ok&&f.data){const m=f.data.currentAcademicYear||null;i(m),!t&&m&&n(m)}}catch{}finally{d&&a(!1)}})(),()=>{d=!1}},[]);const l=d=>{const f=d==="all"?null:d;if(n(f),Lw(f),typeof window<"u"){const m=new URL(window.location.href);f?m.searchParams.set("academicYear",f):m.searchParams.delete("academicYear"),window.history.replaceState({},"",m.toString())}},c=t==="all"||t===null?null:t,u=b.useMemo(()=>({academicYear:t,setAcademicYear:l,apiAcademicYear:c,currentAcademicYear:s,loading:o}),[t,c,s,o]);return r.jsx(Lf.Provider,{value:u,children:e})}function Ow(){return b.useContext(Lf)}const nt=[];for(let e=0;e<256;++e)nt.push((e+256).toString(16).slice(1));function Dw(e,t=0){return(nt[e[t+0]]+nt[e[t+1]]+nt[e[t+2]]+nt[e[t+3]]+"-"+nt[e[t+4]]+nt[e[t+5]]+"-"+nt[e[t+6]]+nt[e[t+7]]+"-"+nt[e[t+8]]+nt[e[t+9]]+"-"+nt[e[t+10]]+nt[e[t+11]]+nt[e[t+12]]+nt[e[t+13]]+nt[e[t+14]]+nt[e[t+15]]).toLowerCase()}const $w=new Uint8Array(16);function Mw(){return crypto.getRandomValues($w)}const to={};function Ti(e,t,n){let s;{const i=Date.now(),o=Mw();Fw(to,i,o),s=Bw(o,to.msecs,to.seq,t,n)}return t??Dw(s)}function Fw(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 Bw(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 no(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 Uw{constructor(){this.handlers=new Map,this.prefixHandlers=new Map,this.globalHandlers=new Set,this.wildcardCount=0}subscribe(t,n){const{kind:s,key:i}=no(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}=no(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}=no(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 vn=new Uw,Sd=new Map,so=new Map;async function Vw(e){const t=Sd.get(e);if(t)return t;const n=so.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?(Sd.set(e,o.attemptId),o.attemptId):e}catch(i){return console.warn("[LMS Bridge] Attempt adopt request failed:",i),e}finally{so.delete(e)}})();return so.set(e,s),s}const gi=new Set;function Ww(e){return gi.add(e),()=>{gi.delete(e)}}function Of(e){if(!e)return null;for(const t of gi)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 kd(e){return typeof document>"u"||!e?!1:Of(e)!==null}function Za(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 Ka=-1,Dn=-2,Hw=4;function qw(e){if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:typeof e.toJSON!="function"}function Ya(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 Za(e);if(typeof e!="object")return 0;if(t>=Hw||!qw(e))return Ka;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?Dn:null);if(Array.isArray(e)){for(let c=0;c<e.length;c++){if(!o&&a(1))return Dn;o=!1;const u=e[c];if(u===void 0||typeof u=="function"||typeof u=="symbol"){if(a(4))return Dn;continue}const d=Ya(u,t+1,n);if(d<0)return d;const f=l(d);if(f!==null)return f}return i}for(const c of Object.keys(e)){let u;try{u=e[c]}catch{return Ka}if(u===void 0||typeof u=="function"||typeof u=="symbol")continue;if(!o&&a(1)||(o=!1,a(Za(c)+1)))return Dn;const d=Ya(u,t+1,n);if(d<0)return d;const f=l(d);if(f!==null)return f}return i}function Gw(e,t=512*1024){if(!e||typeof e=="number"||typeof e=="boolean")return!1;if(typeof e=="string")return Za(e)>t;const s=Ya(e,0,{total:0,limit:t});if(s===Dn)return!0;if(s===Ka)try{return JSON.stringify(e).length>t}catch{return!1}return s>t}async function Zw(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(Gw(t,512*1024)){console.warn("[LMS Bridge] Dropped oversized postMessage (>512KB)");return}if(typeof window<"u"&&(!e.source||e.source!==window&&!kd(e.source)))return;let i=t.attempt_id;const o=t.payload||t;if(!i&&e.source)try{const c=Of(e.source);if(c&&c.contentWindow){const u=c.contentWindow;u.__LMS_STUDENT__?.attempt_id&&(i=u.__LMS_STUDENT__.attempt_id)}}catch{}if(!i||typeof i!="string")return;if(i=await Vw(i),n==="LMS_CONFIG"){wr("courseware.config_reported",i,t.config??o);return}if(n==="LMS_GET_PROGRESS"){const c=t.requestId,u=e.source;if(c&&u&&typeof u.postMessage=="function"){if(u!==window&&!kd(u)){console.warn("[LMS Bridge Security] Dropping response to untrusted window");return}let d;try{d=(await(await fetch(`/api/courseware/attempts/${encodeURIComponent(i)}/progress`)).json()).progress??null}catch{d=null}const f=e.origin&&e.origin!=="null"?e.origin:"*";u.postMessage({type:"LMS_PROGRESS_RESPONSE",requestId:c,progress:d},f)}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){wr("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 u=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${c.status}`,u)}}catch(c){console.error("[LMS Bridge] Failed to submit attempt data to backend:",c)}}else if(l){wr("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 u=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${c.status}`,u)}}catch(c){console.error("[LMS Bridge] Failed to save progress to backend:",c)}}else{wr("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 u=await c.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${c.status}`,u)}}catch(c){console.error("[LMS Bridge] Failed to log event to backend:",c)}}}function wr(e,t,n){vn.publish({id:Ti(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t})}function Kw(e){b.useEffect(()=>{if(!e)return;const t=a=>{Zw(a)};window.addEventListener("message",t);let n=!1;const s=async()=>{try{const a=await fetch("/api/bridge/hook-telemetry");if(!a.ok||n)return;const l=await a.json();typeof l.enabled=="boolean"&&!n&&Yw(l.enabled)}catch{}};s();const i=window.setInterval(()=>{s()},3e4),o=()=>{document.visibilityState==="visible"&&s()};return document.addEventListener("visibilitychange",o),()=>{n=!0,window.clearInterval(i),document.removeEventListener("visibilitychange",o),window.removeEventListener("message",t)}},[e])}function Yl(){const e=[],t=new Set;for(const n of gi)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 Gs(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 Yw(e){if(!(typeof document>"u"))for(const t of Yl())Gs(t,{type:"LMS_HOST_COMMAND",event:"hook-telemetry:changed",payload:{enabled:e}})}function Ql(e,t={},n){if(!(typeof document>"u"))try{const s=n?{theme:e,tokens:t,...n}:{theme:e,tokens:t};Yl().forEach(o=>{Gs(o,{type:"LMS_HOST_COMMAND",event:"theme:changed",payload:s}),Gs(o,{type:"LMS_THEME_CHANGED",...s})})}catch{}}function Df(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));Yl().forEach(s=>{Gs(s,{type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}}),Gs(s,{type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)})})}catch{}}let ro=null,io=null;typeof window<"u"&&(vn.subscribe("theme.changed",e=>{ro&&clearTimeout(ro),ro=setTimeout(()=>{const t=e.payload;t&&typeof t.theme=="string"&&Ql(t.theme,t.tokens??{})},50)}),vn.subscribe("font-scale.changed",e=>{io&&clearTimeout(io),io=setTimeout(()=>{const t=e.payload;t&&typeof t.scale=="number"&&Df(t.scale)},50)}));var vr={exports:{}},oo,jd;function sr(){if(jd)return oo;jd=1;const e="2.0.0",t=256,n=Number.MAX_SAFE_INTEGER||9007199254740991,s=16,i=t-6;return oo={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:s,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:n,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:e,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},oo}var ao,Nd;function _i(){if(Nd)return ao;Nd=1;var e={};return ao=typeof process=="object"&&e&&e.NODE_DEBUG&&/\bsemver\b/i.test(e.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{},ao}var Cd;function rr(){return Cd||(Cd=1,(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:i}=sr(),o=_i();t=e.exports={};const a=t.re=[],l=t.safeRe=[],c=t.src=[],u=t.safeSrc=[],d=t.t={};let f=0;const m="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",i],[m,s]],y=x=>{for(const[g,v]of h)x=x.split(`${g}*`).join(`${g}{0,${v}}`).split(`${g}+`).join(`${g}{1,${v}}`);return x},p=(x,g,v)=>{const w=y(g),E=f++;o(x,E,g),d[x]=E,c[E]=g,u[E]=w,a[E]=new RegExp(g,v?"g":void 0),l[E]=new RegExp(w,v?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${m}*`),p("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${m}+`),p("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),p("FULL",`^${c[d.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),p("LOOSE",`^${c[d.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),p("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),p("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?(?:${c[d.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",c[d.COERCE],!0),p("COERCERTLFULL",c[d.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",p("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",p("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(vr,vr.exports)),vr.exports}var lo,Ed;function Jl(){if(Ed)return lo;Ed=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return lo=s=>s?typeof s!="object"?e:s:t,lo}var co,Id;function $f(){if(Id)return co;Id=1;const e=/^[0-9]+$/,t=(s,i)=>{if(typeof s=="number"&&typeof i=="number")return s===i?0:s<i?-1:1;const o=e.test(s),a=e.test(i);return o&&a&&(s=+s,i=+i),s===i?0:o&&!a?-1:a&&!o?1:s<i?-1:1};return co={compareIdentifiers:t,rcompareIdentifiers:(s,i)=>t(i,s)},co}var uo,Ad;function it(){if(Ad)return uo;Ad=1;const e=_i(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:n}=sr(),{safeRe:s,t:i}=rr(),o=Jl(),{compareIdentifiers:a}=$f(),l=(u,d)=>{const f=d.split(".");if(f.length>u.length)return!1;for(let m=0;m<f.length;m++)if(a(u[m],f[m])!==0)return!1;return!0};class c{constructor(d,f){if(f=o(f),d instanceof c){if(d.loose===!!f.loose&&d.includePrerelease===!!f.includePrerelease)return d;d=d.version}else if(typeof d!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof d}".`);if(d.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",d,f),this.options=f,this.loose=!!f.loose,this.includePrerelease=!!f.includePrerelease;const m=d.trim().match(f.loose?s[i.LOOSE]:s[i.FULL]);if(!m)throw new TypeError(`Invalid Version: ${d}`);if(this.raw=d,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const y=+h;if(y>=0&&y<n)return y}return h}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(d){if(e("SemVer.compare",this.version,this.options,d),!(d instanceof c)){if(typeof d=="string"&&d===this.version)return 0;d=new c(d,this.options)}return d.version===this.version?0:this.compareMain(d)||this.comparePre(d)}compareMain(d){return d instanceof c||(d=new c(d,this.options)),this.major<d.major?-1:this.major>d.major?1:this.minor<d.minor?-1:this.minor>d.minor?1:this.patch<d.patch?-1:this.patch>d.patch?1:0}comparePre(d){if(d instanceof c||(d=new c(d,this.options)),this.prerelease.length&&!d.prerelease.length)return-1;if(!this.prerelease.length&&d.prerelease.length)return 1;if(!this.prerelease.length&&!d.prerelease.length)return 0;let f=0;do{const m=this.prerelease[f],h=d.prerelease[f];if(e("prerelease compare",f,m,h),m===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(m===void 0)return-1;if(m===h)continue;return a(m,h)}while(++f)}compareBuild(d){d instanceof c||(d=new c(d,this.options));let f=0;do{const m=this.build[f],h=d.build[f];if(e("build compare",f,m,h),m===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(m===void 0)return-1;if(m===h)continue;return a(m,h)}while(++f)}inc(d,f,m){if(d.startsWith("pre")){if(!f&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(f){const h=`-${f}`.match(this.options.loose?s[i.PRERELEASELOOSE]:s[i.PRERELEASE]);if(!h||h[1]!==f)throw new Error(`invalid identifier: ${f}`)}}switch(d){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",f,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",f,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",f,m),this.inc("pre",f,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",f,m),this.inc("pre",f,m);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(m)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let y=this.prerelease.length;for(;--y>=0;)typeof this.prerelease[y]=="number"&&(this.prerelease[y]++,y=-2);if(y===-1){if(f===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(f){let y=[f,h];if(m===!1&&(y=[f]),l(this.prerelease,f)){const p=this.prerelease[f.split(".").length];isNaN(p)&&(this.prerelease=y)}else this.prerelease=y}break}default:throw new Error(`invalid increment argument: ${d}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return uo=c,uo}var ho,Td;function jn(){if(Td)return ho;Td=1;const e=it();return ho=(n,s,i=!1)=>{if(n instanceof e)return n;try{return new e(n,s)}catch(o){if(!i)return null;throw o}},ho}var fo,_d;function Qw(){if(_d)return fo;_d=1;const e=jn();return fo=(n,s)=>{const i=e(n,s);return i?i.version:null},fo}var mo,Pd;function Jw(){if(Pd)return mo;Pd=1;const e=jn();return mo=(n,s)=>{const i=e(n.trim().replace(/^[=v]+/,""),s);return i?i.version:null},mo}var po,zd;function Xw(){if(zd)return po;zd=1;const e=it();return po=(n,s,i,o,a)=>{typeof i=="string"&&(a=o,o=i,i=void 0);try{return new e(n instanceof e?n.version:n,i).inc(s,o,a).version}catch{return null}},po}var go,Rd;function ev(){if(Rd)return go;Rd=1;const e=jn();return go=(n,s)=>{const i=e(n,null,!0),o=e(s,null,!0),a=i.compare(o);if(a===0)return null;const l=a>0,c=l?i:o,u=l?o:i,d=!!c.prerelease.length;if(!!u.prerelease.length&&!d){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const m=d?"pre":"";return i.major!==o.major?m+"major":i.minor!==o.minor?m+"minor":i.patch!==o.patch?m+"patch":"prerelease"},go}var xo,Ld;function tv(){if(Ld)return xo;Ld=1;const e=it();return xo=(n,s)=>new e(n,s).major,xo}var bo,Od;function nv(){if(Od)return bo;Od=1;const e=it();return bo=(n,s)=>new e(n,s).minor,bo}var yo,Dd;function sv(){if(Dd)return yo;Dd=1;const e=it();return yo=(n,s)=>new e(n,s).patch,yo}var wo,$d;function rv(){if($d)return wo;$d=1;const e=jn();return wo=(n,s)=>{const i=e(n,s);return i&&i.prerelease.length?i.prerelease:null},wo}var vo,Md;function jt(){if(Md)return vo;Md=1;const e=it();return vo=(n,s,i)=>new e(n,i).compare(new e(s,i)),vo}var So,Fd;function iv(){if(Fd)return So;Fd=1;const e=jt();return So=(n,s,i)=>e(s,n,i),So}var ko,Bd;function ov(){if(Bd)return ko;Bd=1;const e=jt();return ko=(n,s)=>e(n,s,!0),ko}var jo,Ud;function Xl(){if(Ud)return jo;Ud=1;const e=it();return jo=(n,s,i)=>{const o=new e(n,i),a=new e(s,i);return o.compare(a)||o.compareBuild(a)},jo}var No,Vd;function av(){if(Vd)return No;Vd=1;const e=Xl();return No=(n,s)=>n.sort((i,o)=>e(i,o,s)),No}var Co,Wd;function lv(){if(Wd)return Co;Wd=1;const e=Xl();return Co=(n,s)=>n.sort((i,o)=>e(o,i,s)),Co}var Eo,Hd;function Pi(){if(Hd)return Eo;Hd=1;const e=jt();return Eo=(n,s,i)=>e(n,s,i)>0,Eo}var Io,qd;function ec(){if(qd)return Io;qd=1;const e=jt();return Io=(n,s,i)=>e(n,s,i)<0,Io}var Ao,Gd;function Mf(){if(Gd)return Ao;Gd=1;const e=jt();return Ao=(n,s,i)=>e(n,s,i)===0,Ao}var To,Zd;function Ff(){if(Zd)return To;Zd=1;const e=jt();return To=(n,s,i)=>e(n,s,i)!==0,To}var _o,Kd;function tc(){if(Kd)return _o;Kd=1;const e=jt();return _o=(n,s,i)=>e(n,s,i)>=0,_o}var Po,Yd;function nc(){if(Yd)return Po;Yd=1;const e=jt();return Po=(n,s,i)=>e(n,s,i)<=0,Po}var zo,Qd;function Bf(){if(Qd)return zo;Qd=1;const e=Mf(),t=Ff(),n=Pi(),s=tc(),i=ec(),o=nc();return zo=(l,c,u,d)=>{switch(c){case"===":return typeof l=="object"&&(l=l.version),typeof u=="object"&&(u=u.version),l===u;case"!==":return typeof l=="object"&&(l=l.version),typeof u=="object"&&(u=u.version),l!==u;case"":case"=":case"==":return e(l,u,d);case"!=":return t(l,u,d);case">":return n(l,u,d);case">=":return s(l,u,d);case"<":return i(l,u,d);case"<=":return o(l,u,d);default:throw new TypeError(`Invalid operator: ${c}`)}},zo}var Ro,Jd;function cv(){if(Jd)return Ro;Jd=1;const e=it(),t=jn(),{safeRe:n,t:s}=rr();return Ro=(o,a)=>{if(o instanceof e)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;a=a||{};let l=null;if(!a.rtl)l=o.match(a.includePrerelease?n[s.COERCEFULL]:n[s.COERCE]);else{const h=a.includePrerelease?n[s.COERCERTLFULL]:n[s.COERCERTL];let y;for(;(y=h.exec(o))&&(!l||l.index+l[0].length!==o.length);)(!l||y.index+y[0].length!==l.index+l[0].length)&&(l=y),h.lastIndex=y.index+y[1].length+y[2].length;h.lastIndex=-1}if(l===null)return null;const c=l[2],u=l[3]||"0",d=l[4]||"0",f=a.includePrerelease&&l[5]?`-${l[5]}`:"",m=a.includePrerelease&&l[6]?`+${l[6]}`:"";return t(`${c}.${u}.${d}${f}${m}`,a)},Ro}var Lo,Xd;function dv(){if(Xd)return Lo;Xd=1;const e=jn(),t=sr(),n=it(),s=(l,c,u)=>{if(!t.RELEASE_TYPES.includes(c))return null;const d=i(l,u);return d&&o(d,c)},i=(l,c)=>{const u=l instanceof n?l.version:l;return e(u,c)},o=(l,c)=>{if(a(c))return l.version;switch(l.prerelease=[],c){case"major":l.minor=0,l.patch=0;break;case"minor":l.patch=0;break}return l.format()},a=l=>l.startsWith("pre");return Lo=s,Lo}var Oo,eu;function uv(){if(eu)return Oo;eu=1;class e{constructor(){this.max=1e3,this.map=new Map}get(n){const s=this.map.get(n);if(s!==void 0)return this.map.delete(n),this.map.set(n,s),s}delete(n){return this.map.delete(n)}set(n,s){if(!this.delete(n)&&s!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(n,s)}return this}}return Oo=e,Oo}var Do,tu;function Nt(){if(tu)return Do;tu=1;const e=/\s+/g;class t{constructor(A,L){if(L=i(L),A instanceof t)return A.loose===!!L.loose&&A.includePrerelease===!!L.includePrerelease?A:new t(A.raw,L);if(A instanceof o)return this.raw=A.value,this.set=[[A]],this.formatted=void 0,this;if(this.options=L,this.loose=!!L.loose,this.includePrerelease=!!L.includePrerelease,this.raw=A.trim().replace(e," "),this.set=this.raw.split("||").map(S=>this.parseRange(S.trim())).filter(S=>S.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const S=this.set[0];if(this.set=this.set.filter(R=>!g(R[0])),this.set.length===0)this.set=[S];else if(this.set.length>1){for(const R of this.set)if(R.length===1&&v(R[0])){this.set=[R];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let A=0;A<this.set.length;A++){A>0&&(this.formatted+="||");const L=this.set[A];for(let S=0;S<L.length;S++)S>0&&(this.formatted+=" "),this.formatted+=L[S].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(A){A=A.replace(x,"");const S=((this.options.includePrerelease&&y)|(this.options.loose&&p))+":"+A,R=s.get(S);if(R)return R;const D=this.options.loose,P=D?c[d.HYPHENRANGELOOSE]:c[d.HYPHENRANGE];A=A.replace(P,F(this.options.includePrerelease)),a("hyphen replace",A),A=A.replace(c[d.COMPARATORTRIM],f),a("comparator trim",A),A=A.replace(c[d.TILDETRIM],m),a("tilde trim",A),A=A.replace(c[d.CARETTRIM],h),a("caret trim",A);let Y=A.split(" ").map(ae=>E(ae,this.options)).join(" ").split(/\s+/).map(ae=>k(ae,this.options));D&&(Y=Y.filter(ae=>(a("loose invalid filter",ae,this.options),!!ae.match(c[d.COMPARATORLOOSE])))),a("range list",Y);const H=new Map,ee=Y.map(ae=>new o(ae,this.options));for(const ae of ee){if(g(ae))return[ae];H.set(ae.value,ae)}H.size>1&&H.has("")&&H.delete("");const le=[...H.values()];return s.set(S,le),le}intersects(A,L){if(!(A instanceof t))throw new TypeError("a Range is required");return this.set.some(S=>w(S,L)&&A.set.some(R=>w(R,L)&&S.every(D=>R.every(P=>D.intersects(P,L)))))}test(A){if(!A)return!1;if(typeof A=="string")try{A=new l(A,this.options)}catch{return!1}for(let L=0;L<this.set.length;L++)if(Z(this.set[L],A,this.options))return!0;return!1}}Do=t;const n=uv(),s=new n,i=Jl(),o=zi(),a=_i(),l=it(),{safeRe:c,src:u,t:d,comparatorTrimReplace:f,tildeTrimReplace:m,caretTrimReplace:h}=rr(),{FLAG_INCLUDE_PRERELEASE:y,FLAG_LOOSE:p}=sr(),x=new RegExp(u[d.BUILD],"g"),g=M=>M.value==="<0.0.0-0",v=M=>M.value==="",w=(M,A)=>{let L=!0;const S=M.slice();let R=S.pop();for(;L&&S.length;)L=S.every(D=>R.intersects(D,A)),R=S.pop();return L},E=(M,A)=>(M=M.replace(c[d.BUILD],""),a("comp",M,A),M=$(M,A),a("caret",M),M=I(M,A),a("tildes",M),M=B(M,A),a("xrange",M),M=U(M,A),a("stars",M),M),N=M=>!M||M.toLowerCase()==="x"||M==="*",j=(M,A,L)=>N(M)&&!N(A)||N(A)&&L&&!N(L),I=(M,A)=>M.trim().split(/\s+/).map(L=>z(L,A)).join(" "),z=(M,A)=>{const L=A.loose?c[d.TILDELOOSE]:c[d.TILDE];return M.replace(L,(S,R,D,P,Y)=>{a("tilde",M,S,R,D,P,Y);let H;return N(R)?H="":N(D)?H=`>=${R}.0.0 <${+R+1}.0.0-0`:N(P)?H=`>=${R}.${D}.0 <${R}.${+D+1}.0-0`:Y?(a("replaceTilde pr",Y),H=`>=${R}.${D}.${P}-${Y} <${R}.${+D+1}.0-0`):H=`>=${R}.${D}.${P} <${R}.${+D+1}.0-0`,a("tilde return",H),H})},$=(M,A)=>M.trim().split(/\s+/).map(L=>V(L,A)).join(" "),V=(M,A)=>{a("caret",M,A);const L=A.loose?c[d.CARETLOOSE]:c[d.CARET],S=A.includePrerelease?"-0":"";return M.replace(L,(R,D,P,Y,H)=>{a("caret",M,R,D,P,Y,H);let ee;return N(D)?ee="":N(P)?ee=`>=${D}.0.0${S} <${+D+1}.0.0-0`:N(Y)?D==="0"?ee=`>=${D}.${P}.0${S} <${D}.${+P+1}.0-0`:ee=`>=${D}.${P}.0${S} <${+D+1}.0.0-0`:H?(a("replaceCaret pr",H),D==="0"?P==="0"?ee=`>=${D}.${P}.${Y}-${H} <${D}.${P}.${+Y+1}-0`:ee=`>=${D}.${P}.${Y}-${H} <${D}.${+P+1}.0-0`:ee=`>=${D}.${P}.${Y}-${H} <${+D+1}.0.0-0`):(a("no pr"),D==="0"?P==="0"?ee=`>=${D}.${P}.${Y} <${D}.${P}.${+Y+1}-0`:ee=`>=${D}.${P}.${Y} <${D}.${+P+1}.0-0`:ee=`>=${D}.${P}.${Y} <${+D+1}.0.0-0`),a("caret return",ee),ee})},B=(M,A)=>(a("replaceXRanges",M,A),M.split(/\s+/).map(L=>_(L,A)).join(" ")),_=(M,A)=>{M=M.trim();const L=A.loose?c[d.XRANGELOOSE]:c[d.XRANGE];return M.replace(L,(S,R,D,P,Y,H)=>{if(a("xRange",M,S,R,D,P,Y,H),j(D,P,Y))return M;const ee=N(D),le=ee||N(P),ae=le||N(Y),fe=ae;return R==="="&&fe&&(R=""),H=A.includePrerelease?"-0":"",ee?R===">"||R==="<"?S="<0.0.0-0":S="*":R&&fe?(le&&(P=0),Y=0,R===">"?(R=">=",le?(D=+D+1,P=0,Y=0):(P=+P+1,Y=0)):R==="<="&&(R="<",le?D=+D+1:P=+P+1),R==="<"&&(H="-0"),S=`${R+D}.${P}.${Y}${H}`):le?S=`>=${D}.0.0${H} <${+D+1}.0.0-0`:ae&&(S=`>=${D}.${P}.0${H} <${D}.${+P+1}.0-0`),a("xRange return",S),S})},U=(M,A)=>(a("replaceStars",M,A),M.trim().replace(c[d.STAR],"")),k=(M,A)=>(a("replaceGTE0",M,A),M.trim().replace(c[A.includePrerelease?d.GTE0PRE:d.GTE0],"")),F=M=>(A,L,S,R,D,P,Y,H,ee,le,ae,fe)=>(N(S)?L="":N(R)?L=`>=${S}.0.0${M?"-0":""}`:N(D)?L=`>=${S}.${R}.0${M?"-0":""}`:P?L=`>=${L}`:L=`>=${L}${M?"-0":""}`,N(ee)?H="":N(le)?H=`<${+ee+1}.0.0-0`:N(ae)?H=`<${ee}.${+le+1}.0-0`:fe?H=`<=${ee}.${le}.${ae}-${fe}`:M?H=`<${ee}.${le}.${+ae+1}-0`:H=`<=${H}`,`${L} ${H}`.trim()),Z=(M,A,L)=>{for(let S=0;S<M.length;S++)if(!M[S].test(A))return!1;if(A.prerelease.length&&!L.includePrerelease){for(let S=0;S<M.length;S++)if(a(M[S].semver),M[S].semver!==o.ANY&&M[S].semver.prerelease.length>0){const R=M[S].semver;if(R.major===A.major&&R.minor===A.minor&&R.patch===A.patch)return!0}return!1}return!0};return Do}var $o,nu;function zi(){if(nu)return $o;nu=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(d,f){if(f=n(f),d instanceof t){if(d.loose===!!f.loose)return d;d=d.value}d=d.trim().split(/\s+/).join(" "),a("comparator",d,f),this.options=f,this.loose=!!f.loose,this.parse(d),this.semver===e?this.value="":this.value=this.operator+this.semver.version,a("comp",this)}parse(d){const f=this.options.loose?s[i.COMPARATORLOOSE]:s[i.COMPARATOR],m=d.match(f);if(!m)throw new TypeError(`Invalid comparator: ${d}`);this.operator=m[1]!==void 0?m[1]:"",this.operator==="="&&(this.operator=""),m[2]?this.semver=new l(m[2],this.options.loose):this.semver=e}toString(){return this.value}test(d){if(a("Comparator.test",d,this.options.loose),this.semver===e||d===e)return!0;if(typeof d=="string")try{d=new l(d,this.options)}catch{return!1}return o(d,this.operator,this.semver,this.options)}intersects(d,f){if(!(d instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(d.value,f).test(this.value):d.operator===""?d.value===""?!0:new c(this.value,f).test(d.semver):(f=n(f),f.includePrerelease&&(this.value==="<0.0.0-0"||d.value==="<0.0.0-0")||!f.includePrerelease&&(this.value.startsWith("<0.0.0")||d.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&d.operator.startsWith(">")||this.operator.startsWith("<")&&d.operator.startsWith("<")||this.semver.version===d.semver.version&&this.operator.includes("=")&&d.operator.includes("=")||o(this.semver,"<",d.semver,f)&&this.operator.startsWith(">")&&d.operator.startsWith("<")||o(this.semver,">",d.semver,f)&&this.operator.startsWith("<")&&d.operator.startsWith(">")))}}$o=t;const n=Jl(),{safeRe:s,t:i}=rr(),o=Bf(),a=_i(),l=it(),c=Nt();return $o}var Mo,su;function Ri(){if(su)return Mo;su=1;const e=Nt();return Mo=(n,s,i)=>{try{s=new e(s,i)}catch{return!1}return s.test(n)},Mo}var Fo,ru;function hv(){if(ru)return Fo;ru=1;const e=Nt();return Fo=(n,s)=>new e(n,s).set.map(i=>i.map(o=>o.value).join(" ").trim().split(" ")),Fo}var Bo,iu;function fv(){if(iu)return Bo;iu=1;const e=it(),t=Nt();return Bo=(s,i,o)=>{let a=null,l=null,c=null;try{c=new t(i,o)}catch{return null}return s.forEach(u=>{c.test(u)&&(!a||l.compare(u)===-1)&&(a=u,l=new e(a,o))}),a},Bo}var Uo,ou;function mv(){if(ou)return Uo;ou=1;const e=it(),t=Nt();return Uo=(s,i,o)=>{let a=null,l=null,c=null;try{c=new t(i,o)}catch{return null}return s.forEach(u=>{c.test(u)&&(!a||l.compare(u)===1)&&(a=u,l=new e(a,o))}),a},Uo}var Vo,au;function pv(){if(au)return Vo;au=1;const e=it(),t=Nt(),n=Pi();return Vo=(i,o)=>{i=new t(i,o);let a=new e("0.0.0");if(i.test(a)||(a=new e("0.0.0-0"),i.test(a)))return a;a=null;for(let l=0;l<i.set.length;++l){const c=i.set[l];let u=null;c.forEach(d=>{const f=new e(d.semver.version);switch(d.operator){case">":f.prerelease.length===0?f.patch++:f.prerelease.push(0),f.raw=f.format();case"":case">=":(!u||n(f,u))&&(u=f);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${d.operator}`)}}),u&&(!a||n(a,u))&&(a=u)}return a&&i.test(a)?a:null},Vo}var Wo,lu;function gv(){if(lu)return Wo;lu=1;const e=Nt();return Wo=(n,s)=>{try{return new e(n,s).range||"*"}catch{return null}},Wo}var Ho,cu;function sc(){if(cu)return Ho;cu=1;const e=it(),t=zi(),{ANY:n}=t,s=Nt(),i=Ri(),o=Pi(),a=ec(),l=nc(),c=tc();return Ho=(d,f,m,h)=>{d=new e(d,h),f=new s(f,h);let y,p,x,g,v;switch(m){case">":y=o,p=l,x=a,g=">",v=">=";break;case"<":y=a,p=c,x=o,g="<",v="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(d,f,h))return!1;for(let w=0;w<f.set.length;++w){const E=f.set[w];let N=null,j=null;if(E.forEach(I=>{I.semver===n&&(I=new t(">=0.0.0")),N=N||I,j=j||I,y(I.semver,N.semver,h)?N=I:x(I.semver,j.semver,h)&&(j=I)}),N.operator===g||N.operator===v||(!j.operator||j.operator===g)&&p(d,j.semver))return!1;if(j.operator===v&&x(d,j.semver))return!1}return!0},Ho}var qo,du;function xv(){if(du)return qo;du=1;const e=sc();return qo=(n,s,i)=>e(n,s,">",i),qo}var Go,uu;function bv(){if(uu)return Go;uu=1;const e=sc();return Go=(n,s,i)=>e(n,s,"<",i),Go}var Zo,hu;function yv(){if(hu)return Zo;hu=1;const e=Nt();return Zo=(n,s,i)=>(n=new e(n,i),s=new e(s,i),n.intersects(s,i)),Zo}var Ko,fu;function wv(){if(fu)return Ko;fu=1;const e=Ri(),t=jt();return Ko=(n,s,i)=>{const o=[];let a=null,l=null;const c=n.sort((m,h)=>t(m,h,i));for(const m of c)e(m,s,i)?(l=m,a||(a=m)):(l&&o.push([a,l]),l=null,a=null);a&&o.push([a,null]);const u=[];for(const[m,h]of o)m===h?u.push(m):!h&&m===c[0]?u.push("*"):h?m===c[0]?u.push(`<=${h}`):u.push(`${m} - ${h}`):u.push(`>=${m}`);const d=u.join(" || "),f=typeof s.raw=="string"?s.raw:String(s);return d.length<f.length?d:s},Ko}var Yo,mu;function vv(){if(mu)return Yo;mu=1;const e=Nt(),t=zi(),{ANY:n}=t,s=Ri(),i=jt(),o=(f,m,h={})=>{if(f===m)return!0;f=new e(f,h),m=new e(m,h);let y=!1;e:for(const p of f.set){for(const x of m.set){const g=c(p,x,h);if(y=y||g!==null,g)continue e}if(y)return!1}return!0},a=[new t(">=0.0.0-0")],l=[new t(">=0.0.0")],c=(f,m,h)=>{if(f===m)return!0;if(f.length===1&&f[0].semver===n){if(m.length===1&&m[0].semver===n)return!0;h.includePrerelease?f=a:f=l}if(m.length===1&&m[0].semver===n){if(h.includePrerelease)return!0;m=l}const y=new Set;let p,x;for(const z of f)z.operator===">"||z.operator===">="?p=u(p,z,h):z.operator==="<"||z.operator==="<="?x=d(x,z,h):y.add(z.semver);if(y.size>1)return null;let g;if(p&&x){if(g=i(p.semver,x.semver,h),g>0)return null;if(g===0&&(p.operator!==">="||x.operator!=="<="))return null}for(const z of y){if(p&&!s(z,String(p),h)||x&&!s(z,String(x),h))return null;for(const $ of m)if(!s(z,String($),h))return!1;return!0}let v,w,E,N,j=x&&!h.includePrerelease&&x.semver.prerelease.length?x.semver:!1,I=p&&!h.includePrerelease&&p.semver.prerelease.length?p.semver:!1;j&&j.prerelease.length===1&&x.operator==="<"&&j.prerelease[0]===0&&(j=!1);for(const z of m){if(N=N||z.operator===">"||z.operator===">=",E=E||z.operator==="<"||z.operator==="<=",p){if(I&&z.semver.prerelease&&z.semver.prerelease.length&&z.semver.major===I.major&&z.semver.minor===I.minor&&z.semver.patch===I.patch&&(I=!1),z.operator===">"||z.operator===">="){if(v=u(p,z,h),v===z&&v!==p)return!1}else if(p.operator===">="&&!z.test(p.semver))return!1}if(x){if(j&&z.semver.prerelease&&z.semver.prerelease.length&&z.semver.major===j.major&&z.semver.minor===j.minor&&z.semver.patch===j.patch&&(j=!1),z.operator==="<"||z.operator==="<="){if(w=d(x,z,h),w===z&&w!==x)return!1}else if(x.operator==="<="&&!z.test(x.semver))return!1}if(!z.operator&&(x||p)&&g!==0)return!1}return!(p&&E&&!x&&g!==0||x&&N&&!p&&g!==0||I||j)},u=(f,m,h)=>{if(!f)return m;const y=i(f.semver,m.semver,h);return y>0?f:y<0||m.operator===">"&&f.operator===">="?m:f},d=(f,m,h)=>{if(!f)return m;const y=i(f.semver,m.semver,h);return y<0?f:y>0||m.operator==="<"&&f.operator==="<="?m:f};return Yo=o,Yo}var Qo,pu;function Sv(){if(pu)return Qo;pu=1;const e=rr(),t=sr(),n=it(),s=$f(),i=jn(),o=Qw(),a=Jw(),l=Xw(),c=ev(),u=tv(),d=nv(),f=sv(),m=rv(),h=jt(),y=iv(),p=ov(),x=Xl(),g=av(),v=lv(),w=Pi(),E=ec(),N=Mf(),j=Ff(),I=tc(),z=nc(),$=Bf(),V=cv(),B=dv(),_=zi(),U=Nt(),k=Ri(),F=hv(),Z=fv(),M=mv(),A=pv(),L=gv(),S=sc(),R=xv(),D=bv(),P=yv(),Y=wv(),H=vv();return Qo={parse:i,valid:o,clean:a,inc:l,diff:c,major:u,minor:d,patch:f,prerelease:m,compare:h,rcompare:y,compareLoose:p,compareBuild:x,sort:g,rsort:v,gt:w,lt:E,eq:N,neq:j,gte:I,lte:z,cmp:$,coerce:V,truncate:B,Comparator:_,Range:U,satisfies:k,toComparators:F,maxSatisfying:Z,minSatisfying:M,minVersion:A,validRange:L,outside:S,gtr:R,ltr:D,intersects:P,simplifyRange:Y,subset:H,SemVer:n,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:s.compareIdentifiers,rcompareIdentifiers:s.rcompareIdentifiers},Qo}Sv();const kv=new Set(["fonts.googleapis.com","fonts.gstatic.com"]),Uf="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Segoe UI', system-ui, sans-serif",Jo=`<style data-openlearn-local-font-fallback="1">:where(html, body) { font-family: ${Uf}; }</style>`;function Kn(e){if(!e||typeof e!="string")return!1;const t=e.trim();if(!t)return!1;try{const n=t.startsWith("//")?`https:${t}`:t,s=new URL(n,"https://local.invalid");if(s.hostname==="local.invalid")return!1;const i=s.hostname.toLowerCase();for(const o of kv)if(i===o||i.endsWith(`.${o}`))return!0;return!1}catch{return!1}}function jv(e){if(!e||typeof e!="string")return{html:e||"",strippedCount:0};let t=0,n=e.replace(/<link\b[^>]*>/gi,s=>{const i=s.match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),o=i?i[1]??i[2]??i[3]??"":"";return Kn(o)?(t+=1,"<!-- Removed external font link (CSP/offline fallback active) -->"):s});return n=n.replace(/@import\s+(?:url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]+))\s*\)|(?:"([^"]*)"|'([^']*)'))[^;\n]*(?:;|$)/gi,(s,i,o,a,l,c)=>Kn(i??o??a??l??c??"")?(t+=1,"/* Removed external font import (CSP/offline fallback active) */"):s),t>0&&!n.includes("data-openlearn-local-font-fallback")&&(/<\/head>/i.test(n)?n=n.replace(/<\/head>/i,`${Jo}</head>`):/<head\b[^>]*>/i.test(n)?n=n.replace(/<head\b[^>]*>/i,s=>`${s}${Jo}`):n=`${Jo}${n}`),{html:n,strippedCount:t}}const Nv=["light","dark","eyecare","chalkboard"],Dt={login:{arrangement:"centered",order:["brand","auth-form","seed-hint"],cardPosition:"center"},teacher:{navPosition:"left",contentMaxWidth:"full"},student:{headerPosition:"top",order:["status-banner","main-content","quick-tools"],cardColumns:2},admin:{navStyle:"tabs",sectionOrder:["overview","users","site-settings","themes","diagnostics"]}},Cv=["brand","auth-form","seed-hint"],Ev=["status-banner","main-content","quick-tools"],Iv=["overview","users","site-settings","themes","diagnostics"],Av=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function qr(e){return Nv.includes(e)}function Xo(e,t){const n=new Set(t),s=[];if(Array.isArray(e))for(const i of e)n.has(i)&&!s.includes(i)&&s.push(i);for(const i of t)s.includes(i)||s.push(i);return s}function zs(e){if(!e||typeof e!="object")return{login:{...Dt.login,order:[...Dt.login.order]},teacher:{...Dt.teacher},student:{...Dt.student,order:[...Dt.student.order]},admin:{...Dt.admin,sectionOrder:[...Dt.admin.sectionOrder]}};const t=e.login?.arrangement&&["centered","split-left","split-right","top-banner"].includes(e.login.arrangement)?e.login.arrangement:"centered",n=e.login?.cardPosition&&["start","center","end"].includes(e.login.cardPosition)?e.login.cardPosition:"center",s=e.teacher?.navPosition&&["left","right","top"].includes(e.teacher.navPosition)?e.teacher.navPosition:"left",i=e.teacher?.contentMaxWidth&&["full","wide","focused"].includes(e.teacher.contentMaxWidth)?e.teacher.contentMaxWidth:"full",o=e.student?.headerPosition&&["top","bottom"].includes(e.student.headerPosition)?e.student.headerPosition:"top",a=e.student?.cardColumns===1||e.student?.cardColumns===2||e.student?.cardColumns===3?e.student.cardColumns:2,l=e.admin?.navStyle&&["tabs","sidebar-left","sidebar-right"].includes(e.admin.navStyle)?e.admin.navStyle:"tabs";return{login:{arrangement:t,order:Xo(e.login?.order,Cv),cardPosition:n},teacher:{navPosition:s,contentMaxWidth:i},student:{headerPosition:o,order:Xo(e.student?.order,Ev),cardColumns:a},admin:{navStyle:l,sectionOrder:Xo(e.admin?.sectionOrder,Iv)}}}function Tv(e){if(typeof e!="string")return null;const t=e.trim().replace(/^\.\//,"");if(!t||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||/^(?:https?|ftp|javascript|data|vbscript|blob):/i.test(t))return null;const n=t.split("/");return n.some(s=>!s||s==="."||s===".."||s.startsWith("."))?null:n.join("/")}function _v(e){if(!e||typeof e!="string")return null;const t=e.trim();return Av.test(t)?t:null}function Pv(e,t,n={},s){const i=t==="dark"?{...e.modes.light,...e.modes.dark}:{...e.modes.dark,...e.modes.light},o=_v(n.primaryColor),a=n.borderRadius||e.appearance.borderRadius||"rounded",l=n.density||e.appearance.density||"comfortable",c=typeof n.fontScale=="number"&&n.fontScale>=.85&&n.fontScale<=1.25?n.fontScale:e.typography.baseScale||1,u={sharp:"0.25rem",rounded:"0.875rem",pill:"1.5rem"},d={sharp:"0.2rem",rounded:"0.625rem",pill:"9999px"},f={compact:"0.75rem",comfortable:"1.25rem",spacious:"1.75rem"},m={flat:"none",bordered:"0 1px 2px 0 rgb(15 23 42 / 0.05)",elevated:"0 10px 28px -6px rgb(15 23 42 / 0.14)",glass:"0 8px 32px 0 rgb(15 23 42 / 0.12)"},h={...i,"--ol-radius-card":u[a],"--ol-radius-control":d[a],"--ol-density-gap":f[l],"--ol-shadow-card":m[e.appearance.cardStyle||"bordered"],"--ol-font-scale":String(c)};e.typography.fontSans&&(h["--ol-font-sans"]=e.typography.fontSans,h["--font-sans"]=e.typography.fontSans),e.typography.fontDisplay&&(h["--ol-font-display"]=e.typography.fontDisplay),e.typography.fontMono&&(h["--ol-font-mono"]=e.typography.fontMono),o&&(h["--color-primary"]=o,h["--primary-solid"]=o,h["--primary-ink"]=o);const y=[];for(const w of e.typography.fontFaces||[]){if(Kn(w.src))continue;const E=s?s(w.src):w.src;if(Kn(E))continue;const N=w.src.split(".").pop()?.toLowerCase(),j=N==="woff2"?"woff2":N==="woff"?"woff":N==="otf"?"opentype":"truetype";y.push(`@font-face {
|
|
11
|
+
font-family: "${w.family}";
|
|
12
|
+
src: url("${E}") format("${j}");
|
|
13
|
+
font-weight: ${w.weight||"100 900"};
|
|
14
|
+
font-style: ${w.style||"normal"};
|
|
15
|
+
font-display: swap;
|
|
16
|
+
}`)}const p=Object.entries(h).map(([w,E])=>` ${w}: ${E};`).join(`
|
|
17
|
+
`),x=`
|
|
18
|
+
[data-theme="${e.manifest.id}"] {
|
|
19
|
+
${p}
|
|
20
|
+
font-family: var(--ol-font-sans, var(--font-sans));
|
|
21
|
+
}
|
|
22
|
+
[data-theme="${e.manifest.id}"] [data-theme-surface="card"] {
|
|
23
|
+
border-radius: var(--ol-radius-card);
|
|
24
|
+
box-shadow: var(--ol-shadow-card);
|
|
25
|
+
}
|
|
26
|
+
[data-theme="${e.manifest.id}"] [data-theme-control] {
|
|
27
|
+
border-radius: var(--ol-radius-control);
|
|
28
|
+
}
|
|
29
|
+
`;let g=e.scopedCss||"";s&&g&&(g=g.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,(w,E,N)=>{if(N.startsWith("data:")||N.startsWith("#")||N.startsWith("/api/themes/"))return`url('${N}')`;const j=Tv(N);return j?`url('${s(j)}')`:`url('${N}')`}));const v=e.appearance.backgroundImage&&s?`
|
|
30
|
+
[data-theme="${e.manifest.id}"] [data-theme-bg-canvas] { background-image: url('${s(e.appearance.backgroundImage)}'); background-size: cover; background-position: center; }
|
|
31
|
+
`:"";return{cssText:[...y,x,v,g].filter(Boolean).join(`
|
|
32
|
+
`),effectiveTokens:h,effectiveMode:t}}async function zv(){try{const e=await fetch("/api/themes/public");return e.ok?await e.json():null}catch{return null}}async function gu(){try{const e=await fetch("/api/themes");if(!e.ok)return null;const t=await e.json();return Array.isArray(t?.themes)?t.themes:[]}catch{return null}}async function Rv(){try{const e=await fetch("/api/themes/me");return e.ok?await e.json():null}catch{return null}}async function ea(e){const t=await fetch("/api/themes/me",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok)throw new Error(n?.error||"保存主题偏好失败");return n}async function Lv(){try{const e=await fetch("/api/themes/me/reset",{method:"POST"});return e.ok?await e.json():null}catch{return null}}async function Ov(e){const t=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):e,n=await fetch("/api/themes/install",{method:"POST",headers:{"Content-Type":"application/zip"},body:t}),s=await n.json();if(!n.ok)throw new Error(s?.error||"主题包安装失败");return s}async function Dv(e){const t=await fetch(`/api/themes/${encodeURIComponent(e)}/disable`,{method:"POST"}),n=await t.json();if(!t.ok)throw new Error(n?.error||"停用主题失败");return n.theme}async function $v(e){const t=await fetch(`/api/themes/${encodeURIComponent(e)}/enable`,{method:"POST"}),n=await t.json();if(!t.ok)throw new Error(n?.error||"启用主题失败");return n.theme}async function Mv(e){const t=await fetch(`/api/themes/${encodeURIComponent(e)}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n?.error||"删除主题失败")}}function Fv(e,t){const n=`/api/themes/${encodeURIComponent(e)}/export`;return t?`${n}?version=${encodeURIComponent(t)}`:n}async function Bv(e,t){try{const n=t?`?version=${encodeURIComponent(t)}`:"",s=await fetch(`/api/themes/${encodeURIComponent(e)}/bundle${n}`);return s.ok?await s.json():null}catch{return null}}function Uv(e,t,n){const s=n.replace(/^\.?\//,"");return`/api/themes/${encodeURIComponent(e)}/assets/${encodeURIComponent(t)}/${s.split("/").map(encodeURIComponent).join("/")}`}const Vf=[{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"}],xn={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"}},Qa="openlearn_theme",Ns="openlearn_custom_themes",rc="openlearn_browser_appearance",Ja="openlearn-thirdparty-theme",Sn={},Xa={};function ir(e){return Xa[e]?Xa[e]:Sn[e]?Sn[e]:e in xn?xn[e]:xn.light}function xu(e){if(!e||!e.startsWith("#"))return!1;const t=e.trim().slice(1),n=t.length===3?t.split("").map(l=>l+l).join(""):t.slice(0,6);if(n.length!==6)return!1;const s=Number.parseInt(n,16);if(Number.isNaN(s))return!1;const[i,o,a]=[s>>16&255,s>>8&255,s&255].map(l=>{const c=l/255;return c<=.04045?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*i+.7152*o+.0722*a<.35}function Vv(){if(typeof window<"u"&&typeof window.matchMedia=="function")try{return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch{return"light"}return"light"}function Gt(e,t="auto",n){if(e==="dark"||e==="chalkboard")return"dark";if(e==="light"||e==="eyecare")return"light";if(n){const i=t==="auto"?Vv():t,o=Object.keys(n.modes.light||{}).length>0,a=Object.keys(n.modes.dark||{}).length>0;if(i==="dark"&&a)return"dark";if(i==="light"&&o)return"light";const l=n.modes[i]?.["--bg-app"]||n.modes.light?.["--bg-app"]||n.modes.dark?.["--bg-app"];return xu(l)?"dark":"light"}const s=ir(e);return xu(s["--bg-app"])?"dark":"light"}function bu(){if(typeof window>"u")return null;try{const e=localStorage.getItem(rc);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object"||typeof t.themeId!="string")return null;const n=t.mode==="light"||t.mode==="dark"||t.mode==="auto"?t.mode:"auto",s=t.appearanceOverrides&&typeof t.appearanceOverrides=="object"?t.appearanceOverrides:{};return{themeId:t.themeId,mode:n,appearanceOverrides:s}}catch{return null}}function Cs(e){if(!(typeof window>"u"))try{const t={themeId:String(e.themeId||"light"),mode:e.mode==="light"||e.mode==="dark"||e.mode==="auto"?e.mode:"auto",appearanceOverrides:{...e.appearanceOverrides?.primaryColor?{primaryColor:e.appearanceOverrides.primaryColor}:{},...e.appearanceOverrides?.borderRadius?{borderRadius:e.appearanceOverrides.borderRadius}:{},...e.appearanceOverrides?.density?{density:e.appearanceOverrides.density}:{},...e.appearanceOverrides?.fontScale!==void 0?{fontScale:e.appearanceOverrides.fontScale}:{}}};localStorage.setItem(rc,JSON.stringify(t)),localStorage.setItem(Qa,t.themeId)}catch{}}function el(){if(typeof document>"u")return;const e=document.getElementById(Ja);e&&e.parentNode&&e.parentNode.removeChild(e)}const Wv={sharp:"0.375rem",rounded:"1rem",pill:"1.5rem"},Hv={sharp:"0.25rem",rounded:"0.75rem",pill:"9999px"},qv={compact:"0.875rem",comfortable:"1.25rem",spacious:"1.75rem"};function tl(){if(typeof document>"u")return;const e=document.documentElement.style;for(const t of["--color-primary","--primary-solid","--primary-ink","--ol-radius-card","--ol-radius-control","--ol-density-gap","--ol-font-scale","--ol-font-sans","--ol-font-display","--ol-font-mono","--ol-shadow-card"])e.removeProperty(t)}function Ct(e,t,n,s){if(typeof document>"u")return{ok:!0,effectiveTokens:ir(e),resolvedLayouts:zs(n?n.layouts:null)};try{tl();let i={...xn[e]||Sn[e]||xn.light},o=zs(null);if(n){const a=Pv(n,t,s,c=>Uv(n.manifest.id,n.manifest.version,c));Xa[n.manifest.id]=a.effectiveTokens,i=a.effectiveTokens,o=n.layouts||zs(n.manifest.layouts);let l=document.getElementById(Ja);l||(l=document.createElement("style"),l.id=Ja,document.head.appendChild(l)),l.textContent=a.cssText}else el(),s.primaryColor&&(document.documentElement.style.setProperty("--color-primary",s.primaryColor),document.documentElement.style.setProperty("--primary-solid",s.primaryColor),document.documentElement.style.setProperty("--primary-ink",s.primaryColor),i["--color-primary"]=s.primaryColor,i["--primary-solid"]=s.primaryColor,i["--primary-ink"]=s.primaryColor),s.borderRadius&&(document.documentElement.style.setProperty("--ol-radius-card",Wv[s.borderRadius]),document.documentElement.style.setProperty("--ol-radius-control",Hv[s.borderRadius])),s.density&&document.documentElement.style.setProperty("--ol-density-gap",qv[s.density]),s.fontScale&&document.documentElement.style.setProperty("--ol-font-scale",String(s.fontScale));return document.documentElement.setAttribute("data-theme",e),document.documentElement.setAttribute("data-color-scheme",t),document.documentElement.style.colorScheme=t,{ok:!0,effectiveTokens:i,resolvedLayouts:o}}catch(i){return el(),tl(),document.documentElement.setAttribute("data-theme","light"),document.documentElement.setAttribute("data-color-scheme","light"),document.documentElement.style.colorScheme="light",{ok:!1,effectiveTokens:xn.light,resolvedLayouts:Dt,errorReason:i instanceof Error?i.message:"主题应用异常,已自动恢复安全默认主题"}}}function Wf(e,t,n,s,i){return{theme:e,colorScheme:t,tokens:n,appearance:{borderRadius:i.borderRadius||s?.appearance.borderRadius||"rounded",cardStyle:s?.appearance.cardStyle||"bordered",density:i.density||s?.appearance.density||"comfortable",fontScale:i.fontScale||s?.typography.baseScale||1},fonts:{sans:s?.typography.fontSans||"system-ui, sans-serif",display:s?.typography.fontDisplay||s?.typography.fontSans||"system-ui, sans-serif",mono:s?.typography.fontMono||"ui-monospace, monospace"}}}function Et(e,t,n,s,i){if(typeof window>"u")return;const o=Wf(e,t,n,s,i);try{vn.publish({id:Ti(),type:"theme.changed",source:"theme-store",payload:{theme:e,tokens:n,colorScheme:o.colorScheme,appearance:o.appearance,fonts:o.fonts},timestamp:Date.now()})}catch{}Ql(e,n,{colorScheme:o.colorScheme,appearance:o.appearance,fonts:o.fonts})}function Gv(e,t){if(typeof document>"u")return;Sn[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(`
|
|
33
|
+
`);s.textContent=`[data-theme="${e}"] {
|
|
34
|
+
${i}
|
|
35
|
+
}`}function Zv(e){if(typeof document>"u")return;delete Sn[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}const Ie=Ll((e,t)=>({theme:"light",availableThemes:[...Vf],catalog:[],activeBundle:null,installedVersion:null,latestVersion:null,upgradeAvailable:!1,upgradeChangelog:void 0,colorMode:"auto",resolvedColorScheme:"light",appearanceOverrides:{},resolvedLayouts:zs(null),defaultSiteThemeId:"light",fallbackNotice:null,principalKey:null,previewState:null,initTheme:()=>{if(typeof window>"u")return;try{const f=localStorage.getItem(Ns);if(f){const m=JSON.parse(f);Array.isArray(m)&&m.forEach(h=>{h&&h.spec&&h.spec.id&&t().registerTheme(h.spec,h.cssVariables)})}}catch{}const n=bu(),s=localStorage.getItem(Qa),i=n?.themeId||s||"light",o=n?.mode||"auto",a=n?.appearanceOverrides||{},l=Gt(i,o,null),c=Ct(i,l,null,a),u=c.ok?i:"light",d=c.ok?l:"light";e({theme:u,colorMode:o,resolvedColorScheme:d,appearanceOverrides:a,resolvedLayouts:c.resolvedLayouts,fallbackNotice:c.ok?null:c.errorReason||null}),Et(u,d,c.effectiveTokens,null,a)},setTheme:n=>{const{colorMode:s,appearanceOverrides:i}=t(),o=qr(n)||n in Sn?null:t().activeBundle?.manifest.id===n?t().activeBundle:null,a=Gt(n,s,o),l=Ct(n,a,o,i),c=l.ok?n:"light",u=l.ok?a:"light";Cs({themeId:c,mode:s,appearanceOverrides:i}),e({theme:c,activeBundle:l.ok?o:null,resolvedColorScheme:u,resolvedLayouts:l.resolvedLayouts,previewState:null,fallbackNotice:l.ok?t().fallbackNotice:l.errorReason||null}),Et(c,u,l.effectiveTokens,l.ok?o:null,i)},registerTheme:(n,s)=>{s&&Gv(n.id,s),e(i=>({availableThemes:[...i.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{Zv(n),e(s=>{const i=s.availableThemes.filter(a=>a.id!==n),o=s.theme===n?"light":s.theme;if(s.theme===n){const a=Ct("light","light",null,s.appearanceOverrides);Cs({themeId:"light",mode:s.colorMode,appearanceOverrides:s.appearanceOverrides}),Et("light","light",a.effectiveTokens,null,s.appearanceOverrides)}return{availableThemes:i,theme:o,activeBundle:s.theme===n?null:s.activeBundle}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const i=localStorage.getItem(Ns);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(Ns,JSON.stringify(o))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(Ns);if(s){let i=JSON.parse(s);Array.isArray(i)&&(i=i.filter(o=>o.spec.id!==n),localStorage.setItem(Ns,JSON.stringify(i)))}}catch{}t().unregisterTheme(n)},applyServerUserState:n=>{const s=Gt(n.themeId,n.mode,n.activeBundle),i=Ct(n.themeId,s,n.activeBundle,n.appearanceOverrides),o=i.ok?n.themeId:"light",a=i.ok?s:"light",l=i.ok?n.activeBundle:null;Cs({themeId:o,mode:n.mode,appearanceOverrides:n.appearanceOverrides}),e({principalKey:n.principalKey,theme:o,activeBundle:l,installedVersion:i.ok?n.installedVersion:null,latestVersion:i.ok?n.latestVersion:null,upgradeAvailable:i.ok?n.upgradeAvailable:!1,upgradeChangelog:i.ok?n.upgradeChangelog:void 0,colorMode:n.mode,resolvedColorScheme:a,appearanceOverrides:n.appearanceOverrides,resolvedLayouts:i.resolvedLayouts,defaultSiteThemeId:n.defaultSiteThemeId,previewState:null,fallbackNotice:i.ok?n.fallbackApplied?n.fallbackReason||"已自动回退到安全默认主题":null:i.errorReason||"主题资源异常,已自动回退至安全默认主题"}),Et(o,a,i.effectiveTokens,l,n.appearanceOverrides)},syncWithSession:async n=>{if(!n){e({principalKey:null,upgradeAvailable:!1,upgradeChangelog:void 0,installedVersion:null,latestVersion:null,previewState:null});const o=await zv(),a=bu();let l=a?.themeId||o?.defaultThemeId||"light",c=null;!qr(l)&&!(l in Sn)&&(o?.defaultThemeBundle&&o.defaultThemeBundle.manifest.id===l?c=o.defaultThemeBundle:(l=o?.defaultThemeId&&qr(o.defaultThemeId)?o.defaultThemeId:"light",o?.defaultThemeBundle&&l===o.defaultThemeBundle.manifest.id&&(c=o.defaultThemeBundle)));const u=a?.mode||"auto",d=a?.appearanceOverrides||{},f=Gt(l,u,c),m=Ct(l,f,c,d),h=m.ok?l:"light",y=m.ok?f:"light";e({theme:h,activeBundle:m.ok?c:null,colorMode:u,resolvedColorScheme:y,appearanceOverrides:d,resolvedLayouts:m.resolvedLayouts,defaultSiteThemeId:o?.defaultThemeId||"light",catalog:[],fallbackNotice:m.ok?null:m.errorReason||null}),Et(h,y,m.effectiveTokens,m.ok?c:null,d);return}const[s,i]=await Promise.all([Rv(),gu()]);i&&e({catalog:i}),s&&t().applyServerUserState(s)},refreshCatalog:async()=>{const n=await gu();n&&e({catalog:n})},installThemeZip:async n=>{const s=await Ov(n);return await t().refreshCatalog(),s.item},selectTheme:async(n,s)=>{const i=t();if(i.principalKey){const o=await ea({themeId:n,installedVersion:s?.version??null,mode:s?.mode??i.colorMode,appearanceOverrides:i.appearanceOverrides});t().applyServerUserState(o);return}s?.mode&&e({colorMode:s.mode}),t().setTheme(n)},setColorMode:async n=>{const s=t();if(s.principalKey){const a=await ea({mode:n});t().applyServerUserState(a);return}const i=Gt(s.theme,n,s.activeBundle),o=Ct(s.theme,i,s.activeBundle,s.appearanceOverrides);Cs({themeId:s.theme,mode:n,appearanceOverrides:s.appearanceOverrides}),e({colorMode:n,resolvedColorScheme:i,resolvedLayouts:o.resolvedLayouts}),Et(s.theme,i,o.effectiveTokens,s.activeBundle,s.appearanceOverrides)},setAppearanceOverrides:async n=>{const s=t();if(s.principalKey){const a=await ea({appearanceOverrides:n});t().applyServerUserState(a);return}const i=Gt(s.theme,s.colorMode,s.activeBundle),o=Ct(s.theme,i,s.activeBundle,n);Cs({themeId:s.theme,mode:s.colorMode,appearanceOverrides:n}),e({appearanceOverrides:n,resolvedLayouts:o.resolvedLayouts}),Et(s.theme,i,o.effectiveTokens,s.activeBundle,n)},upgradeCurrentTheme:async()=>{const n=t();!n.latestVersion||!n.theme||await t().selectTheme(n.theme,{version:n.latestVersion})},startPreview:n=>{const s=Gt(n.themeId,n.mode,n.bundle),i=Ct(n.themeId,s,n.bundle,n.appearanceOverrides);if(!i.ok){e({previewState:null,fallbackNotice:i.errorReason||"预览失败,已保留当前安全主题"});return}e({previewState:n,resolvedColorScheme:s,resolvedLayouts:i.resolvedLayouts}),Et(n.themeId,s,i.effectiveTokens,n.bundle,n.appearanceOverrides)},cancelPreview:()=>{const n=t();if(!n.previewState)return;const s=Gt(n.theme,n.colorMode,n.activeBundle),i=Ct(n.theme,s,n.activeBundle,n.appearanceOverrides);e({previewState:null,resolvedColorScheme:s,resolvedLayouts:i.resolvedLayouts}),Et(n.theme,s,i.effectiveTokens,n.activeBundle,n.appearanceOverrides)},resetToSafeDefault:async()=>{if(el(),tl(),typeof window<"u")try{localStorage.removeItem(rc),localStorage.setItem(Qa,"light")}catch{}const n=Ct("light","light",null,{});if(e({theme:"light",activeBundle:null,installedVersion:null,latestVersion:null,upgradeAvailable:!1,upgradeChangelog:void 0,colorMode:"light",resolvedColorScheme:"light",appearanceOverrides:{},resolvedLayouts:Dt,previewState:null,fallbackNotice:"已一键恢复至安全默认主题(浅色日间)"}),Et("light","light",n.effectiveTokens,null,{}),t().principalKey){const s=await Lv();s&&e({defaultSiteThemeId:s.defaultSiteThemeId})}},clearFallbackNotice:()=>e({fallbackNotice:null}),getUnifiedPluginThemePayload:()=>{const n=t(),s=n.previewState?.themeId||n.theme,i=n.previewState?n.previewState.bundle:n.activeBundle,o=n.previewState?.appearanceOverrides||n.appearanceOverrides,a=n.resolvedColorScheme,l=ir(s);return Wf(s,a,l,i,o)}})),Kv=/\p{Script=Han}/u;function Yv(e){const t=e.trim();return!t||t.length>64?!1:Kv.test(t)||t.replace(/\s+/g,"").length>=2}function Qv(){return"0.7.16".trim()}function Jv(e){const t=e.trim().replace(/^v/i,"");return t?`v${t}`:""}const Xv=Ue.memo(function({onLoginSuccess:t,lang:n}){const[s,i]=b.useState("teacher"),[o,a]=b.useState(null),[l,c]=b.useState(Qv),[u,d]=b.useState([]),f=Ie(oe=>oe.resolvedLayouts.login),[m,h]=b.useState(""),[y,p]=b.useState(""),[x,g]=b.useState(""),[v,w]=b.useState(!1),[E,N]=b.useState(""),[j,I]=b.useState(""),[z,$]=b.useState(""),[V,B]=b.useState(!1),[_,U]=b.useState(!0),[k,F]=b.useState(!1),[Z,M]=b.useState([]),[A,L]=b.useState(!1),[S,R]=b.useState(""),[D,P]=b.useState(""),[Y,H]=b.useState([]),[ee,le]=b.useState(!1),[ae,fe]=b.useState(!1),[be,ye]=b.useState(!1),[Se,me]=b.useState(""),C=b.useRef(null),J=b.useRef(null),se=b.useRef(null),W=b.useRef(!1);b.useEffect(()=>{(async()=>{try{const ce=await fetch("/api/site-settings");if(ce.ok){const pe=await ce.json();a(pe),U(pe?.allowPublicStudentLookup!==!1)}}catch(ce){console.warn("Failed to fetch site settings for login branding:",ce)}})()},[]),b.useEffect(()=>{(async()=>{try{const ce=await fetch("/api/auth/seed-status");if(ce.ok){const pe=await ce.json();Array.isArray(pe?.defaultAccounts)&&d(pe.defaultAccounts)}}catch{}})()},[]),b.useEffect(()=>{let oe=!1;return(async()=>{try{const pe=await fetch("/health");if(!pe.ok)return;const xe=await pe.json(),ve=typeof xe?.version=="string"?xe.version.trim():"";!oe&&ve&&c(ve)}catch{}})(),()=>{oe=!0}},[]);const T=async oe=>{oe.preventDefault(),g(""),w(!0);try{const ce=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:m.trim(),password:y})});if(ce.ok){const pe=await ce.json();t(pe.session)}else{const pe=await ce.json();g(pe.error||(n==="zh"?"用户名或密码错误":"Invalid credentials"))}}catch{g(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{w(!1)}},q=async()=>{L(!0);try{const oe=await fetch("/api/auth/public-classes");if(oe.ok){const ce=await oe.json();Array.isArray(ce?.items)&&M(ce.items)}}catch{}finally{L(!1)}},X=()=>{me(""),F(!0);const oe=C.current;oe&&(typeof oe.showModal=="function"?oe.open||oe.showModal():oe.setAttribute("open","")),typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>J.current?.focus()):J.current?.focus(),Z.length===0&&q()},ne=()=>{const oe=C.current;oe&&(typeof oe.close=="function"&&oe.open?oe.close():oe.removeAttribute("open")),F(!1)},Q=async oe=>{if(oe.preventDefault(),me(""),!Yv(S)){me(n==="zh"?"请输入至少 2 个字符(或至少 1 个汉字)进行查询":"Please enter at least 2 characters (or 1 Chinese character)"),J.current?.focus();return}ye(!0);try{const ce=new URLSearchParams({name:S.trim()});D&&ce.set("classId",D);const pe=await fetch(`/api/auth/student-lookup?${ce.toString()}`),xe=await pe.json().catch(()=>({}));if(!pe.ok){H([]),le(!1),fe(!1),me(xe?.error||(n==="zh"?"查询失败,请稍后重试":"Lookup failed. Please try again later."));return}H(Array.isArray(xe?.items)?xe.items:[]),le(!!xe?.truncated),fe(!0)}catch{me(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{ye(!1)}},re=oe=>{N(oe),$(""),ne(),se.current?.focus()},de=async oe=>{oe.preventDefault(),$("");const ce=E.trim();if(!ce){$(n==="zh"?"请输入学号":"Please enter Student ID");return}if(!j.trim()){$(n==="zh"?"请输入个人密码或班级临时密码":"Please enter your password or class passcode");return}B(!0);try{const pe=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:ce,password:j.trim()})});if(pe.ok){const xe=await pe.json();t(xe.session)}else{const xe=await pe.json();$(xe.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{$(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{B(!1)}},te=f.arrangement,O=te==="split-left"||te==="split-right",G=f.cardPosition==="start"?"items-start":f.cardPosition==="end"?"items-end":"items-center",ie=Jv(l),ue=r.jsxs("div",{"data-login-region":"brand",className:O?"text-left space-y-3":"text-center mb-6",children:[o?.logoUrl?r.jsx("img",{src:o.logoUrl,alt:o.siteName||"logo",width:64,height:64,fetchPriority:"high",decoding:"async",className:`${O?"":"inline-block"} h-16 w-16 object-contain mb-3 rounded-xl`}):r.jsx("div",{className:"inline-flex items-center justify-center p-3 bg-primary-theme rounded-2xl shadow-lg mb-3 text-white","data-theme-control":"badge",children:r.jsx(Oa,{size:32})}),r.jsxs("h1",{className:`text-2xl sm:text-3xl font-black text-main tracking-tight flex items-center ${O?"justify-start":"justify-center"} gap-2`,children:[o?.siteName||"OpenLearn Next"," ",ie&&r.jsx("span",{"data-testid":"login-version-badge",className:"text-primary-ink font-medium text-xs bg-primary-theme/15 px-2 py-0.5 rounded-full border border-primary-theme/30 theme-accent-badge",children:ie})]}),r.jsx("p",{className:"text-muted text-xs sm:text-sm mt-1",children:o?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]},"brand"),he=u.length>0?r.jsxs("div",{"data-login-region":"seed-hint",className:"mb-5 rounded-xl border border-amber-500/35 bg-amber-500/10 p-3 text-xs text-amber-800 dark:text-amber-200 flex items-start gap-2",id:"login_default_credential_hint",children:[r.jsx(Si,{size:14,className:"shrink-0 mt-0.5"}),r.jsxs("div",{className:"space-y-1 min-w-0",children:[r.jsx("p",{className:"font-bold",children:n==="zh"?"首次安装?可以直接用默认口令登录":"First run? Sign in with the default password"}),r.jsx("p",{className:"font-mono break-all",children:u.map(oe=>`${oe} / ${oe}`).join(" · ")}),r.jsx("p",{className:"opacity-85 leading-relaxed",children:n==="zh"?"口令与账号名相同。登录后会强制你改密,改完这条提示自动消失。":"Password equals the username. You will be required to change it right after signing in."})]})]},"seed-hint"):null,K=r.jsxs("div",{"data-login-region":"auth-form",children:[r.jsxs("div",{className:"flex bg-surface-secondary p-1 rounded-xl border border-theme gap-1 mb-6",children:[r.jsxs("button",{type:"button",onClick:()=>i("teacher"),"data-theme-control":"tab",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 focus-visible:ring-2 focus-visible:ring-indigo-400 cursor-pointer ${s==="teacher"?"bg-primary-theme text-white shadow-md":"text-muted hover:text-main hover:bg-surface/60"}`,children:[r.jsx(Zh,{size:14,"aria-hidden":"true"}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),r.jsxs("button",{type:"button",onClick:()=>i("student"),"data-theme-control":"tab",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 focus-visible:ring-2 focus-visible:ring-indigo-400 cursor-pointer ${s==="student"?"bg-primary-theme text-white shadow-md":"text-muted hover:text-main hover:bg-surface/60"}`,children:[r.jsx(Ol,{size:14,"aria-hidden":"true"}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?r.jsxs("form",{onSubmit:T,className:"space-y-4",children:[x&&r.jsxs("div",{className:"p-3 bg-rose-500/10 border border-rose-500/40 text-rose-700 dark:text-rose-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Pt,{size:15,className:"shrink-0"}),r.jsx("span",{children:x})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{htmlFor:"teacher-username",className:"text-xs font-medium text-muted flex items-center gap-1.5",children:[r.jsx(wn,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),r.jsx("input",{id:"teacher-username",name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,value:m,onChange:oe=>h(oe.target.value),placeholder:n==="zh"?"输入教工账户名":"Enter staff username","data-theme-control":"input",className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-3 text-main outline-none placeholder-muted transition-colors",required:!0})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{htmlFor:"teacher-password",className:"text-xs font-medium text-muted flex items-center gap-1.5",children:[r.jsx(Da,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),r.jsx("input",{id:"teacher-password",name:"password",type:"password",autoComplete:"current-password",value:y,onChange:oe=>p(oe.target.value),placeholder:n==="zh"?"输入登录密码":"Enter access password","data-theme-control":"input",className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-3 text-main outline-none placeholder-muted transition-colors",required:!0})]}),r.jsxs("button",{type:"submit",disabled:v,"data-theme-control":"submit",className:"w-full mt-6 bg-primary-theme hover:opacity-95 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 active:scale-[0.98]",children:[r.jsx("span",{children:v?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),r.jsx(li,{size:15})]})]}):r.jsxs("form",{onSubmit:de,className:"space-y-4",children:[z&&r.jsxs("div",{className:"p-3 bg-rose-500/10 border border-rose-500/40 text-rose-700 dark:text-rose-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Pt,{size:15,className:"shrink-0"}),r.jsx("span",{children:z})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("label",{htmlFor:"student-access-key",className:"text-xs font-medium text-muted flex items-center gap-1.5",children:[r.jsx(wn,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),_&&r.jsxs("button",{type:"button",onClick:X,className:"text-xs font-semibold text-primary-ink hover:text-primary-ink-hover inline-flex items-center gap-1 cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400 rounded px-1 py-0.5 transition-colors",children:[r.jsx(qi,{size:12,"aria-hidden":"true"}),r.jsx("span",{children:n==="zh"?"忘记学号?查询学号":"Forgot ID? Look up"})]})]}),r.jsx("input",{id:"student-access-key",name:"studentAccessKey",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,value:E,onChange:oe=>{N(oe.target.value)},placeholder:n==="zh"?"输入您的学号":"Enter your Student ID","data-theme-control":"input",className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-3 text-main outline-none placeholder-muted transition-colors"})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{htmlFor:"student-password",className:"text-xs font-medium text-muted flex items-center gap-1.5",children:[r.jsx(Da,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),r.jsx("input",{ref:se,id:"student-password",name:"studentPassword",type:"password",autoComplete:"current-password",required:!0,value:j,onChange:oe=>I(oe.target.value),placeholder:n==="zh"?"输入个人密码或临时班级密码":"Enter personal password or class passcode","data-theme-control":"input",className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-3 text-main outline-none placeholder-muted transition-colors"})]}),r.jsxs("button",{type:"submit",disabled:V,"data-theme-control":"submit",className:"w-full mt-6 bg-primary-theme hover:opacity-95 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 active:scale-[0.98]",children:[r.jsx("span",{children:V?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),r.jsx(li,{size:15})]})]})]},"auth-form"),we={brand:ue,"seed-hint":he,"auth-form":K};return r.jsxs("main",{id:"login_page_container","data-theme-bg-canvas":"login","data-login-arrangement":te,className:`min-h-screen bg-app text-main flex flex-col ${G} justify-center p-4 sm:p-8 relative overflow-hidden font-sans transition-colors duration-200`,children:[r.jsx("div",{className:"pointer-events-none absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-primary-theme/10 blur-3xl -z-10"}),r.jsx("div",{className:"pointer-events-none absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-primary-theme/10 blur-3xl -z-10"}),O?r.jsxs("div",{className:`w-full max-w-4xl flex flex-col ${te==="split-right"?"lg:flex-row-reverse":"lg:flex-row"} items-center gap-8 lg:gap-12`,children:[r.jsxs("div",{className:"flex-1 w-full max-w-md space-y-4",children:[ue,he]}),r.jsx("div",{id:"login_card","data-theme-surface":"card",className:"w-full max-w-md bg-surface/95 backdrop-blur-md rounded-2xl border border-theme shadow-2xl p-6 sm:p-8",children:K})]}):r.jsx("div",{id:"login_card","data-theme-surface":"card",className:`w-full ${te==="top-banner"?"max-w-lg":"max-w-md"} bg-surface/95 backdrop-blur-md rounded-2xl border border-theme shadow-2xl p-6 sm:p-8 flex flex-col`,children:f.order.map(oe=>we[oe])}),r.jsx("dialog",{ref:C,id:"student-lookup-dialog","aria-labelledby":"student-lookup-dialog-title",closedby:"any",onClose:()=>{C.current&&(C.current.returnValue=""),F(!1)},onPointerDown:oe=>{if(typeof HTMLDialogElement<"u"&&"closedBy"in HTMLDialogElement.prototype)return;const ce=oe.currentTarget.getBoundingClientRect();W.current=oe.clientX<ce.left||oe.clientX>ce.right||oe.clientY<ce.top||oe.clientY>ce.bottom},onPointerUp:oe=>{if(typeof HTMLDialogElement<"u"&&"closedBy"in HTMLDialogElement.prototype)return;const ce=oe.currentTarget.getBoundingClientRect(),pe=oe.clientX<ce.left||oe.clientX>ce.right||oe.clientY<ce.top||oe.clientY>ce.bottom;W.current&&pe&&ne(),W.current=!1},className:"m-auto w-[calc(100vw-2rem)] max-w-md rounded-2xl border border-theme bg-surface text-main shadow-2xl p-0 overflow-hidden",children:k&&r.jsxs("div",{className:"p-5 sm:p-6 space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary-theme/15 text-primary-ink",children:r.jsx(qi,{size:16,"aria-hidden":"true"})}),r.jsx("h2",{id:"student-lookup-dialog-title",className:"text-base font-bold text-main truncate",children:n==="zh"?"自助查询学号":"Student ID Lookup"})]}),r.jsx("button",{type:"button",onClick:ne,"aria-label":n==="zh"?"关闭学号查询弹窗":"Close student ID lookup dialog",className:"p-1.5 rounded-lg text-muted hover:text-main hover:bg-surface-secondary transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:r.jsx(De,{size:16,"aria-hidden":"true"})})]}),r.jsxs("form",{role:"search",onSubmit:Q,className:"space-y-3","aria-labelledby":"student-lookup-dialog-title",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{htmlFor:"student-lookup-class",className:"text-xs font-medium text-muted block",children:n==="zh"?"所在班级(可选,用于区分重名)":"Class (optional, narrows duplicate names)"}),r.jsxs("select",{id:"student-lookup-class",name:"classId",value:D,onChange:oe=>P(oe.target.value),disabled:A,className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-2.5 text-main outline-none transition-colors cursor-pointer",children:[r.jsx("option",{value:"",children:n==="zh"?"全部班级":"All classes"}),Z.map(oe=>r.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{htmlFor:"student-lookup-name",className:"text-xs font-medium text-muted block",children:[n==="zh"?"学生姓名":"Student Name"," ",r.jsx("span",{className:"text-rose-500","aria-hidden":"true",children:"*"})]}),r.jsx("input",{ref:J,id:"student-lookup-name",name:"studentName",type:"search",autoFocus:!0,autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,enterKeyHint:"search",maxLength:64,required:!0,"aria-describedby":"student-lookup-name-help","aria-invalid":Se?"true":void 0,value:S,onChange:oe=>{R(oe.target.value),Se&&me("")},placeholder:n==="zh"?"输入姓名或名字关键词(如:张伟)":"Enter student name or keyword",className:"w-full bg-surface-secondary border border-theme focus:border-primary-theme focus:ring-1 focus:ring-primary-theme rounded-xl text-xs sm:text-sm p-2.5 text-main outline-none placeholder-muted transition-colors"}),r.jsx("p",{id:"student-lookup-name-help",className:"text-xs text-subtle",children:n==="zh"?"支持精确或模糊匹配,至少输入 2 个字符(或 1 个汉字),单次最多展示 10 条记录。":"Exact or partial match (at least 2 characters or 1 Chinese character; up to 10 results)."})]}),r.jsxs("button",{type:"submit",disabled:be,className:"w-full bg-primary-theme hover:opacity-95 disabled:opacity-50 text-white font-bold py-2.5 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all cursor-pointer shadow-sm",children:[r.jsx(qi,{size:14,"aria-hidden":"true"}),r.jsx("span",{children:be?n==="zh"?"正在查询...":"Searching...":n==="zh"?"查询学号":"Look Up Student ID"})]})]}),r.jsxs("div",{role:"status","aria-live":"polite",className:"space-y-2",children:[Se&&r.jsxs("div",{className:"p-3 bg-rose-500/10 border border-rose-500/40 text-rose-700 dark:text-rose-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Pt,{size:15,className:"shrink-0","aria-hidden":"true"}),r.jsx("span",{children:Se})]}),!Se&&ae&&Y.length===0&&r.jsx("div",{className:"p-4 rounded-xl border border-theme bg-surface-secondary text-center text-xs text-muted",children:n==="zh"?"未找到匹配的学生记录,请检查姓名拼写或切换班级后再试。":"No matching student found. Please check the spelling or try another class."}),ee&&r.jsx("div",{className:"p-2.5 rounded-xl border border-amber-500/35 bg-amber-500/10 text-amber-800 dark:text-amber-200 text-xs",children:n==="zh"?"匹配结果超过 10 条,仅展示前 10 条。请输入更完整的姓名或选择班级缩小范围。":"More than 10 matches found (showing top 10). Enter a fuller name or select a class to narrow results."})]}),Y.length>0&&r.jsx("ul",{className:"max-h-60 overflow-y-auto space-y-2 pr-0.5","aria-label":n==="zh"?"查询结果":"Lookup results",children:Y.map(oe=>{const ce=oe.classes.length>0?oe.classes.join(n==="zh"?"、":", "):n==="zh"?"未分班":"Unassigned";return r.jsxs("li",{className:"flex items-center justify-between gap-3 p-3 rounded-xl border border-theme bg-surface-secondary/70",children:[r.jsxs("div",{className:"min-w-0 space-y-0.5",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"text-sm font-bold text-main truncate",children:oe.name}),r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-surface border border-theme text-muted truncate max-w-[12rem]",children:ce})]}),r.jsxs("p",{className:"text-xs text-primary-ink",children:[n==="zh"?"学号:":"ID: ",r.jsx("span",{className:"font-mono font-semibold select-all",children:oe.studentNumber})]})]}),r.jsxs("button",{type:"button",onClick:()=>re(oe.studentNumber),className:"shrink-0 px-3 py-1.5 rounded-lg bg-primary-theme hover:opacity-95 text-white text-xs font-bold inline-flex items-center gap-1 cursor-pointer transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400",children:[r.jsx(Xe,{size:13,"aria-hidden":"true"}),r.jsx("span",{children:n==="zh"?"使用此学号":"Use ID"})]})]},`${oe.studentNumber}-${oe.name}`)})})]})})]})});function bn({id:e,name:t,label:n,hint:s,value:i,onChange:o,onBlur:a,autoComplete:l,required:c=!1,minLength:u,pattern:d,placeholder:f,enterKeyHint:m,error:h,lang:y="zh",className:p="w-full border border-slate-300 rounded-lg px-3 py-2 pr-10 text-sm text-slate-800 bg-white focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",labelClassName:x="block text-xs font-medium text-slate-600 mb-1",wrapperClassName:g="space-y-1",inputRef:v,dataTestId:w}){const E=b.useId(),N=e||E,j=`${N}-hint`,I=`${N}-error`,[z,$]=b.useState(!1),V=!!(h&&h.trim().length>0),B=[s?j:null,V?I:null].filter(Boolean).join(" ")||void 0,_=y==="zh"?z?"隐藏密码":"显示密码":z?"Hide password":"Show password";return r.jsxs("div",{className:g,children:[r.jsx("label",{htmlFor:N,className:x,children:n}),s&&r.jsx("p",{id:j,className:"text-xs text-slate-500",children:s}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:v,id:N,name:t||N,type:z?"text":"password",value:i,onChange:U=>o(U.target.value),onBlur:a,autoComplete:l,required:c,minLength:u,pattern:d,placeholder:f,enterKeyHint:m,"aria-invalid":V?"true":"false","aria-describedby":B,"data-testid":w,className:p}),r.jsx("button",{type:"button",onClick:()=>$(U=>!U),"aria-pressed":z,"aria-label":_,className:"absolute inset-y-0 end-0 flex items-center justify-center px-2.5 text-slate-500 hover:text-slate-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 rounded-e-lg cursor-pointer",children:z?r.jsx(Jb,{size:16,"aria-hidden":"true"}):r.jsx(kn,{size:16,"aria-hidden":"true"})})]}),V&&r.jsxs("p",{id:I,className:"text-xs text-red-600 flex items-center gap-1",role:"status",children:[r.jsx("span",{role:"img","aria-label":y==="zh"?"错误":"Error",children:"⚠"}),r.jsx("span",{children:h})]})]})}function eS({lang:e,username:t,onDone:n,onLogout:s}){const[i,o]=b.useState(""),[a,l]=b.useState(""),[c,u]=b.useState(""),[d,f]=b.useState({}),[m,h]=b.useState(null),[y,p]=b.useState(!1),x=b.useRef(null),g=b.useRef(null),v=b.useRef(null),w=e==="zh",E=()=>{if(!i){const I=w?"请输入当前密码":"Current password is required";return{message:I,fields:{old:I},firstInvalid:x.current}}if(!a){const I=w?"请输入新密码":"New password is required";return{message:I,fields:{new:I},firstInvalid:g.current}}if(a.length<8){const I=w?"新密码至少 8 位":"Password must be at least 8 characters long";return{message:I,fields:{new:I},firstInvalid:g.current}}if(!/[a-zA-Z]/.test(a)||!/[0-9]/.test(a)){const I=w?"新密码需同时包含字母和数字":"Password must contain both letters and numbers";return{message:I,fields:{new:I},firstInvalid:g.current}}if(a===i){const I=w?"新密码不能与当前密码相同":"New password must differ from the current one";return{message:I,fields:{new:I},firstInvalid:g.current}}if(!c){const I=w?"请再次确认新密码":"Please confirm the new password";return{message:I,fields:{confirm:I},firstInvalid:v.current}}if(a!==c){const I=w?"两次输入的新密码不一致":"Passwords do not match";return{message:I,fields:{confirm:I},firstInvalid:v.current}}return{message:null,fields:{}}},N=async()=>{const I=E();if(I.message){f(I.fields),h(I.message),I.firstInvalid?.focus();return}p(!0),f({}),h(null);try{const z=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:i,newPassword:a})}),$=await z.json().catch(()=>({}));if(!z.ok){const V=$.error||(w?"修改失败,请重试":"Change failed, please retry");h(V),f({old:V}),x.current?.focus();return}n()}catch{h(w?"网络异常,请重试":"Network error, please retry")}finally{p(!1)}},j="w-full px-3 py-2 pr-10 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("main",{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(Kh,{size:20,className:"text-amber-600","aria-hidden":"true"})}),r.jsx("h1",{id:"forced-change-heading",className:"text-lg font-bold text-slate-800",children:w?"安全要求:修改默认密码":"Security: Change Default Password"})]}),r.jsx("p",{className:"text-xs text-slate-500 leading-relaxed mb-5",children:w?`当前账号${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("form",{"aria-labelledby":"forced-change-heading",noValidate:!0,onSubmit:I=>{I.preventDefault(),N()},children:[r.jsxs("div",{className:"space-y-3",children:[r.jsx(bn,{id:"force-old-password",name:"old_password",label:w?"当前密码":"Current password",value:i,onChange:I=>{o(I),d.old&&f(z=>({...z,old:void 0}))},autoComplete:"current-password",required:!0,enterKeyHint:"next",lang:e,className:j,error:d.old,inputRef:x}),r.jsx(bn,{id:"force-new-password",name:"new_password",label:w?"新密码":"New password",hint:w?"至少 8 位,需同时包含字母和数字,且不能与当前密码相同":"At least 8 characters with letters and numbers, different from current password",value:a,onChange:I=>{l(I),d.new&&f(z=>({...z,new:void 0}))},autoComplete:"new-password",required:!0,minLength:8,enterKeyHint:"next",lang:e,className:j,error:d.new,inputRef:g}),r.jsx(bn,{id:"force-confirm-password",name:"confirm_password",label:w?"确认新密码":"Confirm new password",value:c,onChange:I=>{u(I),d.confirm&&f(z=>({...z,confirm:void 0}))},autoComplete:"new-password",required:!0,minLength:8,enterKeyHint:"done",lang:e,className:j,error:d.confirm,inputRef:v})]}),m&&r.jsx("div",{"data-testid":"force-change-error",role:"alert",className:"mt-3 text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:m}),r.jsxs("button",{type:"submit",disabled:y,"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:[y?r.jsx(dt,{size:16,className:"animate-spin"}):r.jsx(Si,{size:16}),w?"修改密码并继续":"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(ki,{size:13}),w?"退出登录":"Log out"]})]})})}function Zs(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.data)?e.data:[]}async function tS(){const e=await fetch("/api/lessons?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function nS(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 sS(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 rS(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 iS(e){const t=await fetch(`/api/lessons/${e}/whiteboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const oS=(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 tS();if(n){const i=Zs(s);e(o=>({lessons:i,selectedLesson:o.selectedLesson??(aS(t())&&i.length>0?i[0].id:o.selectedLesson)}))}}catch(n){console.warn("Failed to fetch lessons",n)}}});function aS(e){return e.session?.role==="teacher"}async function lS(){const e=await fetch("/api/classes?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function cS(){const e=await fetch("/api/students?pageSize=all");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function dS(e){const t=await fetch(`/api/classes/${e}/students`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}const uS=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 lS();t&&e(s=>({classes:Zs(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch classes",t)}},loadStudents:async()=>{try{const{ok:t,data:n}=await cS();t&&e(s=>({students:Zs(n),dataVersion:s.dataVersion+1}))}catch(t){console.warn("Failed to fetch students",t)}}}),hS=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})}),fS=e=>({session:null,sessionLoading:!0,dbConnected:!1,setSession:t=>e({session:t}),setSessionLoading:t=>e({sessionLoading:t}),setDbConnected:t=>e({dbConnected:t})}),mS=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})}),pS=e=>({studentDashboardData:null,notifications:[],setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t})});function Hf(e){return"#/"+e}function Fs(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}function gS(e){return window.location.pathname+window.location.search+Hf(e)}function xS(e){const t=gS(e);window.open(t,"_blank","noopener,noreferrer")}function bS(){if(typeof window<"u"&&window.location?.hash){const e=Fs(window.location.hash);if(e)return e}return"live_class"}const Ge=Lt(e=>({lang:"zh",activeRole:"teacher",teacherTab:bS(),pendingTimetableSubTab:null,pendingLiveClassLaunch:null,profileOpen:!1,isCourseWizardOpen:!1,isImportLessonsOpen:!1,isQuizGeneratorOpen:!1,isSystemResourceLibraryOpen:!1,batchPicker:null,isExportWeightModalOpen:!1,classroomDrawerTab:null,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}),setClassroomDrawerTab:t=>e({classroomDrawerTab: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})})),yS=e=>tn(Ge,e),wS=e=>({lang:Ge.getState().lang,teacherTab:Ge.getState().teacherTab,toasts:Ge.getState().toasts,siteInfo:Ge.getState().siteInfo,setLang:t=>{Ge.getState().setLang(t),e({lang:t})},setTeacherTab:t=>{Ge.getState().setTeacherTab(t),e({teacherTab:t})},addToast:t=>{Ge.getState().addToast(t),e({toasts:Ge.getState().toasts})},removeToast:t=>{Ge.getState().removeToast(t),e({toasts:Ge.getState().toasts})},setSiteInfo:t=>{Ge.getState().setSiteInfo(t),e({siteInfo:t})}}),Te=Lt()((...e)=>({...oS(...e),...uS(...e),...hS(...e),...fS(...e),...mS(...e),...pS(...e),...wS(...e)})),ke=e=>tn(Te,e);class vS{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 u=Array.from(c);if(u.length===1)return await u[0](i);const d=await Promise.all(u.map(f=>f(i)));if(t.type==="host:refresh"){const f=new Set;for(const m of d)m&&Array.isArray(m.refreshed)&&m.refreshed.forEach(h=>f.add(h));return{success:!0,refreshed:Array.from(f)}}return d[d.length-1]}};let l=(async()=>{let c=-1;const u=async d=>{if(d<=c)throw new Error("next() called multiple times in middleware");if(c=d,d<this.middlewares.length){const f=this.middlewares[d];return f(i,()=>u(d+1))}return o()};return u(0)})();if(n?.timeoutMs&&n.timeoutMs>0){let c;const u=new Promise((d,f)=>{c=setTimeout(()=>{f(new Error(`Action "${t.type}" timed out after ${n.timeoutMs}ms`))},n.timeoutMs)});l=Promise.race([l,u]).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=Te.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{Te.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{Te.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 qf=new vS,SS=({dispatcher:e})=>{const t=e||qf,[n,s]=b.useState([]);if(b.useEffect(()=>{const p=t;if(typeof p.subscribeModals=="function"){const x=p.subscribeModals(g=>{s([...g])});return()=>{x.dispose()}}},[t]),b.useEffect(()=>{if(n.length===0)return;const p=x=>{if(x.key==="Escape"){const g=n[n.length-1],v=t;v.resolveModal&&(g.type==="confirm"?v.resolveModal(g.id,{confirmed:!1}):v.resolveModal(g.id,{closed:!0}))}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[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})},u=(p,x)=>{o.resolveModal?.(i.id,{actionId:p,closed:!!x})},f={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",m=()=>{switch(i.variant){case"danger":return r.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 text-red-600 flex items-center justify-center shrink-0",children:r.jsx(Bt,{size:20})});case"warning":return r.jsx("div",{className:"w-10 h-10 rounded-full bg-amber-100 text-amber-600 flex items-center justify-center shrink-0",children:r.jsx(Pt,{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(Dl,{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"}},y=p=>{switch(p){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:p=>{p.target===p.currentTarget&&i.closableByBackdrop!==!1&&c()},children:r.jsxs("div",{className:`w-full ${f} 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:p=>p.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"&&m(),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(De,{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(p=>r.jsx("button",{onClick:()=>u(p.actionId,p.isClose),className:`px-4 py-2 text-xs font-bold rounded-xl transition-all cursor-pointer ${y(p.variant)}`,children:p.label},p.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:"关闭"})})]})})},ic=b.createContext(null);function kS({children:e,host:t}){return r.jsxs(ic.Provider,{value:t,children:[e,r.jsx(SS,{dispatcher:t?.getDispatcher?.()})]})}function jS(){const e=b.useContext(ic);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}function Gf(){return b.useContext(ic)}typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("storage",e=>{e.key===oc&&Re.setState({dashboardVisibility:Zf()})});const oc="openlearn:dashboardVisibility";function Zf(){try{const e=localStorage.getItem(oc);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function yu(e){try{localStorage.setItem(oc,JSON.stringify([...e.entries()]))}catch{}}const Re=Ll()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:Zf(),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(u=>u.id===s.id?s:u)),{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(d=>d.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(d=>d.id!==s),u=new Map(o.extensionPoints);return c.length===0?u.delete(n):u.set(n,c),{extensionPoints:u}}),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(u=>u.pluginId!==n||u.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),yu(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 yu(i),{dashboardVisibility:i}})}));function NS(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 CS(e){return!(!e||e.length>8||/^[a-zA-Z0-9_-]+$/.test(e))}function ES(e){if(!e)return null;const t=ci;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 dn({icon:e,size:t=18,className:n="shrink-0",fallback:s=ji,alt:i=""}){const[o,a]=b.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(NS(l))return o?r.jsx(s,{size:t,className:n}):r.jsx("img",{src:l,alt:i,width:t,height:t,style:{width:`${t}px`,height:`${t}px`},className:`object-contain rounded-xs ${n}`,onError:()=>a(!0),loading:"lazy",decoding:"async"});if(CS(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=ES(l);if(c)return r.jsx(c,{size:t,className:n})}return r.jsx(s,{size:t,className:n})}const ac="zh",Mt={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 lc(e){return e?e.toLowerCase().startsWith("en")?"en":"zh":ac}const Yn=new Map;let cc="zh";function IS(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=lc(i);n[a]={...n[a]||{},...o}}const s=Yn.get(e)||{};Yn.set(e,{...s,...n,...Object.fromEntries(Object.entries(n).map(([i,o])=>[i,{...s[i]||{},...o}]))})}function AS(e){Yn.delete(e)}function TS(){return cc}function un(e,t){return!e||!t?e:e.replace(/\{([^{}]+)\}/g,(n,s)=>{const i=t[s.trim()];return i!=null?String(i):n})}function Kf(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 Yf(e,t,n,s){let i,o,a=s||cc;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=lc(a),c=ac;if(e.includes(":")){const u=e.indexOf(":"),d=e.substring(0,u),f=e.substring(u+1),m=Yn.get(d);if(m){if(m[l]&&m[l][f]!==void 0)return un(m[l][f],o);if(m[c]&&m[c][f]!==void 0)return un(m[c][f],o)}}if(Mt[l]?.[e]!==void 0)return un(Mt[l][e],o);if(Mt[c]?.[e]!==void 0)return un(Mt[c][e],o);for(const[,u]of Yn){if(u[l]?.[e]!==void 0)return un(u[l][e],o);if(u[c]?.[e]!==void 0)return un(u[c][e],o)}return i!=null?un(i,o):Kf(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=lc(n||cc),l=ac;if(t){const c=Yn.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 Mt[a]?.[o]!==void 0?Mt[a][o]:Mt[l]?.[o]!==void 0?Mt[l][o]:Kf(o)}return s.includes(":")&&!s.includes(" ")&&!s.includes("/")?Yf(s,void 0,void 0,n):s}const nl=Mt,Qf=3,_S=300*1e3,Ks=new Map;function PS(e){const t=Date.now(),n=Ks.get(e);if(!n||t-n.lastAt>_S)return Ks.set(e,{count:1,lastAt:t,blown:!1}),{shouldBreak:!1,count:1};n.count+=1,n.lastAt=t;const s=n.count>=Qf;return s&&(n.blown=!0),{shouldBreak:s,count:n.count}}function zS(e){Ks.delete(e)}function Sr(e){return Ks.get(e)?.blown??!1}function kr(e){Ks.delete(e)}function RS(e){if(typeof e!="string")return"";const t=e.split(/[\\/]/).pop()||"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n).toLowerCase()}const LS=Object.freeze({".pdf":"application/pdf",".rtf":"application/rtf",".odt":"application/vnd.oasis.opendocument.text",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".txt":"text/plain",".md":"text/plain",".csv":"text/plain",".json":"text/plain",".xml":"text/plain",".html":"text/plain",".css":"text/plain",".py":"text/plain",".js":"text/plain",".mjs":"text/plain",".cjs":"text/plain",".ts":"text/plain",".tsx":"text/plain",".jsx":"text/plain",".java":"text/plain",".c":"text/plain",".h":"text/plain",".cpp":"text/plain",".cs":"text/plain",".go":"text/plain",".rs":"text/plain",".rb":"text/plain",".php":"text/plain",".sql":"text/plain",".ino":"text/plain",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".heic":"image/heic",".zip":"application/zip"}),OS=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".heic"]),DS=new Set([".txt",".md",".csv",".json",".xml",".html",".css",".py",".js",".mjs",".cjs",".ts",".tsx",".jsx",".java",".c",".h",".cpp",".cs",".go",".rs",".rb",".php",".sql",".ino"]),$S=new Set(["application/pdf","text/plain","image/png","image/jpeg","image/gif","image/webp","image/bmp"]),GT=512*1024;function ZT(e){const t=RS(e?.name??""),n=LS[t]??"application/octet-stream";return t===".pdf"?{kind:"pdf",extension:t,contentType:n,inlineSafe:!0,asText:!1}:OS.has(t)?{kind:"image",extension:t,contentType:n,inlineSafe:$S.has(n),asText:!1}:DS.has(t)?{kind:"text",extension:t,contentType:"text/plain",inlineSafe:!0,asText:!0}:{kind:"unsupported",extension:t,contentType:n,inlineSafe:!1,asText:!1}}function MS(e,t){if(!Array.isArray(e))return!1;const n=(t||"").toLowerCase(),s=e.filter(i=>typeof i=="string").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return s.includes("*")?!0:n?s.some(i=>(i.startsWith(".")?i:`.${i}`)===n):!1}class FS{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 BS=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function Jf(e,t){const n=t+".";return e.startsWith(n)||BS.test(e)?e:n+e}const sl="api:write",rl="api:admin",il="grades:write",ol="agent:tool",al="ai:invoke",ll="ai:persona",Rs="task:register",US="student-data:read",VS="student-data:write",WS={ASSIGNMENT_MANAGE:"assignment:manage",ASSIGNMENT_READ:"assignment:read",ASSIGNMENT_REVIEW:"assignment:review",ASSIGNMENT_SUBMIT:"assignment:submit",ASSIGNMENT_WRITE:"assignment:write",LESSON_DELETE:"lesson:delete",LESSON_READ:"lesson:read",LESSON_WRITE:"lesson:write",MANAGEMENT_READ:"management:read",MANAGEMENT_WRITE:"management:write",PLUGIN_READ:"plugin:read",PLUGIN_WRITE:"plugin:write",PROCESS_READ:"process:read",PROCESS_WRITE:"process:write",STUDENT_WRITE:"student:write",VFS_READ:"vfs:read",VFS_WRITE:"vfs:write",WHITEBOARD_READ:"whiteboard:read",WHITEBOARD_WRITE:"whiteboard:write",CLASS_READ:"class:read",CLASS_WRITE:"class:write",STUDENT_READ:"student:read",API_WRITE:sl,API_ADMIN:rl,GRADES_WRITE:il,AGENT_TOOL:ol,AI_INVOKE:al,AI_PERSONA:ll,TASK_REGISTER:Rs,STUDENT_DATA_READ:US,STUDENT_DATA_WRITE:VS,SEGMENT_GATE_EVAL:"segment:gate_eval"},HS=Object.freeze(Array.from(new Set(Object.values(WS))));new Set(HS);const qS=Object.freeze(["/api/plugins","/api/users","/api/auth","/api/ai-providers","/api/agent","/api/grade-sync","/api/site-settings","/api/approvals"]),GS=Object.freeze(["/gdpr-delete"]),ZS=/^\/api\/[^/]+\/[^/]+$/;function KS(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 YS(e){return!Array.isArray(e)||e.length===0?"":KS(e[0])}function Zt(e,t){return e.some(n=>typeof n=="string"&&(n===t||n.startsWith(`${t}:`)))}function QS(e){return e==="get"||e.startsWith("get")}function JS(e){const{token:t,method:n,args:s,tokens:i}=e,o=e.caps??[];if(i.frontendApi&&t===i.frontendApi){if(QS(n)||n==="request"&&!Array.isArray(s))return null;const a=YS(s),l=qS.some(d=>a===d||a.startsWith(`${d}/`)),c=GS.some(d=>a.endsWith(d)),u=n==="del"&&ZS.test(a);return l||c||u?Zt(o,rl)?null:`${c?`不可逆操作 '${a}'`:u?`实体级删除 '${a}'`:`写入高危路径 '${a||"<未提供路径>"}'`} 需要 manifest 声明 '${rl}' 能力`:Zt(o,sl)?null:`写操作(${n})需要 manifest 声明 '${sl}' 能力(普通只读调用请用 get)`}if(i.socketService&&t===i.socketService)return n==="disconnect"||n==="destroy"?`插件无权调用 ${n}()——断开课堂实时通道会中断正在进行的教学`:null;if(i.semesterGradeService&&t===i.semesterGradeService)return n.startsWith("save")||n.startsWith("write")||n.startsWith("set")?Zt(o,il)?null:`写入学期成绩需要 manifest 声明 '${il}' 能力('grades' 或 'grades:read' 不足以解锁写入)`:null;if(i.processService&&t===i.processService)return n==="registerHandler"||n==="registerInterval"?Zt(o,Rs)?null:`注册后台任务(${n})需要 manifest 声明 '${Rs}' 能力`:n==="restore"?Zt(o,Rs)?null:`恢复后台任务(restore)会重放全部插件的 running 进程,需要 manifest 声明 '${Rs}' 能力`:null;if(i.aiService&&t===i.aiService)return n==="generateText"||n==="chat"||n==="complete"?Zt(o,al)?null:`调用 AI 生成(${n})需要 manifest 声明 '${al}' 能力`:n==="registerAIPersona"||n==="registerAIContextProvider"?Zt(o,ll)?null:`注册 AI Persona / 上下文提供者(${n})需要 manifest 声明 '${ll}' 能力`: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 Zt(o,ol)?null:`注册对外暴露的 action 需要 manifest 声明 '${ol}' 能力(如不希望进入 AI Agent 工具列表,请设置 exposeToAgent: false)`}return null}return i.storageService&&t===i.storageService||i.uiService&&t===i.uiService,null}const Ls="@openlearn/frontend:IFrontendAPI",cl="@openlearn/frontend:ISocketService",Gr="@openlearn/frontend:IUIService",Zr="@openlearn/frontend:IStorageService",Xf="@openlearn/frontend:ISemesterGradeService",XS="@openlearn/frontend:IHostActionDispatcher";var He=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(He||{});const e1=Object.freeze({frontendApi:Ls,socketService:cl,uiService:Gr,storageService:Zr,semesterGradeService:Xf});function t1(e,t,n,s=[]){return JS({token:e,method:t,args:n,caps:s,tokens:e1})}const Os="ol-plugin-frame",jr="ol-plugin-view",n1="allow-scripts",s1="/plugin-sandbox/frame";function wu(e){return!!e&&typeof e=="object"&&e.channel===Os}function r1(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const i1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,o1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,a1={};function vu(e,t){return(a1.jsx?o1:i1).test(e)}const l1=/[ \t\n\f\r]/g;function c1(e){return typeof e=="object"?e.type==="text"?Su(e.value):!1:Su(e)}function Su(e){return e.replace(l1,"")===""}class or{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}or.prototype.normal={};or.prototype.property={};or.prototype.space=void 0;function em(e,t){const n={},s={};for(const i of e)Object.assign(n,i.property),Object.assign(s,i.normal);return new or(n,s,t)}function dl(e){return e.toLowerCase()}class ht{constructor(t,n){this.attribute=n,this.property=t}}ht.prototype.attribute="";ht.prototype.booleanish=!1;ht.prototype.boolean=!1;ht.prototype.commaOrSpaceSeparated=!1;ht.prototype.commaSeparated=!1;ht.prototype.defined=!1;ht.prototype.mustUseProperty=!1;ht.prototype.number=!1;ht.prototype.overloadedBoolean=!1;ht.prototype.property="";ht.prototype.spaceSeparated=!1;ht.prototype.space=void 0;let d1=0;const Ee=Nn(),Ze=Nn(),ul=Nn(),ge=Nn(),$e=Nn(),yn=Nn(),pt=Nn();function Nn(){return 2**++d1}const hl=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ee,booleanish:Ze,commaOrSpaceSeparated:pt,commaSeparated:yn,number:ge,overloadedBoolean:ul,spaceSeparated:$e},Symbol.toStringTag,{value:"Module"})),ta=Object.keys(hl);class dc extends ht{constructor(t,n,s,i){let o=-1;if(super(t,n),ku(this,"space",i),typeof s=="number")for(;++o<ta.length;){const a=ta[o];ku(this,ta[o],(s&hl[a])===hl[a])}}}dc.prototype.defined=!0;function ku(e,t,n){n&&(e[t]=n)}function Xn(e){const t={},n={};for(const[s,i]of Object.entries(e.properties)){const o=new dc(s,e.transform(e.attributes||{},s),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(o.mustUseProperty=!0),t[s]=o,n[dl(s)]=s,n[dl(o.attribute)]=s}return new or(t,n,e.space)}const tm=Xn({properties:{ariaActiveDescendant:null,ariaAtomic:Ze,ariaAutoComplete:null,ariaBusy:Ze,ariaChecked:Ze,ariaColCount:ge,ariaColIndex:ge,ariaColSpan:ge,ariaControls:$e,ariaCurrent:null,ariaDescribedBy:$e,ariaDetails:null,ariaDisabled:Ze,ariaDropEffect:$e,ariaErrorMessage:null,ariaExpanded:Ze,ariaFlowTo:$e,ariaGrabbed:Ze,ariaHasPopup:null,ariaHidden:Ze,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:$e,ariaLevel:ge,ariaLive:null,ariaModal:Ze,ariaMultiLine:Ze,ariaMultiSelectable:Ze,ariaOrientation:null,ariaOwns:$e,ariaPlaceholder:null,ariaPosInSet:ge,ariaPressed:Ze,ariaReadOnly:Ze,ariaRelevant:null,ariaRequired:Ze,ariaRoleDescription:$e,ariaRowCount:ge,ariaRowIndex:ge,ariaRowSpan:ge,ariaSelected:Ze,ariaSetSize:ge,ariaSort:null,ariaValueMax:ge,ariaValueMin:ge,ariaValueNow:ge,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function nm(e,t){return t in e?e[t]:t}function sm(e,t){return nm(e,t.toLowerCase())}const u1=Xn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:yn,acceptCharset:$e,accessKey:$e,action:null,allow:null,allowFullScreen:Ee,allowPaymentRequest:Ee,allowUserMedia:Ee,alpha:Ee,alt:null,as:null,async:Ee,autoCapitalize:null,autoComplete:$e,autoFocus:Ee,autoPlay:Ee,blocking:$e,capture:null,charSet:null,checked:Ee,cite:null,className:$e,closedBy:null,colorSpace:null,cols:ge,colSpan:ge,command:null,commandFor:null,content:null,contentEditable:Ze,controls:Ee,controlsList:$e,coords:ge|yn,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ee,defer:Ee,dir:null,dirName:null,disabled:Ee,download:ul,draggable:Ze,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ee,formTarget:null,headers:$e,height:ge,hidden:ul,high:ge,href:null,hrefLang:null,htmlFor:$e,httpEquiv:$e,id:null,imageSizes:null,imageSrcSet:null,inert:Ee,inputMode:null,integrity:null,is:null,isMap:Ee,itemId:null,itemProp:$e,itemRef:$e,itemScope:Ee,itemType:$e,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ee,low:ge,manifest:null,max:null,maxLength:ge,media:null,method:null,min:null,minLength:ge,multiple:Ee,muted:Ee,name:null,nonce:null,noModule:Ee,noValidate:Ee,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:Ee,optimum:ge,pattern:null,ping:$e,placeholder:null,playsInline:Ee,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ee,referrerPolicy:null,rel:$e,required:Ee,reversed:Ee,rows:ge,rowSpan:ge,sandbox:$e,scope:null,scoped:Ee,seamless:Ee,selected:Ee,shadowRootClonable:Ee,shadowRootCustomElementRegistry:Ee,shadowRootDelegatesFocus:Ee,shadowRootMode:null,shadowRootSerializable:Ee,shape:null,size:ge,sizes:null,slot:null,span:ge,spellCheck:Ze,src:null,srcDoc:null,srcLang:null,srcSet:null,start:ge,step:null,style:null,tabIndex:ge,target:null,title:null,translate:null,type:null,typeMustMatch:Ee,useMap:null,value:Ze,width:ge,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:$e,axis:null,background:null,bgColor:null,border:ge,borderColor:null,bottomMargin:ge,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ee,declare:Ee,event:null,face:null,frame:null,frameBorder:null,hSpace:ge,leftMargin:ge,link:null,longDesc:null,lowSrc:null,marginHeight:ge,marginWidth:ge,noResize:Ee,noHref:Ee,noShade:Ee,noWrap:Ee,object:null,profile:null,prompt:null,rev:null,rightMargin:ge,rules:null,scheme:null,scrolling:Ze,standby:null,summary:null,text:null,topMargin:ge,valueType:null,version:null,vAlign:null,vLink:null,vSpace:ge,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:Ee,disablePictureInPicture:Ee,disableRemotePlayback:Ee,exportParts:yn,part:$e,prefix:null,property:null,results:ge,security:null,unselectable:null},space:"html",transform:sm}),h1=Xn({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:pt,accentHeight:ge,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:ge,amplitude:ge,arabicForm:null,ascent:ge,attributeName:null,attributeType:null,azimuth:ge,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:ge,by:null,calcMode:null,capHeight:ge,className:$e,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:ge,diffuseConstant:ge,direction:null,display:null,dur:null,divisor:ge,dominantBaseline:null,download:Ee,dx:null,dy:null,edgeMode:null,editable:null,elevation:ge,enableBackground:null,end:null,event:null,exponent:ge,externalResourcesRequired:null,fill:null,fillOpacity:ge,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:yn,g2:yn,glyphName:yn,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:ge,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:ge,horizOriginX:ge,horizOriginY:ge,id:null,ideographic:ge,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:ge,k:ge,k1:ge,k2:ge,k3:ge,k4:ge,kernelMatrix:pt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:ge,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:ge,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:ge,overlineThickness:ge,paintOrder:null,panose1:null,path:null,pathLength:ge,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:$e,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:ge,pointsAtY:ge,pointsAtZ:ge,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:pt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:pt,rev:pt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:pt,requiredFeatures:pt,requiredFonts:pt,requiredFormats:pt,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:ge,specularExponent:ge,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:ge,strikethroughThickness:ge,string:null,stroke:null,strokeDashArray:pt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:ge,strokeOpacity:ge,strokeWidth:null,style:null,surfaceScale:ge,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:pt,tabIndex:ge,tableValues:null,target:null,targetX:ge,targetY:ge,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:pt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:ge,underlineThickness:ge,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:ge,values:null,vAlphabetic:ge,vMathematical:ge,vectorEffect:null,vHanging:ge,vIdeographic:ge,version:null,vertAdvY:ge,vertOriginX:ge,vertOriginY:ge,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:ge,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:nm}),rm=Xn({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()}}),im=Xn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:sm}),om=Xn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),f1={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"},m1=/[A-Z]/g,ju=/-[a-z]/g,p1=/^data[-\w.:]+$/i;function g1(e,t){const n=dl(t);let s=t,i=ht;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&p1.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(ju,b1);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!ju.test(o)){let a=o.replace(m1,x1);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=dc}return new i(s,t)}function x1(e){return"-"+e.toLowerCase()}function b1(e){return e.charAt(1).toUpperCase()}const y1=em([tm,u1,rm,im,om],"html"),uc=em([tm,h1,rm,im,om],"svg");function w1(e){return e.join(" ").trim()}var Pn={},na,Nu;function v1(){if(Nu)return na;Nu=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=`
|
|
36
|
+
`,u="/",d="*",f="",m="comment",h="declaration";function y(x,g){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];g=g||{};var v=1,w=1;function E(k){var F=k.match(t);F&&(v+=F.length);var Z=k.lastIndexOf(c);w=~Z?k.length-Z:w+k.length}function N(){var k={line:v,column:w};return function(F){return F.position=new j(k),$(),F}}function j(k){this.start=k,this.end={line:v,column:w},this.source=g.source}j.prototype.content=x;function I(k){var F=new Error(g.source+":"+v+":"+w+": "+k);if(F.reason=k,F.filename=g.source,F.line=v,F.column=w,F.source=x,!g.silent)throw F}function z(k){var F=k.exec(x);if(F){var Z=F[0];return E(Z),x=x.slice(Z.length),F}}function $(){z(n)}function V(k){var F;for(k=k||[];F=B();)F!==!1&&k.push(F);return k}function B(){var k=N();if(!(u!=x.charAt(0)||d!=x.charAt(1))){for(var F=2;f!=x.charAt(F)&&(d!=x.charAt(F)||u!=x.charAt(F+1));)++F;if(F+=2,f===x.charAt(F-1))return I("End of comment missing");var Z=x.slice(2,F-2);return w+=2,E(Z),x=x.slice(F),w+=2,k({type:m,comment:Z})}}function _(){var k=N(),F=z(s);if(F){if(B(),!z(i))return I("property missing ':'");var Z=z(o),M=k({type:h,property:p(F[0].replace(e,f)),value:Z?p(Z[0].replace(e,f)):f});return z(a),M}}function U(){var k=[];V(k);for(var F;F=_();)F!==!1&&(k.push(F),V(k));return k}return $(),U()}function p(x){return x?x.replace(l,f):f}return na=y,na}var Cu;function S1(){if(Cu)return Pn;Cu=1;var e=Pn&&Pn.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.default=n;const t=e(v1());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:u,value:d}=c;l?i(u,d,c):d&&(o=o||{},o[u]=d)}),o}return Pn}var Es={},Eu;function k1(){if(Eu)return Es;Eu=1,Object.defineProperty(Es,"__esModule",{value:!0}),Es.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,o=function(u){return!u||n.test(u)||e.test(u)},a=function(u,d){return d.toUpperCase()},l=function(u,d){return"".concat(d,"-")},c=function(u,d){return d===void 0&&(d={}),o(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(i,l):u=u.replace(s,l),u.replace(t,a))};return Es.camelCase=c,Es}var Is,Iu;function j1(){if(Iu)return Is;Iu=1;var e=Is&&Is.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(S1()),n=k1();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,Is=s,Is}var N1=j1();const C1=Rl(N1),am=lm("end"),hc=lm("start");function lm(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 E1(e){const t=hc(e),n=am(e);if(t&&n)return{start:t,end:n}}function Bs(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Au(e.position):"start"in e||"end"in e?Au(e):"line"in e||"column"in e?fl(e):""}function fl(e){return Tu(e&&e.line)+":"+Tu(e&&e.column)}function Au(e){return fl(e&&e.start)+"-"+fl(e&&e.end)}function Tu(e){return e&&typeof e=="number"?e:1}class ot 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}}ot.prototype.file="";ot.prototype.name="";ot.prototype.reason="";ot.prototype.message="";ot.prototype.stack="";ot.prototype.column=void 0;ot.prototype.line=void 0;ot.prototype.ancestors=void 0;ot.prototype.cause=void 0;ot.prototype.fatal=void 0;ot.prototype.place=void 0;ot.prototype.ruleId=void 0;ot.prototype.source=void 0;const fc={}.hasOwnProperty,I1=new Map,A1=/[A-Z]/g,T1=new Set(["table","tbody","thead","tfoot","tr"]),_1=new Set(["td","th"]),cm="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function P1(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=F1(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=M1(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"?uc:y1,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=dm(i,e,void 0);return o&&typeof o!="string"?o:i.create(e,i.Fragment,{children:o||void 0},void 0)}function dm(e,t,n){if(t.type==="element")return z1(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return R1(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return O1(e,t,n);if(t.type==="mdxjsEsm")return L1(e,t);if(t.type==="root")return D1(e,t,n);if(t.type==="text")return $1(e,t)}function z1(e,t,n){const s=e.schema;let i=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(i=uc,e.schema=i),e.ancestors.push(t);const o=hm(e,t.tagName,!1),a=B1(e,t);let l=pc(e,t);return T1.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!c1(c):!0})),um(e,a,o,t),mc(a,l),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function R1(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)}Ys(e,t.position)}function L1(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Ys(e,t.position)}function O1(e,t,n){const s=e.schema;let i=s;t.name==="svg"&&s.space==="html"&&(i=uc,e.schema=i),e.ancestors.push(t);const o=t.name===null?e.Fragment:hm(e,t.name,!0),a=U1(e,t),l=pc(e,t);return um(e,a,o,t),mc(a,l),e.ancestors.pop(),e.schema=s,e.create(t,o,a,n)}function D1(e,t,n){const s={};return mc(s,pc(e,t)),e.create(t,e.Fragment,s,n)}function $1(e,t){return t.value}function um(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function mc(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function M1(e,t,n){return s;function s(i,o,a,l){const u=Array.isArray(a.children)?n:t;return l?u(o,a,l):u(o,a)}}function F1(e,t){return n;function n(s,i,o,a){const l=Array.isArray(o.children),c=hc(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 B1(e,t){const n={};let s,i;for(i in t.properties)if(i!=="children"&&fc.call(t.properties,i)){const o=V1(e,i,t.properties[i]);if(o){const[a,l]=o;e.tableCellAlignToStyle&&a==="align"&&typeof l=="string"&&_1.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 U1(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 Ys(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 Ys(e,t.position);else o=s.value===null?!0:s.value;n[i]=o}return n}function pc(e,t){const n=[];let s=-1;const i=e.passKeys?new Map:I1;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 u=i.get(c)||0;a=c+"-"+u,i.set(c,u+1)}}const l=dm(e,o,a);l!==void 0&&n.push(l)}return n}function V1(e,t,n){const s=g1(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?r1(n):w1(n)),s.property==="style"){let i=typeof n=="object"?n:W1(e,String(n));return e.stylePropertyNameCase==="css"&&(i=H1(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&s.space?f1[s.property]||s.property:s.attribute,n]}}function W1(e,t){try{return C1(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,i=new ot("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=cm+"#cannot-parse-style-attribute",i}}function hm(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=vu(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=vu(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const i=s.value;return fc.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(s);Ys(e)}function Ys(e,t){const n=new ot("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=cm+"#cannot-handle-mdx-estrees-without-createevaluater",n}function H1(e){const t={};let n;for(n in e)fc.call(e,n)&&(t[q1(n)]=e[n]);return t}function q1(e){let t=e.replace(A1,G1);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function G1(e){return"-"+e.toLowerCase()}const sa={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"]},Z1={};function K1(e,t){const n=Z1,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return fm(e,s,i)}function fm(e,t,n){if(Y1(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 _u(e.children,t,n)}return Array.isArray(e)?_u(e,t,n):""}function _u(e,t,n){const s=[];let i=-1;for(;++i<e.length;)s[i]=fm(e[i],t,n);return s.join("")}function Y1(e){return!!(e&&typeof e=="object")}const Pu=document.createElement("i");function gc(e){const t="&"+e+";";Pu.innerHTML=t;const n=Pu.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function zt(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 wt(e,t){return e.length>0?(zt(e,e.length,0,t),e):t}const zu={}.hasOwnProperty;function Q1(e){const t={};let n=-1;for(;++n<e.length;)J1(t,e[n]);return t}function J1(e,t){let n;for(n in t){const i=(zu.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let a;if(o)for(a in o){zu.call(i,a)||(i[a]=[]);const l=o[a];X1(i[a],Array.isArray(l)?l:l?[l]:[])}}}function X1(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);zt(e,0,0,s)}function mm(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 Vn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const _t=sn(/[A-Za-z]/),xt=sn(/[\dA-Za-z]/),ek=sn(/[#-'*+\--9=?A-Z^-~]/);function ml(e){return e!==null&&(e<32||e===127)}const pl=sn(/\d/),tk=sn(/[\dA-Fa-f]/),nk=sn(/[!-/:-@[-`{-~]/);function Ce(e){return e!==null&&e<-2}function ct(e){return e!==null&&(e<0||e===32)}function Le(e){return e===-2||e===-1||e===32}const sk=sn(/\p{P}|\p{S}/u),rk=sn(/\s/);function sn(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function es(e){const t=[];let n=-1,s=0,i=0;for(;++n<e.length;){const o=e.charCodeAt(n);let a="";if(o===37&&xt(e.charCodeAt(n+1))&&xt(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 Fe(e,t,n,s){const i=s?s-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(c){return Le(c)?(e.enter(n),l(c)):t(c)}function l(c){return Le(c)&&o++<i?(e.consume(c),l):(e.exit(n),t(c))}}const ik={tokenize:ok};function ok(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"),Fe(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 Ce(l)?(e.consume(l),e.exit("chunkText"),o):(e.consume(l),a)}}const ak={tokenize:lk},Ru={tokenize:ck};function lk(e){const t=this,n=[];let s=0,i,o,a;return l;function l(w){if(s<n.length){const E=n[s];return t.containerState=E[1],e.attempt(E[0].continuation,c,u)(w)}return u(w)}function c(w){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();const E=t.events.length;let N=E,j;for(;N--;)if(t.events[N][0]==="exit"&&t.events[N][1].type==="chunkFlow"){j=t.events[N][1].end;break}g(s);let I=E;for(;I<t.events.length;)t.events[I][1].end={...j},I++;return zt(t.events,N+1,0,t.events.slice(E)),t.events.length=I,u(w)}return l(w)}function u(w){if(s===n.length){if(!i)return m(w);if(i.currentConstruct&&i.currentConstruct.concrete)return y(w);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Ru,d,f)(w)}function d(w){return i&&v(),g(s),m(w)}function f(w){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,y(w)}function m(w){return t.containerState={},e.attempt(Ru,h,y)(w)}function h(w){return s++,n.push([t.currentConstruct,t.containerState]),m(w)}function y(w){if(w===null){i&&v(),g(0),e.consume(w);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),p(w)}function p(w){if(w===null){x(e.exit("chunkFlow"),!0),g(0),e.consume(w);return}return Ce(w)?(e.consume(w),x(e.exit("chunkFlow")),s=0,t.interrupt=void 0,l):(e.consume(w),p)}function x(w,E){const N=t.sliceStream(w);if(E&&N.push(null),w.previous=o,o&&(o.next=w),o=w,i.defineSkip(w.start),i.write(N),t.parser.lazy[w.start.line]){let j=i.events.length;for(;j--;)if(i.events[j][1].start.offset<a&&(!i.events[j][1].end||i.events[j][1].end.offset>a))return;const I=t.events.length;let z=I,$,V;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){if($){V=t.events[z][1].end;break}$=!0}for(g(s),j=I;j<t.events.length;)t.events[j][1].end={...V},j++;zt(t.events,z+1,0,t.events.slice(I)),t.events.length=j}}function g(w){let E=n.length;for(;E-- >w;){const N=n[E];t.containerState=N[1],N[0].exit.call(t,e)}n.length=w}function v(){i.write([null]),o=void 0,i=void 0,t.containerState._closeFlow=void 0}}function ck(e,t,n){return Fe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Lu(e){if(e===null||ct(e)||rk(e))return 1;if(sk(e))return 2}function xc(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 gl={name:"attention",resolveAll:dk,tokenize:uk};function dk(e,t){let n=-1,s,i,o,a,l,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(s=n;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[s][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const f={...e[s][1].end},m={...e[n][1].start};Ou(f,-c),Ou(m,c),a={type:c>1?"strongSequence":"emphasisSequence",start:f,end:{...e[s][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},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},u=[],e[s][1].end.offset-e[s][1].start.offset&&(u=wt(u,[["enter",e[s][1],t],["exit",e[s][1],t]])),u=wt(u,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",o,t]]),u=wt(u,xc(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),u=wt(u,[["exit",o,t],["enter",l,t],["exit",l,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=wt(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,zt(e,s-1,n-s+3,u),n=s+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function uk(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,i=Lu(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 u=e.exit("attentionSequence"),d=Lu(c),f=!d||d===2&&i||n.includes(c),m=!i||i===2&&d||n.includes(s);return u._open=!!(o===42?f:f&&(i||!m)),u._close=!!(o===42?m:m&&(d||!f)),t(c)}}function Ou(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const hk={name:"autolink",tokenize:fk};function fk(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 _t(h)?(e.consume(h),a):h===64?n(h):u(h)}function a(h){return h===43||h===45||h===46||xt(h)?(s=1,l(h)):u(h)}function l(h){return h===58?(e.consume(h),s=0,c):(h===43||h===45||h===46||xt(h))&&s++<32?(e.consume(h),l):(s=0,u(h))}function c(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||ml(h)?n(h):(e.consume(h),c)}function u(h){return h===64?(e.consume(h),d):ek(h)?(e.consume(h),u):n(h)}function d(h){return xt(h)?f(h):n(h)}function f(h){return h===46?(e.consume(h),s=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):m(h)}function m(h){if((h===45||xt(h))&&s++<63){const y=h===45?m:f;return e.consume(h),y}return n(h)}}const Li={partial:!0,tokenize:mk};function mk(e,t,n){return s;function s(o){return Le(o)?Fe(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||Ce(o)?t(o):n(o)}}const pm={continuation:{tokenize:gk},exit:xk,name:"blockQuote",tokenize:pk};function pk(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 Le(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function gk(e,t,n){const s=this;return i;function i(a){return Le(a)?Fe(e,o,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):o(a)}function o(a){return e.attempt(pm,t,n)(a)}}function xk(e){e.exit("blockQuote")}const gm={name:"characterEscape",tokenize:bk};function bk(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 nk(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const xm={name:"characterReference",tokenize:yk};function yk(e,t,n){const s=this;let i=0,o,a;return l;function l(f){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),c}function c(f){return f===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(f),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,a=xt,d(f))}function u(f){return f===88||f===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(f),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,a=tk,d):(e.enter("characterReferenceValue"),o=7,a=pl,d(f))}function d(f){if(f===59&&i){const m=e.exit("characterReferenceValue");return a===xt&&!gc(s.sliceSerialize(m))?n(f):(e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(f)&&i++<o?(e.consume(f),d):n(f)}}const Du={partial:!0,tokenize:vk},$u={concrete:!0,name:"codeFenced",tokenize:wk};function wk(e,t,n){const s=this,i={partial:!0,tokenize:N};let o=0,a=0,l;return c;function c(j){return u(j)}function u(j){const I=s.events[s.events.length-1];return o=I&&I[1].type==="linePrefix"?I[2].sliceSerialize(I[1],!0).length:0,l=j,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(j)}function d(j){return j===l?(a++,e.consume(j),d):a<3?n(j):(e.exit("codeFencedFenceSequence"),Le(j)?Fe(e,f,"whitespace")(j):f(j))}function f(j){return j===null||Ce(j)?(e.exit("codeFencedFence"),s.interrupt?t(j):e.check(Du,p,E)(j)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(j))}function m(j){return j===null||Ce(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),f(j)):Le(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Fe(e,h,"whitespace")(j)):j===96&&j===l?n(j):(e.consume(j),m)}function h(j){return j===null||Ce(j)?f(j):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),y(j))}function y(j){return j===null||Ce(j)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),f(j)):j===96&&j===l?n(j):(e.consume(j),y)}function p(j){return e.attempt(i,E,x)(j)}function x(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),g}function g(j){return o>0&&Le(j)?Fe(e,v,"linePrefix",o+1)(j):v(j)}function v(j){return j===null||Ce(j)?e.check(Du,p,E)(j):(e.enter("codeFlowValue"),w(j))}function w(j){return j===null||Ce(j)?(e.exit("codeFlowValue"),v(j)):(e.consume(j),w)}function E(j){return e.exit("codeFenced"),t(j)}function N(j,I,z){let $=0;return V;function V(F){return j.enter("lineEnding"),j.consume(F),j.exit("lineEnding"),B}function B(F){return j.enter("codeFencedFence"),Le(F)?Fe(j,_,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):_(F)}function _(F){return F===l?(j.enter("codeFencedFenceSequence"),U(F)):z(F)}function U(F){return F===l?($++,j.consume(F),U):$>=a?(j.exit("codeFencedFenceSequence"),Le(F)?Fe(j,k,"whitespace")(F):k(F)):z(F)}function k(F){return F===null||Ce(F)?(j.exit("codeFencedFence"),I(F)):z(F)}}}function vk(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 ra={name:"codeIndented",tokenize:kk},Sk={partial:!0,tokenize:jk};function kk(e,t,n){const s=this;return i;function i(u){return e.enter("codeIndented"),Fe(e,o,"linePrefix",5)(u)}function o(u){const d=s.events[s.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?c(u):Ce(u)?e.attempt(Sk,a,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||Ce(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function jk(e,t,n){const s=this;return i;function i(a){return s.parser.lazy[s.now().line]?n(a):Ce(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):Fe(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):Ce(a)?i(a):n(a)}}const Nk={name:"codeText",previous:Ek,resolve:Ck,tokenize:Ik};function Ck(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 Ek(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Ik(e,t,n){let s=0,i,o;return a;function a(f){return e.enter("codeText"),e.enter("codeTextSequence"),l(f)}function l(f){return f===96?(e.consume(f),s++,l):(e.exit("codeTextSequence"),c(f))}function c(f){return f===null?n(f):f===32?(e.enter("space"),e.consume(f),e.exit("space"),c):f===96?(o=e.enter("codeTextSequence"),i=0,d(f)):Ce(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(f))}function u(f){return f===null||f===32||f===96||Ce(f)?(e.exit("codeTextData"),c(f)):(e.consume(f),u)}function d(f){return f===96?(e.consume(f),i++,d):i===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(f)):(o.type="codeTextData",u(f))}}class Ak{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&&As(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),As(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),As(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);As(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);As(this.left,n.reverse())}}}function As(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 bm(e){const t={};let n=-1,s,i,o,a,l,c,u;const d=new Ak(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(s=d.get(n),n&&s[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=s[1]._tokenizer.events,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,Tk(d,n)),n=t[n],u=!0);else if(s[1]._container){for(o=n,i=void 0;o--;)if(a=d.get(o),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(d.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={...d.get(i)[1].start},l=d.slice(i,n),l.unshift(s),d.splice(i,n-i+1,l))}}return zt(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Tk(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=[],u={};let d,f,m=-1,h=n,y=0,p=0;const x=[p];for(;h;){for(;e.get(++i)[1]!==h;);o.push(i),h._tokenizer||(d=s.sliceStream(h),h.next||d.push(null),f&&a.defineSkip(h.start),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),h._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),f=h,h=h.next}for(h=n;++m<l.length;)l[m][0]==="exit"&&l[m-1][0]==="enter"&&l[m][1].type===l[m-1][1].type&&l[m][1].start.line!==l[m][1].end.line&&(p=m+1,x.push(p),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(a.events=[],h?(h._tokenizer=void 0,h.previous=void 0):x.pop(),m=x.length;m--;){const g=l.slice(x[m],x[m+1]),v=o.pop();c.push([v,v+g.length-1]),e.splice(v,2,g)}for(c.reverse(),m=-1;++m<c.length;)u[y+c[m][0]]=y+c[m][1],y+=c[m][1]-c[m][0]-1;return u}const _k={resolve:zk,tokenize:Rk},Pk={partial:!0,tokenize:Lk};function zk(e){return bm(e),e}function Rk(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):Ce(l)?e.check(Pk,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 Lk(e,t,n){const s=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Fe(e,o,"linePrefix")}function o(a){if(a===null||Ce(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 ym(e,t,n,s,i,o,a,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return f;function f(g){return g===60?(e.enter(s),e.enter(i),e.enter(o),e.consume(g),e.exit(o),m):g===null||g===32||g===41||ml(g)?n(g):(e.enter(s),e.enter(a),e.enter(l),e.enter("chunkString",{contentType:"string"}),p(g))}function m(g){return g===62?(e.enter(o),e.consume(g),e.exit(o),e.exit(i),e.exit(s),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),h(g))}function h(g){return g===62?(e.exit("chunkString"),e.exit(l),m(g)):g===null||g===60||Ce(g)?n(g):(e.consume(g),g===92?y:h)}function y(g){return g===60||g===62||g===92?(e.consume(g),h):h(g)}function p(g){return!d&&(g===null||g===41||ct(g))?(e.exit("chunkString"),e.exit(l),e.exit(a),e.exit(s),t(g)):d<u&&g===40?(e.consume(g),d++,p):g===41?(e.consume(g),d--,p):g===null||g===32||g===40||ml(g)?n(g):(e.consume(g),g===92?x:p)}function x(g){return g===40||g===41||g===92?(e.consume(g),p):p(g)}}function wm(e,t,n,s,i,o){const a=this;let l=0,c;return u;function u(h){return e.enter(s),e.enter(i),e.consume(h),e.exit(i),e.enter(o),d}function d(h){return l>999||h===null||h===91||h===93&&!c||h===94&&!l&&"_hiddenFootnoteSupport"in a.parser.constructs?n(h):h===93?(e.exit(o),e.enter(i),e.consume(h),e.exit(i),e.exit(s),t):Ce(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),f(h))}function f(h){return h===null||h===91||h===93||Ce(h)||l++>999?(e.exit("chunkString"),d(h)):(e.consume(h),c||(c=!Le(h)),h===92?m:f)}function m(h){return h===91||h===92||h===93?(e.consume(h),l++,f):f(h)}}function vm(e,t,n,s,i,o){let a;return l;function l(m){return m===34||m===39||m===40?(e.enter(s),e.enter(i),e.consume(m),e.exit(i),a=m===40?41:m,c):n(m)}function c(m){return m===a?(e.enter(i),e.consume(m),e.exit(i),e.exit(s),t):(e.enter(o),u(m))}function u(m){return m===a?(e.exit(o),c(a)):m===null?n(m):Ce(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),Fe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===a||m===null||Ce(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?f:d)}function f(m){return m===a||m===92?(e.consume(m),d):d(m)}}function Us(e,t){let n;return s;function s(i){return Ce(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,s):Le(i)?Fe(e,s,n?"linePrefix":"lineSuffix")(i):t(i)}}const Ok={name:"definition",tokenize:$k},Dk={partial:!0,tokenize:Mk};function $k(e,t,n){const s=this;let i;return o;function o(h){return e.enter("definition"),a(h)}function a(h){return wm.call(s,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function l(h){return i=Vn(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 ct(h)?Us(e,u)(h):u(h)}function u(h){return ym(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(Dk,f,f)(h)}function f(h){return Le(h)?Fe(e,m,"whitespace")(h):m(h)}function m(h){return h===null||Ce(h)?(e.exit("definition"),s.parser.defined.push(i),t(h)):n(h)}}function Mk(e,t,n){return s;function s(l){return ct(l)?Us(e,i)(l):n(l)}function i(l){return vm(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function o(l){return Le(l)?Fe(e,a,"whitespace")(l):a(l)}function a(l){return l===null||Ce(l)?t(l):n(l)}}const Fk={name:"hardBreakEscape",tokenize:Bk};function Bk(e,t,n){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),i}function i(o){return Ce(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const Uk={name:"headingAtx",resolve:Vk,tokenize:Wk};function Vk(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"},zt(e,s,n-s+1,[["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t]])),e}function Wk(e,t,n){let s=0;return i;function i(d){return e.enter("atxHeading"),o(d)}function o(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&s++<6?(e.consume(d),a):d===null||ct(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||Ce(d)?(e.exit("atxHeading"),t(d)):Le(d)?Fe(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||ct(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const Hk=["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"],Mu=["pre","script","style","textarea"],qk={concrete:!0,name:"htmlFlow",resolveTo:Kk,tokenize:Yk},Gk={partial:!0,tokenize:Jk},Zk={partial:!0,tokenize:Qk};function Kk(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 Yk(e,t,n){const s=this;let i,o,a,l,c;return u;function u(P){return d(P)}function d(P){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(P),f}function f(P){return P===33?(e.consume(P),m):P===47?(e.consume(P),o=!0,p):P===63?(e.consume(P),i=3,s.interrupt?t:S):_t(P)?(e.consume(P),a=String.fromCharCode(P),x):n(P)}function m(P){return P===45?(e.consume(P),i=2,h):P===91?(e.consume(P),i=5,l=0,y):_t(P)?(e.consume(P),i=4,s.interrupt?t:S):n(P)}function h(P){return P===45?(e.consume(P),s.interrupt?t:S):n(P)}function y(P){const Y="CDATA[";return P===Y.charCodeAt(l++)?(e.consume(P),l===Y.length?s.interrupt?t:_:y):n(P)}function p(P){return _t(P)?(e.consume(P),a=String.fromCharCode(P),x):n(P)}function x(P){if(P===null||P===47||P===62||ct(P)){const Y=P===47,H=a.toLowerCase();return!Y&&!o&&Mu.includes(H)?(i=1,s.interrupt?t(P):_(P)):Hk.includes(a.toLowerCase())?(i=6,Y?(e.consume(P),g):s.interrupt?t(P):_(P)):(i=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(P):o?v(P):w(P))}return P===45||xt(P)?(e.consume(P),a+=String.fromCharCode(P),x):n(P)}function g(P){return P===62?(e.consume(P),s.interrupt?t:_):n(P)}function v(P){return Le(P)?(e.consume(P),v):V(P)}function w(P){return P===47?(e.consume(P),V):P===58||P===95||_t(P)?(e.consume(P),E):Le(P)?(e.consume(P),w):V(P)}function E(P){return P===45||P===46||P===58||P===95||xt(P)?(e.consume(P),E):N(P)}function N(P){return P===61?(e.consume(P),j):Le(P)?(e.consume(P),N):w(P)}function j(P){return P===null||P===60||P===61||P===62||P===96?n(P):P===34||P===39?(e.consume(P),c=P,I):Le(P)?(e.consume(P),j):z(P)}function I(P){return P===c?(e.consume(P),c=null,$):P===null||Ce(P)?n(P):(e.consume(P),I)}function z(P){return P===null||P===34||P===39||P===47||P===60||P===61||P===62||P===96||ct(P)?N(P):(e.consume(P),z)}function $(P){return P===47||P===62||Le(P)?w(P):n(P)}function V(P){return P===62?(e.consume(P),B):n(P)}function B(P){return P===null||Ce(P)?_(P):Le(P)?(e.consume(P),B):n(P)}function _(P){return P===45&&i===2?(e.consume(P),Z):P===60&&i===1?(e.consume(P),M):P===62&&i===4?(e.consume(P),R):P===63&&i===3?(e.consume(P),S):P===93&&i===5?(e.consume(P),L):Ce(P)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Gk,D,U)(P)):P===null||Ce(P)?(e.exit("htmlFlowData"),U(P)):(e.consume(P),_)}function U(P){return e.check(Zk,k,D)(P)}function k(P){return e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),F}function F(P){return P===null||Ce(P)?U(P):(e.enter("htmlFlowData"),_(P))}function Z(P){return P===45?(e.consume(P),S):_(P)}function M(P){return P===47?(e.consume(P),a="",A):_(P)}function A(P){if(P===62){const Y=a.toLowerCase();return Mu.includes(Y)?(e.consume(P),R):_(P)}return _t(P)&&a.length<8?(e.consume(P),a+=String.fromCharCode(P),A):_(P)}function L(P){return P===93?(e.consume(P),S):_(P)}function S(P){return P===62?(e.consume(P),R):P===45&&i===2?(e.consume(P),S):_(P)}function R(P){return P===null||Ce(P)?(e.exit("htmlFlowData"),D(P)):(e.consume(P),R)}function D(P){return e.exit("htmlFlow"),t(P)}}function Qk(e,t,n){const s=this;return i;function i(a){return Ce(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 Jk(e,t,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Li,t,n)}}const Xk={name:"htmlText",tokenize:ej};function ej(e,t,n){const s=this;let i,o,a;return l;function l(S){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(S),c}function c(S){return S===33?(e.consume(S),u):S===47?(e.consume(S),N):S===63?(e.consume(S),w):_t(S)?(e.consume(S),z):n(S)}function u(S){return S===45?(e.consume(S),d):S===91?(e.consume(S),o=0,y):_t(S)?(e.consume(S),v):n(S)}function d(S){return S===45?(e.consume(S),h):n(S)}function f(S){return S===null?n(S):S===45?(e.consume(S),m):Ce(S)?(a=f,M(S)):(e.consume(S),f)}function m(S){return S===45?(e.consume(S),h):f(S)}function h(S){return S===62?Z(S):S===45?m(S):f(S)}function y(S){const R="CDATA[";return S===R.charCodeAt(o++)?(e.consume(S),o===R.length?p:y):n(S)}function p(S){return S===null?n(S):S===93?(e.consume(S),x):Ce(S)?(a=p,M(S)):(e.consume(S),p)}function x(S){return S===93?(e.consume(S),g):p(S)}function g(S){return S===62?Z(S):S===93?(e.consume(S),g):p(S)}function v(S){return S===null||S===62?Z(S):Ce(S)?(a=v,M(S)):(e.consume(S),v)}function w(S){return S===null?n(S):S===63?(e.consume(S),E):Ce(S)?(a=w,M(S)):(e.consume(S),w)}function E(S){return S===62?Z(S):w(S)}function N(S){return _t(S)?(e.consume(S),j):n(S)}function j(S){return S===45||xt(S)?(e.consume(S),j):I(S)}function I(S){return Ce(S)?(a=I,M(S)):Le(S)?(e.consume(S),I):Z(S)}function z(S){return S===45||xt(S)?(e.consume(S),z):S===47||S===62||ct(S)?$(S):n(S)}function $(S){return S===47?(e.consume(S),Z):S===58||S===95||_t(S)?(e.consume(S),V):Ce(S)?(a=$,M(S)):Le(S)?(e.consume(S),$):Z(S)}function V(S){return S===45||S===46||S===58||S===95||xt(S)?(e.consume(S),V):B(S)}function B(S){return S===61?(e.consume(S),_):Ce(S)?(a=B,M(S)):Le(S)?(e.consume(S),B):$(S)}function _(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),i=S,U):Ce(S)?(a=_,M(S)):Le(S)?(e.consume(S),_):(e.consume(S),k)}function U(S){return S===i?(e.consume(S),i=void 0,F):S===null?n(S):Ce(S)?(a=U,M(S)):(e.consume(S),U)}function k(S){return S===null||S===34||S===39||S===60||S===61||S===96?n(S):S===47||S===62||ct(S)?$(S):(e.consume(S),k)}function F(S){return S===47||S===62||ct(S)?$(S):n(S)}function Z(S){return S===62?(e.consume(S),e.exit("htmlTextData"),e.exit("htmlText"),t):n(S)}function M(S){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),A}function A(S){return Le(S)?Fe(e,L,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):L(S)}function L(S){return e.enter("htmlTextData"),a(S)}}const bc={name:"labelEnd",resolveAll:rj,resolveTo:ij,tokenize:oj},tj={tokenize:aj},nj={tokenize:lj},sj={tokenize:cj};function rj(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&&zt(e,0,e.length,n),e}function ij(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}},u={type:"label",start:{...e[o][1].start},end:{...e[a][1].end}},d={type:"labelText",start:{...e[o+s+2][1].end},end:{...e[a-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=wt(l,e.slice(o+1,o+s+3)),l=wt(l,[["enter",d,t]]),l=wt(l,xc(t.parser.constructs.insideSpan.null,e.slice(o+s+4,a-3),t)),l=wt(l,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),l=wt(l,e.slice(a+1)),l=wt(l,[["exit",c,t]]),zt(e,o,e.length,l),e}function oj(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(m){return o?o._inactive?f(m):(a=s.parser.defined.includes(Vn(s.sliceSerialize({start:o.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):n(m)}function c(m){return m===40?e.attempt(tj,d,a?d:f)(m):m===91?e.attempt(nj,d,a?u:f)(m):a?d(m):f(m)}function u(m){return e.attempt(sj,d,f)(m)}function d(m){return t(m)}function f(m){return o._balanced=!0,n(m)}}function aj(e,t,n){return s;function s(f){return e.enter("resource"),e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),i}function i(f){return ct(f)?Us(e,o)(f):o(f)}function o(f){return f===41?d(f):ym(e,a,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function a(f){return ct(f)?Us(e,c)(f):d(f)}function l(f){return n(f)}function c(f){return f===34||f===39||f===40?vm(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):d(f)}function u(f){return ct(f)?Us(e,d)(f):d(f)}function d(f){return f===41?(e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),e.exit("resource"),t):n(f)}}function lj(e,t,n){const s=this;return i;function i(l){return wm.call(s,e,o,a,"reference","referenceMarker","referenceString")(l)}function o(l){return s.parser.defined.includes(Vn(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function a(l){return n(l)}}function cj(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 dj={name:"labelStartImage",resolveAll:bc.resolveAll,tokenize:uj};function uj(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 hj={name:"labelStartLink",resolveAll:bc.resolveAll,tokenize:fj};function fj(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 ia={name:"lineEnding",tokenize:mj};function mj(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Fe(e,t,"linePrefix")}}const Kr={name:"thematicBreak",tokenize:pj};function pj(e,t,n){let s=0,i;return o;function o(u){return e.enter("thematicBreak"),a(u)}function a(u){return i=u,l(u)}function l(u){return u===i?(e.enter("thematicBreakSequence"),c(u)):s>=3&&(u===null||Ce(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===i?(e.consume(u),s++,c):(e.exit("thematicBreakSequence"),Le(u)?Fe(e,l,"whitespace")(u):l(u))}}const lt={continuation:{tokenize:yj},exit:vj,name:"list",tokenize:bj},gj={partial:!0,tokenize:Sj},xj={partial:!0,tokenize:wj};function bj(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 y=s.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!s.containerState.marker||h===s.containerState.marker:pl(h)){if(s.containerState.type||(s.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(Kr,n,u)(h):u(h);if(!s.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(h)}return n(h)}function c(h){return pl(h)&&++a<10?(e.consume(h),c):(!s.interrupt||a<2)&&(s.containerState.marker?h===s.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||h,e.check(Li,s.interrupt?n:d,e.attempt(gj,m,f))}function d(h){return s.containerState.initialBlankLine=!0,o++,m(h)}function f(h){return Le(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),m):n(h)}function m(h){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function yj(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Li,i,o);function i(l){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Fe(e,t,"listItemIndent",s.containerState.size+1)(l)}function o(l){return s.containerState.furtherBlankLines||!Le(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(xj,t,a)(l))}function a(l){return s.containerState._closeFlow=!0,s.interrupt=void 0,Fe(e,e.attempt(lt,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function wj(e,t,n){const s=this;return Fe(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 vj(e){e.exit(this.containerState.type)}function Sj(e,t,n){const s=this;return Fe(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!Le(o)&&a&&a[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const Fu={name:"setextUnderline",resolveTo:kj,tokenize:jj};function kj(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 jj(e,t,n){const s=this;let i;return o;function o(u){let d=s.events.length,f;for(;d--;)if(s.events[d][1].type!=="lineEnding"&&s.events[d][1].type!=="linePrefix"&&s.events[d][1].type!=="content"){f=s.events[d][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||f)?(e.enter("setextHeadingLine"),i=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===i?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),Le(u)?Fe(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||Ce(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Nj={tokenize:Cj};function Cj(e){const t=this,n=e.attempt(Li,s,e.attempt(this.parser.constructs.flowInitial,i,Fe(e,e.attempt(this.parser.constructs.flow,i,e.attempt(_k,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 Ej={resolveAll:km()},Ij=Sm("string"),Aj=Sm("text");function Sm(e){return{resolveAll:km(e==="text"?Tj: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(d){return u(d)?o(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),o(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const f=i[d];let m=-1;if(f)for(;++m<f.length;){const h=f[m];if(!h.previous||h.previous.call(s,s.previous))return!0}return!1}}}function km(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 Tj(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 u=i[o];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)l++,a--;if(a)break;a=-1}else if(u===-2)c=!0,l++;else if(u!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const u={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={...u.start},s.start.offset===s.end.offset?Object.assign(s,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const _j={42:lt,43:lt,45:lt,48:lt,49:lt,50:lt,51:lt,52:lt,53:lt,54:lt,55:lt,56:lt,57:lt,62:pm},Pj={91:Ok},zj={[-2]:ra,[-1]:ra,32:ra},Rj={35:Uk,42:Kr,45:[Fu,Kr],60:qk,61:Fu,95:Kr,96:$u,126:$u},Lj={38:xm,92:gm},Oj={[-5]:ia,[-4]:ia,[-3]:ia,33:dj,38:xm,42:gl,60:[hk,Xk],91:hj,92:[Fk,gm],93:bc,95:gl,96:Nk},Dj={null:[gl,Ej]},$j={null:[42,95]},Mj={null:[]},Fj=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:$j,contentInitial:Pj,disable:Mj,document:_j,flow:Rj,flowInitial:zj,insideSpan:Dj,string:Lj,text:Oj},Symbol.toStringTag,{value:"Module"}));function Bj(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:I(N),check:I(j),consume:v,enter:w,exit:E,interrupt:I(j,{interrupt:!0})},u={code:null,containerState:{},defineSkip:p,events:[],now:y,parser:e,previous:null,sliceSerialize:m,sliceStream:h,write:f};let d=t.tokenize.call(u,c);return t.resolveAll&&o.push(t),u;function f(B){return a=wt(a,B),x(),a[a.length-1]!==null?[]:(z(t,0),u.events=xc(o,u.events,u),u.events)}function m(B,_){return Vj(h(B),_)}function h(B){return Uj(a,B)}function y(){const{_bufferIndex:B,_index:_,line:U,column:k,offset:F}=s;return{_bufferIndex:B,_index:_,line:U,column:k,offset:F}}function p(B){i[B.line]=B.column,V()}function x(){let B;for(;s._index<a.length;){const _=a[s._index];if(typeof _=="string")for(B=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===B&&s._bufferIndex<_.length;)g(_.charCodeAt(s._bufferIndex));else g(_)}}function g(B){d=d(B)}function v(B){Ce(B)?(s.line++,s.column=1,s.offset+=B===-3?2:1,V()):B!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===a[s._index].length&&(s._bufferIndex=-1,s._index++)),u.previous=B}function w(B,_){const U=_||{};return U.type=B,U.start=y(),u.events.push(["enter",U,u]),l.push(U),U}function E(B){const _=l.pop();return _.end=y(),u.events.push(["exit",_,u]),_}function N(B,_){z(B,_.from)}function j(B,_){_.restore()}function I(B,_){return U;function U(k,F,Z){let M,A,L,S;return Array.isArray(k)?D(k):"tokenize"in k?D([k]):R(k);function R(ee){return le;function le(ae){const fe=ae!==null&&ee[ae],be=ae!==null&&ee.null,ye=[...Array.isArray(fe)?fe:fe?[fe]:[],...Array.isArray(be)?be:be?[be]:[]];return D(ye)(ae)}}function D(ee){return M=ee,A=0,ee.length===0?Z:P(ee[A])}function P(ee){return le;function le(ae){return S=$(),L=ee,ee.partial||(u.currentConstruct=ee),ee.name&&u.parser.constructs.disable.null.includes(ee.name)?H():ee.tokenize.call(_?Object.assign(Object.create(u),_):u,c,Y,H)(ae)}}function Y(ee){return B(L,S),F}function H(ee){return S.restore(),++A<M.length?P(M[A]):Z}}}function z(B,_){B.resolveAll&&!o.includes(B)&&o.push(B),B.resolve&&zt(u.events,_,u.events.length-_,B.resolve(u.events.slice(_),u)),B.resolveTo&&(u.events=B.resolveTo(u.events,u))}function $(){const B=y(),_=u.previous,U=u.currentConstruct,k=u.events.length,F=Array.from(l);return{from:k,restore:Z};function Z(){s=B,u.previous=_,u.currentConstruct=U,u.events.length=k,l=F,V()}}function V(){s.line in i&&s.column<2&&(s.column=i[s.line],s.offset+=i[s.line]-1)}}function Uj(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 Vj(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=`
|
|
37
|
+
`;break}case-3:{a=`\r
|
|
38
|
+
`;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 Wj(e){const s={constructs:Q1([Fj,...(e||{}).extensions||[]]),content:i(ik),defined:[],document:i(ak),flow:i(Nj),lazy:{},string:i(Ij),text:i(Aj)};return s;function i(o){return a;function a(l){return Bj(s,o,l)}}}function Hj(e){for(;!bm(e););return e}const Bu=/[\0\t\n\r]/g;function qj(){let e=1,t="",n=!0,s;return i;function i(o,a,l){const c=[];let u,d,f,m,h;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),f=0,t="",n&&(o.charCodeAt(0)===65279&&f++,n=void 0);f<o.length;){if(Bu.lastIndex=f,u=Bu.exec(o),m=u&&u.index!==void 0?u.index:o.length,h=o.charCodeAt(m),!u){t=o.slice(f);break}if(h===10&&f===m&&s)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),f<m&&(c.push(o.slice(f,m)),e+=m-f),h){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:s=!0,e=1}f=m+1}return l&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const Gj=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Zj(e){return e.replace(Gj,Kj)}function Kj(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),o=i===120||i===88;return mm(n.slice(o?2:1),o?16:10)}return gc(n)||e}const jm={}.hasOwnProperty;function Yj(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),Qj(n)(Hj(Wj(n).document().write(qj()(e,t,!0))))}function Qj(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(q),autolinkProtocol:$,autolinkEmail:$,atxHeading:o(J),blockQuote:o(be),characterEscape:$,characterReference:$,codeFenced:o(ye),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(ye,a),codeText:o(Se,a),codeTextData:$,data:$,codeFlowValue:$,definition:o(me),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(C),hardBreakEscape:o(se),hardBreakTrailing:o(se),htmlFlow:o(W,a),htmlFlowData:$,htmlText:o(W,a),htmlTextData:$,image:o(T),label:a,link:o(q),listItem:o(ne),listItemValue:m,listOrdered:o(X,f),listUnordered:o(X),paragraph:o(Q),reference:P,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(J),strong:o(re),thematicBreak:o(te)},exit:{atxHeading:c(),atxHeadingSequence:N,autolink:c(),autolinkEmail:fe,autolinkProtocol:ae,blockQuote:c(),characterEscapeValue:V,characterReferenceMarkerHexadecimal:H,characterReferenceMarkerNumeric:H,characterReferenceValue:ee,characterReference:le,codeFenced:c(x),codeFencedFence:p,codeFencedFenceInfo:h,codeFencedFenceMeta:y,codeFlowValue:V,codeIndented:c(g),codeText:c(F),codeTextData:V,data:V,definition:c(),definitionDestinationString:E,definitionLabelString:v,definitionTitleString:w,emphasis:c(),hardBreakEscape:c(_),hardBreakTrailing:c(_),htmlFlow:c(U),htmlFlowData:V,htmlText:c(k),htmlTextData:V,image:c(M),label:L,labelText:A,lineEnding:B,link:c(Z),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:Y,resourceDestinationString:S,resourceTitleString:R,resource:D,setextHeading:c(z),setextHeadingLineSequence:I,setextHeadingText:j,strong:c(),thematicBreak:c()}};Nm(t,(e||{}).mdastExtensions||[]);const n={};return s;function s(O){let G={type:"root",children:[]};const ie={stack:[G],tokenStack:[],config:t,enter:l,exit:u,buffer:a,resume:d,data:n},ue=[];let he=-1;for(;++he<O.length;)if(O[he][1].type==="listOrdered"||O[he][1].type==="listUnordered")if(O[he][0]==="enter")ue.push(he);else{const K=ue.pop();he=i(O,K,he)}for(he=-1;++he<O.length;){const K=t[O[he][0]];jm.call(K,O[he][1].type)&&K[O[he][1].type].call(Object.assign({sliceSerialize:O[he][2].sliceSerialize},ie),O[he][1])}if(ie.tokenStack.length>0){const K=ie.tokenStack[ie.tokenStack.length-1];(K[1]||Uu).call(ie,void 0,K[0])}for(G.position={start:Kt(O.length>0?O[0][1].start:{line:1,column:1,offset:0}),end:Kt(O.length>0?O[O.length-2][1].end:{line:1,column:1,offset:0})},he=-1;++he<t.transforms.length;)G=t.transforms[he](G)||G;return G}function i(O,G,ie){let ue=G-1,he=-1,K=!1,we,oe,ce,pe;for(;++ue<=ie;){const xe=O[ue];switch(xe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{xe[0]==="enter"?he++:he--,pe=void 0;break}case"lineEndingBlank":{xe[0]==="enter"&&(we&&!pe&&!he&&!ce&&(ce=ue),pe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:pe=void 0}if(!he&&xe[0]==="enter"&&xe[1].type==="listItemPrefix"||he===-1&&xe[0]==="exit"&&(xe[1].type==="listUnordered"||xe[1].type==="listOrdered")){if(we){let ve=ue;for(oe=void 0;ve--;){const _e=O[ve];if(_e[1].type==="lineEnding"||_e[1].type==="lineEndingBlank"){if(_e[0]==="exit")continue;oe&&(O[oe][1].type="lineEndingBlank",K=!0),_e[1].type="lineEnding",oe=ve}else if(!(_e[1].type==="linePrefix"||_e[1].type==="blockQuotePrefix"||_e[1].type==="blockQuotePrefixWhitespace"||_e[1].type==="blockQuoteMarker"||_e[1].type==="listItemIndent"))break}ce&&(!oe||ce<oe)&&(we._spread=!0),we.end=Object.assign({},oe?O[oe][1].start:xe[1].end),O.splice(oe||ue,0,["exit",we,xe[2]]),ue++,ie++}if(xe[1].type==="listItemPrefix"){const ve={type:"listItem",_spread:!1,start:Object.assign({},xe[1].start),end:void 0};we=ve,O.splice(ue,0,["enter",ve,xe[2]]),ue++,ie++,ce=void 0,pe=!0}}}return O[G][1]._spread=K,ie}function o(O,G){return ie;function ie(ue){l.call(this,O(ue),ue),G&&G.call(this,ue)}}function a(){this.stack.push({type:"fragment",children:[]})}function l(O,G,ie){this.stack[this.stack.length-1].children.push(O),this.stack.push(O),this.tokenStack.push([G,ie||void 0]),O.position={start:Kt(G.start),end:void 0}}function c(O){return G;function G(ie){O&&O.call(this,ie),u.call(this,ie)}}function u(O,G){const ie=this.stack.pop(),ue=this.tokenStack.pop();if(ue)ue[0].type!==O.type&&(G?G.call(this,O,ue[0]):(ue[1]||Uu).call(this,O,ue[0]));else throw new Error("Cannot close `"+O.type+"` ("+Bs({start:O.start,end:O.end})+"): it’s not open");ie.position.end=Kt(O.end)}function d(){return K1(this.stack.pop())}function f(){this.data.expectingFirstListItemValue=!0}function m(O){if(this.data.expectingFirstListItemValue){const G=this.stack[this.stack.length-2];G.start=Number.parseInt(this.sliceSerialize(O),10),this.data.expectingFirstListItemValue=void 0}}function h(){const O=this.resume(),G=this.stack[this.stack.length-1];G.lang=O}function y(){const O=this.resume(),G=this.stack[this.stack.length-1];G.meta=O}function p(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const O=this.resume(),G=this.stack[this.stack.length-1];G.value=O.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){const O=this.resume(),G=this.stack[this.stack.length-1];G.value=O.replace(/(\r?\n|\r)$/g,"")}function v(O){const G=this.resume(),ie=this.stack[this.stack.length-1];ie.label=G,ie.identifier=Vn(this.sliceSerialize(O)).toLowerCase()}function w(){const O=this.resume(),G=this.stack[this.stack.length-1];G.title=O}function E(){const O=this.resume(),G=this.stack[this.stack.length-1];G.url=O}function N(O){const G=this.stack[this.stack.length-1];if(!G.depth){const ie=this.sliceSerialize(O).length;G.depth=ie}}function j(){this.data.setextHeadingSlurpLineEnding=!0}function I(O){const G=this.stack[this.stack.length-1];G.depth=this.sliceSerialize(O).codePointAt(0)===61?1:2}function z(){this.data.setextHeadingSlurpLineEnding=void 0}function $(O){const ie=this.stack[this.stack.length-1].children;let ue=ie[ie.length-1];(!ue||ue.type!=="text")&&(ue=de(),ue.position={start:Kt(O.start),end:void 0},ie.push(ue)),this.stack.push(ue)}function V(O){const G=this.stack.pop();G.value+=this.sliceSerialize(O),G.position.end=Kt(O.end)}function B(O){const G=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ie=G.children[G.children.length-1];ie.position.end=Kt(O.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(G.type)&&($.call(this,O),V.call(this,O))}function _(){this.data.atHardBreak=!0}function U(){const O=this.resume(),G=this.stack[this.stack.length-1];G.value=O}function k(){const O=this.resume(),G=this.stack[this.stack.length-1];G.value=O}function F(){const O=this.resume(),G=this.stack[this.stack.length-1];G.value=O}function Z(){const O=this.stack[this.stack.length-1];if(this.data.inReference){const G=this.data.referenceType||"shortcut";O.type+="Reference",O.referenceType=G,delete O.url,delete O.title}else delete O.identifier,delete O.label;this.data.referenceType=void 0}function M(){const O=this.stack[this.stack.length-1];if(this.data.inReference){const G=this.data.referenceType||"shortcut";O.type+="Reference",O.referenceType=G,delete O.url,delete O.title}else delete O.identifier,delete O.label;this.data.referenceType=void 0}function A(O){const G=this.sliceSerialize(O),ie=this.stack[this.stack.length-2];ie.label=Zj(G),ie.identifier=Vn(G).toLowerCase()}function L(){const O=this.stack[this.stack.length-1],G=this.resume(),ie=this.stack[this.stack.length-1];if(this.data.inReference=!0,ie.type==="link"){const ue=O.children;ie.children=ue}else ie.alt=G}function S(){const O=this.resume(),G=this.stack[this.stack.length-1];G.url=O}function R(){const O=this.resume(),G=this.stack[this.stack.length-1];G.title=O}function D(){this.data.inReference=void 0}function P(){this.data.referenceType="collapsed"}function Y(O){const G=this.resume(),ie=this.stack[this.stack.length-1];ie.label=G,ie.identifier=Vn(this.sliceSerialize(O)).toLowerCase(),this.data.referenceType="full"}function H(O){this.data.characterReferenceType=O.type}function ee(O){const G=this.sliceSerialize(O),ie=this.data.characterReferenceType;let ue;ie?(ue=mm(G,ie==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ue=gc(G);const he=this.stack[this.stack.length-1];he.value+=ue}function le(O){const G=this.stack.pop();G.position.end=Kt(O.end)}function ae(O){V.call(this,O);const G=this.stack[this.stack.length-1];G.url=this.sliceSerialize(O)}function fe(O){V.call(this,O);const G=this.stack[this.stack.length-1];G.url="mailto:"+this.sliceSerialize(O)}function be(){return{type:"blockquote",children:[]}}function ye(){return{type:"code",lang:null,meta:null,value:""}}function Se(){return{type:"inlineCode",value:""}}function me(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function C(){return{type:"emphasis",children:[]}}function J(){return{type:"heading",depth:0,children:[]}}function se(){return{type:"break"}}function W(){return{type:"html",value:""}}function T(){return{type:"image",title:null,url:"",alt:null}}function q(){return{type:"link",title:null,url:"",children:[]}}function X(O){return{type:"list",ordered:O.type==="listOrdered",start:null,spread:O._spread,children:[]}}function ne(O){return{type:"listItem",spread:O._spread,checked:null,children:[]}}function Q(){return{type:"paragraph",children:[]}}function re(){return{type:"strong",children:[]}}function de(){return{type:"text",value:""}}function te(){return{type:"thematicBreak"}}}function Kt(e){return{line:e.line,column:e.column,offset:e.offset}}function Nm(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Nm(e,s):Jj(e,s)}}function Jj(e,t){let n;for(n in t)if(jm.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 Uu(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 Xj(e){const t=this;t.parser=n;function n(s){return Yj(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function eN(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 tN(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
39
|
+
`}]}function nN(e,t){const n=t.value?t.value+`
|
|
40
|
+
`:"",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 sN(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function rN(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function iN(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),i=es(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 u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function oN(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 aN(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function Cm(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 lN(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return Cm(e,t);const i={src:es(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 cN(e,t){const n={src:es(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 dN(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 uN(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return Cm(e,t);const i={href:es(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 hN(e,t){const n={href:es(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 fN(e,t,n){const s=e.all(t),i=n?mN(n):Em(t),o={},a=[];if(typeof t.checked=="boolean"){const d=s[0];let f;d&&d.type==="element"&&d.tagName==="p"?f=d:(f={type:"element",tagName:"p",properties:{},children:[]},s.unshift(f)),f.children.length>0&&f.children.unshift({type:"text",value:" "}),f.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 d=s[l];(i||l!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
|
|
41
|
+
`}),d.type==="element"&&d.tagName==="p"&&!i?a.push(...d.children):a.push(d)}const c=s[s.length-1];c&&(i||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
|
|
42
|
+
`});const u={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,u),e.applyData(t,u)}function mN(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=Em(n[s])}return t}function Em(e){const t=e.spread;return t??e.children.length>1}function pN(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 gN(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function xN(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function bN(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yN(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=hc(t.children[1]),c=am(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 wN(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 u=[];for(;++c<l;){const f=t.children[c],m={},h=a?a[c]:void 0;h&&(m.align=h);let y={type:"element",tagName:o,properties:m,children:[]};f&&(y.children=e.all(f),e.patch(f,y),y=e.applyData(f,y)),u.push(y)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function vN(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Vu=9,Wu=32;function SN(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),i=0;const o=[];for(;s;)o.push(Hu(t.slice(i,s.index),i>0,!0),s[0]),i=s.index+s[0].length,s=n.exec(t);return o.push(Hu(t.slice(i),i>0,!1)),o.join("")}function Hu(e,t,n){let s=0,i=e.length;if(t){let o=e.codePointAt(s);for(;o===Vu||o===Wu;)s++,o=e.codePointAt(s)}if(n){let o=e.codePointAt(i-1);for(;o===Vu||o===Wu;)i--,o=e.codePointAt(i-1)}return i>s?e.slice(s,i):""}function kN(e,t){const n={type:"text",value:SN(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function jN(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const NN={blockquote:eN,break:tN,code:nN,delete:sN,emphasis:rN,footnoteReference:iN,heading:oN,html:aN,imageReference:lN,image:cN,inlineCode:dN,linkReference:uN,link:hN,listItem:fN,list:pN,paragraph:gN,root:xN,strong:bN,table:yN,tableCell:vN,tableRow:wN,text:kN,thematicBreak:jN,toml:Nr,yaml:Nr,definition:Nr,footnoteDefinition:Nr};function Nr(){}const Im=-1,Oi=0,Vs=1,xi=2,yc=3,wc=4,vc=5,Sc=6,Am=7,Tm=8,CN=typeof self=="object"?self:globalThis,qu=(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 CN[e](t)},EN=(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 Oi:case Im:return n(a,i);case Vs:{const l=n([],i);for(const c of a)l.push(s(c));return l}case xi:{const l=n({},i);for(const[c,u]of a)l[s(c)]=s(u);return l}case yc:return n(new Date(a),i);case wc:{const{source:l,flags:c}=a;return n(new RegExp(l,c),i)}case vc:{const l=n(new Map,i);for(const[c,u]of a)l.set(s(c),s(u));return l}case Sc:{const l=n(new Set,i);for(const c of a)l.add(s(c));return l}case Am:{const{name:l,message:c}=a;return n(qu(l,c),i)}case Tm: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(qu(o,a),i)};return s},Gu=e=>EN(new Map,e)(0),zn="",{toString:IN}={},{keys:AN}=Object,Ts=e=>{const t=typeof e;if(t!=="object"||!e)return[Oi,t];const n=IN.call(e).slice(8,-1);switch(n){case"Array":return[Vs,zn];case"Object":return[xi,zn];case"Date":return[yc,zn];case"RegExp":return[wc,zn];case"Map":return[vc,zn];case"Set":return[Sc,zn];case"DataView":return[Vs,n]}return n.includes("Array")?[Vs,n]:n.includes("Error")?[Am,n]:[xi,n]},Cr=([e,t])=>e===Oi&&(t==="function"||t==="symbol"),TN=(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]=Ts(a);switch(l){case Oi:{let d=a;switch(c){case"bigint":l=Tm,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return i([Im],a)}return i([l,d],a)}case Vs:{if(c){let m=a;return c==="DataView"?m=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(a)),i([c,[...m]],a)}const d=[],f=i([l,d],a);for(const m of a)d.push(o(m));return f}case xi:{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 d=[],f=i([l,d],a);for(const m of AN(a))(e||!Cr(Ts(a[m])))&&d.push([o(m),o(a[m])]);return f}case yc:return i([l,a.toISOString()],a);case wc:{const{source:d,flags:f}=a;return i([l,{source:d,flags:f}],a)}case vc:{const d=[],f=i([l,d],a);for(const[m,h]of a)(e||!(Cr(Ts(m))||Cr(Ts(h))))&&d.push([o(m),o(h)]);return f}case Sc:{const d=[],f=i([l,d],a);for(const m of a)(e||!Cr(Ts(m)))&&d.push(o(m));return f}}const{message:u}=a;return i([l,{name:c,message:u}],a)};return o},Zu=(e,{json:t,lossy:n}={})=>{const s=[];return TN(!(t||n),!!t,new Map,s)(e),s},bi=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Gu(Zu(e,t)):structuredClone(e):(e,t)=>Gu(Zu(e,t));function _N(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 PN(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function zN(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||_N,s=e.options.footnoteBackLabel||PN,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 u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),f=String(u.identifier).toUpperCase(),m=es(f.toLowerCase());let h=0;const y=[],p=e.footnoteCounts.get(f);for(;p!==void 0&&++h<=p;){y.length>0&&y.push({type:"text",value:" "});let v=typeof n=="string"?n:n(c,h);typeof v=="string"&&(v={type:"text",value:v}),y.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,h),className:["data-footnote-backref"]},children:Array.isArray(v)?v:[v]})}const x=d[d.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const v=x.children[x.children.length-1];v&&v.type==="text"?v.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...y)}else d.push(...y);const g={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(u,g),l.push(g)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...bi(a),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
|
|
43
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:`
|
|
44
|
+
`}]}}const _m=(function(e){if(e==null)return DN;if(typeof e=="function")return Di(e);if(typeof e=="object")return Array.isArray(e)?RN(e):LN(e);if(typeof e=="string")return ON(e);throw new Error("Expected function, string, or object as test")});function RN(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=_m(e[n]);return Di(s);function s(...i){let o=-1;for(;++o<t.length;)if(t[o].apply(this,i))return!0;return!1}}function LN(e){const t=e;return Di(n);function n(s){const i=s;let o;for(o in e)if(i[o]!==t[o])return!1;return!0}}function ON(e){return Di(t);function t(n){return n&&n.type===e}}function Di(e){return t;function t(n,s,i){return!!($N(n)&&e.call(this,n,typeof s=="number"?s:void 0,i||void 0))}}function DN(){return!0}function $N(e){return e!==null&&typeof e=="object"&&"type"in e}const Pm=[],MN=!0,Ku=!1,FN="skip";function BN(e,t,n,s){let i;typeof t=="function"&&typeof n!="function"?(s=n,n=t):i=t;const o=_m(i),a=s?-1:1;l(e,void 0,[])();function l(c,u,d){const f=c&&typeof c=="object"?c:{};if(typeof f.type=="string"){const h=typeof f.tagName=="string"?f.tagName:typeof f.name=="string"?f.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(h?"<"+h+">":""))+")"})}return m;function m(){let h=Pm,y,p,x;if((!t||o(c,u,d[d.length-1]||void 0))&&(h=UN(n(c,d)),h[0]===Ku))return h;if("children"in c&&c.children){const g=c;if(g.children&&h[0]!==FN)for(p=(s?g.children.length:-1)+a,x=d.concat(g);p>-1&&p<g.children.length;){const v=g.children[p];if(y=l(v,p,x)(),y[0]===Ku)return y;p=typeof y[1]=="number"?y[1]:p+a}}return h}}}function UN(e){return Array.isArray(e)?e:typeof e=="number"?[MN,e]:e==null?Pm:[e]}function zm(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),BN(e,o,l,i);function l(c,u){const d=u[u.length-1],f=d?d.children.indexOf(c):void 0;return a(c,f,d)}}const xl={}.hasOwnProperty,VN={};function WN(e,t){const n=t||VN,s=new Map,i=new Map,o=new Map,a={...NN,...n.handlers},l={all:u,applyData:qN,definitionById:s,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:a,one:c,options:n,patch:HN,wrap:ZN};return zm(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const f=d.type==="definition"?s:i,m=String(d.identifier).toUpperCase();f.has(m)||f.set(m,d)}}),l;function c(d,f){const m=d.type,h=l.handlers[m];if(xl.call(l.handlers,m)&&h)return h(l,d,f);if(l.options.passThrough&&l.options.passThrough.includes(m)){if("children"in d){const{children:p,...x}=d,g=bi(x);return g.children=l.all(d),g}return bi(d)}return(l.options.unknownHandler||GN)(l,d,f)}function u(d){const f=[];if("children"in d){const m=d.children;let h=-1;for(;++h<m.length;){const y=l.one(m[h],d);if(y){if(h&&m[h-1].type==="break"&&(!Array.isArray(y)&&y.type==="text"&&(y.value=Yu(y.value)),!Array.isArray(y)&&y.type==="element")){const p=y.children[0];p&&p.type==="text"&&(p.value=Yu(p.value))}Array.isArray(y)?f.push(...y):f.push(y)}}}return f}}function HN(e,t){e.position&&(t.position=E1(e))}function qN(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,bi(o)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function GN(e,t){const n=t.data||{},s="value"in t&&!(xl.call(n,"hProperties")||xl.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 ZN(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
|
|
45
|
+
`});++s<e.length;)s&&n.push({type:"text",value:`
|
|
46
|
+
`}),n.push(e[s]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
47
|
+
`}),n}function Yu(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Qu(e,t){const n=WN(e,t),s=n.one(e,void 0),i=zN(n),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return i&&o.children.push({type:"text",value:`
|
|
48
|
+
`},i),o}function KN(e,t){return e&&"run"in e?async function(n,s){const i=Qu(n,{file:s,...t});await e.run(i,s)}:function(n,s){return Qu(n,{file:s,...e||t})}}function Ju(e){if(e)throw e}var oa,Xu;function YN(){if(Xu)return oa;Xu=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},o=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),f=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!f)return!1;var m;for(m in u);return typeof m>"u"||e.call(u,m)},a=function(u,d){n&&d.name==="__proto__"?n(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},l=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(s)return s(u,d).value}else return;return u[d]};return oa=function c(){var u,d,f,m,h,y,p=arguments[0],x=1,g=arguments.length,v=!1;for(typeof p=="boolean"&&(v=p,p=arguments[1]||{},x=2),(p==null||typeof p!="object"&&typeof p!="function")&&(p={});x<g;++x)if(u=arguments[x],u!=null)for(d in u)f=l(p,d),m=l(u,d),p!==m&&(v&&m&&(o(m)||(h=i(m)))?(h?(h=!1,y=f&&i(f)?f:[]):y=f&&o(f)?f:{},a(p,{name:d,newValue:c(v,y,m)})):typeof m<"u"&&a(p,{name:d,newValue:m}));return p},oa}var QN=YN();const aa=Rl(QN);function bl(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 JN(){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,...u){const d=e[++o];let f=-1;if(c){a(c);return}for(;++f<i.length;)(u[f]===null||u[f]===void 0)&&(u[f]=i[f]);i=u,d?XN(d,l)(...u):a(null,...u)}}function s(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function XN(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(u){const d=u;if(l&&n)throw d;return i(d)}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 Tt={basename:eC,dirname:tC,extname:nC,join:sC,sep:"/"};function eC(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ar(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 tC(e){if(ar(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 nC(e){ar(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 sC(...e){let t=-1,n;for(;++t<e.length;)ar(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":rC(n)}function rC(e){ar(e);const t=e.codePointAt(0)===47;let n=iC(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function iC(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 ar(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const oC={cwd:aC};function aC(){return"/"}function yl(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function lC(e){if(typeof e=="string")e=new URL(e);else if(!yl(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 cC(e)}function cC(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 la=["history","path","basename","stem","extname","dirname"];class Rm{constructor(t){let n;t?yl(t)?n={path:t}:typeof t=="string"||dC(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":oC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<la.length;){const o=la[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)la.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?Tt.basename(this.path):void 0}set basename(t){da(t,"basename"),ca(t,"basename"),this.path=Tt.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Tt.dirname(this.path):void 0}set dirname(t){eh(this.basename,"dirname"),this.path=Tt.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Tt.extname(this.path):void 0}set extname(t){if(ca(t,"extname"),eh(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=Tt.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){yl(t)&&(t=lC(t)),da(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Tt.basename(this.path,this.extname):void 0}set stem(t){da(t,"stem"),ca(t,"stem"),this.path=Tt.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 ot(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 ca(e,t){if(e&&e.includes(Tt.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Tt.sep+"`")}function da(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function eh(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function dC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const uC=(function(e){const s=this.constructor.prototype,i=s[e],o=function(){return i.apply(o,arguments)};return Object.setPrototypeOf(o,s),o}),hC={}.hasOwnProperty;class kc extends uC{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=JN()}copy(){const t=new kc;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(aa(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(fa("data",this.frozen),this.namespace[t]=n,this):hC.call(this.namespace,t)&&this.namespace[t]||void 0:t?(fa("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=Er(t),s=this.parser||this.Parser;return ua("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),ua("process",this.parser||this.Parser),ha("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(o,a){const l=Er(t),c=s.parse(l);s.run(c,l,function(d,f,m){if(d||!f||!m)return u(d);const h=f,y=s.stringify(h,m);pC(y)?m.value=y:m.result=y,u(d,m)});function u(d,f){d||!f?a(d):o?o(f):n(void 0,f)}}}processSync(t){let n=!1,s;return this.freeze(),ua("processSync",this.parser||this.Parser),ha("processSync",this.compiler||this.Compiler),this.process(t,i),nh("processSync","process",n),s;function i(o,a){n=!0,Ju(o),s=a}}run(t,n,s){th(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=Er(n);i.run(t,c,u);function u(d,f,m){const h=f||t;d?l(d):a?a(h):s(void 0,h,m)}}}runSync(t,n){let s=!1,i;return this.run(t,n,o),nh("runSync","run",s),i;function o(a,l){Ju(a),i=l,s=!0}}stringify(t,n){this.freeze();const s=Er(n),i=this.compiler||this.Compiler;return ha("stringify",i),th(t),i(t,s)}use(t,...n){const s=this.attachers,i=this.namespace;if(fa("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(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...f]=u;c(d,f)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(i.settings=aa(!0,i.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const f=u[d];o(f)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let f=-1,m=-1;for(;++f<s.length;)if(s[f][0]===u){m=f;break}if(m===-1)s.push([u,...d]);else if(d.length>0){let[h,...y]=d;const p=s[m][1];bl(p)&&bl(h)&&(h=aa(!0,p,h)),s[m]=[u,h,...y]}}}}const fC=new kc().freeze();function ua(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ha(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function fa(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 th(e){if(!bl(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function nh(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Er(e){return mC(e)?e:new Rm(e)}function mC(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function pC(e){return typeof e=="string"||gC(e)}function gC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const xC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",sh=[],rh={allowDangerousHtml:!0},bC=/^(https?|ircs?|mailto|xmpp)$/i,yC=[{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 wC(e){const t=vC(e),n=SC(e);return kC(t.runSync(t.parse(n),n),e)}function vC(e){const t=e.rehypePlugins||sh,n=e.remarkPlugins||sh,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...rh}:rh;return fC().use(Xj).use(n).use(KN,s).use(t)}function SC(e){const t=e.children||"",n=new Rm;return typeof t=="string"&&(n.value=t),n}function kC(e,t){const n=t.allowedElements,s=t.allowElement,i=t.components,o=t.disallowedElements,a=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||jC;for(const d of yC)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+xC+d.id,void 0);return zm(e,u),P1(e,{Fragment:r.Fragment,components:i,ignoreInvalidStyle:!0,jsx:r.jsx,jsxs:r.jsxs,passKeys:!0,passNode:!0});function u(d,f,m){if(d.type==="raw"&&m&&typeof f=="number")return a?m.children.splice(f,1):m.children[f]={type:"text",value:d.value},f;if(d.type==="element"){let h;for(h in sa)if(Object.hasOwn(sa,h)&&Object.hasOwn(d.properties,h)){const y=d.properties[h],p=sa[h];(p===null||p.includes(d.tagName))&&(d.properties[h]=c(String(y||""),h,d))}}if(d.type==="element"){let h=n?!n.includes(d.tagName):o?o.includes(d.tagName):!1;if(!h&&s&&typeof f=="number"&&(h=!s(d,f,m)),h&&m&&typeof f=="number")return l&&d.children?m.children.splice(f,1,...d.children):m.children.splice(f,1),f}}}function jC(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||bC.test(e.slice(0,t))?e:""}let NC=0;function CC(e,t){const{html:n}=jv(e||""),i={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++NC}`},o={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
|
|
49
|
+
<html><head>
|
|
50
|
+
<script>
|
|
51
|
+
window.__LMS_STUDENT__ = ${JSON.stringify(i)};
|
|
52
|
+
window.__LMS_COURSEWARE__ = ${JSON.stringify(o)};
|
|
53
|
+
(function() {
|
|
54
|
+
try {
|
|
55
|
+
// Override window.postMessage (self-targeting, always works)
|
|
56
|
+
var origPM = window.postMessage;
|
|
57
|
+
window.postMessage = function(msg, targetOrigin, transfer) {
|
|
58
|
+
var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
|
|
59
|
+
try { return origPM.call(this, msg, origin, transfer); }
|
|
60
|
+
catch(err) { if (err.name === 'SyntaxError') return origPM.call(this, msg, '*', transfer); throw err; }
|
|
61
|
+
};
|
|
62
|
+
// Shadow window.parent / window.top with Proxy to intercept .postMessage()
|
|
63
|
+
// Direct assignment (window.parent.postMessage = ...) silently fails on cross-origin WindowProxy
|
|
64
|
+
function proxyWin(realRef, propName) {
|
|
65
|
+
try {
|
|
66
|
+
var safePost = function(msg, targetOrigin, transfer) {
|
|
67
|
+
var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
|
|
68
|
+
try { return realRef.postMessage.call(realRef, msg, origin, transfer); }
|
|
69
|
+
catch(err) { if (err.name === 'SyntaxError') return realRef.postMessage.call(realRef, msg, '*', transfer); throw err; }
|
|
70
|
+
};
|
|
71
|
+
var px = new Proxy(realRef, {
|
|
72
|
+
get: function(t, p) {
|
|
73
|
+
if (p === 'postMessage') return safePost;
|
|
74
|
+
try { var v = t[p]; return typeof v === 'function' ? v.bind(t) : v; } catch(e) { return undefined; }
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
Object.defineProperty(window, propName, { get: function() { return px; }, configurable: true });
|
|
78
|
+
} catch(e) {}
|
|
79
|
+
}
|
|
80
|
+
if (window.parent && window.parent !== window) proxyWin(window.parent, 'parent');
|
|
81
|
+
try { if (window.top && window.top !== window) proxyWin(window.top, 'top'); } catch(e) {}
|
|
82
|
+
} catch(e) {}
|
|
83
|
+
})();
|
|
84
|
+
<\/script>
|
|
85
|
+
<script src="/bridge.js?cw=${encodeURIComponent(t||"")}"><\/script>
|
|
86
|
+
</head><body>
|
|
87
|
+
${n}
|
|
88
|
+
</body></html>`}class EC{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 Yr=new EC,IC=4;let Ir=0;const wl=new Set;function ih(){return Ir>=IC?null:(Ir+=1,()=>{Ir=Math.max(0,Ir-1);for(const e of wl)e()})}function AC(e){return wl.add(e),()=>{wl.delete(e)}}function TC(e,t){const[n,s]=b.useState(!e),[i,o]=b.useState(!1),a=b.useRef(null);return b.useEffect(()=>{if(!e||n)return;const l=t.current;if(!l)return;if(typeof IntersectionObserver>"u"){s(!0);return}const c=new IntersectionObserver(u=>{u.some(d=>d.isIntersecting)&&(s(!0),c.disconnect())},{rootMargin:"200px"});return c.observe(l),()=>c.disconnect()},[e,n,t]),b.useEffect(()=>{if(!n){a.current?.(),a.current=null,o(!1);return}const l=ih();if(l)a.current=l,o(!0);else{const c=AC(()=>{const u=ih();u&&(c(),a.current=u,o(!0))});return()=>c()}},[n]),b.useEffect(()=>()=>{a.current?.()},[]),i}const ma="openlearn_font_scale",$n=85,Mn=140,pa=5,Qr=100,oh=[{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 ga(e){if(typeof document>"u")return;const t=Math.min(Mn,Math.max($n,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 xa(e){if(!(typeof window>"u"))try{vn.publish({id:Ti(),type:"font-scale.changed",source:"font-size-store",payload:{scale:e},timestamp:Date.now()})}catch{}}let ah=!1;const Fn=Ll((e,t)=>({scale:Qr,minScale:$n,maxScale:Mn,step:pa,initFontSize:()=>{if(typeof window>"u")return;let n=Qr;try{const s=localStorage.getItem(ma);if(s){const i=Number(s);!isNaN(i)&&i>=$n&&i<=Mn&&(n=i)}}catch{}if(ga(n),e({scale:n}),xa(n),!ah){ah=!0;try{window.addEventListener("storage",s=>{if(s.key===ma&&s.newValue){const i=Number(s.newValue);!isNaN(i)&&i>=$n&&i<=Mn&&(ga(i),e({scale:i}),xa(i))}})}catch{}}},setScale:n=>{const s=Math.min(Mn,Math.max($n,Math.round(n)));if(ga(s),typeof window<"u")try{localStorage.setItem(ma,String(s))}catch{}e({scale:s}),xa(s)},increaseScale:()=>{const n=t().scale,s=Math.min(Mn,n+pa);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max($n,n-pa);t().setScale(s)},resetScale:()=>{t().setScale(Qr)}}));let Qn=null;const vl=new Set;function Lm(e){if(Qn=e,!!e)for(const t of vl)try{t(e)}catch(n){console.error("[socket-service] socket-ready listener error:",n)}}function jc(e){if(vl.add(e),Qn)try{e(Qn)}catch(t){console.error("[socket-service] socket listener error:",t)}return()=>{vl.delete(e)}}function _C(){if(!Qn)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return Qn}function yt(){return Qn}class PC{constructor(t){this.socket=t,Lm(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 Om=200;function zC(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 RC{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??Om,this.persist=t.persist??!1}ingest(t,n){const s={id:Ti(),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=zC(s);vn.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||lh(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(lh(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 LC(),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 lh(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 Ar=null;function LC(){return Ar||(Ar=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)}),Ar)}const Jt=new RC({capacity:Om,persist:!1});typeof window<"u"&&vn.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);Jt.ingest({source:"iframe.bridge",type:e.type,attemptId:i,coursewareUuid:typeof s.courseware_uuid=="string"?s.courseware_uuid:void 0,payload:{...s,attemptId:i},raw:n},{skipBusSync:!0})});function fn(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 OC=new Set(["guest","teacher","teacher_preview"]);function DC(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 $C(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 MC({data:e,lessonId:t,elementId:n,className:s,title:i,lazy:o=!0}){const a=Ue.useRef(null),l=Ue.useRef(null),c=TC(o,a),{theme:u}=Ie(),{scale:d}=Fn(),f=ke(R=>R.session),[m,h]=b.useState([]),[y,p]=b.useState(!1),[x,g]=b.useState(null),[v,w]=b.useState(null),E=Yr.resolve(e,{lessonId:t}),N=!!e.code&&!e.coursewareUuid&&!e.resourceId&&!E,j=e.coursewareUuid??(N?v:null);b.useEffect(()=>{if(!N||!e.code){w(null);return}let R=!1;return fetch("/api/courseware/inline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e.code})}).then(D=>D.ok?D.json():Promise.reject(new Error(`HTTP ${D.status}`))).then(D=>{!R&&typeof D?.uuid=="string"&&D.uuid&&w(D.uuid)}).catch(()=>{}),()=>{R=!0}},[N,e.code]),b.useEffect(()=>{if(!j){g(null);return}let R=!1;return fetch(`/api/courseware/${encodeURIComponent(j)}/access-token`).then(D=>D.ok?D.json():Promise.reject(new Error(`HTTP ${D.status}`))).then(D=>{!R&&typeof D?.token=="string"&&D.token&&g(D.token)}).catch(()=>{}),()=>{R=!0}},[j]),b.useEffect(()=>{const R=e.coursewareUuid;if(!R)return;let D=!1;const P=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(R)}&pageSize=all`).then(le=>le.ok?le.json():{data:[]}).then(le=>{D||h(Zs(le))}).catch(()=>{})};P();let Y=null,H=null;const ee=()=>P();try{Y=_C(),Y.on("courseware-attempt-updated",ee)}catch{H=setInterval(P,5e3)}return()=>{D=!0,Y&&Y.off("courseware-attempt-updated",ee),H&&clearInterval(H)}},[e.coursewareUuid]);const I=()=>{Ql(u,ir(u)),Df(d)};b.useEffect(()=>{const R=n??e.title??void 0,D=e.coursewareUuid;if(!R&&!D||!c)return;const P=a.current?.querySelector("iframe");if(!P||!(P instanceof HTMLIFrameElement)||!P.contentWindow)return;const Y=H=>{if(H.source!==P.contentWindow)return;const ee=H.data;if(!(!ee||typeof ee!="object"))if(ee.type==="LMS_SUBMIT"){const le=ee.payload??{};Jt.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:R,coursewareUuid:D,attemptId:typeof ee.attempt_id=="string"?ee.attempt_id:void 0,payload:{score:fn(le.score??le.grade),total:fn(le.total??le.fullScore),completion:fn(le.completion??le.progress),comment:typeof le.comment=="string"?le.comment:void 0},raw:ee})}else if(ee.type==="LMS_SAVE_PROGRESS"){const le=ee.payload??{};Jt.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:R,coursewareUuid:D,attemptId:typeof ee.attempt_id=="string"?ee.attempt_id:void 0,payload:{score:fn(le.score),completion:fn(le.completion??le.progress)},raw:ee})}else if(ee.type==="LMS_FINISH")Jt.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:R,coursewareUuid:D,attemptId:typeof ee.attempt_id=="string"?ee.attempt_id:void 0,payload:{},raw:ee});else if(ee.type==="courseware:score"||ee.type==="openlearn-cw-sdk:score"){const le=ee.payload??ee;Jt.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:R,coursewareUuid:D,payload:{score:fn(le.score),total:fn(le.total),detail:le.detail,source:typeof ee.source=="string"?ee.source:"openlearn-cw-sdk"},raw:ee})}else typeof ee.type=="string"&&ee.type.startsWith("LMS_")&&Jt.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:R,coursewareUuid:D,payload:{originalType:ee.type},raw:ee})};return window.addEventListener("message",Y),()=>window.removeEventListener("message",Y)},[c,n,e.title,e.coursewareUuid,t]);const z=e.coursewareUuid?`/runtime/${e.coursewareUuid}/${x?`?ct=${encodeURIComponent(x)}`:""}`:e.resourceId?`/api/resources/${e.resourceId}/`:E??(v?`/runtime/${v}/${x?`?ct=${encodeURIComponent(x)}`:""}`:void 0);b.useEffect(()=>{if(!c)return;const R=l.current??a.current?.querySelector("iframe");if(R&&R instanceof HTMLIFrameElement)return Ww(R)},[c,z]);const $=m.filter(R=>R.finished_at!==null&&R.finished_at!==void 0),V=$.filter(R=>R.score!==null&&R.score!==void 0),B=V.length>0?V.reduce((R,D)=>R+(D.score||0),0)/V.length:null,_=60,U=f?.role==="student"&&(f.studentId||f.userId)||null,k=DC(m),F=$.filter(R=>!OC.has(R.studentId)||R.studentId===U),Z=$C(F,k),M=U?F.find(R=>R.studentId===U)??null:null,A=M?k.get(M.attemptId)??null:null,L=k.size,S=!!e.coursewareUuid&&m.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:z,srcDoc:z?void 0:CC(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads","data-lms-bridge":"true",referrerPolicy:"no-referrer",title:i??e.title??"Interactive Courseware",credentialless:"true",onLoad:I}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"}),S&&r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",onClick:()=>p(R=>!R),"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:y?"隐藏成绩":`查看成绩 (${Z.length})`}),y&&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:[Z.length," 人已提交",B!==null&&` · 均分 ${B.toFixed(1)}`]})}),U&&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:M?`我的成绩 ${typeof M.score=="number"?M.score:"—"}${A!==null?` · 全班第 ${A}/${L} 名`:""}`:"我还没有提交"}),Z.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:Z.map(R=>{const D=typeof R.score=="number"?R.score:null,P=typeof R.completion=="number"?Math.round(R.completion*100):null,Y=k.get(R.attemptId),H=!!U&&R.studentId===U;return r.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${H?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${R.attemptId}`,children:[r.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:Y??"-"}),r.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[R.studentName||R.studentId,H&&r.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),r.jsxs("span",{className:`font-mono font-bold ${D!==null&&D>=_?"text-green-600":"text-red-500"}`,children:[D!==null?D:"-",P!==null&&r.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[P,"%"]})]})]},R.attemptId)})})]})]})]})}const FC=["http:","https:"],BC=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,UC=/[\u0000-\u001f\u007f]/;function Jr(e){if(typeof e!="string")return null;const t=e.trim();if(!t||UC.test(t)||t.startsWith("//")||t.startsWith("\\\\"))return null;if(BC.exec(t)){const s=t.slice(0,t.indexOf(":")+1).toLowerCase();if(!FC.includes(s))return null}return t}class VC{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 Xr=new VC,KT=({type:e,title:t,data:n,containerSize:s,onClose:i,lessonId:o,elementId:a,dismissible:l=!0,readOnly:c=!1,renderContent:u})=>{Ue.useEffect(()=>{if(!l)return;const N=j=>{j.key==="Escape"&&i()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[i,l]);const d=l?i:()=>{},f=Xr.getEffectiveRenderer(e),[m,h]=b.useState({width:window.innerWidth,height:window.innerHeight});b.useEffect(()=>{const N=()=>h({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]);const y=Ue.useRef(null),[p,x]=b.useState({width:0,height:0}),g=Ue.useRef(null),v=Ue.useCallback(()=>{const N=y.current;if(!N)return;const j=window.getComputedStyle(N),I=N.clientWidth-(parseFloat(j.paddingLeft)||0)-(parseFloat(j.paddingRight)||0),z=N.clientHeight-(parseFloat(j.paddingTop)||0)-(parseFloat(j.paddingBottom)||0);x({width:Math.max(0,I),height:Math.max(0,z)})},[]),w=Ue.useCallback(N=>{y.current=N,g.current?.disconnect(),g.current=null,N&&typeof ResizeObserver<"u"&&(g.current=new ResizeObserver(v),g.current.observe(N))},[v]);b.useLayoutEffect(()=>{v()},[v]);const E=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,m.width-32),height:Math.max(300,m.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($a,{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($a,{size:12})," 教师同步视图"]})})]}),(()=>{const N=e==="quiz"||e==="assignment";return r.jsxs("div",{ref:w,"data-testid":"fullscreen-content",className:"flex-1 overflow-auto p-6 relative",style:{pointerEvents:c&&!N?"none":"auto"},children:[f?r.jsx(f,{elementType:e,data:n,onClose:d,containerSize:m,lessonId:o,elementId:a}):u?u(p):r.jsx(HC,{elementType:e,data:n,onClose:d,containerSize:m,lessonId:o}),c&&!N&&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:j=>{j.stopPropagation(),j.preventDefault()},onPointerDown:j=>{j.stopPropagation(),j.preventDefault()}})]})})()]})});return Yb.createPortal(E,document.body)},WC=[{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 HC({data:e,lessonId:t}){const n=WC.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(Xs,{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(wC,{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,u)=>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"[u],"."]}),c]},u))})]})}if(s==="url"){const l=Jr(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(MC,{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 qC{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 ba=new qC;class GC{constructor(){this.store=Lt(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId,i={...t,editFields:Array.isArray(t.editFields)?t.editFields:[],pluginId:s};this.store.setState(o=>{const a=new Map(o.items);return a.set(t.type,{config:i,pluginId:s}),{items:a}})}unregister(t,n){this.store.setState(s=>{const i=s.items.get(t);if(!i||n&&i.pluginId!==n)return s;const o=new Map(s.items);return o.delete(t),{items:o}})}unregisterPlugin(t){this.store.setState(n=>{let s=!1;const i=new Map(n.items);for(const[o,a]of n.items)a.pluginId===t&&(i.delete(o),s=!0);return s?{items:i}:n})}get(t){return this.store.getState().items.get(t)?.config}getAll(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}has(t){return this.store.getState().items.has(t)}getStore(){return this.store}}const Wn=new GC;function YT(){return tn(Wn.getStore(),Gh(e=>Array.from(e.items.values()).map(t=>t.config)))}const Nc=[{id:"intro",labelZh:"准备环节",labelEn:"Intro",icon:Xb},{id:"lecture",labelZh:"讲授新课",labelEn:"Lecture",icon:Ni},{id:"practice",labelZh:"互动练习",labelEn:"Practice",icon:e0},{id:"quiz",labelZh:"随堂测试",labelEn:"Quiz",icon:Dl},{id:"summary",labelZh:"要点总结",labelEn:"Summary",icon:bt}],lr=Lt(()=>({items:new Map}));function Dm(e){if(e&&typeof e!="string")return e;if(typeof e=="string"&&e.trim()){const t=ci;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 Yh}function $m(e,t){const n=t||e.pluginId;lr.setState(s=>{const i=new Map(s.items);return i.set(e.id,{meta:{...e,icon:Dm(e.icon),pluginId:n},pluginId:n}),{items:i}})}function ZC(e,t){lr.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 KC(e){lr.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 YC(){return[...Nc,...Array.from(lr.getState().items.values()).map(e=>e.meta)]}function QT(){return tn(lr,Gh(e=>[...Nc,...Array.from(e.items.values()).map(t=>t.meta)]))}const Sl=[{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"}],JT=Sl[1].color;function XT(e){return YC().find(t=>t.id===e)||Nc[1]}function e_(e){return Sl.find(t=>t.color===e)||Sl[1]}class QC{constructor(){this.store=Lt(()=>({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 ya=new QC;class JC{constructor(){this.store=Lt(()=>({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 $t=new JC,XC=new Set(["slate","blue","violet","amber","rose","emerald","cyan","pink","indigo"]);function eE(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=XC.has(o)?o:"violet",l=String(e.group??e.category??"custom"),c=e.defaultData&&typeof e.defaultData=="object"&&!Array.isArray(e.defaultData)?e.defaultData:{},u=Array.isArray(e.editFields)?e.editFields:[];Wn.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:u,pluginId:t},t)}function tE(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&&$m({id:i,labelZh:n,labelEn:s,icon:Dm(typeof e.icon=="string"?e.icon:null),pluginId:t},t)}const Bn=()=>null;function wa(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 nE(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:Bn,pluginId:t,origin:"manifest"});const i=s.contributes;if(i&&i.locales&&typeof i.locales=="object"&&IS(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,u=String(c.id??c.type??"");u&&(e.registerExtensionPoint(o,{id:u,label:String(c.title??c.label??c.name??u),icon:typeof c.icon=="string"?c.icon:void 0,view:typeof c.view=="string"?c.view:void 0,slotProps:c.commandType?{...c,commandType:Jf(String(c.commandType),n)}:c,component:Bn,pluginId:t,origin:"manifest"}),o==="editor.palette_item"?eE(c,t):o==="editor.timeline_segment"&&tE(c,t))}}}class sE{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.dispatcher=qf,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}async initialize(t,n,s,i,o){o&&(this.dispatcher=o);const a=new FS;await a.register(Ls,t),await a.register(cl,n),await a.register(Gr,s),await a.register(Zr,i),await a.register(Xf,new rE(t)),await a.register(XS,this.dispatcher),this.registry=a,this.initialized=!0,Re.getState().initialize(a)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),Re.getState().addPlugin({id:t.id,name:t.name,version:t.version,state:He.INSTALLED,executionMode:"inline",icon:t.icon,capabilitiesProposed:Array.isArray(t.capabilitiesProposed)?[...t.capabilitiesProposed]:[]})}registerManifestContributions(t,n){nE(Re.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:Os,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",n1),i.setAttribute("src",s1),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),Re.getState().updatePluginState(t,He.ERROR))};i.addEventListener("load",a),document.body.appendChild(i),this.sandboxFrames.set(t,i);const l=this.registry?await this.registry.resolve(Ls):null,c=this.registry?await this.registry.resolve(Zr):null,u=this.registry?await this.registry.resolve(Gr):null,d=Array.isArray(n.capabilitiesProposed)?n.capabilitiesProposed:[],f=m=>{if(!m.source||m.source!==i.contentWindow||!wu(m.data))return;const h=m.data;h.type!=="call"||!h.callId||!h.op||this.answerSandboxCall(i,h.callId,h.op,h.args??[],{pluginId:t,manifest:n,caps:d,frontendApi:l,storageService:c,uiService:u}).catch(y=>{i.contentWindow?.postMessage({channel:Os,type:"reply",callId:h.callId,ok:!1,error:y instanceof Error?y.message:String(y)},"*")})};window.addEventListener("message",f),this.sandboxCleanups.set(t,()=>{i.removeEventListener("load",a),window.removeEventListener("message",f)}),await new Promise((m,h)=>{let y=!1;const p=window.setTimeout(()=>{y||(window.removeEventListener("message",g),h(new Error("Activation timeout (5000ms)")))},5e3),x=v=>{y||(y=!0,window.clearTimeout(p),window.removeEventListener("message",g),v?h(v):m())},g=v=>{if(!v.source||v.source!==i.contentWindow||!wu(v.data))return;const w=v.data;if(w.type==="ready"){i.contentWindow?.postMessage({channel:Os,type:"load",id:t,pluginId:t,manifest:n,source:s},"*");return}if(w.type==="activated"&&w.id===t){x();return}if(w.type==="activate-error"&&w.id===t){x(new Error(w.error||"sandbox activation failed"));return}};window.addEventListener("message",g)})}async answerSandboxCall(t,n,s,i,o){const a=(l,c,u)=>{t.contentWindow?.postMessage({channel:Os,type:"reply",callId:n,ok:l,value:c,error:u},"*")};try{let l;if(s==="api.get"||s==="api.post"||s==="api.del"){const c=s.slice(4),u=t1(Ls,c,i,o.caps);if(u)throw new Error(u);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 u=i[1];o.storageService.set(c,typeof u=="string"?u:JSON.stringify(u??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]??""),u=i[1]&&typeof i[1]=="object"?i[1]:{};Re.getState().registerExtensionPoint(c,{...u,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=Te.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,s){const i=Re.getState();if(!n||typeof n.id!="string"||!n.id)throw new Error(`Invalid remote plugin manifest for "${t}": missing manifest.id`);const o=i.activePlugins.find(l=>l.id===t);if(o&&(o.state===He.ACTIVE||o.state===He.ACTIVATING))return;if(i.updatePluginState(t,He.ACTIVATING),this.manifests.set(t,n),this.registerManifestContributions(t,n),!(s?.hasFrontend??o?.hasFrontend??!0)){this.pluginModules.set(t,{manifest:n,activate:async()=>{},deactivate:async()=>{}}),i.updatePluginState(t,He.ACTIVE),kr(t),i.clearPluginError(t);return}try{const l=`/plugins/${t}/frontend.js`,c=await fetch(l,{credentials:"same-origin"});if(!c.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${c.status}`);let u=await c.text();if(window.HostSharedDeps&&(u=oE(u)),o?.executionMode==="inline"){const f=new Blob([u],{type:"text/javascript"}),m=URL.createObjectURL(f);try{const h=await import(m),y=h.default??h,p=y.activate??h.activate,x=y.deactivate??h.deactivate;if(typeof p=="function"){const g=await this.buildContext(t,n);await Promise.race([p(g),new Promise((v,w)=>setTimeout(()=>w(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:p,deactivate:typeof x=="function"?x:void 0})}}finally{URL.revokeObjectURL(m)}}else await this.mountSandboxFrame(t,n,u),this.pluginModules.set(t,{manifest:n,activate:async()=>{},deactivate:async()=>{this.destroySandboxFrame(t)}});i.updatePluginState(t,He.ACTIVE),kr(t),i.clearPluginError(t)}catch(l){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,l),i.updatePluginState(t,He.ERROR),this.destroySandboxFrame(t),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),i.setPluginError(t,wa(l)),l}}async activatePlugin(t){const n=Re.getState(),s=n.activePlugins.find(i=>i.id===t);if(!s)throw new Error(`Plugin not found: ${t}`);if(s.executionMode!=="inline")throw new Error(`Unsupported execution mode for activation: ${s.executionMode}`);n.updatePluginState(t,He.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,u=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 d=await this.buildContext(t,l);await Promise.race([c(d),new Promise((f,m)=>setTimeout(()=>m(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:l,activate:c,deactivate:typeof u=="function"?u:void 0}),n.updatePluginState(t,He.ACTIVE),kr(t),n.clearPluginError(t),this.manifests.set(t,l)}catch(i){throw n.updatePluginState(t,He.ERROR),this.unregisterPluginResources(t,{preserveManifestContributions:!0}),n.setPluginError(t,wa(i)),i}}async deactivatePlugin(t){const n=Re.getState(),s=n.activePlugins.find(i=>i.id===t);if(!(!s||s.state!==He.ACTIVE)){n.updatePluginState(t,He.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,He.INACTIVE)}}}async suspendPlugin(t){const n=Re.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,He.ERROR),Re.getState().pluginErrors.get(t)||n.setPluginError(t,"插件前端连续崩溃,已自动降级")}}async retryPlugin(t){const n=Re.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(i)await this.activateRemotePlugin(t,i,{hasFrontend:s.hasFrontend});else if(s.executionMode==="inline")await this.activatePlugin(t);else throw new Error(`无法重试插件 "${t}":缺少 manifest 缓存`);return!0}catch(i){return console.error(`[FrontendPluginHost] Retry failed for plugin "${t}":`,i),n.setPluginError(t,wa(i)),!1}}async uninstallPlugin(t){const n=Re.getState();n.activePlugins.find(i=>i.id===t)?.state===He.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 Re.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?Re.getState().unregisterPluginRuntimeExtensionPoints(t):Re.getState().unregisterPluginExtensionPoints(t),Xr.unregisterPlugin(t),ba.unregisterPlugin(t),Yr.unregisterPlugin(t),Wn.unregisterPlugin(t),KC(t),ya.clearOwned(t),$t.clearOwned(t),AS(t),n?.keepBreakerState||kr(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(Ls),i=await this.registry.resolve(cl),o=await this.registry.resolve(Gr),a=await this.registry.resolve(Zr),l=this.dispatcher.createScopedDispatcher?this.dispatcher.createScopedDispatcher(t):{dispatch:(c,u)=>this.dispatcher.dispatch(c,{sourcePluginId:t,...u}),registerHandler:(c,u)=>this.dispatcher.registerHandler(c,u),subscribe:(c,u)=>this.dispatcher.subscribe(c,u),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,u)=>{Re.getState().registerExtensionPoint(c,{...u,pluginId:t,origin:"runtime"})},unregisterExtensionPoint:(c,u)=>{Re.getState().unregisterExtensionPoint(c,u,t)},registerFullscreenRenderer:(c,u)=>{Xr.register(c,u,t)},unregisterFullscreenRenderer:c=>{Xr.unregister(c,t)},registerPropertyEditor:(c,u)=>{ba.register(c,u,t)},unregisterPropertyEditor:c=>{ba.unregister(c,t)},registerCoursewareSource:c=>{Yr.register(c,t)},unregisterCoursewareSource:c=>{Yr.unregister(c,t)},registerPaletteItem:c=>{Wn.register(c,t)},unregisterPaletteItem:c=>{Wn.unregister(c,t)},registerSegmentType:c=>{$m(c,t)},unregisterSegmentType:c=>{ZC(c,t)},registerAssignmentQuestionRenderer:c=>{ya.register(c,t)},unregisterAssignmentQuestionRenderer:c=>{ya.unregister(c,t)},registerAssessmentQuestionType:c=>{$t.register(c,t)},unregisterAssessmentQuestionType:c=>{$t.unregister(c,t)}},navigation:{getTeacherTab:()=>Te.getState().teacherTab,setTeacherTab:c=>Te.getState().setTeacherTab(c),setSelectedLesson:c=>Te.getState().setSelectedLesson(c),subscribeTeacherTab:c=>{let u=Te.getState().teacherTab;return this.trackDisposer(t,Te.subscribe(d=>{const f=d.teacherTab;f!==u&&(u=f,c(f))}))}},context:{get:()=>{const c=Te.getState();return{lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId}},subscribe:c=>{const u=Te.getState();let d={lessonId:u.selectedLesson,classId:u.liveClassSelectedClassId};return this.trackDisposer(t,Te.subscribe(f=>{const m={lessonId:f.selectedLesson,classId:f.liveClassSelectedClassId};(m.lessonId!==d.lessonId||m.classId!==d.classId)&&(d=m,c(m))}))}},i18n:{t:(c,u,d)=>{const f=c.includes(":")?c:`${t}:${c}`;return Yf(f,u,d)},getLanguage:()=>TS()},invokeCommand:async(c,u)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const d=Jf(c,n.id),f=await s.post("/api/plugins/execute-command",{type:d,payload:u});if(f.success&&f.result!==void 0)return f.result;throw new Error(f.error||"Command execution failed")},registerPanel:c=>{const u=c.slot||"teacher.dashboard.widget";Re.getState().registerExtensionPoint(u,{...c,pluginId:t,origin:"runtime"})},registerMenu:c=>{const u=c.slot||"teacher.panel";Re.getState().registerExtensionPoint(u,{...c,pluginId:t,origin:"runtime"})},registerToolbarButton:c=>{Re.getState().registerExtensionPoint("classroom.tool",{...c,pluginId:t,origin:"runtime"})}}}}class rE{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 ch={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 dh(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 iE(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],u=dh(i[2]);return n.push(`const ${c} = ${t}?.default ?? ${t};`),u&&n.push(`const { ${u} } = ${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 { ${dh(a[1])} } = ${t};`;const l=e.match(/^([a-zA-Z_$][\w$]*)$/);return l?`const ${l[1]} = ${t}?.default ?? ${t};`:null}function oE(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>ch[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,i)=>{const o=ch[i];if(!o)return n;const a=iE(s,o);return a||n}),t}function aE(e){if(typeof e!="string"||!e.trim())return null;const t=e.trim();return t.includes("://")||t.startsWith("//")||t.startsWith("\\")||t.includes("..")||/^(javascript|data|blob):/i.test(t)?null:t.replace(/^\/+/,"")}function Tr({pluginId:e,view:t,label:n,slot:s,lessonId:i,classId:o,studentId:a,studentName:l,className:c,onResize:u,variant:d="panel",style:f,locked:m=!1}){const h=b.useRef(null),[y,p]=b.useState(!1),[x,g]=b.useState(null),v=ke(L=>L.lang),w=ke(L=>L.selectedLesson),E=ke(L=>L.liveClassSelectedClassId),N=Ie(L=>L.previewState?.themeId||L.theme),j=Ie(L=>L.resolvedColorScheme),I=Ie(L=>L.appearanceOverrides),z=Ie(L=>L.activeBundle),$=Ie(L=>L.getUnifiedPluginThemePayload),V=i!==void 0?i:w,B=o!==void 0?o:E,_=aE(t),U=b.useCallback(()=>{const L=h.current;if(!L||!L.contentWindow)return;const S=$();L.contentWindow.postMessage({channel:jr,type:"init",payload:{pluginId:e,slot:s,lessonId:V,classId:B,studentId:a??null,studentName:l??null,lang:v,theme:N,themeMeta:S}},"*")},[e,s,V,B,a,l,v,N,j,I,z,$]);if(b.useEffect(()=>{const L=async S=>{const R=h.current;if(!R||!S.source||S.source!==R.contentWindow)return;const D=S.data;if(!(!D||D.channel!==jr)){if(D.type==="ready"){p(!0),U();return}if(D.type==="resize"&&typeof D.height=="number"&&D.height>0){g(D.height),u?.(D.height);return}if(D.type==="call"&&D.callId&&D.op){const{callId:P,op:Y,args:H=[]}=D,ee=(le,ae,fe)=>{R.contentWindow?.postMessage({channel:jr,type:"reply",callId:P,ok:le,value:ae,error:fe},"*")};try{if(Y==="ui.toast"){const le=String(H[0]??""),ae=H[1],fe=ae==="success"||ae==="warning"||ae==="error"?ae:"info";Te.getState().addToast({id:Math.random().toString(16).slice(2),title:n||e,message:le,type:fe}),ee(!0,!0)}else if(Y==="command.invoke"){const le=String(H[0]??""),ae=H[1],fe=await fetch(`/api/plugins/${encodeURIComponent(e)}/sandbox-command`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({type:le,payload:ae})}),be=await fe.json();!fe.ok||be.success===!1?ee(!1,void 0,be.error||`Command failed with HTTP ${fe.status}`):ee(!0,be.result)}else if(Y==="api.get"||Y==="api.post"||Y==="api.del"){const le=String(H[0]??"").replace(/^\/+/,""),ae=le.startsWith("api/plugins/")?`/${le}`:`/api/plugins/${encodeURIComponent(e)}/${le}`,be=await fetch(ae,{method:Y==="api.get"?"GET":Y==="api.post"?"POST":"DELETE",headers:Y==="api.post"?{"Content-Type":"application/json"}:void 0,credentials:"include",body:Y==="api.post"?JSON.stringify(H[1]):void 0});let ye;try{ye=await be.json()}catch{ye=await be.text()}if(be.ok)ee(!0,ye);else{const Se=typeof ye=="object"&&ye!==null&&"error"in ye?String(ye.error):`Request failed with HTTP ${be.status}`;ee(!1,void 0,Se)}}else if(Y==="storage.get"){const le=`ol_pv_${e}_${String(H[0]??"")}`,ae=localStorage.getItem(le);let fe=ae;try{fe=JSON.parse(ae??"")}catch{}ee(!0,fe??ae)}else if(Y==="storage.set"){const le=`ol_pv_${e}_${String(H[0]??"")}`,ae=typeof H[1]=="string"?H[1]:JSON.stringify(H[1]??null);localStorage.setItem(le,ae),ee(!0,!0)}else if(Y==="storage.delete"){const le=`ol_pv_${e}_${String(H[0]??"")}`;localStorage.removeItem(le),ee(!0,!0)}else ee(!1,void 0,`Unsupported op "${Y}"`)}catch(le){const ae=le instanceof Error?le.message:String(le);ee(!1,void 0,ae)}}}};return window.addEventListener("message",L),()=>{window.removeEventListener("message",L)}},[e,n,u,U]),b.useEffect(()=>{if(!y||!h.current?.contentWindow)return;const L=$();h.current.contentWindow.postMessage({channel:jr,type:"context-update",payload:{lessonId:V,classId:B,studentId:a??null,studentName:l??null,lang:v,theme:N,themeMeta:L}},"*")},[V,B,a,l,v,N,j,I,z,$,y]),!_)return r.jsxs("div",{className:"flex flex-col items-center justify-center p-6 text-center text-red-600 bg-red-50/50 rounded-xl border border-red-200 m-4",children:[r.jsx(Pt,{size:32,className:"mb-2 text-red-500"}),r.jsx("p",{className:"text-sm font-semibold",children:v==="zh"?"非法的插件视图路径":"Invalid Plugin View Path"}),r.jsx("p",{className:"text-xs text-red-400 mt-1 font-mono",children:t||"(empty)"})]});const k=`/plugins/${encodeURIComponent(e)}/${_}`,F=d==="floating",Z=m&&F,M=F?`fixed bottom-6 left-6 z-40 flex w-[300px] max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl transition-transform duration-300 ease-out dark:border-slate-700 dark:bg-slate-900 ${c||""}`:`relative w-full h-full flex flex-col min-h-0 bg-white dark:bg-slate-900 ${c||""}`,A={...f||{},...F?{height:`${x??180}px`}:x?{minHeight:`${x}px`}:{},...Z?{transform:"translateY(calc(100% + 1.5rem))"}:{}};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`${M}${Z?" pointer-events-none":""}`,style:A,"data-plugin-view-variant":d,"data-plugin-view-locked":m?"true":void 0,"data-plugin-view-collapsed":Z?"true":void 0,"aria-hidden":Z?!0:void 0,children:[!y&&r.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center bg-slate-50/80 dark:bg-slate-900/80 backdrop-blur-2xs transition-opacity duration-200",children:[r.jsx(dt,{size:24,className:"animate-spin text-indigo-500 mb-2"}),r.jsx("span",{className:"text-xs font-medium text-slate-500",children:v==="zh"?"正在加载插件视图...":"Loading plugin view..."})]}),r.jsx("iframe",{ref:h,src:k,title:n||`${e} view`,sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",onLoad:()=>{p(!0),U()},inert:m?!0:void 0,className:`w-full flex-1 border-none transition-opacity duration-200 ${y?"opacity-100":"opacity-0"}${m?" pointer-events-none":""}`}),m&&!F&&r.jsx("div",{"data-testid":"plugin-view-lock-cover",className:"absolute inset-0 z-20 flex items-center justify-center bg-slate-900/15 backdrop-blur-[1px] cursor-not-allowed select-none",title:v==="zh"?"老师已开启全班专注锁定,当前为只读跟随":"Classroom focus lock is on — read-only follow mode",onClick:L=>{L.stopPropagation(),L.preventDefault()},onPointerDown:L=>{L.stopPropagation(),L.preventDefault()},children:r.jsxs("span",{className:"px-2 py-1 rounded-full bg-slate-900/70 text-white text-[10px] font-bold tracking-wide",children:["🔒 ",v==="zh"?"专注锁定中":"Focus locked"]})})]}),Z&&r.jsxs("button",{type:"button","data-testid":"plugin-view-lock-collapsed","aria-expanded":!1,"aria-label":v==="zh"?`${n||e} 已收起:老师已开启全班专注锁定`:`${n||e} collapsed: classroom focus lock is on`,title:v==="zh"?"老师已开启全班专注锁定,互动浮层已收起":"Classroom focus lock is on — the floating panel is collapsed",className:"fixed bottom-6 left-6 z-40 flex items-center gap-1 rounded-full border border-slate-300 bg-white/95 px-2.5 py-1.5 text-slate-500 shadow-lg backdrop-blur-xs transition-colors hover:text-slate-700 dark:border-slate-600 dark:bg-slate-800/95 dark:text-slate-300",style:f,onClick:()=>Te.getState().addToast({id:Math.random().toString(16).slice(2),title:n||e,message:v==="zh"?"老师已开启全班专注锁定,互动浮层暂时收起,解锁后自动恢复。":"Classroom focus lock is on — the floating panel is collapsed and will return after unlock.",type:"info"}),children:[r.jsx(Qh,{size:14}),r.jsx("span",{className:"text-[10px] font-bold",children:"🔒"})]})]})}class Mm{constructor(t=""){this.baseUrl=t}async get(t){return this.request("GET",t)}async post(t,n){return this.request("POST",t,n)}async del(t){return this.request("DELETE",t)}async request(t,n,s){try{const i=`${this.baseUrl}${n}`,o={method:t,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return s!==void 0&&t!=="GET"&&t!=="DELETE"&&(o.body=JSON.stringify(s)),await(await fetch(i,o)).json()}catch(i){return{success:!1,error:i.message??"Network error"}}}}const Fm=new Mm,lE=new Set(["student.classroom.overlay"]);function va(e){return lE.has(e)?"floating":"panel"}function _r(e,t){Re.getState().unregisterPluginRuntimeExtensionPoints(e),(t?.suspendPlugin?t.suspendPlugin(e):t?.deactivatePlugin(e))?.catch(i=>console.error(`[ExtensionBreaker] auto-deactivate "${e}" failed:`,i))}function Sa(){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(dt,{size:24,className:"text-gray-400 animate-spin"}),r.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}function Rn({pluginId:e,message:t,lang:n="zh",compact:s=!1}){const i=Gf(),[o,a]=Ue.useState(!1),l=n==="zh",c=Ue.useCallback(()=>{!i||o||(a(!0),i.retryPlugin(e).catch(()=>!1).finally(()=>a(!1)))},[i,e,o]),u=l?"插件加载失败":"Plugin failed to load",d=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(Bt,{size:s?20:32,className:"text-amber-500 mb-2","aria-hidden":"true"}),r.jsx("p",{className:`font-semibold text-amber-800 ${s?"text-xs":"text-sm"}`,children:u}),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(dt,{size:13,className:"animate-spin","aria-hidden":"true"}):r.jsx(Ci,{size:13,"aria-hidden":"true"}),o?l?"重试中…":"Retrying…":d]})]})}class Pr extends Ue.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}=PS(n);if(console.error(`[ExtensionBreaker] Plugin "${n}" frontend crash #${i}/${Qf}`+(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 zr({pluginId:e,children:t}){return Ue.useEffect(()=>{e&&zS(e)}),r.jsx(r.Fragment,{children:t})}function Rr({ext:e,route:t,slotProps:n,slot:s}){const i=Ue.useRef(null),o=JSON.stringify(n||{});Ue.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 Lr=new WeakMap;function Or(e){const t=e?.component;if(typeof t!="function")return()=>null;const n=Lr.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=Ue.lazy(t);return Lr.set(t,s),s}if(typeof t=="function"&&!t.prototype?.isReactComponent){let s=!1;const i=Ue,o=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE||i.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,a=o?.H??o?.ReactCurrentDispatcher?.current;try{o&&("H"in o&&(o.H=null),o.ReactCurrentDispatcher&&(o.ReactCurrentDispatcher.current=null));const l=t();l&&typeof l.then=="function"&&(s=!0)}catch{}finally{o&&("H"in o&&(o.H=a),o.ReactCurrentDispatcher&&(o.ReactCurrentDispatcher.current=a))}if(s){console.error(`[ExtensionPoint] Detected an UNMARKED lazy factory (function returned a Promise). React would suspend forever without throwing. Auto-wrapping with React.lazy; please set \`__isLazyFactory = true\` on the factory or register the component directly. Offending function: ${t.name||"(anonymous)"}`);const l=Ue.lazy(t);return Lr.set(t,l),l}}return Lr.set(t,t),t}function mn(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 qe({slot:e,fallback:t,lang:n,route:s,slotProps:i,placement:o,locked:a=!1}){const l=Ue.useRef(new Set),c=Gf(),u=Re(x=>x.activePlugins),d=Re(x=>x.dashboardVisibility),f=Re(x=>x.pluginErrors),m=ke(x=>x.selectedLesson),h=ke(x=>x.liveClassSelectedClassId);if(!c)return t??null;let y=c.getExtensions(e);if(o&&(y=y.filter(x=>(x.placement??"after")===o)),e==="assignment.file.preview"){const x=String(i?.fileExtension??"").toLowerCase();if(!x)return null;y=y.filter(g=>{const v=g.slotProps??{},w=Array.isArray(v.extensions)?v.extensions:[];if(MS(w,x))return!0;const E=Array.isArray(v.mimeTypes)?v.mimeTypes.filter(j=>typeof j=="string").map(j=>j.toLowerCase()):[],N=String(i?.file?.mime??"").toLowerCase();return N!==""&&E.includes(N)})}if(y.length===0)return null;const p=(x,g,v)=>{const w=f.get(x.pluginId);if(w)return r.jsx(Rn,{pluginId:x.pluginId,message:w});if(Sr(x.pluginId))return l.current.has(x.pluginId)||(l.current.add(x.pluginId),console.warn(`[ExtensionBreaker] Plugin "${x.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(Rn,{pluginId:x.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"});const E=typeof x.component=="function"&&x.component!==Bn,N=typeof x.render=="function",j=!!(x.slotProps?.view||x.view);if(!E&&!N&&!j)return null;const I={...x.slotProps,...g,dispatcher:mn(c,x.pluginId,i?.dispatcher)};return r.jsx(Pr,{pluginId:x.pluginId,onBreakerTrip:z=>_r(z,c),fallback:r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:v}),children:r.jsx(b.Suspense,{fallback:r.jsx(Sa,{}),children:r.jsx(zr,{pluginId:x.pluginId,children:E?Ue.createElement(Or(x),I):N?r.jsx(Rr,{ext:x,route:x.route||s,slotProps:I,slot:e}):r.jsx(Tr,{pluginId:x.pluginId,view:String(x.slotProps?.view||x.view),label:x.label,slot:e,lessonId:m,classId:i?.classId||h,studentId:i?.studentId??null,studentName:i?.studentName??null,variant:va(e),locked:a})})})},`${x.pluginId}/${x.id}`)};if(e==="class.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:y.map((g,v)=>{const w=`plugin:${g.pluginId}/${g.id}`,E=i?.classActiveTab===w,N=g.title||g.label||g.id,j=hn(N,g.pluginId,x),I=u.find($=>$.id===g.pluginId),z=g.icon||I?.icon;return r.jsxs("button",{onClick:$=>{$.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 ${E?"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:j,children:[r.jsx(dn,{icon:z,size:12,className:"shrink-0",alt:j}),r.jsx("span",{children:j})]},`${g.pluginId}/${g.id}`)})})}if(e==="class.tab"&&i?.renderType==="panel"){const x=i?.classActiveTab,g=y.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return g?p(g,{classId:i?.classId,students:i?.students,lang:i?.lang},"扩展 Tab 加载失败"):null}if(e==="timetable.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:y.map((g,v)=>{const w=`plugin:${g.pluginId}/${g.id}`,E=i?.timetableActiveTab===w,N=g.title||g.label||g.id,j=hn(N,g.pluginId,x),I=u.find($=>$.id===g.pluginId),z=g.icon||I?.icon;return r.jsxs("button",{onClick:$=>{$.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 ${E?"bg-white text-indigo-700 shadow-sm font-bold":"text-gray-500 hover:text-gray-800"}`,title:j,children:[r.jsx(dn,{icon:z,size:14,className:"shrink-0",alt:j}),r.jsx("span",{children:j})]},`${g.pluginId}/${g.id}`)})})}if(e==="timetable.tab"&&i?.renderType==="panel"){const x=i?.timetableActiveTab,g=y.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return g?p(g,{classes:i?.classes,lessons:i?.lessons,lang:i?.lang,onSchedulesUpdated:i?.onSchedulesUpdated,onClassesUpdated:i?.onClassesUpdated},"课表扩展 Tab 加载失败"):null}if(e==="ai_sidebar.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:y.map((g,v)=>{const w=`plugin:${g.pluginId}/${g.id}`,E=i?.activeTab===w,N=g.title||g.label||g.id,j=hn(N,g.pluginId,x),I=u.find($=>$.id===g.pluginId),z=g.icon||I?.icon;return r.jsxs("button",{onClick:$=>{$.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 ${E?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,title:j,children:[r.jsx(dn,{icon:z,size:14,className:"shrink-0",alt:j}),r.jsx("span",{className:"truncate",children:j})]},`${g.pluginId}/${g.id}`)})})}if(e==="ai_sidebar.tab"&&i?.renderType==="panel"){const x=i?.activeTab,g=y.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return g?p(g,{activeTab:i?.activeTab,lang:i?.lang},"扩展面板加载失败"):null}if(e==="admin.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:y.map((g,v)=>{const w=`plugin:${g.pluginId}/${g.id}`,E=i?.adminActiveTab===w,N=g.title||g.label||g.id,j=hn(N,g.pluginId,x),I=u.find($=>$.id===g.pluginId),z=g.icon||I?.icon;return r.jsxs("button",{onClick:$=>{$.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 ${E?"bg-white text-indigo-700 shadow-xs":"text-gray-500 hover:text-gray-800"}`,title:j,children:[r.jsx(dn,{icon:z,size:14,className:"shrink-0",alt:j}),r.jsx("span",{children:j})]},`${g.pluginId}/${g.id}`)})})}if(e==="admin.tab"&&i?.renderType==="panel"){const x=i?.adminActiveTab,g=y.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return g?p(g,{currentUserId:i?.currentUserId,currentUserRole:i?.currentUserRole,lang:i?.lang,siteInfo:i?.siteInfo,aiProviders:i?.aiProviders},"管理后台扩展 Tab 加载失败"):null}if(e==="student.profile.tab"&&i?.renderType==="button"){const x=i?.lang||"zh";return r.jsx(r.Fragment,{children:y.map((g,v)=>{const w=`plugin:${g.pluginId}/${g.id}`,E=i?.studentActiveTab===w,N=g.title||g.label||g.id,j=hn(N,g.pluginId,x),I=u.find($=>$.id===g.pluginId),z=g.icon||I?.icon;return r.jsxs("button",{onClick:$=>{$.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 ${E?"bg-surface text-primary-theme shadow-xs border border-theme/60":"text-muted hover:text-main"}`,title:j,children:[r.jsx(dn,{icon:z,size:14,className:"shrink-0",alt:j}),r.jsx("span",{children:j})]},`${g.pluginId}/${g.id}`)})})}if(e==="student.profile.tab"&&i?.renderType==="panel"){const x=i?.studentActiveTab,g=y.find(v=>`plugin:${v.pluginId}/${v.id}`===x);return g?p(g,{student:i?.student,lessonId:i?.lessonId,classId:i?.classId,lang:i?.lang,progressHistory:i?.progressHistory},"学生画像扩展 Tab 加载失败"):null}if(e==="teacher.tab"&&i?.renderType==="button"){const x=[...y].sort((w,E)=>(w.position??100)-(E.position??100)),g=i?.lang??"zh",v=nl[g];return r.jsx(r.Fragment,{children:x.map(w=>{const E=`${w.pluginId}/${w.id}`,N=i?.teacherTab===E,j=w.title||w.label||w.id,I=hn(j,w.pluginId,g),z=u.find(U=>U.id===w.pluginId),$=w.icon||z?.icon,V=f.has(w.pluginId),B=g==="zh"?`在新标签页打开"${I}"`:`Open "${I}" in a new tab`,_=E.replace(/[^a-zA-Z0-9_-]/g,"_");return r.jsxs("div",{className:`group relative flex items-center rounded-xl transition-all duration-150 ${N?"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"} ${V?"ring-1 ring-amber-400/70":""} ${i?.mainNavCollapsed?"justify-center":""}`,title:I,children:[r.jsxs("button",{type:"button",onClick:()=>i?.setTeacherTab?.(E),id:`nav_btn_${_}`,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 ${N?"font-bold":""} ${i?.mainNavCollapsed?"justify-center px-2":"pl-2.5 pr-8"}`,children:[r.jsx(dn,{icon:$,size:18,className:"shrink-0",alt:I}),r.jsx("span",{className:i?.mainNavCollapsed?"hidden":"block truncate",children:I})]}),!i?.mainNavCollapsed&&r.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),xS(E)},id:`nav_btn_${_}_newtab`,"aria-label":B,title:v.openInNewTab,"data-testid":`nav_newtab_${_}`,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(Jh,{size:12,className:"shrink-0"})})]},`${w.pluginId}/${w.id}`)})})}if(e==="whiteboard.renderer"){const x=i?.elementType;if(!x)return null;const g=y.find(j=>{const I=j;return I.targetType===x||j.id===x||j.route===x||`${j.pluginId}/${j.id}`===x||I.slotProps?.elementType===x||I.slotProps?.targetType===x});if(!g)return null;const v=f.get(g.pluginId);if(v)return r.jsx(Rn,{pluginId:g.pluginId,message:v,compact:!0});if(Sr(g.pluginId))return l.current.has(g.pluginId)||(l.current.add(g.pluginId),console.warn(`[ExtensionBreaker] Plugin "${g.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(Rn,{pluginId:g.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh",compact:!0});const w=typeof g.component=="function"&&g.component!==Bn,E=typeof g.render=="function",N=!!(g.slotProps?.view||g.view);return!w&&!E&&!N?null:r.jsx(Pr,{pluginId:g.pluginId,onBreakerTrip:j=>_r(j,c),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(b.Suspense,{fallback:t??r.jsx(Sa,{}),children:r.jsx(zr,{pluginId:g.pluginId,children:w?Ue.createElement(Or(g),{...g.slotProps,...i,dispatcher:mn(c,g.pluginId,i?.dispatcher)}):E?r.jsx(Rr,{ext:g,route:g.route||s,slotProps:{...g.slotProps,...i,dispatcher:mn(c,g.pluginId,i?.dispatcher)},slot:e}):r.jsx(Tr,{pluginId:g.pluginId,view:String(g.slotProps?.view||g.view),label:g.label,slot:e,lessonId:i?.lessonId??m,classId:i?.classId||h,variant:"panel",locked:a,style:{width:"100%",height:"100%"}})})})},`${g.pluginId}/${g.id}`)}if(e==="whiteboard.selection.toolbar"||e==="whiteboard.context_menu"){const x=e==="whiteboard.context_menu";return r.jsx(r.Fragment,{children:y.map(g=>{const v=g.targetType??g.slotProps?.targetType;if(v&&v!=="*"&&v!==i?.elementType)return null;const w=g.slotProps?.target;if(x&&w&&w!=="*"&&w!==i?.target||f.get(g.pluginId)||Sr(g.pluginId))return null;const E=typeof g.component=="function"&&g.component!==Bn,N=typeof g.render=="function",j=!!(g.slotProps?.view||g.view),I=typeof g.slotProps?.commandType=="string"?g.slotProps.commandType:"";if(!E&&!N&&!j&&I){const z=hn(g.label||g.id,n),$=async()=>{i?.onClose?.();const V=typeof g.slotProps?.payload=="object"&&g.slotProps.payload!==null?g.slotProps.payload:{},B=await Fm.post("/api/plugins/execute-command",{type:I,payload:{...V,elementId:i?.elementId,elementType:i?.elementType,target:i?.target,lessonId:i?.lessonId??m,pageId:i?.pageId}});B.success||Ge.getState().addToast({id:`wb-slot-cmd-err-${Date.now()}`,type:"error",title:n==="en"?"Plugin action failed":"插件命令执行失败",message:B.error||I})};return r.jsxs("button",{type:"button","data-plugin-id":g.pluginId,"data-extension-id":g.id,onClick:()=>{$()},className:x?"w-full px-3 py-1.5 text-left text-xs font-medium text-main hover:bg-primary-theme-light hover:text-primary-theme rounded-md transition-colors flex items-center gap-2 cursor-pointer":"px-2 py-1 text-xs font-medium text-main hover:bg-primary-theme-light hover:text-primary-theme rounded-md transition-colors flex items-center gap-1 cursor-pointer whitespace-nowrap",title:z,children:[g.icon?r.jsx(dn,{icon:g.icon,size:13}):null,r.jsx("span",{children:z})]},`${g.pluginId}/${g.id}`)}return!E&&!N&&!j?null:r.jsx(Pr,{pluginId:g.pluginId,onBreakerTrip:z=>_r(z,c),fallback:null,children:r.jsx(b.Suspense,{fallback:null,children:r.jsx(zr,{pluginId:g.pluginId,children:E?Ue.createElement(Or(g),{route:g.route||s,lessonId:m,classId:h,dispatcher:mn(c,g.pluginId,i?.dispatcher),...g.slotProps,...i}):N?r.jsx(Rr,{ext:g,route:g.route||s,slotProps:{lessonId:m,classId:h,dispatcher:mn(c,g.pluginId,i?.dispatcher),...g.slotProps,...i},slot:e}):r.jsx(Tr,{pluginId:g.pluginId,view:String(g.slotProps?.view||g.view),label:g.label,slot:e,lessonId:i?.lessonId??m,classId:i?.classId||h,variant:"panel",locked:a})})})},`${g.pluginId}/${g.id}`)})})}return r.jsx(r.Fragment,{children:y.map((x,g)=>{const v=typeof x.component=="function"&&x.component!==Bn,w=typeof x.render=="function",E=!!(x.slotProps?.view||x.view);if(e==="teacher.dashboard.widget"&&d.get(x.pluginId)===!1||!v&&!w&&!E)return null;const N=f.get(x.pluginId);return N?r.jsx(Rn,{pluginId:x.pluginId,message:N},`${x.pluginId}/${x.id}`):Sr(x.pluginId)?(l.current.has(x.pluginId)||(l.current.add(x.pluginId),console.warn(`[ExtensionBreaker] Plugin "${x.pluginId}" 已熔断(连续崩溃 ≥3 次),跳过渲染。重新激活插件可恢复。`)),r.jsx(Rn,{pluginId:x.pluginId,message:n==="en"?"The plugin frontend crashed repeatedly and was suspended.":"插件前端连续崩溃,已自动降级。",lang:n==="en"?"en":"zh"},`${x.pluginId}/${x.id}`)):r.jsx(Pr,{pluginId:x.pluginId,onBreakerTrip:j=>_r(j,c),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(b.Suspense,{fallback:t??r.jsx(Sa,{}),children:r.jsx(zr,{pluginId:x.pluginId,children:v?Ue.createElement(Or(x),{route:x.route||s,lessonId:m,classId:h,dispatcher:mn(c,x.pluginId,i?.dispatcher),...x.slotProps,...i}):w?r.jsx(Rr,{ext:x,route:x.route||s,slotProps:{lessonId:m,classId:h,dispatcher:mn(c,x.pluginId,i?.dispatcher),...x.slotProps,...i},slot:e}):r.jsx(Tr,{pluginId:x.pluginId,view:String(x.slotProps?.view||x.view),label:x.label,slot:e,lessonId:m,classId:i?.classId||h,studentId:i?.studentId??null,studentName:i?.studentName??null,variant:va(e),locked:a,style:va(e)==="floating"&&g>0?{left:`calc(1.5rem + ${g*316}px)`}:void 0})})})},`${x.pluginId}/${x.id}`)})})}const cE=({state:e,onToggleAnonymous:t,onOpenRubricModal:n,onToggleVoiceDanmaku:s,onAdvanceStage:i,onAddMinute:o,onTogglePauseTimer:a,isFullscreen:l,onToggleFullscreen:c,onClose:u})=>{const d=m=>{const h=Math.floor(Math.max(0,m)/60),y=Math.max(0,m)%60;return`${String(h).padStart(2,"0")}:${String(y).padStart(2,"0")}`},f=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(qn,{size:13,className:"text-[#908fa0]"}),r.jsx("span",{children:"收卷归档"}),r.jsx(qn,{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(Xh,{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(t0,{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:[d(e.timeRemainingSeconds),r.jsxs("span",{className:"text-[#908fa0] text-xs font-normal",children:[" / ",d(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($l,{size:12,className:"text-[#4edea3]"}):r.jsx(n0,{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:`${f}, 100`,strokeLinecap:"round",strokeWidth:"3.5"})]}),r.jsxs("span",{className:"absolute text-[9px] font-mono text-[#dae2fd] font-semibold",children:[f,"%"]})]}),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(s0,{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(Ml,{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(r0,{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(Fl,{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(qe,{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($a,{size:16}):r.jsx(Bl,{size:16})}),u&&r.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-xl text-[#ffb4ab] hover:text-white hover:bg-[#93000a]/50 transition-colors ml-1",title:"关闭大屏互评",children:r.jsx(De,{size:16})})]})]})},dE=({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(ef,{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(bt,{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(li,{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,u)=>r.jsx(di,{size:13,className:u<o.stars?"text-[#ffb95f] fill-[#ffb95f]":"text-[#464554]"},u))}),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(Ul,{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(qe,{slot:"peer_review.badge"})]})]})},uE=({workA:e,workB:t,annotations:n,isAnonymous:s=!1,onFullscreenCanvas:i,onSyncSandboxToClass:o,onAddAnnotation:a})=>{const[l,c]=b.useState("visual"),[u,d]=b.useState(!1),[f,m]=b.useState(""),[h,y]=b.useState(null);if(!e&&!t)return null;const p=(v,w)=>!w||v.length<=1?v:`${v[0]}**`,x=v=>{v.preventDefault(),f.trim()&&(a?.(f.trim()),m(""),d(!1))},g=v=>{const w=v.files?.filter(N=>N.isImage||/\.(jpe?g|png|gif|webp|svg)$/i.test(N.name||N.url||""))||[],E=v.files?.filter(N=>!w.includes(N))||[];return r.jsxs("div",{"data-testid":`work-preview-${v.slot}`,className:"w-full h-44 rounded-lg bg-[#060e20] flex flex-col justify-center relative overflow-hidden border border-[#2d3449]/60",children:[r.jsx(qe,{slot:"peer_review.work.preview",slotProps:{work:v,slot:v.slot,isAnonymous:s}}),w.length>0?r.jsxs("div",{className:"w-full h-full p-2.5 flex items-center gap-2 overflow-x-auto",children:[w.map((N,j)=>r.jsxs("div",{onClick:()=>N.url&&y(N.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:`${N.name} (点击放大)`,children:[r.jsx("img",{src:N.url,alt:N.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(kn,{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:N.name})]},j)),E.length>0&&r.jsx("div",{className:"h-full flex flex-col justify-center gap-1 shrink-0 pl-1",children:E.map((N,j)=>{const I=Jr(N.url);return I?r.jsxs("a",{href:I,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-[#171f33] hover:bg-[#222a3d] border border-[#2d3449] text-[11px] text-[#c0c1ff] hover:text-white transition-colors",children:[r.jsx(Gi,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:N.name}),r.jsx(Jh,{size:11,className:"opacity-70"})]},j):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(Gi,{size:13,className:"text-[#8083ff]"}),r.jsx("span",{className:"max-w-[120px] truncate",children:N.name})]},j)})})]}):E.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(nf,{size:13,className:"text-[#8083ff]"}),r.jsxs("span",{children:["提交附件 (",E.length," 个文件)"]})]}),E.map((N,j)=>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(Gi,{size:15,className:"text-[#8083ff] shrink-0"}),r.jsx("span",{className:"text-[#dae2fd] truncate font-medium",children:N.name}),typeof N.size=="number"&&r.jsxs("span",{className:"text-[10px] text-[#908fa0] shrink-0",children:["(",(N.size/1024).toFixed(1)," KB)"]})]}),N.url&&Jr(N.url)&&r.jsxs("a",{href:Jr(N.url),target:"_blank",rel:"noreferrer",download:N.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($s,{size:12}),r.jsx("span",{children:"下载"})]})]},j))]}):v.codeLines&&v.codeLines.length>0?r.jsx("pre",{className:"px-4 py-3 font-mono text-[11px] leading-5 text-[#dae2fd] overflow-y-auto max-h-full whitespace-pre-wrap break-words",children:v.codeLines.map((N,j)=>r.jsx("div",{className:N.isHighlight?"text-[#4edea3]":"",style:{paddingLeft:`${(N.indent||0)*12}px`},children:N.text},j))}):v.textContent?r.jsx("div",{className:"px-4 py-3 font-sans text-xs leading-5 text-[#dae2fd] overflow-y-auto max-h-full whitespace-pre-wrap break-words",children:v.textContent}):r.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 px-6 text-center",children:[r.jsx(a0,{size:28,className:"text-[#4a5570]"}),r.jsxs("span",{className:"text-[11px] text-[#908fa0] leading-relaxed",children:["该作品没有可展示的作答内容",r.jsx("br",{}),r.jsx("span",{className:"text-[10px] opacity-70",children:"(原始作答流水为空或为纯数值型)"})]})]}),v.workContent&&r.jsxs("span",{className:"absolute bottom-2 right-2 text-[10px] font-mono text-[#908fa0] bg-[#131b2e]/90 px-1.5 py-0.5 rounded border border-[#2d3449]/50",children:["真实作答 · ",v.workContent.eventCount," 条事件"]})]})};return r.jsxs("div",{id:"spotlight-dual-work-arena",className:"flex flex-col gap-4 w-full select-none",children:[r.jsxs("div",{className:"bg-[#131b2e] p-4 rounded-xl border border-[#2d3449]/60 flex flex-wrap items-center justify-between gap-3 shadow-md",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#8083ff]/20 flex items-center justify-center text-[#c0c1ff] border border-[#8083ff]/30",children:r.jsx(tf,{size:20})}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h1",{className:"text-base font-bold text-[#dae2fd]",children:"大屏焦点作品对比赏析"}),r.jsxs("span",{className:"px-2 py-0.5 rounded bg-[#ca8100]/20 text-[#ffb95f] font-mono text-[10px] font-semibold flex items-center gap-1 border border-[#ca8100]/30",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#ffb95f] animate-ping"}),"教师激光笔协同标记中"]})]}),r.jsxs("span",{className:"text-xs text-[#c7c4d7] mt-0.5",children:["标杆创新解法 (",e?p(e.studentName,s):"作品 A 待就绪",") ⟷ 经典逆风翻盘解法 (",t?p(t.studentName,s):"作品 B 待就绪",")"]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[o&&r.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#171f33] hover:bg-[#222a3d] text-[#c7c4d7] hover:text-white border border-[#2d3449]/60 transition-colors text-xs font-medium",title:"将对比沙箱推送到全班学生机",children:[r.jsx(i0,{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(Bl,{size:16})})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e?r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md relative",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-[#8083ff] text-white flex items-center justify-center font-bold text-xs shadow-sm",children:s?"A":e.studentInitial}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("span",{className:"text-sm font-semibold text-[#dae2fd]",children:[p(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(di,{size:13,className:"text-[#ffb95f] fill-[#ffb95f]"}),r.jsx("span",{className:"font-mono text-xs font-semibold",children:typeof e.rating=="number"?e.rating.toFixed(1):"—"}),r.jsxs("span",{className:"text-[10px] text-[#908fa0]",children:["(",e.reviewCount??0,"评)"]})]})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.badges?.map((v,w)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${v.colorClass}`,children:v.label},w))}),g(e),e.codeLines?.some(v=>v.comment)?r.jsxs("div",{className:"bg-[#060e20] rounded-lg p-3 font-mono text-[11px] leading-5 border border-[#2d3449]/60 overflow-x-auto text-[#dae2fd]",children:[r.jsxs("div",{className:"text-[#908fa0] mb-1",children:["# ",e.codeTitle??""]}),e.codeLines.filter(v=>v.comment).map((v,w)=>r.jsx("div",{className:v.isHighlight?"bg-[#8083ff]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#908fa0]",children:v.comment})},w))]}):null]}):r.jsxs("div",{"data-testid":"work-slot-a-placeholder",className:"bg-[#131b2e]/60 rounded-xl p-6 flex flex-col items-center justify-center gap-2 border border-dashed border-[#2d3449] min-h-[280px] text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-[#8083ff]/10 text-[#8083ff] flex items-center justify-center font-bold text-sm",children:"A"}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"待选作品 A"}),r.jsx("span",{className:"text-[11px] text-[#908fa0]",children:"请在上方全班作品池中点击「设为焦点 A」进行对比"})]}),t?r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md relative",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-[#00a572] text-white flex items-center justify-center font-bold text-xs shadow-sm",children:s?"B":t.studentInitial}),r.jsxs("div",{className:"flex flex-col",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[r.jsxs("span",{className:"text-sm font-semibold text-[#dae2fd]",children:[p(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(di,{size:13,className:"text-[#ffb95f] fill-[#ffb95f]"}),r.jsx("span",{className:"font-mono text-xs font-semibold",children:typeof t.rating=="number"?t.rating.toFixed(1):"—"}),r.jsxs("span",{className:"text-[10px] text-[#908fa0]",children:["(",t.reviewCount??0,"评)"]})]})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.badges?.map((v,w)=>r.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-mono font-medium ${v.colorClass}`,children:v.label},w))}),g(t),t.codeLines?.some(v=>v.comment)?r.jsxs("div",{className:"bg-[#060e20] rounded-lg p-3 font-mono text-[11px] leading-5 border border-[#2d3449]/60 overflow-x-auto text-[#dae2fd]",children:[r.jsxs("div",{className:"text-[#908fa0] mb-1",children:["# ",t.codeTitle??""]}),t.codeLines.filter(v=>v.comment).map((v,w)=>r.jsx("div",{className:v.isSuccess?"bg-[#00a572]/20 px-1 rounded -mx-1":"",children:r.jsx("span",{className:"text-[#4edea3] text-[10px]",children:v.comment})},w))]}):null]}):r.jsxs("div",{"data-testid":"work-slot-b-placeholder",className:"bg-[#131b2e]/60 rounded-xl p-6 flex flex-col items-center justify-center gap-2 border border-dashed border-[#2d3449] min-h-[280px] text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-[#00a572]/10 text-[#00a572] flex items-center justify-center font-bold text-sm",children:"B"}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:"待选作品 B"}),r.jsx("span",{className:"text-[11px] text-[#908fa0]",children:"请在上方全班作品池中点击「设为焦点 B」进行并排对比"})]})]}),r.jsxs("div",{className:"bg-[#131b2e] rounded-xl p-4 flex flex-col gap-3 border border-[#2d3449]/60 shadow-md",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(o0,{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:()=>d(!u),className:"text-[11px] text-[#c0c1ff] hover:text-white font-medium transition-colors",children:u?"取消批注":"+ 追加教师批注"})]})]}),u&&r.jsxs("form",{onSubmit:x,className:"flex gap-2",children:[r.jsx("input",{type:"text",value:f,onChange:v=>m(v.target.value),placeholder:"输入大屏协同批注要点...",className:"flex-1 px-3 py-1.5 rounded-lg bg-[#060e20] border border-[#2d3449] text-xs text-[#dae2fd] placeholder-[#908fa0] focus:outline-none focus:border-[#8083ff]"}),r.jsx("button",{type:"submit",className:"px-3 py-1.5 rounded-lg bg-[#c0c1ff] text-[#1000a9] font-semibold text-xs hover:bg-[#8083ff] hover:text-white transition-colors",children:"发送批注"})]}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(v=>r.jsxs("div",{className:"bg-[#171f33] p-3 rounded-lg flex flex-col gap-1.5 relative overflow-hidden border border-[#2d3449]/50",children:[r.jsx("div",{className:"w-1 absolute left-0 top-0 bottom-0",style:{backgroundColor:v.borderColor}}),r.jsxs("div",{className:"flex items-center justify-between pl-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold ${v.authorType==="teacher"?"bg-[#8083ff] text-white":"bg-[#00a572] text-white"}`,children:v.authorRole}),r.jsx("span",{className:"text-xs font-semibold text-[#dae2fd]",children:p(v.authorName,s)})]}),r.jsx("span",{className:"text-[10px] font-mono text-[#908fa0]",children:v.timeAgo})]}),r.jsx("p",{className:"text-xs text-[#dae2fd] pl-2 leading-relaxed",children:v.content})]},v.id))})]}),r.jsx(qe,{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:()=>y(null),children:r.jsxs("div",{className:"relative max-w-4xl max-h-[90vh] bg-[#131b2e] rounded-xl overflow-hidden border border-[#2d3449] shadow-2xl p-2",onClick:v=>v.stopPropagation(),children:[r.jsx("button",{type:"button",onClick:()=>y(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(De,{size:18})}),r.jsx("img",{src:h,alt:"Work preview",className:"max-w-full max-h-[85vh] object-contain rounded-lg"})]})})]})},hE=({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(qe,{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(Ma,{size:13,className:"text-[#4edea3]"}),typeof i=="number"?`${i}台学生端已同步点赞动画`:"学生端同步状态未知"]})]})]}),fE=({podiumStudents:e,isAnonymous:t=!1,onAwardPeerReviewPoints:n,onArchiveTopWorks:s,onCallStudentMic:i,onInviteScreenShare:o,onAdvanceToStage3:a})=>{const l=(c,u)=>!u||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(l0,{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(Fl,{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(ut,{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(Xs,{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,u=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(Fa,{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:!u,onClick:()=>u&&o(u),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(Xh,{size:14,className:"text-[#4edea3]"}),r.jsx("span",{children:u?`邀请 ${l(u,t)} 投屏分享`:"暂无提名,无法投屏"})]}),r.jsx("span",{className:"text-[#908fa0] text-[10px] font-mono",children:"邀请"})]})]})})()}),r.jsx(qe,{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(li,{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"})})]})]})]})},mE=({isVisible:e,danmakuList:t,onSendDanmaku:n,isAnonymous:s=!1})=>{const[i,o]=b.useState(""),[a,l]=b.useState(!1);if(!e)return null;const c=d=>{d.preventDefault(),i.trim()&&(n?.(i.trim(),"text"),o(""))},u=()=>{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(d=>r.jsx("div",{className:"absolute whitespace-nowrap animate-danmaku-slide pointer-events-auto",style:{top:`${d.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:[d.type==="voice"?r.jsxs("span",{className:"flex items-center gap-1 text-[#4edea3] font-mono text-[11px]",children:[r.jsx(Fa,{size:12,className:"animate-pulse"}),r.jsxs("span",{children:[d.voiceDuration||3,"s"]})]}):r.jsx("span",{className:"text-sm",children:"💬"}),r.jsxs("span",{className:"text-[#c0c1ff] font-medium",children:[s&&d.sender.length>1?`${d.sender[0]}**`:d.sender,":"]}),r.jsx("span",{className:d.color||"text-white",children:d.text})]})},d.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:d=>o(d.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(c0,{size:13})}),r.jsx("button",{type:"button",onClick:u,className:"p-1.5 rounded-full bg-[#171f33] hover:bg-[#222a3d] text-[#4edea3] transition-colors",title:"发送语音弹幕",children:r.jsx(Fa,{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(sf,{size:13,className:"text-[#c0c1ff]"}),r.jsx("span",{children:"发弹幕"})]})})]})},pE=({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(Ml,{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(De,{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(qe,{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 gE(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 xE=({isOpen:e,onClose:t,onAdvanceToStage3:n,lessonTitle:s="",addToast:i,workA:o,workB:a,showcaseWorks:l=[],onSelectSpotlightWork:c,reviewProgress:u,countdownSeconds:d,onAutoAssign:f,autoAssigning:m=!1,matchingItems:h,badges:y,annotations:p,rubricDimensions:x,reactions:g,podiumStudents:v,danmaku:w,syncedStudentsCount:E,teacherName:N,stageLabel:j})=>{const[I,z]=b.useState({stage:j||"",isLocked:!0,isDualScreen:!0,isAnonymous:!0,timeRemainingSeconds:d??0,totalTimeSeconds:d??0,isPaused:!1,completedReviews:u?.completed??0,totalStudents:u?.total??0,totalLikes:0,totalNominations:0,showVoiceDanmaku:!0,showDanmaku:!0}),[$,V]=b.useState(!1),[B,_]=b.useState(!1),[U,k]=b.useState(!1),[F,Z]=b.useState(h??[]),[M,A]=b.useState(y??[]),[L,S]=b.useState(o??null),[R,D]=b.useState(a??null),[P,Y]=b.useState(p??[]),[H,ee]=b.useState(x??[]),[le,ae]=b.useState(g??[]),[fe,be]=b.useState(v??[]),[ye,Se]=b.useState(w??[]);b.useEffect(()=>{o!==void 0&&S(o??null)},[o]),b.useEffect(()=>{a!==void 0&&D(a??null)},[a]),b.useEffect(()=>{h&&Z(h)},[h]),b.useEffect(()=>{y&&A(y)},[y]),b.useEffect(()=>{p&&Y(p)},[p]),b.useEffect(()=>{x&&ee(x)},[x]),b.useEffect(()=>{g&&ae(g)},[g]),b.useEffect(()=>{v&&be(v)},[v]),b.useEffect(()=>{w&&Se(w)},[w]),b.useEffect(()=>{if(!e||I.isPaused)return;const O=setInterval(()=>{z(G=>G.timeRemainingSeconds<=1?{...G,timeRemainingSeconds:0,isPaused:!0}:{...G,timeRemainingSeconds:G.timeRemainingSeconds-1})},1e3);return()=>clearInterval(O)},[e,I.isPaused]);const me=b.useCallback(O=>{e&&(O.key==="Enter"?(O.preventDefault(),te()):O.key==="Escape"?(O.preventDefault(),t()):O.code==="Space"&&O.target===document.body&&(O.preventDefault(),se()))},[e,t]);if(b.useEffect(()=>(window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)),[me]),!e)return null;const C=()=>{z(O=>({...O,isAnonymous:!O.isAnonymous})),i?.("互评模式已切换",I.isAnonymous?"已恢复显示真实学生姓名":"已开启双盲匿名评价模式","info")},J=()=>{z(O=>({...O,timeRemainingSeconds:O.timeRemainingSeconds+60,totalTimeSeconds:O.totalTimeSeconds+60})),i?.("互评加时","倒计时已增加 1 分钟","success")},se=()=>{z(O=>({...O,isPaused:!O.isPaused}))},W=()=>{document.fullscreenElement?document.exitFullscreen&&(document.exitFullscreen().catch(()=>{}),V(!1)):(document.documentElement.requestFullscreen().catch(()=>{}),V(!0))},T=O=>{ae(G=>G.map(ie=>ie.id===O?{...ie,count:ie.count+1}:ie)),z(G=>({...G,totalLikes:G.totalLikes+1}))},q=O=>{const G={id:`ann-${Date.now()}`,authorType:"teacher",authorRole:"主讲教师",authorName:N||"教师",timeAgo:"刚刚",content:O,borderColor:"#8083ff"};Y(ie=>[G,...ie]),i?.("批注已挂载","协同板书批注已同步至大屏","success")},X=(O,G="text")=>{const ie={id:`d-${Date.now()}`,sender:N||"教师",text:O,type:G,voiceDuration:void 0,color:"text-[#4edea3]"};Se(ue=>[...ue,ie])},ne=()=>{i?.("功能尚未接入","批量积分发放通道建设中,本次未写入任何积分。","warning")},Q=()=>{i?.("功能尚未接入","作品归档通道建设中,本次未做任何存储。","warning")},re=O=>{i?.("功能尚未接入",`向 ${O} 发起连麦的信令通道建设中。`,"warning")},de=O=>{i?.("功能尚未接入",`向 ${O} 的投屏邀请通道建设中。`,"warning")},te=()=>{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(cE,{state:I,onToggleAnonymous:C,onOpenRubricModal:()=>_(!0),onToggleVoiceDanmaku:()=>z(O=>({...O,showDanmaku:!O.showDanmaku})),onAdvanceStage:te,onAddMinute:J,onTogglePauseTimer:se,isFullscreen:$,onToggleFullscreen:W,onClose:t}),r.jsxs("main",{className:"relative flex-1 overflow-y-auto w-full px-6 py-5",children:[!L&&!R&&l.length===0&&F.length===0&&fe.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 份」自动分配。"}),f&&r.jsx("button",{type:"button",disabled:m,onClick:()=>void f(),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:m?"分配中…":"一键分配互评"})]}),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:()=>k(!U),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:U?"收起作品池 ▲":`展开作品池 (${l.length}) ▼`})]}),U&&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(O=>{const G=L?.id===O.workId,ie=R?.id===O.workId,ue=I.isAnonymous&&O.studentName.length>1?`${O.studentName[0]}**`:O.studentName;return r.jsxs("div",{className:`p-2.5 rounded-lg border text-xs flex flex-col gap-1.5 transition-all ${G?"bg-[#8083ff]/15 border-[#8083ff]":ie?"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:ue}),r.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-medium border ${O.source==="plugin"?"bg-[#8083ff]/20 text-[#c0c1ff] border-[#8083ff]/30":O.source==="assignment"?"bg-[#00a572]/20 text-[#4edea3] border-[#00a572]/30":"bg-[#ca8100]/20 text-[#ffb95f] border-[#ca8100]/30"}`,children:O.sourceLabel})]}),r.jsx("div",{className:"text-[11px] text-[#908fa0] truncate",title:O.title,children:O.title}),O.files&&O.files.length>0&&r.jsxs("div",{className:"text-[10px] text-[#8083ff] truncate",children:["📎 ",O.files.length," 个附件 (",O.files.map(he=>he.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",O.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${G?"bg-[#8083ff] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#8083ff]/40 text-[#dae2fd]"}`,children:G?"焦点 A ★":"设为焦点 A"}),r.jsx("button",{type:"button",onClick:()=>c?.("B",O.workId),className:`flex-1 py-1 rounded text-[10px] font-semibold transition-colors cursor-pointer ${ie?"bg-[#00a572] text-white shadow-xs":"bg-[#222a3d] hover:bg-[#00a572]/40 text-[#dae2fd]"}`,children:ie?"焦点 B ★":"设为焦点 B"})]})]},O.workId)})})]}),r.jsx(mE,{isVisible:I.showDanmaku,danmakuList:ye,onSendDanmaku:X,isAnonymous:I.isAnonymous}),r.jsxs("div",{className:"grid grid-cols-12 gap-5 items-start",children:[r.jsx("div",{className:"col-span-12 lg:col-span-3",children:r.jsx(dE,{matchingItems:F,badges:M,isAnonymous:I.isAnonymous,onSelectMatchingItem:O=>{i?.(`查看互评明细 ${O.code}`,`${O.reviewerName} 正在审阅 ${O.targetStudentName} 的作业`,"info")}})}),r.jsxs("div",{className:"col-span-12 lg:col-span-6 flex flex-col gap-4",children:[!L&&!R&&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:"学生提交课件作业后,此处将自动展示两份真实作品的并排对比。"})]}),L||R?r.jsx(uE,{workA:L,workB:R,annotations:P,isAnonymous:I.isAnonymous,onFullscreenCanvas:W,onSyncSandboxToClass:()=>{i?.("沙箱广播已生效",`对比范本已同步至全班 ${I.totalStudents||0} 台学生机控制台`,"success")},onAddAnnotation:q}):null,r.jsx(hE,{dimensions:H,averagePercentage:gE(H),reactions:le,onReactionClick:T,syncedStudentsCount:E})]}),r.jsx("div",{className:"col-span-12 lg:col-span-3",children:r.jsx(fE,{podiumStudents:fe,isAnonymous:I.isAnonymous,onAwardPeerReviewPoints:ne,onArchiveTopWorks:Q,onCallStudentMic:re,onInviteScreenShare:de,onAdvanceToStage3:te})})]})]}),r.jsx(pE,{isOpen:B,onClose:()=>_(!1)})]})};function uh(e){return e===401||e===403}function Bm(e){return e===401||e===403||e===404}const ei={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},bE=["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"],yE=4e3;function wE(e,t={}){const{enabled:n=!0,reconcileMs:s=yE}=t,[i,o]=b.useState(ei),[a,l]=b.useState("polling"),[c,u]=b.useState(null),[d,f]=b.useState(null),m=b.useRef(0),h=b.useRef(!0),y=b.useRef(!1),p=b.useRef(null),x=b.useCallback(()=>{p.current&&(clearInterval(p.current),p.current=null)},[]);b.useEffect(()=>{y.current=!1,u(null)},[e]),b.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);const g=b.useCallback(async()=>{if(!e||y.current)return;const v=++m.current;try{const w=await fetch(`/api/classroom/stage/${encodeURIComponent(e)}/data`);if(Bm(w.status)){if(y.current=!0,x(),!h.current)return;l("error"),u({status:w.status,message:w.status===401?"登录状态已失效(401)":w.status===403?"当前账号无权查看该课节的大屏展台(403)":"目标课节或展台数据不存在(404)"});return}if(!w.ok)throw new Error(`stage data HTTP ${w.status}`);const E=await w.json();if(!h.current||v!==m.current)return;o({...ei,...E,pacing:{...ei.pacing,...E.pacing||{}}}),f(Date.now()),u(null),l(N=>N==="reconnecting"?"live":N==="error"?"polling":N)}catch(w){if(!h.current||y.current)return;l(E=>E==="live"?"reconnecting":E),console.warn("[StageDisplay] sync failed:",w)}},[e,x]);return b.useEffect(()=>{if(!n||!e)return;let v=!0;return g().then(()=>{!v||y.current||(p.current=setInterval(()=>{if(y.current){x();return}g()},s))}),()=>{v=!1,x()}},[n,e,s,g,x]),b.useEffect(()=>{if(!n||!e)return;let v=null;const w=()=>{v||y.current||(v=setTimeout(()=>{v=null,y.current||g()},120))};let E=null;const N=jc(j=>{E?.(),j.emit("join-room",e);const I=bE.map(B=>{const _=U=>{const k=U?.lessonId;k&&k!==e||w()};return j.on(B,_),[B,_]}),z=()=>{y.current||(l("live"),g())},$=()=>l("reconnecting"),V=()=>l("reconnecting");j.on("connect",z),j.on("disconnect",$),j.on("connect_error",V),j.connected&&l("live"),E=()=>{for(const[B,_]of I)j.off(B,_);j.off("connect",z),j.off("disconnect",$),j.off("connect_error",V)}});return()=>{N(),E?.(),v&&clearTimeout(v)}},[n,e,g]),{data:i,health:a,terminalError:c,lastSyncedAt:d,refresh:g}}const vE={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 Cc(e,t="zh"){const n=vE[e];return n?t==="zh"?n.zh:n.en:e}let hh=0;function Qt(e){return hh+=1,`${e}-${Date.now().toString(36)}-${hh}`}function SE(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=Cc(t.stage,s),y=t.stage==="ARCHIVED_REPORT",p=t.stage==="WRAP_UP_EXIT_TICKET";let x;p?x=o?"请提醒学生在设备上完成 60 秒结课通票":"Remind students to complete the 60s exit ticket":y&&(x=o?"本课节已归档,大屏将展示学情简报":"Lesson archived; the stage will show the learning report");let g="info",v="🎓";p?(g="accent",v="🎫"):y&&(g="warning",v="📦"),a.push({id:Qt("stage"),tone:g,icon:v,title:o?`课堂环节已切换:${h}`:`Stage changed: ${h}`,detail:x,dedupeKey:`stage:${t.stage}`})}const l=e.activePoll?.id??null,c=t.activePoll?.id??null;if(c&&c!==l)a.push({id:Qt("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:Qt("poll-end"),tone:"info",icon:"📊",title:o?"课堂投票已结束":"Quick poll closed",detail:o?`本轮共 ${h} 人作答`:`${h} responded in this round`,dedupeKey:`poll-end:${l}`})}const u=e.activeBuzzer?.id??null,d=t.activeBuzzer?.id??null,f=e.activeBuzzer?.status??null,m=t.activeBuzzer?.status??null;if(d&&d!==u)a.push({id:Qt("buzz-start"),tone:"accent",icon:"🔔",title:o?"抢答已开始":"Buzz-in started",detail:t.activeBuzzer?.title?String(t.activeBuzzer.title):void 0,dedupeKey:`buzz-start:${d}`});else if(d&&d===u&&m==="LOCKED"&&f!=="LOCKED"){const h=t.activeBuzzer?.winnerName,y=t.activeBuzzer?.responseTimeMs;a.push({id:Qt("buzz-winner"),tone:"success",icon:"🏆",title:o?"抢答已产生赢家":"Buzz-in winner decided",detail:h?o?`${h}${y?` · 响应用时 ${y} 毫秒`:""}`:`${h}${y?` · ${y} ms`:""}`:void 0,dedupeKey:`buzz-winner:${d}`})}else d&&d===u&&m==="READY"&&f==="LOCKED"&&a.push({id:Qt("buzz-reset"),tone:"info",icon:"♻️",title:o?"抢答已重置,可以开始新一轮":"Buzzer reset — ready for a new round",dedupeKey:`buzz-reset:${d}`});return a}function kE(e,t,n="zh"){const s=n==="zh";return e===t?null:e==="reconnecting"?{id:Qt("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:Qt("conn"),tone:"success",icon:"✅",title:s?"实时连接已恢复":"Live connection restored",dedupeKey:"conn:live"}:null}const fh={info:{ring:"border-sky-500/50 bg-sky-500/10 text-sky-200",icon:rf},success:{ring:"border-emerald-500/50 bg-emerald-500/10 text-emerald-200",icon:bt},warning:{ring:"border-amber-500/50 bg-amber-500/10 text-amber-200",icon:Bt},accent:{ring:"border-indigo-500/50 bg-indigo-500/10 text-indigo-200",icon:ut}},jE=6e3,mh=8e3;function NE({notices:e,onDismiss:t,lang:n="zh"}){const s=e.slice(-4),i=b.useRef(new Map);return b.useEffect(()=>{for(const a of s){if(i.current.has(a.id))continue;const l=setTimeout(()=>{i.current.delete(a.id),t(a.id)},jE);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]),b.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=fh[o.tone]??fh.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(De,{size:14})})]},o.id)})})}function CE(e="zh"){const[t,n]=b.useState([]),s=b.useRef(new Map),i=b.useCallback(l=>{if(l.length===0)return;const c=Date.now();n(u=>{let d=u;for(const f of l){const m=s.current.get(f.dedupeKey);if(!(m&&c-m<mh)){s.current.set(f.dedupeKey,c);for(const[h,y]of s.current)c-y>mh&&s.current.delete(h);d=[...d,f]}}return d.length>40?d.slice(d.length-40):d})},[]),o=b.useCallback(l=>{n(c=>c.filter(u=>u.id!==l))},[]),a=b.useCallback(()=>n([]),[]);return{notices:t,push:i,dismiss:o,clear:a}}function EE({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:Ma},reconnecting:{label:s?"重连中":"Reconnecting",cls:"text-amber-300 border-amber-500/40 bg-amber-500/10",dot:"bg-amber-400 animate-ping",Icon:Qc},polling:{label:s?"轮询同步":"Polling",cls:"text-sky-300 border-sky-500/40 bg-sky-500/10",dot:"bg-sky-400",Icon:Ma},error:{label:s?"连接异常":"Error",cls:"text-rose-300 border-rose-500/40 bg-rose-500/10",dot:"bg-rose-400",Icon:Qc}}[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 IE(){if(typeof document>"u")return!1;const e=document.documentElement;return!!(e.requestFullscreen||e.webkitRequestFullscreen)}function Dr(){return typeof document>"u"?!1:!!(document.fullscreenElement||document.webkitFullscreenElement)}function AE(){const[e,t]=b.useState(!1),[n,s]=b.useState(!1),i=b.useRef(!1);b.useEffect(()=>{if(typeof document>"u")return;const c=()=>{const u=Dr();s(u),u||(i.current=!1,t(!1))};return document.addEventListener("fullscreenchange",c),document.addEventListener("webkitfullscreenchange",c),()=>{document.removeEventListener("fullscreenchange",c),document.removeEventListener("webkitfullscreenchange",c)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const c=u=>{u.key==="Escape"&&(Dr()||i.current&&(i.current=!1,t(!1)))};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[]);const o=b.useCallback(async()=>{if(t(!0),!IE()){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=b.useCallback(async()=>{if(i.current=!1,t(!1),s(!1),Dr())try{await document.exitFullscreen?.()}catch(c){console.warn("[ViewportFullscreen] exit failed:",c)}},[]),l=b.useCallback(()=>{Dr()||i.current?a():o()},[o,a]);return{isFullscreen:e,nativeActive:n,toggle:l,exit:a}}function Ft(e){return typeof e=="number"&&Number.isFinite(e)?String(e):"—"}function Ws(e,t){return!t||t<=0?"—":`${Math.round(e/t*100)}%`}function TE({attendance:e,zh:t=!0}){const n=e?.onlineInClass??0,s=e?.expected??0,i=e?.attended??0,o=Ws(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(Ol,{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"," ",Ft(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:Ft(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:Ft(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:Ft(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:Ws(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:Ws(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 _E({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(d0,{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:Ft(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:Ft(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:[Ft(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:Ws(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:Ws(i,n)}})})]}):r.jsxs("p",{className:"text-[11px] text-slate-400 leading-relaxed flex items-center gap-2",children:[r.jsx(Ml,{size:14,className:"shrink-0"}),t?"还没有学生打开互动课件。展示口径为平台累计(含往期课节),作答数据将在学生开始操作后实时出现。":"No courseware activity yet."]})]})}const PE={quiz_answered:"✅",checkin:"🙋",achievement:"🏅",assignment_submitted:"📄",assignment_graded:"🖊️",progress:"📈",courseware_submitted:"🖥️",answer:"💡",success:"🎉",info:"ℹ️"};function zE({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(Ul,{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:PE[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(of,{size:14,className:"shrink-0"}),t?"课堂动态会在学生答题、签到、提交课件时实时出现在这里。":"Live events will appear here."]})]})}function RE({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(u0,{size:13,className:"text-indigo-400"}),n?"结课通票已提交":"Exit tickets submitted"]}),r.jsxs("span",{className:"font-mono font-bold text-white",children:[Ft(s),i>0?` / ${Ft(i)}`:""]})]})}function LE({lessonId:e,lessonTitle:t="互动课堂",data:n,lang:s="zh",health:i,lastSyncedAt:o,showCloseButton:a=!0,onClose:l,peerReview:c,syncedStudentsCount:u,peerReviewOpen:d,onOpenPeerReview:f,onClosePeerReview:m}){const{isFullscreen:h,toggle:y}=AE(),[p,x]=b.useState(""),[g,v]=b.useState(!1),w=d??g,E=I=>{d===void 0&&v(I),I?f?.():m?.()};b.useEffect(()=>{const I=()=>{x(new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}))};I();const z=setInterval(I,1e3);return()=>clearInterval(z)},[]);const N=n.pacing??ei.pacing,j=(N.TOO_FAST||0)+(N.CONFUSED||0)+(N.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:Cc(n.stage,s)})]}),r.jsxs("div",{className:"flex items-center gap-6",children:[i&&r.jsx(EE,{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(er,{size:20,className:"text-blue-400"}),r.jsx("span",{children:p})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(qe,{slot:"stage.display.action",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s,onToggleFullscreen:y,onOpenPeerReview:()=>E(!0)}}),r.jsxs("button",{id:"stage-peer-review-toggle",type:"button",onClick:()=>E(!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(tf,{size:15}),r.jsx("span",{children:"作业互评赏析"})]}),r.jsx("button",{id:"stage-fullscreen-toggle",onClick:y,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(h0,{size:20}):r.jsx(f0,{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(De,{size:20})})]})]})]}),r.jsx("div",{className:"max-h-12 overflow-hidden shrink-0",children:r.jsx(qe,{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(of,{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(ut,{size:24})}),r.jsxs("div",{children:[r.jsx("span",{className:"text-xs font-bold text-amber-400 uppercase tracking-wide",children:s==="zh"?"课堂极速互动":"Quick Activity"}),r.jsx("h3",{className:"text-xl font-bold text-white",children:n.activePoll.title})]})]}),r.jsxs("div",{className:"text-right",children:[r.jsx("span",{className:"text-3xl font-black text-amber-400 font-mono",children:n.activePoll.totalVotes||0}),r.jsx("span",{className:"text-xs text-slate-400 block",children:s==="zh"?"人已作答":"Responded"})]})]}),r.jsx("div",{className:"grid grid-cols-2 gap-4 my-2",children:(Array.isArray(n.activePoll.options)&&n.activePoll.options.length>0?n.activePoll.options:[]).map(I=>{const z=n.activePoll.distribution?.[I]||0,$=Math.round(z/(n.activePoll.totalVotes||1)*100);return r.jsxs("div",{className:"p-5 bg-slate-800/50 rounded-2xl border border-slate-700/50 flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-10 h-10 rounded-xl bg-blue-600 text-white font-bold text-lg flex items-center justify-center shadow-md",children:I}),r.jsxs("span",{className:"font-semibold text-slate-200 text-lg",children:["选项 ",I]})]}),r.jsxs("span",{className:"font-mono font-bold text-xl text-blue-400",children:[$,"% (",z,")"]})]}),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:`${$}%`}})})]},I)})})]}),n.activeBuzzer&&r.jsxs("div",{className:"bg-slate-900/90 rounded-3xl border border-slate-800 p-8 shadow-xl flex flex-col items-center text-center justify-center",children:[r.jsx("div",{className:"p-4 bg-rose-500/10 rounded-2xl border border-rose-500/20 text-rose-400 mb-4",children:r.jsx(ui,{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(Fl,{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(m0,{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(Ni,{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(qe,{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(TE,{attendance:n.attendance,zh:s==="zh"}),r.jsx(_E,{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(RE,{submitted:n.exitTicketSubmitted,expected:n.attendance?.expected,zh:s==="zh"})}),r.jsx(zE,{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(p0,{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:[j," ",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:N.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:`${j>0?(N.CLEAR||0)/j*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:N.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:`${j>0?(N.CONFUSED||0)/j*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:N.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:`${j>0?(N.TOO_FAST||0)/j*100:0}%`}})})]}),r.jsx("p",{className:"text-xs text-slate-400 text-center mt-2",children:s==="zh"?"提示:此数据来自学生端匿名点击,自动脱敏保护学生自尊。":"Aggregated anonymized signals from student devices."})]})]})]}),w&&r.jsx(xE,{isOpen:w,onClose:()=>E(!1),lessonTitle:t,syncedStudentsCount:u,...c??{}}),r.jsx("div",{className:"absolute inset-0 pointer-events-none z-30 overflow-hidden",children:r.jsx(qe,{slot:"stage.display.overlay",slotProps:{lessonId:e,lessonTitle:t,stage:n.stage,data:n,isFullscreen:h,lang:s}})})]})}const OE=/\b(function|const|let|var|class|def|import|return|if|for|while|print|console)\b|[{};]\s*$/;function DE(e){const t=Array.isArray(e)?e.filter(Boolean):[];if(t.length===0)return{kind:"empty",lines:[],eventCount:0};const n=t.filter(d=>{const f=String(d?.eventType??d?.event_type??"").toLowerCase();return f.includes("submit")||f.includes("finish")||f.includes("complete")}),s=n.length>0?n:t,i=s[s.length-1],o=i?.payload??i?.payloadJson??i?.data??{},a=ME(o,["code","source","src","program","html","content","answer"]);if(a&&(OE.test(a)||a.includes(`
|
|
89
|
+
`)||a.length>120))return{kind:"code",lines:a.split(`
|
|
90
|
+
`).slice(0,14).map(d=>({text:d.slice(0,160),indent:Math.floor((d.match(/^\s*/)?.[0].length??0)/2),isHighlight:/correct|answer|正确|对|错|✓|✗/i.test(d)})),eventCount:t.length};const l=Object.entries(o).filter(([,d])=>typeof d!="object"||d===null),c=l.filter(([d])=>!$E.has(d.toLowerCase()));if(c.length>=3)return{kind:"structured",lines:c.slice(0,10).map(([d,f])=>({text:`${d}: ${FE(f)}`,indent:0})),eventCount:t.length};if(a)return{kind:"text",lines:a.split(`
|
|
91
|
+
`).slice(0,12).map(d=>({text:d.slice(0,200),indent:0})),eventCount:t.length};const u=l.filter(([,d])=>typeof d=="number");return u.length>0?{kind:"numeric",lines:u.slice(0,6).map(([d,f])=>({text:`${d}: ${f}`,indent:0})),eventCount:t.length}:{kind:"empty",lines:[],eventCount:t.length}}const $E=new Set(["type","score","comment","completion","timestamp","t","watch","attemptsd","eventtype","payload"]);function ME(e,t){for(const n of t){const s=e?.[n];if(typeof s=="string"&&s.trim())return s}return null}function FE(e){return e==null?"—":Array.isArray(e)?e.map(t=>String(t)).join("、"):typeof e=="object"?JSON.stringify(e):String(e)}const BE={code:"代码",text:"文本作答",structured:"结构化答案",numeric:"数值结果",empty:"无内容"},ph={workA:null,workB:null,matchingItems:[],badges:[],podiumStudents:[],danmaku:[],reactions:[],rubricDimensions:[],reviewProgress:{completed:0,total:0},fromServer:!1};function gh(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(`
|
|
92
|
+
`).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(`
|
|
93
|
+
`).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 UE({lessonId:e,enabled:t,topPerformersEnabled:n=!0,attempts:s,studentCount:i,addToast:o,onTerminalError:a,lang:l="zh"}){const[c,u]=b.useState([]),[d,f]=b.useState(null),[m,h]=b.useState([]),[y,p]=b.useState(null),[x,g]=b.useState(null),[v,w]=b.useState(!1),[E,N]=b.useState(null),j=b.useRef(a);j.current=a;const I=b.useRef(null);b.useEffect(()=>{N(null),I.current=null},[e,n,t]);const z=b.useCallback((M,A)=>{N(M);const L=`${e??""}:${M}`;I.current!==L&&(I.current=L,j.current?.(M,A))},[e]),$=b.useCallback((M,A)=>{M==="A"?p(A):g(A)},[]);b.useEffect(()=>{if(!e||!n){u([]);return}let M=!0,A=!1,L=null;const S=()=>{A=!0,L&&(clearInterval(L),L=null)},R=async()=>{if(!A)try{const D=await fetch(`/api/classroom/sessions/${e}/top-performers?limit=50`);if(!M||A)return;if(Bm(D.status)){S(),u([]),z(D.status,"top-performers");return}if(!D.ok)return;const P=await D.json(),Y=Array.isArray(P?.topPerformers)?P.topPerformers:[];if(!M||A)return;u(Y.map(H=>({studentId:String(H.studentId??""),studentName:String(H.studentName??""),cumulativeScore:Number(H.cumulativeScore)||0,accuracy:Number(H.accuracy)||0})))}catch{}};return R(),A||(L=setInterval(()=>void R(),2e4)),()=>{M=!1,S()}},[e,n,z]);const[V,B]=b.useState({}),_=b.useCallback(async M=>{if(M)try{const A=await fetch(`/api/courseware/attempts/${encodeURIComponent(M)}/raw`);if(!A.ok)return;const L=await A.json(),S=Array.isArray(L?.events)?L.events:Array.isArray(L)?L:[];if(S.length===0)return;B(R=>({...R,[M]:DE(S)}))}catch{}},[]);b.useEffect(()=>{const M=[...s].filter(A=>A?.studentId&&A.studentId!=="teacher"&&A.studentId!=="guest").sort((A,L)=>(Number(L.score)||0)-(Number(A.score)||0)).slice(0,2);for(const A of M)A.attemptId&&!V[A.attemptId]&&_(String(A.attemptId))},[s,V,_]);const U=b.useCallback(async()=>{if(!e)return f(null),h([]),!1;try{const[M,A]=await Promise.all([fetch(`/api/classroom/sessions/${e}/peer-review`),fetch(`/api/classroom/sessions/${e}/showcase-works`)]);if(uh(M.status))return z(M.status,"peer-review"),!1;if(uh(A.status))return z(A.status,"showcase-works"),!1;if(M.ok){const L=await M.json();f(L),Array.isArray(L?.showcaseWorks)&&L.showcaseWorks.length>0&&h(L.showcaseWorks)}if(A.ok){const L=await A.json();Array.isArray(L?.works)&&L.works.length>0&&h(L.works)}}catch{}return!0},[e,z]),k=b.useCallback(async()=>{await U()},[U]);b.useEffect(()=>{if(!t)return;let M=!1,A=null;const L=()=>{M=!0,A&&(clearInterval(A),A=null)},S=async()=>{if(M)return;await U()||L()};return S(),M||(A=setInterval(()=>void S(),5e3)),()=>{L()}},[t,U]);const F=b.useCallback(async()=>{if(e){w(!0);try{const M=await fetch(`/api/classroom/sessions/${e}/peer-review/auto-assign`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({perStudent:2})}),A=await M.json().catch(()=>null);if(!M.ok){o?.(l==="zh"?"分配失败":"Assign failed",A?.error??`HTTP ${M.status}`,"error");return}o?.(l==="zh"?"✅ 互评已分配":"✅ Peer reviews assigned",l==="zh"?`${A.works} 份作品 · 生成 ${A.tasks} 条任务(口径:${A.scope==="lesson"?"本课节作品池":"本班全部"})`:`${A.tasks} tasks created`,"success"),await k()}finally{w(!1)}}},[e,o,l,k]);return{data:b.useMemo(()=>{const M=s.filter(P=>P?.studentId&&P.studentId!=="teacher"&&P.studentId!=="guest"),A=[...M].sort((P,Y)=>(Number(Y.score)||0)-(Number(P.score)||0)),L=(P,Y)=>{if(!P)return null;const H=String(P.studentName||P.studentId),ee=typeof P.score=="number"?P.score:null,le=String(P.attemptId??`work-${Y}`),ae=V[le];return{id:le,slot:Y,studentName:H,studentInitial:H.slice(0,1),workTitle:`${H} · ${P.coursewareName??"课件作品"}`,workSubtitle:ee===null?P.status==="completed"?"已完成提交":"作答中":`得分 ${ee}${typeof P.completion=="number"?` · 完成度 ${Math.round(P.completion*100)}%`:""}`,source:"courseware",sourceLabel:"课件作答",badges:[],workContent:ae??null,codeTitle:ae?`真实作答内容(${BE[ae.kind]})`:void 0,codeLines:ae?.lines.length?ae.lines:void 0}};let S=null,R=null;if(m.length>0){const P=m.find(H=>H.workId===y)||m[0],Y=m.find(H=>H.workId===x)||m.find(H=>H.workId!==P?.workId)||m[1];S=gh(P,"A",V),R=gh(Y,"B",V)}else S=L(A[0],"A"),R=L(A[1],"B");const D=d?.podiumStudents?.length>0?d.podiumStudents:c.slice(0,3).map((P,Y)=>({rank:Y+1,name:P.studentName,votes:P.cumulativeScore,workTitle:`${P.accuracy}% 正确率`,honorTitle:Y===0?"本节最高分":"优秀表现",rankBadgeClass:Y===0?"bg-[#ffb95f] text-[#2a1700]":"bg-[#171f33] text-[#908fa0]",tagBadgeClass:"bg-[#ca8100]/20 text-[#ffb95f]"}));return d?.matchingItems?.length||d?.podiumStudents?.length?{...ph,workA:S,workB:R,matchingItems:d.matchingItems??[],badges:d.badges??[],podiumStudents:D,danmaku:d.danmaku??[],reactions:d.reactions??[],rubricDimensions:d.dimensions??[],reviewProgress:d.progress??{completed:0,total:0},fromServer:!0}:{...ph,workA:S,workB:R,podiumStudents:D,reviewProgress:{completed:M.filter(P=>P.status==="completed").length,total:i}}},[d,s,c,i,V,m,y,x]),topPerformers:c,showcaseWorks:m,selectedWorkAId:y,selectedWorkBId:x,setSpotlightWork:$,autoAssigning:v,autoAssign:F,refresh:k,authErrorStatus:E}}function VE({lessonId:e,lessonTitle:t="互动课堂",lang:n="zh"}){const{data:s,health:i,terminalError:o,lastSyncedAt:a}=wE(e),{notices:l,push:c,dismiss:u}=CE(n),[d,f]=b.useState(!1),[m,h]=b.useState([]),[y,p]=b.useState("");b.useEffect(()=>{if(!d||!e)return;let j=!1;return(async()=>{try{const I=await fetch("/api/courseware/attempts?pageSize=all");I.ok&&!j&&h(Zs(await I.json()))}catch{}})(),()=>{j=!0}},[d,e]),b.useEffect(()=>{let j=!1;return(async()=>{try{const I=await fetch("/api/auth/session");if(I.ok&&!j){const z=await I.json();p(String(z?.session?.name??z?.session?.username??""))}}catch{}})(),()=>{j=!0}},[]);const x=UE({lessonId:e,enabled:d&&!o,topPerformersEnabled:!!e&&!o,attempts:m,studentCount:s.attendance?.expected??0,lang:n}),g=b.useMemo(()=>({workA:x.data.workA,workB:x.data.workB,matchingItems:x.data.matchingItems,badges:x.data.badges,podiumStudents:x.data.podiumStudents,danmaku:x.data.danmaku,reactions:x.data.reactions,rubricDimensions:x.data.rubricDimensions,reviewProgress:x.data.reviewProgress,onAutoAssign:x.autoAssign,autoAssigning:x.autoAssigning,syncedStudentsCount:s.attendance?.onlineInClass,teacherName:y,stageLabel:Cc(s.stage,n)}),[x,s.attendance,y,s.stage,n]),v=b.useRef(null),w=b.useRef(!0),E=b.useRef(i);if(b.useEffect(()=>{if(w.current){w.current=!1,v.current=s;return}const j=v.current;v.current=s,j&&c(SE(j,s,{lang:n,isFirstFrame:!1}))},[s,n,c]),b.useEffect(()=>{const j=kE(i,E.current,n);E.current=i,j&&c([j])},[i,n,c]),!e)return 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."})]});const N=o||(x.authErrorStatus?{status:x.authErrorStatus,message:x.authErrorStatus===401?n==="zh"?"登录状态已失效(401)":"Session expired (401)":n==="zh"?"当前账号无权查看该课节的课堂数据(403)":"You do not have permission to view this classroom stage (403)"}:null);return N?r.jsxs("div",{role:"alert","data-testid":"stage-display-access-error",className:"fixed inset-0 z-[9999] bg-slate-950 text-slate-100 flex flex-col items-center justify-center gap-3 px-6 text-center",children:[r.jsx("div",{className:"text-5xl",children:"🔒"}),r.jsx("h1",{className:"text-2xl font-extrabold",children:N.status===401?n==="zh"?"大屏展台 · 登录已失效":"Stage Display · Session Expired":N.status===404?n==="zh"?"大屏展台 · 课节不存在":"Stage Display · Lesson Not Found":n==="zh"?"大屏展台 · 无访问权限":"Stage Display · Access Denied"}),r.jsx("p",{className:"text-slate-300 text-sm max-w-md",children:N.message}),r.jsx("p",{className:"text-slate-400 text-xs max-w-md",children:n==="zh"?"已自动停止轮询。请使用授课教师账号登录后重新打开对应课节的大屏展台。":"Polling has stopped automatically. Sign in with the assigned teacher account and reopen Stage Display for this lesson."})]}):r.jsxs(r.Fragment,{children:[r.jsx(LE,{lessonId:e,lessonTitle:t,data:s,lang:n,health:i,lastSyncedAt:a,peerReviewOpen:d,onOpenPeerReview:()=>f(!0),onClosePeerReview:()=>f(!1),peerReview:g,showCloseButton:!1}),r.jsx(NE,{notices:l,onDismiss:u,lang:n})]})}function WE(e){const t=Ot(),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??[],u=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(kn,{size:12}),l==="zh"?a?"学生视角预览":"学生模拟模式":a?"Student Preview":"Student View Mode"]}),r.jsx("span",{children:l==="zh"?`您当前正在以学生身份(${c.find(d=>d.id===u)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${c.find(d=>d.id===u)?.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(De,{size:13}):r.jsx(ki,{size:13}),l==="zh"?a?"关闭此预览标签页":"退出模拟并返回教师端":a?"Close Preview Tab":"Exit Student View"]})]}):null}function HE({userId:e,lang:t,onOpenProfile:n}){const s=`edu_os_default_pwd_hint_dismissed_${e||"unknown"}`,[i,o]=b.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(Si,{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(De,{size:13,"aria-hidden":"true"})})]})}const _s="openlearn_timetable_ocr_task",ka="openlearn_timetable_ocr_draft";function xh(e){try{const t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function $r(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 bh(e){try{sessionStorage.removeItem(e)}catch{}}const qE=Lt((e,t)=>({timetableOcrTask:xh(_s),timetableOcrDraft:xh(ka),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}),$r(_s,l),Ge.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})}),u=await c.json();if(!c.ok||!u.success)throw new Error(u.error||(s==="zh"?"识别请求失败":"OCR recognition failed"));const d=Array.isArray(u.entries)?u.entries:[],f={...l,status:"completed",completedAt:Date.now(),result:{entries:d,providerUsed:u.providerUsed}};e({timetableOcrTask:f,isAnyTaskRunning:!1}),$r(_s,f),Ge.getState().addToast({id:`toast_done_${a}`,title:s==="zh"?"🎉 AI 课表识别完成":"🎉 Timetable OCR Completed",message:s==="zh"?`已成功从图片中解析出 ${d.length} 节课程,点击前往核对并导入。`:`Successfully parsed ${d.length} timetable entries. Click to review and import.`,type:"success",action:{label:s==="zh"?"查看并导入课表":"View Timetable",onClick:()=>{Te.getState().setTeacherTab("timetable"),Ge.getState().setPendingTimetableSubTab("ocr_import")}}})}catch(c){console.error("[AsyncTask] Timetable OCR failed:",c);const u={...l,status:"failed",completedAt:Date.now(),error:c?.message||(s==="zh"?"未知识别错误":"Unknown OCR error")};e({timetableOcrTask:u,isAnyTaskRunning:!1}),$r(_s,u),Ge.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}),$r(ka,s,["imagePreview","imageBase64"])},clearTimetableOcrTask:()=>{e({timetableOcrTask:null,isAnyTaskRunning:!1,timetableOcrDraft:null}),bh(_s),bh(ka)}})),GE=e=>tn(qE,e);function ZE({session:e,lang:t,onLogout:n,onProfile:s}){const[i,o]=b.useState(!1),a=b.useRef(null);b.useEffect(()=>{if(!i)return;const c=u=>{a.current&&!a.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[i]);const l=(c,u)=>t==="zh"?c:u;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(wn,{size:20})}),r.jsx(Gn,{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(wn,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),r.jsx(qe,{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(ki,{size:16}),l("注销登录","Sign Out")]})]})]})}async function Qs(e){if(typeof window>"u")return!1;try{if(typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function")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}}var ja={exports:{}};/*!
|
|
94
|
+
|
|
95
|
+
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|
|
96
|
+
<http://stuartk.com/jszip>
|
|
97
|
+
|
|
98
|
+
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
|
|
99
|
+
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
|
|
100
|
+
|
|
101
|
+
JSZip uses the library pako released under the MIT license :
|
|
102
|
+
https://github.com/nodeca/pako/blob/main/LICENSE
|
|
103
|
+
*/var yh;function KE(){return yh||(yh=1,(function(e,t){(function(n){e.exports=n()})(function(){return(function n(s,i,o){function a(u,d){if(!i[u]){if(!s[u]){var f=typeof mr=="function"&&mr;if(!d&&f)return f(u,!0);if(l)return l(u,!0);var m=new Error("Cannot find module '"+u+"'");throw m.code="MODULE_NOT_FOUND",m}var h=i[u]={exports:{}};s[u][0].call(h.exports,function(y){var p=s[u][1][y];return a(p||y)},h,h.exports,n,s,i,o)}return i[u].exports}for(var l=typeof mr=="function"&&mr,c=0;c<o.length;c++)a(o[c]);return a})({1:[function(n,s,i){var o=n("./utils"),a=n("./support"),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(c){for(var u,d,f,m,h,y,p,x=[],g=0,v=c.length,w=v,E=o.getTypeOf(c)!=="string";g<c.length;)w=v-g,f=E?(u=c[g++],d=g<v?c[g++]:0,g<v?c[g++]:0):(u=c.charCodeAt(g++),d=g<v?c.charCodeAt(g++):0,g<v?c.charCodeAt(g++):0),m=u>>2,h=(3&u)<<4|d>>4,y=1<w?(15&d)<<2|f>>6:64,p=2<w?63&f:64,x.push(l.charAt(m)+l.charAt(h)+l.charAt(y)+l.charAt(p));return x.join("")},i.decode=function(c){var u,d,f,m,h,y,p=0,x=0,g="data:";if(c.substr(0,g.length)===g)throw new Error("Invalid base64 input, it looks like a data url.");var v,w=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===l.charAt(64)&&w--,c.charAt(c.length-2)===l.charAt(64)&&w--,w%1!=0)throw new Error("Invalid base64 input, bad content length.");for(v=a.uint8array?new Uint8Array(0|w):new Array(0|w);p<c.length;)u=l.indexOf(c.charAt(p++))<<2|(m=l.indexOf(c.charAt(p++)))>>4,d=(15&m)<<4|(h=l.indexOf(c.charAt(p++)))>>2,f=(3&h)<<6|(y=l.indexOf(c.charAt(p++))),v[x++]=u,h!==64&&(v[x++]=d),y!==64&&(v[x++]=f);return v}},{"./support":30,"./utils":32}],2:[function(n,s,i){var o=n("./external"),a=n("./stream/DataWorker"),l=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function u(d,f,m,h,y){this.compressedSize=d,this.uncompressedSize=f,this.crc32=m,this.compression=h,this.compressedContent=y}u.prototype={getContentWorker:function(){var d=new a(o.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),f=this;return d.on("end",function(){if(this.streamInfo.data_length!==f.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),d},getCompressedWorker:function(){return new a(o.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},u.createWorkerFrom=function(d,f,m){return d.pipe(new l).pipe(new c("uncompressedSize")).pipe(f.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",f)},s.exports=u},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,s,i){var o=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new o("STORE compression")},uncompressWorker:function(){return new o("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,s,i){var o=n("./utils"),a=(function(){for(var l,c=[],u=0;u<256;u++){l=u;for(var d=0;d<8;d++)l=1&l?3988292384^l>>>1:l>>>1;c[u]=l}return c})();s.exports=function(l,c){return l!==void 0&&l.length?o.getTypeOf(l)!=="string"?(function(u,d,f,m){var h=a,y=m+f;u^=-1;for(var p=m;p<y;p++)u=u>>>8^h[255&(u^d[p])];return-1^u})(0|c,l,l.length,0):(function(u,d,f,m){var h=a,y=m+f;u^=-1;for(var p=m;p<y;p++)u=u>>>8^h[255&(u^d.charCodeAt(p))];return-1^u})(0|c,l,l.length,0):0}},{"./utils":32}],5:[function(n,s,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,s,i){var o=null;o=typeof Promise<"u"?Promise:n("lie"),s.exports={Promise:o}},{lie:37}],7:[function(n,s,i){var o=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",a=n("pako"),l=n("./utils"),c=n("./stream/GenericWorker"),u=o?"uint8array":"array";function d(f,m){c.call(this,"FlateWorker/"+f),this._pako=null,this._pakoAction=f,this._pakoOptions=m,this.meta={}}i.magic="\b\0",l.inherits(d,c),d.prototype.processChunk=function(f){this.meta=f.meta,this._pako===null&&this._createPako(),this._pako.push(l.transformTo(u,f.data),!1)},d.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},d.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},d.prototype._createPako=function(){this._pako=new a[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var f=this;this._pako.onData=function(m){f.push({data:m,meta:f.meta})}},i.compressWorker=function(f){return new d("Deflate",f)},i.uncompressWorker=function(){return new d("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,s,i){function o(h,y){var p,x="";for(p=0;p<y;p++)x+=String.fromCharCode(255&h),h>>>=8;return x}function a(h,y,p,x,g,v){var w,E,N=h.file,j=h.compression,I=v!==u.utf8encode,z=l.transformTo("string",v(N.name)),$=l.transformTo("string",u.utf8encode(N.name)),V=N.comment,B=l.transformTo("string",v(V)),_=l.transformTo("string",u.utf8encode(V)),U=$.length!==N.name.length,k=_.length!==V.length,F="",Z="",M="",A=N.dir,L=N.date,S={crc32:0,compressedSize:0,uncompressedSize:0};y&&!p||(S.crc32=h.crc32,S.compressedSize=h.compressedSize,S.uncompressedSize=h.uncompressedSize);var R=0;y&&(R|=8),I||!U&&!k||(R|=2048);var D=0,P=0;A&&(D|=16),g==="UNIX"?(P=798,D|=(function(H,ee){var le=H;return H||(le=ee?16893:33204),(65535&le)<<16})(N.unixPermissions,A)):(P=20,D|=(function(H){return 63&(H||0)})(N.dosPermissions)),w=L.getUTCHours(),w<<=6,w|=L.getUTCMinutes(),w<<=5,w|=L.getUTCSeconds()/2,E=L.getUTCFullYear()-1980,E<<=4,E|=L.getUTCMonth()+1,E<<=5,E|=L.getUTCDate(),U&&(Z=o(1,1)+o(d(z),4)+$,F+="up"+o(Z.length,2)+Z),k&&(M=o(1,1)+o(d(B),4)+_,F+="uc"+o(M.length,2)+M);var Y="";return Y+=`
|
|
104
|
+
\0`,Y+=o(R,2),Y+=j.magic,Y+=o(w,2),Y+=o(E,2),Y+=o(S.crc32,4),Y+=o(S.compressedSize,4),Y+=o(S.uncompressedSize,4),Y+=o(z.length,2),Y+=o(F.length,2),{fileRecord:f.LOCAL_FILE_HEADER+Y+z+F,dirRecord:f.CENTRAL_FILE_HEADER+o(P,2)+Y+o(B.length,2)+"\0\0\0\0"+o(D,4)+o(x,4)+z+F+B}}var l=n("../utils"),c=n("../stream/GenericWorker"),u=n("../utf8"),d=n("../crc32"),f=n("../signature");function m(h,y,p,x){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=p,this.encodeFileName=x,this.streamFiles=h,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(m,c),m.prototype.push=function(h){var y=h.meta.percent||0,p=this.entriesCount,x=this._sources.length;this.accumulate?this.contentBuffer.push(h):(this.bytesWritten+=h.data.length,c.prototype.push.call(this,{data:h.data,meta:{currentFile:this.currentFile,percent:p?(y+100*(p-x-1))/p:100}}))},m.prototype.openedSource=function(h){this.currentSourceOffset=this.bytesWritten,this.currentFile=h.file.name;var y=this.streamFiles&&!h.file.dir;if(y){var p=a(h,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(h){this.accumulate=!1;var y=this.streamFiles&&!h.file.dir,p=a(h,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),y)this.push({data:(function(x){return f.DATA_DESCRIPTOR+o(x.crc32,4)+o(x.compressedSize,4)+o(x.uncompressedSize,4)})(h),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var h=this.bytesWritten,y=0;y<this.dirRecords.length;y++)this.push({data:this.dirRecords[y],meta:{percent:100}});var p=this.bytesWritten-h,x=(function(g,v,w,E,N){var j=l.transformTo("string",N(E));return f.CENTRAL_DIRECTORY_END+"\0\0\0\0"+o(g,2)+o(g,2)+o(v,4)+o(w,4)+o(j.length,2)+j})(this.dirRecords.length,p,h,this.zipComment,this.encodeFileName);this.push({data:x,meta:{percent:100}})},m.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},m.prototype.registerPrevious=function(h){this._sources.push(h);var y=this;return h.on("data",function(p){y.processChunk(p)}),h.on("end",function(){y.closedSource(y.previous.streamInfo),y._sources.length?y.prepareNextSource():y.end()}),h.on("error",function(p){y.error(p)}),this},m.prototype.resume=function(){return!!c.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},m.prototype.error=function(h){var y=this._sources;if(!c.prototype.error.call(this,h))return!1;for(var p=0;p<y.length;p++)try{y[p].error(h)}catch{}return!0},m.prototype.lock=function(){c.prototype.lock.call(this);for(var h=this._sources,y=0;y<h.length;y++)h[y].lock()},s.exports=m},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,s,i){var o=n("../compressions"),a=n("./ZipFileWorker");i.generateWorker=function(l,c,u){var d=new a(c.streamFiles,u,c.platform,c.encodeFileName),f=0;try{l.forEach(function(m,h){f++;var y=(function(v,w){var E=v||w,N=o[E];if(!N)throw new Error(E+" is not a valid compression method !");return N})(h.options.compression,c.compression),p=h.options.compressionOptions||c.compressionOptions||{},x=h.dir,g=h.date;h._compressWorker(y,p).withStreamInfo("file",{name:m,dir:x,date:g,comment:h.comment||"",unixPermissions:h.unixPermissions,dosPermissions:h.dosPermissions}).pipe(d)}),d.entriesCount=f}catch(m){d.error(m)}return d}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,s,i){function o(){if(!(this instanceof o))return new o;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var a=new o;for(var l in this)typeof this[l]!="function"&&(a[l]=this[l]);return a}}(o.prototype=n("./object")).loadAsync=n("./load"),o.support=n("./support"),o.defaults=n("./defaults"),o.version="3.10.1",o.loadAsync=function(a,l){return new o().loadAsync(a,l)},o.external=n("./external"),s.exports=o},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,s,i){var o=n("./utils"),a=n("./external"),l=n("./utf8"),c=n("./zipEntries"),u=n("./stream/Crc32Probe"),d=n("./nodejsUtils");function f(m){return new a.Promise(function(h,y){var p=m.decompressed.getContentWorker().pipe(new u);p.on("error",function(x){y(x)}).on("end",function(){p.streamInfo.crc32!==m.decompressed.crc32?y(new Error("Corrupted zip : CRC32 mismatch")):h()}).resume()})}s.exports=function(m,h){var y=this;return h=o.extend(h||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:l.utf8decode}),d.isNode&&d.isStream(m)?a.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):o.prepareContent("the loaded zip file",m,!0,h.optimizedBinaryString,h.base64).then(function(p){var x=new c(h);return x.load(p),x}).then(function(p){var x=[a.Promise.resolve(p)],g=p.files;if(h.checkCRC32)for(var v=0;v<g.length;v++)x.push(f(g[v]));return a.Promise.all(x)}).then(function(p){for(var x=p.shift(),g=x.files,v=0;v<g.length;v++){var w=g[v],E=w.fileNameStr,N=o.resolve(w.fileNameStr);y.file(N,w.decompressed,{binary:!0,optimizedBinaryString:!0,date:w.date,dir:w.dir,comment:w.fileCommentStr.length?w.fileCommentStr:null,unixPermissions:w.unixPermissions,dosPermissions:w.dosPermissions,createFolders:h.createFolders}),w.dir||(y.file(N).unsafeOriginalName=E)}return x.zipComment.length&&(y.comment=x.zipComment),y})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(n,s,i){var o=n("../utils"),a=n("../stream/GenericWorker");function l(c,u){a.call(this,"Nodejs stream input adapter for "+c),this._upstreamEnded=!1,this._bindStream(u)}o.inherits(l,a),l.prototype._bindStream=function(c){var u=this;(this._stream=c).pause(),c.on("data",function(d){u.push({data:d,meta:{percent:0}})}).on("error",function(d){u.isPaused?this.generatedError=d:u.error(d)}).on("end",function(){u.isPaused?u._upstreamEnded=!0:u.end()})},l.prototype.pause=function(){return!!a.prototype.pause.call(this)&&(this._stream.pause(),!0)},l.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},s.exports=l},{"../stream/GenericWorker":28,"../utils":32}],13:[function(n,s,i){var o=n("readable-stream").Readable;function a(l,c,u){o.call(this,c),this._helper=l;var d=this;l.on("data",function(f,m){d.push(f)||d._helper.pause(),u&&u(m)}).on("error",function(f){d.emit("error",f)}).on("end",function(){d.push(null)})}n("../utils").inherits(a,o),a.prototype._read=function(){this._helper.resume()},s.exports=a},{"../utils":32,"readable-stream":16}],14:[function(n,s,i){s.exports={isNode:typeof Buffer<"u",newBufferFrom:function(o,a){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(o,a);if(typeof o=="number")throw new Error('The "data" argument must not be a number');return new Buffer(o,a)},allocBuffer:function(o){if(Buffer.alloc)return Buffer.alloc(o);var a=new Buffer(o);return a.fill(0),a},isBuffer:function(o){return Buffer.isBuffer(o)},isStream:function(o){return o&&typeof o.on=="function"&&typeof o.pause=="function"&&typeof o.resume=="function"}}},{}],15:[function(n,s,i){function o(N,j,I){var z,$=l.getTypeOf(j),V=l.extend(I||{},d);V.date=V.date||new Date,V.compression!==null&&(V.compression=V.compression.toUpperCase()),typeof V.unixPermissions=="string"&&(V.unixPermissions=parseInt(V.unixPermissions,8)),V.unixPermissions&&16384&V.unixPermissions&&(V.dir=!0),V.dosPermissions&&16&V.dosPermissions&&(V.dir=!0),V.dir&&(N=g(N)),V.createFolders&&(z=x(N))&&v.call(this,z,!0);var B=$==="string"&&V.binary===!1&&V.base64===!1;I&&I.binary!==void 0||(V.binary=!B),(j instanceof f&&j.uncompressedSize===0||V.dir||!j||j.length===0)&&(V.base64=!1,V.binary=!0,j="",V.compression="STORE",$="string");var _=null;_=j instanceof f||j instanceof c?j:y.isNode&&y.isStream(j)?new p(N,j):l.prepareContent(N,j,V.binary,V.optimizedBinaryString,V.base64);var U=new m(N,_,V);this.files[N]=U}var a=n("./utf8"),l=n("./utils"),c=n("./stream/GenericWorker"),u=n("./stream/StreamHelper"),d=n("./defaults"),f=n("./compressedObject"),m=n("./zipObject"),h=n("./generate"),y=n("./nodejsUtils"),p=n("./nodejs/NodejsStreamInputAdapter"),x=function(N){N.slice(-1)==="/"&&(N=N.substring(0,N.length-1));var j=N.lastIndexOf("/");return 0<j?N.substring(0,j):""},g=function(N){return N.slice(-1)!=="/"&&(N+="/"),N},v=function(N,j){return j=j!==void 0?j:d.createFolders,N=g(N),this.files[N]||o.call(this,N,null,{dir:!0,createFolders:j}),this.files[N]};function w(N){return Object.prototype.toString.call(N)==="[object RegExp]"}var E={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(N){var j,I,z;for(j in this.files)z=this.files[j],(I=j.slice(this.root.length,j.length))&&j.slice(0,this.root.length)===this.root&&N(I,z)},filter:function(N){var j=[];return this.forEach(function(I,z){N(I,z)&&j.push(z)}),j},file:function(N,j,I){if(arguments.length!==1)return N=this.root+N,o.call(this,N,j,I),this;if(w(N)){var z=N;return this.filter(function(V,B){return!B.dir&&z.test(V)})}var $=this.files[this.root+N];return $&&!$.dir?$:null},folder:function(N){if(!N)return this;if(w(N))return this.filter(function($,V){return V.dir&&N.test($)});var j=this.root+N,I=v.call(this,j),z=this.clone();return z.root=I.name,z},remove:function(N){N=this.root+N;var j=this.files[N];if(j||(N.slice(-1)!=="/"&&(N+="/"),j=this.files[N]),j&&!j.dir)delete this.files[N];else for(var I=this.filter(function($,V){return V.name.slice(0,N.length)===N}),z=0;z<I.length;z++)delete this.files[I[z].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(N){var j,I={};try{if((I=l.extend(N||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:a.utf8encode})).type=I.type.toLowerCase(),I.compression=I.compression.toUpperCase(),I.type==="binarystring"&&(I.type="string"),!I.type)throw new Error("No output type specified.");l.checkSupport(I.type),I.platform!=="darwin"&&I.platform!=="freebsd"&&I.platform!=="linux"&&I.platform!=="sunos"||(I.platform="UNIX"),I.platform==="win32"&&(I.platform="DOS");var z=I.comment||this.comment||"";j=h.generateWorker(this,I,z)}catch($){(j=new c("error")).error($)}return new u(j,I.type||"string",I.mimeType)},generateAsync:function(N,j){return this.generateInternalStream(N).accumulate(j)},generateNodeStream:function(N,j){return(N=N||{}).type||(N.type="nodebuffer"),this.generateInternalStream(N).toNodejsStream(j)}};s.exports=E},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(n,s,i){s.exports=n("stream")},{stream:void 0}],17:[function(n,s,i){var o=n("./DataReader");function a(l){o.call(this,l);for(var c=0;c<this.data.length;c++)l[c]=255&l[c]}n("../utils").inherits(a,o),a.prototype.byteAt=function(l){return this.data[this.zero+l]},a.prototype.lastIndexOfSignature=function(l){for(var c=l.charCodeAt(0),u=l.charCodeAt(1),d=l.charCodeAt(2),f=l.charCodeAt(3),m=this.length-4;0<=m;--m)if(this.data[m]===c&&this.data[m+1]===u&&this.data[m+2]===d&&this.data[m+3]===f)return m-this.zero;return-1},a.prototype.readAndCheckSignature=function(l){var c=l.charCodeAt(0),u=l.charCodeAt(1),d=l.charCodeAt(2),f=l.charCodeAt(3),m=this.readData(4);return c===m[0]&&u===m[1]&&d===m[2]&&f===m[3]},a.prototype.readData=function(l){if(this.checkOffset(l),l===0)return[];var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},s.exports=a},{"../utils":32,"./DataReader":18}],18:[function(n,s,i){var o=n("../utils");function a(l){this.data=l,this.length=l.length,this.index=0,this.zero=0}a.prototype={checkOffset:function(l){this.checkIndex(this.index+l)},checkIndex:function(l){if(this.length<this.zero+l||l<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+l+"). Corrupted zip ?")},setIndex:function(l){this.checkIndex(l),this.index=l},skip:function(l){this.setIndex(this.index+l)},byteAt:function(){},readInt:function(l){var c,u=0;for(this.checkOffset(l),c=this.index+l-1;c>=this.index;c--)u=(u<<8)+this.byteAt(c);return this.index+=l,u},readString:function(l){return o.transformTo("string",this.readData(l))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var l=this.readInt(4);return new Date(Date.UTC(1980+(l>>25&127),(l>>21&15)-1,l>>16&31,l>>11&31,l>>5&63,(31&l)<<1))}},s.exports=a},{"../utils":32}],19:[function(n,s,i){var o=n("./Uint8ArrayReader");function a(l){o.call(this,l)}n("../utils").inherits(a,o),a.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},s.exports=a},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,s,i){var o=n("./DataReader");function a(l){o.call(this,l)}n("../utils").inherits(a,o),a.prototype.byteAt=function(l){return this.data.charCodeAt(this.zero+l)},a.prototype.lastIndexOfSignature=function(l){return this.data.lastIndexOf(l)-this.zero},a.prototype.readAndCheckSignature=function(l){return l===this.readData(4)},a.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},s.exports=a},{"../utils":32,"./DataReader":18}],21:[function(n,s,i){var o=n("./ArrayReader");function a(l){o.call(this,l)}n("../utils").inherits(a,o),a.prototype.readData=function(l){if(this.checkOffset(l),l===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},s.exports=a},{"../utils":32,"./ArrayReader":17}],22:[function(n,s,i){var o=n("../utils"),a=n("../support"),l=n("./ArrayReader"),c=n("./StringReader"),u=n("./NodeBufferReader"),d=n("./Uint8ArrayReader");s.exports=function(f){var m=o.getTypeOf(f);return o.checkSupport(m),m!=="string"||a.uint8array?m==="nodebuffer"?new u(f):a.uint8array?new d(o.transformTo("uint8array",f)):new l(o.transformTo("array",f)):new c(f)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,s,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,s,i){var o=n("./GenericWorker"),a=n("../utils");function l(c){o.call(this,"ConvertWorker to "+c),this.destType=c}a.inherits(l,o),l.prototype.processChunk=function(c){this.push({data:a.transformTo(this.destType,c.data),meta:c.meta})},s.exports=l},{"../utils":32,"./GenericWorker":28}],25:[function(n,s,i){var o=n("./GenericWorker"),a=n("../crc32");function l(){o.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(l,o),l.prototype.processChunk=function(c){this.streamInfo.crc32=a(c.data,this.streamInfo.crc32||0),this.push(c)},s.exports=l},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,s,i){var o=n("../utils"),a=n("./GenericWorker");function l(c){a.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}o.inherits(l,a),l.prototype.processChunk=function(c){if(c){var u=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=u+c.data.length}a.prototype.processChunk.call(this,c)},s.exports=l},{"../utils":32,"./GenericWorker":28}],27:[function(n,s,i){var o=n("../utils"),a=n("./GenericWorker");function l(c){a.call(this,"DataWorker");var u=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(d){u.dataIsReady=!0,u.data=d,u.max=d&&d.length||0,u.type=o.getTypeOf(d),u.isPaused||u._tickAndRepeat()},function(d){u.error(d)})}o.inherits(l,a),l.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this.data=null},l.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,o.delay(this._tickAndRepeat,[],this)),!0)},l.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(o.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},l.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,u=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,u);break;case"uint8array":c=this.data.subarray(this.index,u);break;case"array":case"nodebuffer":c=this.data.slice(this.index,u)}return this.index=u,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},s.exports=l},{"../utils":32,"./GenericWorker":28}],28:[function(n,s,i){function o(a){this.name=a||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}o.prototype={push:function(a){this.emit("data",a)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(a){this.emit("error",a)}return!0},error:function(a){return!this.isFinished&&(this.isPaused?this.generatedError=a:(this.isFinished=!0,this.emit("error",a),this.previous&&this.previous.error(a),this.cleanUp()),!0)},on:function(a,l){return this._listeners[a].push(l),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(a,l){if(this._listeners[a])for(var c=0;c<this._listeners[a].length;c++)this._listeners[a][c].call(this,l)},pipe:function(a){return a.registerPrevious(this)},registerPrevious:function(a){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=a.streamInfo,this.mergeStreamInfo(),this.previous=a;var l=this;return a.on("data",function(c){l.processChunk(c)}),a.on("end",function(){l.end()}),a.on("error",function(c){l.error(c)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var a=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),a=!0),this.previous&&this.previous.resume(),!a},flush:function(){},processChunk:function(a){this.push(a)},withStreamInfo:function(a,l){return this.extraStreamInfo[a]=l,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var a in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,a)&&(this.streamInfo[a]=this.extraStreamInfo[a])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var a="Worker "+this.name;return this.previous?this.previous+" -> "+a:a}},s.exports=o},{}],29:[function(n,s,i){var o=n("../utils"),a=n("./ConvertWorker"),l=n("./GenericWorker"),c=n("../base64"),u=n("../support"),d=n("../external"),f=null;if(u.nodestream)try{f=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(y,p){return new d.Promise(function(x,g){var v=[],w=y._internalType,E=y._outputType,N=y._mimeType;y.on("data",function(j,I){v.push(j),p&&p(I)}).on("error",function(j){v=[],g(j)}).on("end",function(){try{var j=(function(I,z,$){switch(I){case"blob":return o.newBlob(o.transformTo("arraybuffer",z),$);case"base64":return c.encode(z);default:return o.transformTo(I,z)}})(E,(function(I,z){var $,V=0,B=null,_=0;for($=0;$<z.length;$++)_+=z[$].length;switch(I){case"string":return z.join("");case"array":return Array.prototype.concat.apply([],z);case"uint8array":for(B=new Uint8Array(_),$=0;$<z.length;$++)B.set(z[$],V),V+=z[$].length;return B;case"nodebuffer":return Buffer.concat(z);default:throw new Error("concat : unsupported type '"+I+"'")}})(w,v),N);x(j)}catch(I){g(I)}v=[]}).resume()})}function h(y,p,x){var g=p;switch(p){case"blob":case"arraybuffer":g="uint8array";break;case"base64":g="string"}try{this._internalType=g,this._outputType=p,this._mimeType=x,o.checkSupport(g),this._worker=y.pipe(new a(g)),y.lock()}catch(v){this._worker=new l("error"),this._worker.error(v)}}h.prototype={accumulate:function(y){return m(this,y)},on:function(y,p){var x=this;return y==="data"?this._worker.on(y,function(g){p.call(x,g.data,g.meta)}):this._worker.on(y,function(){o.delay(p,arguments,x)}),this},resume:function(){return o.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(y){if(o.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new f(this,{objectMode:this._outputType!=="nodebuffer"},y)}},s.exports=h},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,s,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",i.nodebuffer=typeof Buffer<"u",i.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")i.blob=!1;else{var o=new ArrayBuffer(0);try{i.blob=new Blob([o],{type:"application/zip"}).size===0}catch{try{var a=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);a.append(o),i.blob=a.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,s,i){for(var o=n("./utils"),a=n("./support"),l=n("./nodejsUtils"),c=n("./stream/GenericWorker"),u=new Array(256),d=0;d<256;d++)u[d]=252<=d?6:248<=d?5:240<=d?4:224<=d?3:192<=d?2:1;u[254]=u[254]=1;function f(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}i.utf8encode=function(h){return a.nodebuffer?l.newBufferFrom(h,"utf-8"):(function(y){var p,x,g,v,w,E=y.length,N=0;for(v=0;v<E;v++)(64512&(x=y.charCodeAt(v)))==55296&&v+1<E&&(64512&(g=y.charCodeAt(v+1)))==56320&&(x=65536+(x-55296<<10)+(g-56320),v++),N+=x<128?1:x<2048?2:x<65536?3:4;for(p=a.uint8array?new Uint8Array(N):new Array(N),v=w=0;w<N;v++)(64512&(x=y.charCodeAt(v)))==55296&&v+1<E&&(64512&(g=y.charCodeAt(v+1)))==56320&&(x=65536+(x-55296<<10)+(g-56320),v++),x<128?p[w++]=x:(x<2048?p[w++]=192|x>>>6:(x<65536?p[w++]=224|x>>>12:(p[w++]=240|x>>>18,p[w++]=128|x>>>12&63),p[w++]=128|x>>>6&63),p[w++]=128|63&x);return p})(h)},i.utf8decode=function(h){return a.nodebuffer?o.transformTo("nodebuffer",h).toString("utf-8"):(function(y){var p,x,g,v,w=y.length,E=new Array(2*w);for(p=x=0;p<w;)if((g=y[p++])<128)E[x++]=g;else if(4<(v=u[g]))E[x++]=65533,p+=v-1;else{for(g&=v===2?31:v===3?15:7;1<v&&p<w;)g=g<<6|63&y[p++],v--;1<v?E[x++]=65533:g<65536?E[x++]=g:(g-=65536,E[x++]=55296|g>>10&1023,E[x++]=56320|1023&g)}return E.length!==x&&(E.subarray?E=E.subarray(0,x):E.length=x),o.applyFromCharCode(E)})(h=o.transformTo(a.uint8array?"uint8array":"array",h))},o.inherits(f,c),f.prototype.processChunk=function(h){var y=o.transformTo(a.uint8array?"uint8array":"array",h.data);if(this.leftOver&&this.leftOver.length){if(a.uint8array){var p=y;(y=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),y.set(p,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var x=(function(v,w){var E;for((w=w||v.length)>v.length&&(w=v.length),E=w-1;0<=E&&(192&v[E])==128;)E--;return E<0||E===0?w:E+u[v[E]]>w?E:w})(y),g=y;x!==y.length&&(a.uint8array?(g=y.subarray(0,x),this.leftOver=y.subarray(x,y.length)):(g=y.slice(0,x),this.leftOver=y.slice(x,y.length))),this.push({data:i.utf8decode(g),meta:h.meta})},f.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=f,o.inherits(m,c),m.prototype.processChunk=function(h){this.push({data:i.utf8encode(h.data),meta:h.meta})},i.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,s,i){var o=n("./support"),a=n("./base64"),l=n("./nodejsUtils"),c=n("./external");function u(p){return p}function d(p,x){for(var g=0;g<p.length;++g)x[g]=255&p.charCodeAt(g);return x}n("setimmediate"),i.newBlob=function(p,x){i.checkSupport("blob");try{return new Blob([p],{type:x})}catch{try{var g=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return g.append(p),g.getBlob(x)}catch{throw new Error("Bug : can't construct the Blob.")}}};var f={stringifyByChunk:function(p,x,g){var v=[],w=0,E=p.length;if(E<=g)return String.fromCharCode.apply(null,p);for(;w<E;)x==="array"||x==="nodebuffer"?v.push(String.fromCharCode.apply(null,p.slice(w,Math.min(w+g,E)))):v.push(String.fromCharCode.apply(null,p.subarray(w,Math.min(w+g,E)))),w+=g;return v.join("")},stringifyByChar:function(p){for(var x="",g=0;g<p.length;g++)x+=String.fromCharCode(p[g]);return x},applyCanBeUsed:{uint8array:(function(){try{return o.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return o.nodebuffer&&String.fromCharCode.apply(null,l.allocBuffer(1)).length===1}catch{return!1}})()}};function m(p){var x=65536,g=i.getTypeOf(p),v=!0;if(g==="uint8array"?v=f.applyCanBeUsed.uint8array:g==="nodebuffer"&&(v=f.applyCanBeUsed.nodebuffer),v)for(;1<x;)try{return f.stringifyByChunk(p,g,x)}catch{x=Math.floor(x/2)}return f.stringifyByChar(p)}function h(p,x){for(var g=0;g<p.length;g++)x[g]=p[g];return x}i.applyFromCharCode=m;var y={};y.string={string:u,array:function(p){return d(p,new Array(p.length))},arraybuffer:function(p){return y.string.uint8array(p).buffer},uint8array:function(p){return d(p,new Uint8Array(p.length))},nodebuffer:function(p){return d(p,l.allocBuffer(p.length))}},y.array={string:m,array:u,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return l.newBufferFrom(p)}},y.arraybuffer={string:function(p){return m(new Uint8Array(p))},array:function(p){return h(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:u,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return l.newBufferFrom(new Uint8Array(p))}},y.uint8array={string:m,array:function(p){return h(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:u,nodebuffer:function(p){return l.newBufferFrom(p)}},y.nodebuffer={string:m,array:function(p){return h(p,new Array(p.length))},arraybuffer:function(p){return y.nodebuffer.uint8array(p).buffer},uint8array:function(p){return h(p,new Uint8Array(p.length))},nodebuffer:u},i.transformTo=function(p,x){if(x=x||"",!p)return x;i.checkSupport(p);var g=i.getTypeOf(x);return y[g][p](x)},i.resolve=function(p){for(var x=p.split("/"),g=[],v=0;v<x.length;v++){var w=x[v];w==="."||w===""&&v!==0&&v!==x.length-1||(w===".."?g.pop():g.push(w))}return g.join("/")},i.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":o.nodebuffer&&l.isBuffer(p)?"nodebuffer":o.uint8array&&p instanceof Uint8Array?"uint8array":o.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(p){if(!o[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(p){var x,g,v="";for(g=0;g<(p||"").length;g++)v+="\\x"+((x=p.charCodeAt(g))<16?"0":"")+x.toString(16).toUpperCase();return v},i.delay=function(p,x,g){setImmediate(function(){p.apply(g||null,x||[])})},i.inherits=function(p,x){function g(){}g.prototype=x.prototype,p.prototype=new g},i.extend=function(){var p,x,g={};for(p=0;p<arguments.length;p++)for(x in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],x)&&g[x]===void 0&&(g[x]=arguments[p][x]);return g},i.prepareContent=function(p,x,g,v,w){return c.Promise.resolve(x).then(function(E){return o.blob&&(E instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(E))!==-1)&&typeof FileReader<"u"?new c.Promise(function(N,j){var I=new FileReader;I.onload=function(z){N(z.target.result)},I.onerror=function(z){j(z.target.error)},I.readAsArrayBuffer(E)}):E}).then(function(E){var N=i.getTypeOf(E);return N?(N==="arraybuffer"?E=i.transformTo("uint8array",E):N==="string"&&(w?E=a.decode(E):g&&v!==!0&&(E=(function(j){return d(j,o.uint8array?new Uint8Array(j.length):new Array(j.length))})(E))),E):c.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(n,s,i){var o=n("./reader/readerFor"),a=n("./utils"),l=n("./signature"),c=n("./zipEntry"),u=n("./support");function d(f){this.files=[],this.loadOptions=f}d.prototype={checkSignature:function(f){if(!this.reader.readAndCheckSignature(f)){this.reader.index-=4;var m=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+a.pretty(m)+", expected "+a.pretty(f)+")")}},isSignature:function(f,m){var h=this.reader.index;this.reader.setIndex(f);var y=this.reader.readString(4)===m;return this.reader.setIndex(h),y},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var f=this.reader.readData(this.zipCommentLength),m=u.uint8array?"uint8array":"array",h=a.transformTo(m,f);this.zipComment=this.loadOptions.decodeFileName(h)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var f,m,h,y=this.zip64EndOfCentralSize-44;0<y;)f=this.reader.readInt(2),m=this.reader.readInt(4),h=this.reader.readData(m),this.zip64ExtensibleData[f]={id:f,length:m,value:h}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var f,m;for(f=0;f<this.files.length;f++)m=this.files[f],this.reader.setIndex(m.localHeaderOffset),this.checkSignature(l.LOCAL_FILE_HEADER),m.readLocalPart(this.reader),m.handleUTF8(),m.processAttributes()},readCentralDir:function(){var f;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(l.CENTRAL_FILE_HEADER);)(f=new c({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(f);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var f=this.reader.lastIndexOfSignature(l.CENTRAL_DIRECTORY_END);if(f<0)throw this.isSignature(0,l.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(f);var m=f;if(this.checkSignature(l.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===a.MAX_VALUE_16BITS||this.diskWithCentralDirStart===a.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===a.MAX_VALUE_16BITS||this.centralDirRecords===a.MAX_VALUE_16BITS||this.centralDirSize===a.MAX_VALUE_32BITS||this.centralDirOffset===a.MAX_VALUE_32BITS){if(this.zip64=!0,(f=this.reader.lastIndexOfSignature(l.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(f),this.checkSignature(l.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,l.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(l.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(l.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var h=this.centralDirOffset+this.centralDirSize;this.zip64&&(h+=20,h+=12+this.zip64EndOfCentralSize);var y=m-h;if(0<y)this.isSignature(m,l.CENTRAL_FILE_HEADER)||(this.reader.zero=y);else if(y<0)throw new Error("Corrupted zip: missing "+Math.abs(y)+" bytes.")},prepareReader:function(f){this.reader=o(f)},load:function(f){this.prepareReader(f),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},s.exports=d},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,s,i){var o=n("./reader/readerFor"),a=n("./utils"),l=n("./compressedObject"),c=n("./crc32"),u=n("./utf8"),d=n("./compressions"),f=n("./support");function m(h,y){this.options=h,this.loadOptions=y}m.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(h){var y,p;if(h.skip(22),this.fileNameLength=h.readInt(2),p=h.readInt(2),this.fileName=h.readData(this.fileNameLength),h.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((y=(function(x){for(var g in d)if(Object.prototype.hasOwnProperty.call(d,g)&&d[g].magic===x)return d[g];return null})(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+a.pretty(this.compressionMethod)+" unknown (inner file : "+a.transformTo("string",this.fileName)+")");this.decompressed=new l(this.compressedSize,this.uncompressedSize,this.crc32,y,h.readData(this.compressedSize))},readCentralPart:function(h){this.versionMadeBy=h.readInt(2),h.skip(2),this.bitFlag=h.readInt(2),this.compressionMethod=h.readString(2),this.date=h.readDate(),this.crc32=h.readInt(4),this.compressedSize=h.readInt(4),this.uncompressedSize=h.readInt(4);var y=h.readInt(2);if(this.extraFieldsLength=h.readInt(2),this.fileCommentLength=h.readInt(2),this.diskNumberStart=h.readInt(2),this.internalFileAttributes=h.readInt(2),this.externalFileAttributes=h.readInt(4),this.localHeaderOffset=h.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");h.skip(y),this.readExtraFields(h),this.parseZIP64ExtraField(h),this.fileComment=h.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var h=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),h==0&&(this.dosPermissions=63&this.externalFileAttributes),h==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var h=o(this.extraFields[1].value);this.uncompressedSize===a.MAX_VALUE_32BITS&&(this.uncompressedSize=h.readInt(8)),this.compressedSize===a.MAX_VALUE_32BITS&&(this.compressedSize=h.readInt(8)),this.localHeaderOffset===a.MAX_VALUE_32BITS&&(this.localHeaderOffset=h.readInt(8)),this.diskNumberStart===a.MAX_VALUE_32BITS&&(this.diskNumberStart=h.readInt(4))}},readExtraFields:function(h){var y,p,x,g=h.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});h.index+4<g;)y=h.readInt(2),p=h.readInt(2),x=h.readData(p),this.extraFields[y]={id:y,length:p,value:x};h.setIndex(g)},handleUTF8:function(){var h=f.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=u.utf8decode(this.fileName),this.fileCommentStr=u.utf8decode(this.fileComment);else{var y=this.findExtraFieldUnicodePath();if(y!==null)this.fileNameStr=y;else{var p=a.transformTo(h,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var x=this.findExtraFieldUnicodeComment();if(x!==null)this.fileCommentStr=x;else{var g=a.transformTo(h,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(g)}}},findExtraFieldUnicodePath:function(){var h=this.extraFields[28789];if(h){var y=o(h.value);return y.readInt(1)!==1||c(this.fileName)!==y.readInt(4)?null:u.utf8decode(y.readData(h.length-5))}return null},findExtraFieldUnicodeComment:function(){var h=this.extraFields[25461];if(h){var y=o(h.value);return y.readInt(1)!==1||c(this.fileComment)!==y.readInt(4)?null:u.utf8decode(y.readData(h.length-5))}return null}},s.exports=m},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,s,i){function o(y,p,x){this.name=y,this.dir=x.dir,this.date=x.date,this.comment=x.comment,this.unixPermissions=x.unixPermissions,this.dosPermissions=x.dosPermissions,this._data=p,this._dataBinary=x.binary,this.options={compression:x.compression,compressionOptions:x.compressionOptions}}var a=n("./stream/StreamHelper"),l=n("./stream/DataWorker"),c=n("./utf8"),u=n("./compressedObject"),d=n("./stream/GenericWorker");o.prototype={internalStream:function(y){var p=null,x="string";try{if(!y)throw new Error("No output type specified.");var g=(x=y.toLowerCase())==="string"||x==="text";x!=="binarystring"&&x!=="text"||(x="string"),p=this._decompressWorker();var v=!this._dataBinary;v&&!g&&(p=p.pipe(new c.Utf8EncodeWorker)),!v&&g&&(p=p.pipe(new c.Utf8DecodeWorker))}catch(w){(p=new d("error")).error(w)}return new a(p,x,"")},async:function(y,p){return this.internalStream(y).accumulate(p)},nodeStream:function(y,p){return this.internalStream(y||"nodebuffer").toNodejsStream(p)},_compressWorker:function(y,p){if(this._data instanceof u&&this._data.compression.magic===y.magic)return this._data.getCompressedWorker();var x=this._decompressWorker();return this._dataBinary||(x=x.pipe(new c.Utf8EncodeWorker)),u.createWorkerFrom(x,y,p)},_decompressWorker:function(){return this._data instanceof u?this._data.getContentWorker():this._data instanceof d?this._data:new l(this._data)}};for(var f=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],m=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},h=0;h<f.length;h++)o.prototype[f[h]]=m;s.exports=o},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,s,i){(function(o){var a,l,c=o.MutationObserver||o.WebKitMutationObserver;if(c){var u=0,d=new c(y),f=o.document.createTextNode("");d.observe(f,{characterData:!0}),a=function(){f.data=u=++u%2}}else if(o.setImmediate||o.MessageChannel===void 0)a="document"in o&&"onreadystatechange"in o.document.createElement("script")?function(){var p=o.document.createElement("script");p.onreadystatechange=function(){y(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},o.document.documentElement.appendChild(p)}:function(){setTimeout(y,0)};else{var m=new o.MessageChannel;m.port1.onmessage=y,a=function(){m.port2.postMessage(0)}}var h=[];function y(){var p,x;l=!0;for(var g=h.length;g;){for(x=h,h=[],p=-1;++p<g;)x[p]();g=h.length}l=!1}s.exports=function(p){h.push(p)!==1||l||a()}}).call(this,typeof fr<"u"?fr:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,s,i){var o=n("immediate");function a(){}var l={},c=["REJECTED"],u=["FULFILLED"],d=["PENDING"];function f(g){if(typeof g!="function")throw new TypeError("resolver must be a function");this.state=d,this.queue=[],this.outcome=void 0,g!==a&&p(this,g)}function m(g,v,w){this.promise=g,typeof v=="function"&&(this.onFulfilled=v,this.callFulfilled=this.otherCallFulfilled),typeof w=="function"&&(this.onRejected=w,this.callRejected=this.otherCallRejected)}function h(g,v,w){o(function(){var E;try{E=v(w)}catch(N){return l.reject(g,N)}E===g?l.reject(g,new TypeError("Cannot resolve promise with itself")):l.resolve(g,E)})}function y(g){var v=g&&g.then;if(g&&(typeof g=="object"||typeof g=="function")&&typeof v=="function")return function(){v.apply(g,arguments)}}function p(g,v){var w=!1;function E(I){w||(w=!0,l.reject(g,I))}function N(I){w||(w=!0,l.resolve(g,I))}var j=x(function(){v(N,E)});j.status==="error"&&E(j.value)}function x(g,v){var w={};try{w.value=g(v),w.status="success"}catch(E){w.status="error",w.value=E}return w}(s.exports=f).prototype.finally=function(g){if(typeof g!="function")return this;var v=this.constructor;return this.then(function(w){return v.resolve(g()).then(function(){return w})},function(w){return v.resolve(g()).then(function(){throw w})})},f.prototype.catch=function(g){return this.then(null,g)},f.prototype.then=function(g,v){if(typeof g!="function"&&this.state===u||typeof v!="function"&&this.state===c)return this;var w=new this.constructor(a);return this.state!==d?h(w,this.state===u?g:v,this.outcome):this.queue.push(new m(w,g,v)),w},m.prototype.callFulfilled=function(g){l.resolve(this.promise,g)},m.prototype.otherCallFulfilled=function(g){h(this.promise,this.onFulfilled,g)},m.prototype.callRejected=function(g){l.reject(this.promise,g)},m.prototype.otherCallRejected=function(g){h(this.promise,this.onRejected,g)},l.resolve=function(g,v){var w=x(y,v);if(w.status==="error")return l.reject(g,w.value);var E=w.value;if(E)p(g,E);else{g.state=u,g.outcome=v;for(var N=-1,j=g.queue.length;++N<j;)g.queue[N].callFulfilled(v)}return g},l.reject=function(g,v){g.state=c,g.outcome=v;for(var w=-1,E=g.queue.length;++w<E;)g.queue[w].callRejected(v);return g},f.resolve=function(g){return g instanceof this?g:l.resolve(new this(a),g)},f.reject=function(g){var v=new this(a);return l.reject(v,g)},f.all=function(g){var v=this;if(Object.prototype.toString.call(g)!=="[object Array]")return this.reject(new TypeError("must be an array"));var w=g.length,E=!1;if(!w)return this.resolve([]);for(var N=new Array(w),j=0,I=-1,z=new this(a);++I<w;)$(g[I],I);return z;function $(V,B){v.resolve(V).then(function(_){N[B]=_,++j!==w||E||(E=!0,l.resolve(z,N))},function(_){E||(E=!0,l.reject(z,_))})}},f.race=function(g){var v=this;if(Object.prototype.toString.call(g)!=="[object Array]")return this.reject(new TypeError("must be an array"));var w=g.length,E=!1;if(!w)return this.resolve([]);for(var N=-1,j=new this(a);++N<w;)I=g[N],v.resolve(I).then(function(z){E||(E=!0,l.resolve(j,z))},function(z){E||(E=!0,l.reject(j,z))});var I;return j}},{immediate:36}],38:[function(n,s,i){var o={};(0,n("./lib/utils/common").assign)(o,n("./lib/deflate"),n("./lib/inflate"),n("./lib/zlib/constants")),s.exports=o},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(n,s,i){var o=n("./zlib/deflate"),a=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/messages"),u=n("./zlib/zstream"),d=Object.prototype.toString,f=0,m=-1,h=0,y=8;function p(g){if(!(this instanceof p))return new p(g);this.options=a.assign({level:m,method:y,chunkSize:16384,windowBits:15,memLevel:8,strategy:h,to:""},g||{});var v=this.options;v.raw&&0<v.windowBits?v.windowBits=-v.windowBits:v.gzip&&0<v.windowBits&&v.windowBits<16&&(v.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new u,this.strm.avail_out=0;var w=o.deflateInit2(this.strm,v.level,v.method,v.windowBits,v.memLevel,v.strategy);if(w!==f)throw new Error(c[w]);if(v.header&&o.deflateSetHeader(this.strm,v.header),v.dictionary){var E;if(E=typeof v.dictionary=="string"?l.string2buf(v.dictionary):d.call(v.dictionary)==="[object ArrayBuffer]"?new Uint8Array(v.dictionary):v.dictionary,(w=o.deflateSetDictionary(this.strm,E))!==f)throw new Error(c[w]);this._dict_set=!0}}function x(g,v){var w=new p(v);if(w.push(g,!0),w.err)throw w.msg||c[w.err];return w.result}p.prototype.push=function(g,v){var w,E,N=this.strm,j=this.options.chunkSize;if(this.ended)return!1;E=v===~~v?v:v===!0?4:0,typeof g=="string"?N.input=l.string2buf(g):d.call(g)==="[object ArrayBuffer]"?N.input=new Uint8Array(g):N.input=g,N.next_in=0,N.avail_in=N.input.length;do{if(N.avail_out===0&&(N.output=new a.Buf8(j),N.next_out=0,N.avail_out=j),(w=o.deflate(N,E))!==1&&w!==f)return this.onEnd(w),!(this.ended=!0);N.avail_out!==0&&(N.avail_in!==0||E!==4&&E!==2)||(this.options.to==="string"?this.onData(l.buf2binstring(a.shrinkBuf(N.output,N.next_out))):this.onData(a.shrinkBuf(N.output,N.next_out)))}while((0<N.avail_in||N.avail_out===0)&&w!==1);return E===4?(w=o.deflateEnd(this.strm),this.onEnd(w),this.ended=!0,w===f):E!==2||(this.onEnd(f),!(N.avail_out=0))},p.prototype.onData=function(g){this.chunks.push(g)},p.prototype.onEnd=function(g){g===f&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=a.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},i.Deflate=p,i.deflate=x,i.deflateRaw=function(g,v){return(v=v||{}).raw=!0,x(g,v)},i.gzip=function(g,v){return(v=v||{}).gzip=!0,x(g,v)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,s,i){var o=n("./zlib/inflate"),a=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/constants"),u=n("./zlib/messages"),d=n("./zlib/zstream"),f=n("./zlib/gzheader"),m=Object.prototype.toString;function h(p){if(!(this instanceof h))return new h(p);this.options=a.assign({chunkSize:16384,windowBits:0,to:""},p||{});var x=this.options;x.raw&&0<=x.windowBits&&x.windowBits<16&&(x.windowBits=-x.windowBits,x.windowBits===0&&(x.windowBits=-15)),!(0<=x.windowBits&&x.windowBits<16)||p&&p.windowBits||(x.windowBits+=32),15<x.windowBits&&x.windowBits<48&&(15&x.windowBits)==0&&(x.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var g=o.inflateInit2(this.strm,x.windowBits);if(g!==c.Z_OK)throw new Error(u[g]);this.header=new f,o.inflateGetHeader(this.strm,this.header)}function y(p,x){var g=new h(x);if(g.push(p,!0),g.err)throw g.msg||u[g.err];return g.result}h.prototype.push=function(p,x){var g,v,w,E,N,j,I=this.strm,z=this.options.chunkSize,$=this.options.dictionary,V=!1;if(this.ended)return!1;v=x===~~x?x:x===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof p=="string"?I.input=l.binstring2buf(p):m.call(p)==="[object ArrayBuffer]"?I.input=new Uint8Array(p):I.input=p,I.next_in=0,I.avail_in=I.input.length;do{if(I.avail_out===0&&(I.output=new a.Buf8(z),I.next_out=0,I.avail_out=z),(g=o.inflate(I,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&$&&(j=typeof $=="string"?l.string2buf($):m.call($)==="[object ArrayBuffer]"?new Uint8Array($):$,g=o.inflateSetDictionary(this.strm,j)),g===c.Z_BUF_ERROR&&V===!0&&(g=c.Z_OK,V=!1),g!==c.Z_STREAM_END&&g!==c.Z_OK)return this.onEnd(g),!(this.ended=!0);I.next_out&&(I.avail_out!==0&&g!==c.Z_STREAM_END&&(I.avail_in!==0||v!==c.Z_FINISH&&v!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(w=l.utf8border(I.output,I.next_out),E=I.next_out-w,N=l.buf2string(I.output,w),I.next_out=E,I.avail_out=z-E,E&&a.arraySet(I.output,I.output,w,E,0),this.onData(N)):this.onData(a.shrinkBuf(I.output,I.next_out)))),I.avail_in===0&&I.avail_out===0&&(V=!0)}while((0<I.avail_in||I.avail_out===0)&&g!==c.Z_STREAM_END);return g===c.Z_STREAM_END&&(v=c.Z_FINISH),v===c.Z_FINISH?(g=o.inflateEnd(this.strm),this.onEnd(g),this.ended=!0,g===c.Z_OK):v!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(I.avail_out=0))},h.prototype.onData=function(p){this.chunks.push(p)},h.prototype.onEnd=function(p){p===c.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=a.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},i.Inflate=h,i.inflate=y,i.inflateRaw=function(p,x){return(x=x||{}).raw=!0,y(p,x)},i.ungzip=y},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(n,s,i){var o=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";i.assign=function(c){for(var u=Array.prototype.slice.call(arguments,1);u.length;){var d=u.shift();if(d){if(typeof d!="object")throw new TypeError(d+"must be non-object");for(var f in d)d.hasOwnProperty(f)&&(c[f]=d[f])}}return c},i.shrinkBuf=function(c,u){return c.length===u?c:c.subarray?c.subarray(0,u):(c.length=u,c)};var a={arraySet:function(c,u,d,f,m){if(u.subarray&&c.subarray)c.set(u.subarray(d,d+f),m);else for(var h=0;h<f;h++)c[m+h]=u[d+h]},flattenChunks:function(c){var u,d,f,m,h,y;for(u=f=0,d=c.length;u<d;u++)f+=c[u].length;for(y=new Uint8Array(f),u=m=0,d=c.length;u<d;u++)h=c[u],y.set(h,m),m+=h.length;return y}},l={arraySet:function(c,u,d,f,m){for(var h=0;h<f;h++)c[m+h]=u[d+h]},flattenChunks:function(c){return[].concat.apply([],c)}};i.setTyped=function(c){c?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,a)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,l))},i.setTyped(o)},{}],42:[function(n,s,i){var o=n("./common"),a=!0,l=!0;try{String.fromCharCode.apply(null,[0])}catch{a=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{l=!1}for(var c=new o.Buf8(256),u=0;u<256;u++)c[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;function d(f,m){if(m<65537&&(f.subarray&&l||!f.subarray&&a))return String.fromCharCode.apply(null,o.shrinkBuf(f,m));for(var h="",y=0;y<m;y++)h+=String.fromCharCode(f[y]);return h}c[254]=c[254]=1,i.string2buf=function(f){var m,h,y,p,x,g=f.length,v=0;for(p=0;p<g;p++)(64512&(h=f.charCodeAt(p)))==55296&&p+1<g&&(64512&(y=f.charCodeAt(p+1)))==56320&&(h=65536+(h-55296<<10)+(y-56320),p++),v+=h<128?1:h<2048?2:h<65536?3:4;for(m=new o.Buf8(v),p=x=0;x<v;p++)(64512&(h=f.charCodeAt(p)))==55296&&p+1<g&&(64512&(y=f.charCodeAt(p+1)))==56320&&(h=65536+(h-55296<<10)+(y-56320),p++),h<128?m[x++]=h:(h<2048?m[x++]=192|h>>>6:(h<65536?m[x++]=224|h>>>12:(m[x++]=240|h>>>18,m[x++]=128|h>>>12&63),m[x++]=128|h>>>6&63),m[x++]=128|63&h);return m},i.buf2binstring=function(f){return d(f,f.length)},i.binstring2buf=function(f){for(var m=new o.Buf8(f.length),h=0,y=m.length;h<y;h++)m[h]=f.charCodeAt(h);return m},i.buf2string=function(f,m){var h,y,p,x,g=m||f.length,v=new Array(2*g);for(h=y=0;h<g;)if((p=f[h++])<128)v[y++]=p;else if(4<(x=c[p]))v[y++]=65533,h+=x-1;else{for(p&=x===2?31:x===3?15:7;1<x&&h<g;)p=p<<6|63&f[h++],x--;1<x?v[y++]=65533:p<65536?v[y++]=p:(p-=65536,v[y++]=55296|p>>10&1023,v[y++]=56320|1023&p)}return d(v,y)},i.utf8border=function(f,m){var h;for((m=m||f.length)>f.length&&(m=f.length),h=m-1;0<=h&&(192&f[h])==128;)h--;return h<0||h===0?m:h+c[f[h]]>m?h:m}},{"./common":41}],43:[function(n,s,i){s.exports=function(o,a,l,c){for(var u=65535&o|0,d=o>>>16&65535|0,f=0;l!==0;){for(l-=f=2e3<l?2e3:l;d=d+(u=u+a[c++]|0)|0,--f;);u%=65521,d%=65521}return u|d<<16|0}},{}],44:[function(n,s,i){s.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(n,s,i){var o=(function(){for(var a,l=[],c=0;c<256;c++){a=c;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;l[c]=a}return l})();s.exports=function(a,l,c,u){var d=o,f=u+c;a^=-1;for(var m=u;m<f;m++)a=a>>>8^d[255&(a^l[m])];return-1^a}},{}],46:[function(n,s,i){var o,a=n("../utils/common"),l=n("./trees"),c=n("./adler32"),u=n("./crc32"),d=n("./messages"),f=0,m=4,h=0,y=-2,p=-1,x=4,g=2,v=8,w=9,E=286,N=30,j=19,I=2*E+1,z=15,$=3,V=258,B=V+$+1,_=42,U=113,k=1,F=2,Z=3,M=4;function A(C,J){return C.msg=d[J],J}function L(C){return(C<<1)-(4<C?9:0)}function S(C){for(var J=C.length;0<=--J;)C[J]=0}function R(C){var J=C.state,se=J.pending;se>C.avail_out&&(se=C.avail_out),se!==0&&(a.arraySet(C.output,J.pending_buf,J.pending_out,se,C.next_out),C.next_out+=se,J.pending_out+=se,C.total_out+=se,C.avail_out-=se,J.pending-=se,J.pending===0&&(J.pending_out=0))}function D(C,J){l._tr_flush_block(C,0<=C.block_start?C.block_start:-1,C.strstart-C.block_start,J),C.block_start=C.strstart,R(C.strm)}function P(C,J){C.pending_buf[C.pending++]=J}function Y(C,J){C.pending_buf[C.pending++]=J>>>8&255,C.pending_buf[C.pending++]=255&J}function H(C,J){var se,W,T=C.max_chain_length,q=C.strstart,X=C.prev_length,ne=C.nice_match,Q=C.strstart>C.w_size-B?C.strstart-(C.w_size-B):0,re=C.window,de=C.w_mask,te=C.prev,O=C.strstart+V,G=re[q+X-1],ie=re[q+X];C.prev_length>=C.good_match&&(T>>=2),ne>C.lookahead&&(ne=C.lookahead);do if(re[(se=J)+X]===ie&&re[se+X-1]===G&&re[se]===re[q]&&re[++se]===re[q+1]){q+=2,se++;do;while(re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&re[++q]===re[++se]&&q<O);if(W=V-(O-q),q=O-V,X<W){if(C.match_start=J,ne<=(X=W))break;G=re[q+X-1],ie=re[q+X]}}while((J=te[J&de])>Q&&--T!=0);return X<=C.lookahead?X:C.lookahead}function ee(C){var J,se,W,T,q,X,ne,Q,re,de,te=C.w_size;do{if(T=C.window_size-C.lookahead-C.strstart,C.strstart>=te+(te-B)){for(a.arraySet(C.window,C.window,te,te,0),C.match_start-=te,C.strstart-=te,C.block_start-=te,J=se=C.hash_size;W=C.head[--J],C.head[J]=te<=W?W-te:0,--se;);for(J=se=te;W=C.prev[--J],C.prev[J]=te<=W?W-te:0,--se;);T+=te}if(C.strm.avail_in===0)break;if(X=C.strm,ne=C.window,Q=C.strstart+C.lookahead,re=T,de=void 0,de=X.avail_in,re<de&&(de=re),se=de===0?0:(X.avail_in-=de,a.arraySet(ne,X.input,X.next_in,de,Q),X.state.wrap===1?X.adler=c(X.adler,ne,de,Q):X.state.wrap===2&&(X.adler=u(X.adler,ne,de,Q)),X.next_in+=de,X.total_in+=de,de),C.lookahead+=se,C.lookahead+C.insert>=$)for(q=C.strstart-C.insert,C.ins_h=C.window[q],C.ins_h=(C.ins_h<<C.hash_shift^C.window[q+1])&C.hash_mask;C.insert&&(C.ins_h=(C.ins_h<<C.hash_shift^C.window[q+$-1])&C.hash_mask,C.prev[q&C.w_mask]=C.head[C.ins_h],C.head[C.ins_h]=q,q++,C.insert--,!(C.lookahead+C.insert<$)););}while(C.lookahead<B&&C.strm.avail_in!==0)}function le(C,J){for(var se,W;;){if(C.lookahead<B){if(ee(C),C.lookahead<B&&J===f)return k;if(C.lookahead===0)break}if(se=0,C.lookahead>=$&&(C.ins_h=(C.ins_h<<C.hash_shift^C.window[C.strstart+$-1])&C.hash_mask,se=C.prev[C.strstart&C.w_mask]=C.head[C.ins_h],C.head[C.ins_h]=C.strstart),se!==0&&C.strstart-se<=C.w_size-B&&(C.match_length=H(C,se)),C.match_length>=$)if(W=l._tr_tally(C,C.strstart-C.match_start,C.match_length-$),C.lookahead-=C.match_length,C.match_length<=C.max_lazy_match&&C.lookahead>=$){for(C.match_length--;C.strstart++,C.ins_h=(C.ins_h<<C.hash_shift^C.window[C.strstart+$-1])&C.hash_mask,se=C.prev[C.strstart&C.w_mask]=C.head[C.ins_h],C.head[C.ins_h]=C.strstart,--C.match_length!=0;);C.strstart++}else C.strstart+=C.match_length,C.match_length=0,C.ins_h=C.window[C.strstart],C.ins_h=(C.ins_h<<C.hash_shift^C.window[C.strstart+1])&C.hash_mask;else W=l._tr_tally(C,0,C.window[C.strstart]),C.lookahead--,C.strstart++;if(W&&(D(C,!1),C.strm.avail_out===0))return k}return C.insert=C.strstart<$-1?C.strstart:$-1,J===m?(D(C,!0),C.strm.avail_out===0?Z:M):C.last_lit&&(D(C,!1),C.strm.avail_out===0)?k:F}function ae(C,J){for(var se,W,T;;){if(C.lookahead<B){if(ee(C),C.lookahead<B&&J===f)return k;if(C.lookahead===0)break}if(se=0,C.lookahead>=$&&(C.ins_h=(C.ins_h<<C.hash_shift^C.window[C.strstart+$-1])&C.hash_mask,se=C.prev[C.strstart&C.w_mask]=C.head[C.ins_h],C.head[C.ins_h]=C.strstart),C.prev_length=C.match_length,C.prev_match=C.match_start,C.match_length=$-1,se!==0&&C.prev_length<C.max_lazy_match&&C.strstart-se<=C.w_size-B&&(C.match_length=H(C,se),C.match_length<=5&&(C.strategy===1||C.match_length===$&&4096<C.strstart-C.match_start)&&(C.match_length=$-1)),C.prev_length>=$&&C.match_length<=C.prev_length){for(T=C.strstart+C.lookahead-$,W=l._tr_tally(C,C.strstart-1-C.prev_match,C.prev_length-$),C.lookahead-=C.prev_length-1,C.prev_length-=2;++C.strstart<=T&&(C.ins_h=(C.ins_h<<C.hash_shift^C.window[C.strstart+$-1])&C.hash_mask,se=C.prev[C.strstart&C.w_mask]=C.head[C.ins_h],C.head[C.ins_h]=C.strstart),--C.prev_length!=0;);if(C.match_available=0,C.match_length=$-1,C.strstart++,W&&(D(C,!1),C.strm.avail_out===0))return k}else if(C.match_available){if((W=l._tr_tally(C,0,C.window[C.strstart-1]))&&D(C,!1),C.strstart++,C.lookahead--,C.strm.avail_out===0)return k}else C.match_available=1,C.strstart++,C.lookahead--}return C.match_available&&(W=l._tr_tally(C,0,C.window[C.strstart-1]),C.match_available=0),C.insert=C.strstart<$-1?C.strstart:$-1,J===m?(D(C,!0),C.strm.avail_out===0?Z:M):C.last_lit&&(D(C,!1),C.strm.avail_out===0)?k:F}function fe(C,J,se,W,T){this.good_length=C,this.max_lazy=J,this.nice_length=se,this.max_chain=W,this.func=T}function be(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=v,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new a.Buf16(2*I),this.dyn_dtree=new a.Buf16(2*(2*N+1)),this.bl_tree=new a.Buf16(2*(2*j+1)),S(this.dyn_ltree),S(this.dyn_dtree),S(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new a.Buf16(z+1),this.heap=new a.Buf16(2*E+1),S(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new a.Buf16(2*E+1),S(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ye(C){var J;return C&&C.state?(C.total_in=C.total_out=0,C.data_type=g,(J=C.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?_:U,C.adler=J.wrap===2?0:1,J.last_flush=f,l._tr_init(J),h):A(C,y)}function Se(C){var J=ye(C);return J===h&&(function(se){se.window_size=2*se.w_size,S(se.head),se.max_lazy_match=o[se.level].max_lazy,se.good_match=o[se.level].good_length,se.nice_match=o[se.level].nice_length,se.max_chain_length=o[se.level].max_chain,se.strstart=0,se.block_start=0,se.lookahead=0,se.insert=0,se.match_length=se.prev_length=$-1,se.match_available=0,se.ins_h=0})(C.state),J}function me(C,J,se,W,T,q){if(!C)return y;var X=1;if(J===p&&(J=6),W<0?(X=0,W=-W):15<W&&(X=2,W-=16),T<1||w<T||se!==v||W<8||15<W||J<0||9<J||q<0||x<q)return A(C,y);W===8&&(W=9);var ne=new be;return(C.state=ne).strm=C,ne.wrap=X,ne.gzhead=null,ne.w_bits=W,ne.w_size=1<<ne.w_bits,ne.w_mask=ne.w_size-1,ne.hash_bits=T+7,ne.hash_size=1<<ne.hash_bits,ne.hash_mask=ne.hash_size-1,ne.hash_shift=~~((ne.hash_bits+$-1)/$),ne.window=new a.Buf8(2*ne.w_size),ne.head=new a.Buf16(ne.hash_size),ne.prev=new a.Buf16(ne.w_size),ne.lit_bufsize=1<<T+6,ne.pending_buf_size=4*ne.lit_bufsize,ne.pending_buf=new a.Buf8(ne.pending_buf_size),ne.d_buf=1*ne.lit_bufsize,ne.l_buf=3*ne.lit_bufsize,ne.level=J,ne.strategy=q,ne.method=se,Se(C)}o=[new fe(0,0,0,0,function(C,J){var se=65535;for(se>C.pending_buf_size-5&&(se=C.pending_buf_size-5);;){if(C.lookahead<=1){if(ee(C),C.lookahead===0&&J===f)return k;if(C.lookahead===0)break}C.strstart+=C.lookahead,C.lookahead=0;var W=C.block_start+se;if((C.strstart===0||C.strstart>=W)&&(C.lookahead=C.strstart-W,C.strstart=W,D(C,!1),C.strm.avail_out===0)||C.strstart-C.block_start>=C.w_size-B&&(D(C,!1),C.strm.avail_out===0))return k}return C.insert=0,J===m?(D(C,!0),C.strm.avail_out===0?Z:M):(C.strstart>C.block_start&&(D(C,!1),C.strm.avail_out),k)}),new fe(4,4,8,4,le),new fe(4,5,16,8,le),new fe(4,6,32,32,le),new fe(4,4,16,16,ae),new fe(8,16,32,32,ae),new fe(8,16,128,128,ae),new fe(8,32,128,256,ae),new fe(32,128,258,1024,ae),new fe(32,258,258,4096,ae)],i.deflateInit=function(C,J){return me(C,J,v,15,8,0)},i.deflateInit2=me,i.deflateReset=Se,i.deflateResetKeep=ye,i.deflateSetHeader=function(C,J){return C&&C.state?C.state.wrap!==2?y:(C.state.gzhead=J,h):y},i.deflate=function(C,J){var se,W,T,q;if(!C||!C.state||5<J||J<0)return C?A(C,y):y;if(W=C.state,!C.output||!C.input&&C.avail_in!==0||W.status===666&&J!==m)return A(C,C.avail_out===0?-5:y);if(W.strm=C,se=W.last_flush,W.last_flush=J,W.status===_)if(W.wrap===2)C.adler=0,P(W,31),P(W,139),P(W,8),W.gzhead?(P(W,(W.gzhead.text?1:0)+(W.gzhead.hcrc?2:0)+(W.gzhead.extra?4:0)+(W.gzhead.name?8:0)+(W.gzhead.comment?16:0)),P(W,255&W.gzhead.time),P(W,W.gzhead.time>>8&255),P(W,W.gzhead.time>>16&255),P(W,W.gzhead.time>>24&255),P(W,W.level===9?2:2<=W.strategy||W.level<2?4:0),P(W,255&W.gzhead.os),W.gzhead.extra&&W.gzhead.extra.length&&(P(W,255&W.gzhead.extra.length),P(W,W.gzhead.extra.length>>8&255)),W.gzhead.hcrc&&(C.adler=u(C.adler,W.pending_buf,W.pending,0)),W.gzindex=0,W.status=69):(P(W,0),P(W,0),P(W,0),P(W,0),P(W,0),P(W,W.level===9?2:2<=W.strategy||W.level<2?4:0),P(W,3),W.status=U);else{var X=v+(W.w_bits-8<<4)<<8;X|=(2<=W.strategy||W.level<2?0:W.level<6?1:W.level===6?2:3)<<6,W.strstart!==0&&(X|=32),X+=31-X%31,W.status=U,Y(W,X),W.strstart!==0&&(Y(W,C.adler>>>16),Y(W,65535&C.adler)),C.adler=1}if(W.status===69)if(W.gzhead.extra){for(T=W.pending;W.gzindex<(65535&W.gzhead.extra.length)&&(W.pending!==W.pending_buf_size||(W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),R(C),T=W.pending,W.pending!==W.pending_buf_size));)P(W,255&W.gzhead.extra[W.gzindex]),W.gzindex++;W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),W.gzindex===W.gzhead.extra.length&&(W.gzindex=0,W.status=73)}else W.status=73;if(W.status===73)if(W.gzhead.name){T=W.pending;do{if(W.pending===W.pending_buf_size&&(W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),R(C),T=W.pending,W.pending===W.pending_buf_size)){q=1;break}q=W.gzindex<W.gzhead.name.length?255&W.gzhead.name.charCodeAt(W.gzindex++):0,P(W,q)}while(q!==0);W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),q===0&&(W.gzindex=0,W.status=91)}else W.status=91;if(W.status===91)if(W.gzhead.comment){T=W.pending;do{if(W.pending===W.pending_buf_size&&(W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),R(C),T=W.pending,W.pending===W.pending_buf_size)){q=1;break}q=W.gzindex<W.gzhead.comment.length?255&W.gzhead.comment.charCodeAt(W.gzindex++):0,P(W,q)}while(q!==0);W.gzhead.hcrc&&W.pending>T&&(C.adler=u(C.adler,W.pending_buf,W.pending-T,T)),q===0&&(W.status=103)}else W.status=103;if(W.status===103&&(W.gzhead.hcrc?(W.pending+2>W.pending_buf_size&&R(C),W.pending+2<=W.pending_buf_size&&(P(W,255&C.adler),P(W,C.adler>>8&255),C.adler=0,W.status=U)):W.status=U),W.pending!==0){if(R(C),C.avail_out===0)return W.last_flush=-1,h}else if(C.avail_in===0&&L(J)<=L(se)&&J!==m)return A(C,-5);if(W.status===666&&C.avail_in!==0)return A(C,-5);if(C.avail_in!==0||W.lookahead!==0||J!==f&&W.status!==666){var ne=W.strategy===2?(function(Q,re){for(var de;;){if(Q.lookahead===0&&(ee(Q),Q.lookahead===0)){if(re===f)return k;break}if(Q.match_length=0,de=l._tr_tally(Q,0,Q.window[Q.strstart]),Q.lookahead--,Q.strstart++,de&&(D(Q,!1),Q.strm.avail_out===0))return k}return Q.insert=0,re===m?(D(Q,!0),Q.strm.avail_out===0?Z:M):Q.last_lit&&(D(Q,!1),Q.strm.avail_out===0)?k:F})(W,J):W.strategy===3?(function(Q,re){for(var de,te,O,G,ie=Q.window;;){if(Q.lookahead<=V){if(ee(Q),Q.lookahead<=V&&re===f)return k;if(Q.lookahead===0)break}if(Q.match_length=0,Q.lookahead>=$&&0<Q.strstart&&(te=ie[O=Q.strstart-1])===ie[++O]&&te===ie[++O]&&te===ie[++O]){G=Q.strstart+V;do;while(te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&te===ie[++O]&&O<G);Q.match_length=V-(G-O),Q.match_length>Q.lookahead&&(Q.match_length=Q.lookahead)}if(Q.match_length>=$?(de=l._tr_tally(Q,1,Q.match_length-$),Q.lookahead-=Q.match_length,Q.strstart+=Q.match_length,Q.match_length=0):(de=l._tr_tally(Q,0,Q.window[Q.strstart]),Q.lookahead--,Q.strstart++),de&&(D(Q,!1),Q.strm.avail_out===0))return k}return Q.insert=0,re===m?(D(Q,!0),Q.strm.avail_out===0?Z:M):Q.last_lit&&(D(Q,!1),Q.strm.avail_out===0)?k:F})(W,J):o[W.level].func(W,J);if(ne!==Z&&ne!==M||(W.status=666),ne===k||ne===Z)return C.avail_out===0&&(W.last_flush=-1),h;if(ne===F&&(J===1?l._tr_align(W):J!==5&&(l._tr_stored_block(W,0,0,!1),J===3&&(S(W.head),W.lookahead===0&&(W.strstart=0,W.block_start=0,W.insert=0))),R(C),C.avail_out===0))return W.last_flush=-1,h}return J!==m?h:W.wrap<=0?1:(W.wrap===2?(P(W,255&C.adler),P(W,C.adler>>8&255),P(W,C.adler>>16&255),P(W,C.adler>>24&255),P(W,255&C.total_in),P(W,C.total_in>>8&255),P(W,C.total_in>>16&255),P(W,C.total_in>>24&255)):(Y(W,C.adler>>>16),Y(W,65535&C.adler)),R(C),0<W.wrap&&(W.wrap=-W.wrap),W.pending!==0?h:1)},i.deflateEnd=function(C){var J;return C&&C.state?(J=C.state.status)!==_&&J!==69&&J!==73&&J!==91&&J!==103&&J!==U&&J!==666?A(C,y):(C.state=null,J===U?A(C,-3):h):y},i.deflateSetDictionary=function(C,J){var se,W,T,q,X,ne,Q,re,de=J.length;if(!C||!C.state||(q=(se=C.state).wrap)===2||q===1&&se.status!==_||se.lookahead)return y;for(q===1&&(C.adler=c(C.adler,J,de,0)),se.wrap=0,de>=se.w_size&&(q===0&&(S(se.head),se.strstart=0,se.block_start=0,se.insert=0),re=new a.Buf8(se.w_size),a.arraySet(re,J,de-se.w_size,se.w_size,0),J=re,de=se.w_size),X=C.avail_in,ne=C.next_in,Q=C.input,C.avail_in=de,C.next_in=0,C.input=J,ee(se);se.lookahead>=$;){for(W=se.strstart,T=se.lookahead-($-1);se.ins_h=(se.ins_h<<se.hash_shift^se.window[W+$-1])&se.hash_mask,se.prev[W&se.w_mask]=se.head[se.ins_h],se.head[se.ins_h]=W,W++,--T;);se.strstart=W,se.lookahead=$-1,ee(se)}return se.strstart+=se.lookahead,se.block_start=se.strstart,se.insert=se.lookahead,se.lookahead=0,se.match_length=se.prev_length=$-1,se.match_available=0,C.next_in=ne,C.input=Q,C.avail_in=X,se.wrap=q,h},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,s,i){s.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(n,s,i){s.exports=function(o,a){var l,c,u,d,f,m,h,y,p,x,g,v,w,E,N,j,I,z,$,V,B,_,U,k,F;l=o.state,c=o.next_in,k=o.input,u=c+(o.avail_in-5),d=o.next_out,F=o.output,f=d-(a-o.avail_out),m=d+(o.avail_out-257),h=l.dmax,y=l.wsize,p=l.whave,x=l.wnext,g=l.window,v=l.hold,w=l.bits,E=l.lencode,N=l.distcode,j=(1<<l.lenbits)-1,I=(1<<l.distbits)-1;e:do{w<15&&(v+=k[c++]<<w,w+=8,v+=k[c++]<<w,w+=8),z=E[v&j];t:for(;;){if(v>>>=$=z>>>24,w-=$,($=z>>>16&255)===0)F[d++]=65535&z;else{if(!(16&$)){if((64&$)==0){z=E[(65535&z)+(v&(1<<$)-1)];continue t}if(32&$){l.mode=12;break e}o.msg="invalid literal/length code",l.mode=30;break e}V=65535&z,($&=15)&&(w<$&&(v+=k[c++]<<w,w+=8),V+=v&(1<<$)-1,v>>>=$,w-=$),w<15&&(v+=k[c++]<<w,w+=8,v+=k[c++]<<w,w+=8),z=N[v&I];n:for(;;){if(v>>>=$=z>>>24,w-=$,!(16&($=z>>>16&255))){if((64&$)==0){z=N[(65535&z)+(v&(1<<$)-1)];continue n}o.msg="invalid distance code",l.mode=30;break e}if(B=65535&z,w<($&=15)&&(v+=k[c++]<<w,(w+=8)<$&&(v+=k[c++]<<w,w+=8)),h<(B+=v&(1<<$)-1)){o.msg="invalid distance too far back",l.mode=30;break e}if(v>>>=$,w-=$,($=d-f)<B){if(p<($=B-$)&&l.sane){o.msg="invalid distance too far back",l.mode=30;break e}if(U=g,(_=0)===x){if(_+=y-$,$<V){for(V-=$;F[d++]=g[_++],--$;);_=d-B,U=F}}else if(x<$){if(_+=y+x-$,($-=x)<V){for(V-=$;F[d++]=g[_++],--$;);if(_=0,x<V){for(V-=$=x;F[d++]=g[_++],--$;);_=d-B,U=F}}}else if(_+=x-$,$<V){for(V-=$;F[d++]=g[_++],--$;);_=d-B,U=F}for(;2<V;)F[d++]=U[_++],F[d++]=U[_++],F[d++]=U[_++],V-=3;V&&(F[d++]=U[_++],1<V&&(F[d++]=U[_++]))}else{for(_=d-B;F[d++]=F[_++],F[d++]=F[_++],F[d++]=F[_++],2<(V-=3););V&&(F[d++]=F[_++],1<V&&(F[d++]=F[_++]))}break}}break}}while(c<u&&d<m);c-=V=w>>3,v&=(1<<(w-=V<<3))-1,o.next_in=c,o.next_out=d,o.avail_in=c<u?u-c+5:5-(c-u),o.avail_out=d<m?m-d+257:257-(d-m),l.hold=v,l.bits=w}},{}],49:[function(n,s,i){var o=n("../utils/common"),a=n("./adler32"),l=n("./crc32"),c=n("./inffast"),u=n("./inftrees"),d=1,f=2,m=0,h=-2,y=1,p=852,x=592;function g(_){return(_>>>24&255)+(_>>>8&65280)+((65280&_)<<8)+((255&_)<<24)}function v(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new o.Buf16(320),this.work=new o.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(_){var U;return _&&_.state?(U=_.state,_.total_in=_.total_out=U.total=0,_.msg="",U.wrap&&(_.adler=1&U.wrap),U.mode=y,U.last=0,U.havedict=0,U.dmax=32768,U.head=null,U.hold=0,U.bits=0,U.lencode=U.lendyn=new o.Buf32(p),U.distcode=U.distdyn=new o.Buf32(x),U.sane=1,U.back=-1,m):h}function E(_){var U;return _&&_.state?((U=_.state).wsize=0,U.whave=0,U.wnext=0,w(_)):h}function N(_,U){var k,F;return _&&_.state?(F=_.state,U<0?(k=0,U=-U):(k=1+(U>>4),U<48&&(U&=15)),U&&(U<8||15<U)?h:(F.window!==null&&F.wbits!==U&&(F.window=null),F.wrap=k,F.wbits=U,E(_))):h}function j(_,U){var k,F;return _?(F=new v,(_.state=F).window=null,(k=N(_,U))!==m&&(_.state=null),k):h}var I,z,$=!0;function V(_){if($){var U;for(I=new o.Buf32(512),z=new o.Buf32(32),U=0;U<144;)_.lens[U++]=8;for(;U<256;)_.lens[U++]=9;for(;U<280;)_.lens[U++]=7;for(;U<288;)_.lens[U++]=8;for(u(d,_.lens,0,288,I,0,_.work,{bits:9}),U=0;U<32;)_.lens[U++]=5;u(f,_.lens,0,32,z,0,_.work,{bits:5}),$=!1}_.lencode=I,_.lenbits=9,_.distcode=z,_.distbits=5}function B(_,U,k,F){var Z,M=_.state;return M.window===null&&(M.wsize=1<<M.wbits,M.wnext=0,M.whave=0,M.window=new o.Buf8(M.wsize)),F>=M.wsize?(o.arraySet(M.window,U,k-M.wsize,M.wsize,0),M.wnext=0,M.whave=M.wsize):(F<(Z=M.wsize-M.wnext)&&(Z=F),o.arraySet(M.window,U,k-F,Z,M.wnext),(F-=Z)?(o.arraySet(M.window,U,k-F,F,0),M.wnext=F,M.whave=M.wsize):(M.wnext+=Z,M.wnext===M.wsize&&(M.wnext=0),M.whave<M.wsize&&(M.whave+=Z))),0}i.inflateReset=E,i.inflateReset2=N,i.inflateResetKeep=w,i.inflateInit=function(_){return j(_,15)},i.inflateInit2=j,i.inflate=function(_,U){var k,F,Z,M,A,L,S,R,D,P,Y,H,ee,le,ae,fe,be,ye,Se,me,C,J,se,W,T=0,q=new o.Buf8(4),X=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!_||!_.state||!_.output||!_.input&&_.avail_in!==0)return h;(k=_.state).mode===12&&(k.mode=13),A=_.next_out,Z=_.output,S=_.avail_out,M=_.next_in,F=_.input,L=_.avail_in,R=k.hold,D=k.bits,P=L,Y=S,J=m;e:for(;;)switch(k.mode){case y:if(k.wrap===0){k.mode=13;break}for(;D<16;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(2&k.wrap&&R===35615){q[k.check=0]=255&R,q[1]=R>>>8&255,k.check=l(k.check,q,2,0),D=R=0,k.mode=2;break}if(k.flags=0,k.head&&(k.head.done=!1),!(1&k.wrap)||(((255&R)<<8)+(R>>8))%31){_.msg="incorrect header check",k.mode=30;break}if((15&R)!=8){_.msg="unknown compression method",k.mode=30;break}if(D-=4,C=8+(15&(R>>>=4)),k.wbits===0)k.wbits=C;else if(C>k.wbits){_.msg="invalid window size",k.mode=30;break}k.dmax=1<<C,_.adler=k.check=1,k.mode=512&R?10:12,D=R=0;break;case 2:for(;D<16;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(k.flags=R,(255&k.flags)!=8){_.msg="unknown compression method",k.mode=30;break}if(57344&k.flags){_.msg="unknown header flags set",k.mode=30;break}k.head&&(k.head.text=R>>8&1),512&k.flags&&(q[0]=255&R,q[1]=R>>>8&255,k.check=l(k.check,q,2,0)),D=R=0,k.mode=3;case 3:for(;D<32;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.head&&(k.head.time=R),512&k.flags&&(q[0]=255&R,q[1]=R>>>8&255,q[2]=R>>>16&255,q[3]=R>>>24&255,k.check=l(k.check,q,4,0)),D=R=0,k.mode=4;case 4:for(;D<16;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.head&&(k.head.xflags=255&R,k.head.os=R>>8),512&k.flags&&(q[0]=255&R,q[1]=R>>>8&255,k.check=l(k.check,q,2,0)),D=R=0,k.mode=5;case 5:if(1024&k.flags){for(;D<16;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.length=R,k.head&&(k.head.extra_len=R),512&k.flags&&(q[0]=255&R,q[1]=R>>>8&255,k.check=l(k.check,q,2,0)),D=R=0}else k.head&&(k.head.extra=null);k.mode=6;case 6:if(1024&k.flags&&(L<(H=k.length)&&(H=L),H&&(k.head&&(C=k.head.extra_len-k.length,k.head.extra||(k.head.extra=new Array(k.head.extra_len)),o.arraySet(k.head.extra,F,M,H,C)),512&k.flags&&(k.check=l(k.check,F,H,M)),L-=H,M+=H,k.length-=H),k.length))break e;k.length=0,k.mode=7;case 7:if(2048&k.flags){if(L===0)break e;for(H=0;C=F[M+H++],k.head&&C&&k.length<65536&&(k.head.name+=String.fromCharCode(C)),C&&H<L;);if(512&k.flags&&(k.check=l(k.check,F,H,M)),L-=H,M+=H,C)break e}else k.head&&(k.head.name=null);k.length=0,k.mode=8;case 8:if(4096&k.flags){if(L===0)break e;for(H=0;C=F[M+H++],k.head&&C&&k.length<65536&&(k.head.comment+=String.fromCharCode(C)),C&&H<L;);if(512&k.flags&&(k.check=l(k.check,F,H,M)),L-=H,M+=H,C)break e}else k.head&&(k.head.comment=null);k.mode=9;case 9:if(512&k.flags){for(;D<16;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(R!==(65535&k.check)){_.msg="header crc mismatch",k.mode=30;break}D=R=0}k.head&&(k.head.hcrc=k.flags>>9&1,k.head.done=!0),_.adler=k.check=0,k.mode=12;break;case 10:for(;D<32;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}_.adler=k.check=g(R),D=R=0,k.mode=11;case 11:if(k.havedict===0)return _.next_out=A,_.avail_out=S,_.next_in=M,_.avail_in=L,k.hold=R,k.bits=D,2;_.adler=k.check=1,k.mode=12;case 12:if(U===5||U===6)break e;case 13:if(k.last){R>>>=7&D,D-=7&D,k.mode=27;break}for(;D<3;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}switch(k.last=1&R,D-=1,3&(R>>>=1)){case 0:k.mode=14;break;case 1:if(V(k),k.mode=20,U!==6)break;R>>>=2,D-=2;break e;case 2:k.mode=17;break;case 3:_.msg="invalid block type",k.mode=30}R>>>=2,D-=2;break;case 14:for(R>>>=7&D,D-=7&D;D<32;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if((65535&R)!=(R>>>16^65535)){_.msg="invalid stored block lengths",k.mode=30;break}if(k.length=65535&R,D=R=0,k.mode=15,U===6)break e;case 15:k.mode=16;case 16:if(H=k.length){if(L<H&&(H=L),S<H&&(H=S),H===0)break e;o.arraySet(Z,F,M,H,A),L-=H,M+=H,S-=H,A+=H,k.length-=H;break}k.mode=12;break;case 17:for(;D<14;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(k.nlen=257+(31&R),R>>>=5,D-=5,k.ndist=1+(31&R),R>>>=5,D-=5,k.ncode=4+(15&R),R>>>=4,D-=4,286<k.nlen||30<k.ndist){_.msg="too many length or distance symbols",k.mode=30;break}k.have=0,k.mode=18;case 18:for(;k.have<k.ncode;){for(;D<3;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.lens[X[k.have++]]=7&R,R>>>=3,D-=3}for(;k.have<19;)k.lens[X[k.have++]]=0;if(k.lencode=k.lendyn,k.lenbits=7,se={bits:k.lenbits},J=u(0,k.lens,0,19,k.lencode,0,k.work,se),k.lenbits=se.bits,J){_.msg="invalid code lengths set",k.mode=30;break}k.have=0,k.mode=19;case 19:for(;k.have<k.nlen+k.ndist;){for(;fe=(T=k.lencode[R&(1<<k.lenbits)-1])>>>16&255,be=65535&T,!((ae=T>>>24)<=D);){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(be<16)R>>>=ae,D-=ae,k.lens[k.have++]=be;else{if(be===16){for(W=ae+2;D<W;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(R>>>=ae,D-=ae,k.have===0){_.msg="invalid bit length repeat",k.mode=30;break}C=k.lens[k.have-1],H=3+(3&R),R>>>=2,D-=2}else if(be===17){for(W=ae+3;D<W;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}D-=ae,C=0,H=3+(7&(R>>>=ae)),R>>>=3,D-=3}else{for(W=ae+7;D<W;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}D-=ae,C=0,H=11+(127&(R>>>=ae)),R>>>=7,D-=7}if(k.have+H>k.nlen+k.ndist){_.msg="invalid bit length repeat",k.mode=30;break}for(;H--;)k.lens[k.have++]=C}}if(k.mode===30)break;if(k.lens[256]===0){_.msg="invalid code -- missing end-of-block",k.mode=30;break}if(k.lenbits=9,se={bits:k.lenbits},J=u(d,k.lens,0,k.nlen,k.lencode,0,k.work,se),k.lenbits=se.bits,J){_.msg="invalid literal/lengths set",k.mode=30;break}if(k.distbits=6,k.distcode=k.distdyn,se={bits:k.distbits},J=u(f,k.lens,k.nlen,k.ndist,k.distcode,0,k.work,se),k.distbits=se.bits,J){_.msg="invalid distances set",k.mode=30;break}if(k.mode=20,U===6)break e;case 20:k.mode=21;case 21:if(6<=L&&258<=S){_.next_out=A,_.avail_out=S,_.next_in=M,_.avail_in=L,k.hold=R,k.bits=D,c(_,Y),A=_.next_out,Z=_.output,S=_.avail_out,M=_.next_in,F=_.input,L=_.avail_in,R=k.hold,D=k.bits,k.mode===12&&(k.back=-1);break}for(k.back=0;fe=(T=k.lencode[R&(1<<k.lenbits)-1])>>>16&255,be=65535&T,!((ae=T>>>24)<=D);){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(fe&&(240&fe)==0){for(ye=ae,Se=fe,me=be;fe=(T=k.lencode[me+((R&(1<<ye+Se)-1)>>ye)])>>>16&255,be=65535&T,!(ye+(ae=T>>>24)<=D);){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}R>>>=ye,D-=ye,k.back+=ye}if(R>>>=ae,D-=ae,k.back+=ae,k.length=be,fe===0){k.mode=26;break}if(32&fe){k.back=-1,k.mode=12;break}if(64&fe){_.msg="invalid literal/length code",k.mode=30;break}k.extra=15&fe,k.mode=22;case 22:if(k.extra){for(W=k.extra;D<W;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.length+=R&(1<<k.extra)-1,R>>>=k.extra,D-=k.extra,k.back+=k.extra}k.was=k.length,k.mode=23;case 23:for(;fe=(T=k.distcode[R&(1<<k.distbits)-1])>>>16&255,be=65535&T,!((ae=T>>>24)<=D);){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if((240&fe)==0){for(ye=ae,Se=fe,me=be;fe=(T=k.distcode[me+((R&(1<<ye+Se)-1)>>ye)])>>>16&255,be=65535&T,!(ye+(ae=T>>>24)<=D);){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}R>>>=ye,D-=ye,k.back+=ye}if(R>>>=ae,D-=ae,k.back+=ae,64&fe){_.msg="invalid distance code",k.mode=30;break}k.offset=be,k.extra=15&fe,k.mode=24;case 24:if(k.extra){for(W=k.extra;D<W;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}k.offset+=R&(1<<k.extra)-1,R>>>=k.extra,D-=k.extra,k.back+=k.extra}if(k.offset>k.dmax){_.msg="invalid distance too far back",k.mode=30;break}k.mode=25;case 25:if(S===0)break e;if(H=Y-S,k.offset>H){if((H=k.offset-H)>k.whave&&k.sane){_.msg="invalid distance too far back",k.mode=30;break}ee=H>k.wnext?(H-=k.wnext,k.wsize-H):k.wnext-H,H>k.length&&(H=k.length),le=k.window}else le=Z,ee=A-k.offset,H=k.length;for(S<H&&(H=S),S-=H,k.length-=H;Z[A++]=le[ee++],--H;);k.length===0&&(k.mode=21);break;case 26:if(S===0)break e;Z[A++]=k.length,S--,k.mode=21;break;case 27:if(k.wrap){for(;D<32;){if(L===0)break e;L--,R|=F[M++]<<D,D+=8}if(Y-=S,_.total_out+=Y,k.total+=Y,Y&&(_.adler=k.check=k.flags?l(k.check,Z,Y,A-Y):a(k.check,Z,Y,A-Y)),Y=S,(k.flags?R:g(R))!==k.check){_.msg="incorrect data check",k.mode=30;break}D=R=0}k.mode=28;case 28:if(k.wrap&&k.flags){for(;D<32;){if(L===0)break e;L--,R+=F[M++]<<D,D+=8}if(R!==(4294967295&k.total)){_.msg="incorrect length check",k.mode=30;break}D=R=0}k.mode=29;case 29:J=1;break e;case 30:J=-3;break e;case 31:return-4;case 32:default:return h}return _.next_out=A,_.avail_out=S,_.next_in=M,_.avail_in=L,k.hold=R,k.bits=D,(k.wsize||Y!==_.avail_out&&k.mode<30&&(k.mode<27||U!==4))&&B(_,_.output,_.next_out,Y-_.avail_out)?(k.mode=31,-4):(P-=_.avail_in,Y-=_.avail_out,_.total_in+=P,_.total_out+=Y,k.total+=Y,k.wrap&&Y&&(_.adler=k.check=k.flags?l(k.check,Z,Y,_.next_out-Y):a(k.check,Z,Y,_.next_out-Y)),_.data_type=k.bits+(k.last?64:0)+(k.mode===12?128:0)+(k.mode===20||k.mode===15?256:0),(P==0&&Y===0||U===4)&&J===m&&(J=-5),J)},i.inflateEnd=function(_){if(!_||!_.state)return h;var U=_.state;return U.window&&(U.window=null),_.state=null,m},i.inflateGetHeader=function(_,U){var k;return _&&_.state?(2&(k=_.state).wrap)==0?h:((k.head=U).done=!1,m):h},i.inflateSetDictionary=function(_,U){var k,F=U.length;return _&&_.state?(k=_.state).wrap!==0&&k.mode!==11?h:k.mode===11&&a(1,U,F,0)!==k.check?-3:B(_,U,F,F)?(k.mode=31,-4):(k.havedict=1,m):h},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(n,s,i){var o=n("../utils/common"),a=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],c=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],u=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];s.exports=function(d,f,m,h,y,p,x,g){var v,w,E,N,j,I,z,$,V,B=g.bits,_=0,U=0,k=0,F=0,Z=0,M=0,A=0,L=0,S=0,R=0,D=null,P=0,Y=new o.Buf16(16),H=new o.Buf16(16),ee=null,le=0;for(_=0;_<=15;_++)Y[_]=0;for(U=0;U<h;U++)Y[f[m+U]]++;for(Z=B,F=15;1<=F&&Y[F]===0;F--);if(F<Z&&(Z=F),F===0)return y[p++]=20971520,y[p++]=20971520,g.bits=1,0;for(k=1;k<F&&Y[k]===0;k++);for(Z<k&&(Z=k),_=L=1;_<=15;_++)if(L<<=1,(L-=Y[_])<0)return-1;if(0<L&&(d===0||F!==1))return-1;for(H[1]=0,_=1;_<15;_++)H[_+1]=H[_]+Y[_];for(U=0;U<h;U++)f[m+U]!==0&&(x[H[f[m+U]]++]=U);if(I=d===0?(D=ee=x,19):d===1?(D=a,P-=257,ee=l,le-=257,256):(D=c,ee=u,-1),_=k,j=p,A=U=R=0,E=-1,N=(S=1<<(M=Z))-1,d===1&&852<S||d===2&&592<S)return 1;for(;;){for(z=_-A,V=x[U]<I?($=0,x[U]):x[U]>I?($=ee[le+x[U]],D[P+x[U]]):($=96,0),v=1<<_-A,k=w=1<<M;y[j+(R>>A)+(w-=v)]=z<<24|$<<16|V|0,w!==0;);for(v=1<<_-1;R&v;)v>>=1;if(v!==0?(R&=v-1,R+=v):R=0,U++,--Y[_]==0){if(_===F)break;_=f[m+x[U]]}if(Z<_&&(R&N)!==E){for(A===0&&(A=Z),j+=k,L=1<<(M=_-A);M+A<F&&!((L-=Y[M+A])<=0);)M++,L<<=1;if(S+=1<<M,d===1&&852<S||d===2&&592<S)return 1;y[E=R&N]=Z<<24|M<<16|j-p|0}}return R!==0&&(y[j+R]=_-A<<24|64<<16|0),g.bits=Z,0}},{"../utils/common":41}],51:[function(n,s,i){s.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(n,s,i){var o=n("../utils/common"),a=0,l=1;function c(T){for(var q=T.length;0<=--q;)T[q]=0}var u=0,d=29,f=256,m=f+1+d,h=30,y=19,p=2*m+1,x=15,g=16,v=7,w=256,E=16,N=17,j=18,I=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],z=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],V=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],B=new Array(2*(m+2));c(B);var _=new Array(2*h);c(_);var U=new Array(512);c(U);var k=new Array(256);c(k);var F=new Array(d);c(F);var Z,M,A,L=new Array(h);function S(T,q,X,ne,Q){this.static_tree=T,this.extra_bits=q,this.extra_base=X,this.elems=ne,this.max_length=Q,this.has_stree=T&&T.length}function R(T,q){this.dyn_tree=T,this.max_code=0,this.stat_desc=q}function D(T){return T<256?U[T]:U[256+(T>>>7)]}function P(T,q){T.pending_buf[T.pending++]=255&q,T.pending_buf[T.pending++]=q>>>8&255}function Y(T,q,X){T.bi_valid>g-X?(T.bi_buf|=q<<T.bi_valid&65535,P(T,T.bi_buf),T.bi_buf=q>>g-T.bi_valid,T.bi_valid+=X-g):(T.bi_buf|=q<<T.bi_valid&65535,T.bi_valid+=X)}function H(T,q,X){Y(T,X[2*q],X[2*q+1])}function ee(T,q){for(var X=0;X|=1&T,T>>>=1,X<<=1,0<--q;);return X>>>1}function le(T,q,X){var ne,Q,re=new Array(x+1),de=0;for(ne=1;ne<=x;ne++)re[ne]=de=de+X[ne-1]<<1;for(Q=0;Q<=q;Q++){var te=T[2*Q+1];te!==0&&(T[2*Q]=ee(re[te]++,te))}}function ae(T){var q;for(q=0;q<m;q++)T.dyn_ltree[2*q]=0;for(q=0;q<h;q++)T.dyn_dtree[2*q]=0;for(q=0;q<y;q++)T.bl_tree[2*q]=0;T.dyn_ltree[2*w]=1,T.opt_len=T.static_len=0,T.last_lit=T.matches=0}function fe(T){8<T.bi_valid?P(T,T.bi_buf):0<T.bi_valid&&(T.pending_buf[T.pending++]=T.bi_buf),T.bi_buf=0,T.bi_valid=0}function be(T,q,X,ne){var Q=2*q,re=2*X;return T[Q]<T[re]||T[Q]===T[re]&&ne[q]<=ne[X]}function ye(T,q,X){for(var ne=T.heap[X],Q=X<<1;Q<=T.heap_len&&(Q<T.heap_len&&be(q,T.heap[Q+1],T.heap[Q],T.depth)&&Q++,!be(q,ne,T.heap[Q],T.depth));)T.heap[X]=T.heap[Q],X=Q,Q<<=1;T.heap[X]=ne}function Se(T,q,X){var ne,Q,re,de,te=0;if(T.last_lit!==0)for(;ne=T.pending_buf[T.d_buf+2*te]<<8|T.pending_buf[T.d_buf+2*te+1],Q=T.pending_buf[T.l_buf+te],te++,ne===0?H(T,Q,q):(H(T,(re=k[Q])+f+1,q),(de=I[re])!==0&&Y(T,Q-=F[re],de),H(T,re=D(--ne),X),(de=z[re])!==0&&Y(T,ne-=L[re],de)),te<T.last_lit;);H(T,w,q)}function me(T,q){var X,ne,Q,re=q.dyn_tree,de=q.stat_desc.static_tree,te=q.stat_desc.has_stree,O=q.stat_desc.elems,G=-1;for(T.heap_len=0,T.heap_max=p,X=0;X<O;X++)re[2*X]!==0?(T.heap[++T.heap_len]=G=X,T.depth[X]=0):re[2*X+1]=0;for(;T.heap_len<2;)re[2*(Q=T.heap[++T.heap_len]=G<2?++G:0)]=1,T.depth[Q]=0,T.opt_len--,te&&(T.static_len-=de[2*Q+1]);for(q.max_code=G,X=T.heap_len>>1;1<=X;X--)ye(T,re,X);for(Q=O;X=T.heap[1],T.heap[1]=T.heap[T.heap_len--],ye(T,re,1),ne=T.heap[1],T.heap[--T.heap_max]=X,T.heap[--T.heap_max]=ne,re[2*Q]=re[2*X]+re[2*ne],T.depth[Q]=(T.depth[X]>=T.depth[ne]?T.depth[X]:T.depth[ne])+1,re[2*X+1]=re[2*ne+1]=Q,T.heap[1]=Q++,ye(T,re,1),2<=T.heap_len;);T.heap[--T.heap_max]=T.heap[1],(function(ie,ue){var he,K,we,oe,ce,pe,xe=ue.dyn_tree,ve=ue.max_code,_e=ue.stat_desc.static_tree,je=ue.stat_desc.has_stree,Me=ue.stat_desc.extra_bits,et=ue.stat_desc.extra_base,Be=ue.stat_desc.max_length,st=0;for(oe=0;oe<=x;oe++)ie.bl_count[oe]=0;for(xe[2*ie.heap[ie.heap_max]+1]=0,he=ie.heap_max+1;he<p;he++)Be<(oe=xe[2*xe[2*(K=ie.heap[he])+1]+1]+1)&&(oe=Be,st++),xe[2*K+1]=oe,ve<K||(ie.bl_count[oe]++,ce=0,et<=K&&(ce=Me[K-et]),pe=xe[2*K],ie.opt_len+=pe*(oe+ce),je&&(ie.static_len+=pe*(_e[2*K+1]+ce)));if(st!==0){do{for(oe=Be-1;ie.bl_count[oe]===0;)oe--;ie.bl_count[oe]--,ie.bl_count[oe+1]+=2,ie.bl_count[Be]--,st-=2}while(0<st);for(oe=Be;oe!==0;oe--)for(K=ie.bl_count[oe];K!==0;)ve<(we=ie.heap[--he])||(xe[2*we+1]!==oe&&(ie.opt_len+=(oe-xe[2*we+1])*xe[2*we],xe[2*we+1]=oe),K--)}})(T,q),le(re,G,T.bl_count)}function C(T,q,X){var ne,Q,re=-1,de=q[1],te=0,O=7,G=4;for(de===0&&(O=138,G=3),q[2*(X+1)+1]=65535,ne=0;ne<=X;ne++)Q=de,de=q[2*(ne+1)+1],++te<O&&Q===de||(te<G?T.bl_tree[2*Q]+=te:Q!==0?(Q!==re&&T.bl_tree[2*Q]++,T.bl_tree[2*E]++):te<=10?T.bl_tree[2*N]++:T.bl_tree[2*j]++,re=Q,G=(te=0)===de?(O=138,3):Q===de?(O=6,3):(O=7,4))}function J(T,q,X){var ne,Q,re=-1,de=q[1],te=0,O=7,G=4;for(de===0&&(O=138,G=3),ne=0;ne<=X;ne++)if(Q=de,de=q[2*(ne+1)+1],!(++te<O&&Q===de)){if(te<G)for(;H(T,Q,T.bl_tree),--te!=0;);else Q!==0?(Q!==re&&(H(T,Q,T.bl_tree),te--),H(T,E,T.bl_tree),Y(T,te-3,2)):te<=10?(H(T,N,T.bl_tree),Y(T,te-3,3)):(H(T,j,T.bl_tree),Y(T,te-11,7));re=Q,G=(te=0)===de?(O=138,3):Q===de?(O=6,3):(O=7,4)}}c(L);var se=!1;function W(T,q,X,ne){Y(T,(u<<1)+(ne?1:0),3),(function(Q,re,de,te){fe(Q),P(Q,de),P(Q,~de),o.arraySet(Q.pending_buf,Q.window,re,de,Q.pending),Q.pending+=de})(T,q,X)}i._tr_init=function(T){se||((function(){var q,X,ne,Q,re,de=new Array(x+1);for(Q=ne=0;Q<d-1;Q++)for(F[Q]=ne,q=0;q<1<<I[Q];q++)k[ne++]=Q;for(k[ne-1]=Q,Q=re=0;Q<16;Q++)for(L[Q]=re,q=0;q<1<<z[Q];q++)U[re++]=Q;for(re>>=7;Q<h;Q++)for(L[Q]=re<<7,q=0;q<1<<z[Q]-7;q++)U[256+re++]=Q;for(X=0;X<=x;X++)de[X]=0;for(q=0;q<=143;)B[2*q+1]=8,q++,de[8]++;for(;q<=255;)B[2*q+1]=9,q++,de[9]++;for(;q<=279;)B[2*q+1]=7,q++,de[7]++;for(;q<=287;)B[2*q+1]=8,q++,de[8]++;for(le(B,m+1,de),q=0;q<h;q++)_[2*q+1]=5,_[2*q]=ee(q,5);Z=new S(B,I,f+1,m,x),M=new S(_,z,0,h,x),A=new S(new Array(0),$,0,y,v)})(),se=!0),T.l_desc=new R(T.dyn_ltree,Z),T.d_desc=new R(T.dyn_dtree,M),T.bl_desc=new R(T.bl_tree,A),T.bi_buf=0,T.bi_valid=0,ae(T)},i._tr_stored_block=W,i._tr_flush_block=function(T,q,X,ne){var Q,re,de=0;0<T.level?(T.strm.data_type===2&&(T.strm.data_type=(function(te){var O,G=4093624447;for(O=0;O<=31;O++,G>>>=1)if(1&G&&te.dyn_ltree[2*O]!==0)return a;if(te.dyn_ltree[18]!==0||te.dyn_ltree[20]!==0||te.dyn_ltree[26]!==0)return l;for(O=32;O<f;O++)if(te.dyn_ltree[2*O]!==0)return l;return a})(T)),me(T,T.l_desc),me(T,T.d_desc),de=(function(te){var O;for(C(te,te.dyn_ltree,te.l_desc.max_code),C(te,te.dyn_dtree,te.d_desc.max_code),me(te,te.bl_desc),O=y-1;3<=O&&te.bl_tree[2*V[O]+1]===0;O--);return te.opt_len+=3*(O+1)+5+5+4,O})(T),Q=T.opt_len+3+7>>>3,(re=T.static_len+3+7>>>3)<=Q&&(Q=re)):Q=re=X+5,X+4<=Q&&q!==-1?W(T,q,X,ne):T.strategy===4||re===Q?(Y(T,2+(ne?1:0),3),Se(T,B,_)):(Y(T,4+(ne?1:0),3),(function(te,O,G,ie){var ue;for(Y(te,O-257,5),Y(te,G-1,5),Y(te,ie-4,4),ue=0;ue<ie;ue++)Y(te,te.bl_tree[2*V[ue]+1],3);J(te,te.dyn_ltree,O-1),J(te,te.dyn_dtree,G-1)})(T,T.l_desc.max_code+1,T.d_desc.max_code+1,de+1),Se(T,T.dyn_ltree,T.dyn_dtree)),ae(T),ne&&fe(T)},i._tr_tally=function(T,q,X){return T.pending_buf[T.d_buf+2*T.last_lit]=q>>>8&255,T.pending_buf[T.d_buf+2*T.last_lit+1]=255&q,T.pending_buf[T.l_buf+T.last_lit]=255&X,T.last_lit++,q===0?T.dyn_ltree[2*X]++:(T.matches++,q--,T.dyn_ltree[2*(k[X]+f+1)]++,T.dyn_dtree[2*D(q)]++),T.last_lit===T.lit_bufsize-1},i._tr_align=function(T){Y(T,2,3),H(T,w,B),(function(q){q.bi_valid===16?(P(q,q.bi_buf),q.bi_buf=0,q.bi_valid=0):8<=q.bi_valid&&(q.pending_buf[q.pending++]=255&q.bi_buf,q.bi_buf>>=8,q.bi_valid-=8)})(T)}},{"../utils/common":41}],53:[function(n,s,i){s.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,s,i){(function(o){(function(a,l){if(!a.setImmediate){var c,u,d,f,m=1,h={},y=!1,p=a.document,x=Object.getPrototypeOf&&Object.getPrototypeOf(a);x=x&&x.setTimeout?x:a,c={}.toString.call(a.process)==="[object process]"?function(E){process.nextTick(function(){v(E)})}:(function(){if(a.postMessage&&!a.importScripts){var E=!0,N=a.onmessage;return a.onmessage=function(){E=!1},a.postMessage("","*"),a.onmessage=N,E}})()?(f="setImmediate$"+Math.random()+"$",a.addEventListener?a.addEventListener("message",w,!1):a.attachEvent("onmessage",w),function(E){a.postMessage(f+E,"*")}):a.MessageChannel?((d=new MessageChannel).port1.onmessage=function(E){v(E.data)},function(E){d.port2.postMessage(E)}):p&&"onreadystatechange"in p.createElement("script")?(u=p.documentElement,function(E){var N=p.createElement("script");N.onreadystatechange=function(){v(E),N.onreadystatechange=null,u.removeChild(N),N=null},u.appendChild(N)}):function(E){setTimeout(v,0,E)},x.setImmediate=function(E){typeof E!="function"&&(E=new Function(""+E));for(var N=new Array(arguments.length-1),j=0;j<N.length;j++)N[j]=arguments[j+1];var I={callback:E,args:N};return h[m]=I,c(m),m++},x.clearImmediate=g}function g(E){delete h[E]}function v(E){if(y)setTimeout(v,0,E);else{var N=h[E];if(N){y=!0;try{(function(j){var I=j.callback,z=j.args;switch(z.length){case 0:I();break;case 1:I(z[0]);break;case 2:I(z[0],z[1]);break;case 3:I(z[0],z[1],z[2]);break;default:I.apply(l,z)}})(N)}finally{g(E),y=!1}}}}function w(E){E.source===a&&typeof E.data=="string"&&E.data.indexOf(f)===0&&v(+E.data.slice(f.length))}})(typeof self>"u"?o===void 0?this:o:self)}).call(this,typeof fr<"u"?fr:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(ja)),ja.exports}var YE=KE();const QE=Rl(YE),JE=[{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"}}],wh={...xn.light};function XE({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:i,deleteCustomTheme:o}=Ie(),a=b.useId(),[l,c]=b.useState("custom-mytheme"),[u,d]=b.useState("我的专属主题"),[f,m]=b.useState("自定义教学调色板配置"),[h,y]=b.useState({...wh}),[p,x]=b.useState("none"),[g,v]=b.useState(""),[w,E]=b.useState(!1),[N,j]=b.useState(null);if(!e)return null;const I=s.filter(A=>A.category==="custom"),z=A=>{j(A),setTimeout(()=>j(null),3e3)},$=A=>{c(A.id),d(A.label),m(A.description),y({...A.tokens}),z(`已载入预设: ${A.label}`)},V=A=>{c(A.id),d(A.label),m(A.description);const L=ir(A.id);L&&Object.keys(L).length>0&&y({...L}),z(`已载入自定义主题: ${A.label}`)},B=(A,L)=>{y(S=>({...S,[A]:L}))},_=()=>{const A=l.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!A){alert("请输入有效的主题标识 (ID)");return}const L={id:A,label:u.trim()||"未命名主题",description:f.trim()||"自定义主题",previewBg:h["--bg-app"]||"#ffffff",previewPrimary:h["--color-primary"]||"#4f46e5",category:"custom"};i(L,h),z(`主题「${L.label}」已保存并成功激活!`)},U=()=>{v(JSON.stringify({version:"1.0",id:l,label:u,description:f,tokens:h},null,2)),x("export")},k=()=>{v(""),x("import")},F=()=>{try{const A=JSON.parse(g);if(!A.tokens||typeof A.tokens!="object")throw new Error("缺少合法的 tokens 字段");A.id&&c(A.id),A.label&&d(A.label),A.description&&m(A.description),y(L=>({...L,...A.tokens})),x("none"),z("主题配置导入成功!")}catch(A){alert(`导入失败: ${A instanceof Error?A.message:"JSON 格式解析错误"}`)}},Z=()=>{Qs(g),E(!0),setTimeout(()=>E(!1),2e3)},M=[{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(Ba,{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:k,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(Ua,{size:14}),n==="zh"?"导入配置":"Import"]}),r.jsxs("button",{onClick:U,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($s,{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(De,{size:18})})]})]}),N&&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(Xe,{size:14}),N]}),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(ut,{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:JE.map(A=>r.jsxs("button",{onClick:()=>$(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(g0,{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:u,onChange:A=>d(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:f,onChange:A=>m(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(Ba,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),r.jsx("div",{className:"space-y-2.5",children:M.map(A=>{const L=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:L.startsWith("#")&&L.length===7?L:"#4f46e5",onChange:S=>B(A.key,S.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:L,onChange:S=>B(A.key,S.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)})})]}),I.length>0&&r.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[r.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[r.jsx(Yh,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),r.jsx("div",{className:"space-y-2",children:I.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:()=>V(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),z(`已删除主题「${A.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:r.jsx(Jn,{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(kn,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),r.jsxs("span",{className:"text-xs text-muted font-mono",children:["当前预览: ",u," (",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(Xs,{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:()=>{y({...wh}),z("已重置为系统默认调色板")},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(Vl,{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:_,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(x0,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),p!=="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:p==="export"?r.jsxs(r.Fragment,{children:[r.jsx($s,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):r.jsxs(r.Fragment,{children:[r.jsx(Ua,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),r.jsx("button",{onClick:()=>x("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:r.jsx(De,{size:16})})]}),r.jsx("div",{children:r.jsx("textarea",{value:g,readOnly:p==="export",onChange:A=>v(A.target.value),placeholder:p==="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:p==="export"?r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:async()=>{const A=(l||"custom-theme").toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^-+/,"custom-"),L={schemaVersion:1,id:A.length>=2?A:"custom-theme",name:u||"Custom Theme",version:"1.0.0",description:f||"Exported from OpenLearn Theme Designer",author:"Theme Designer User",defaultMode:"auto",tokens:h,modes:{light:{tokens:h},dark:{tokens:h}},stylesFile:"styles.css"},S=new QE;S.file("theme.json",JSON.stringify(L,null,2)),S.file("styles.css",`/* Custom theme styles for ${L.id} */
|
|
105
|
+
`);const R=await S.generateAsync({type:"blob"}),D=URL.createObjectURL(R),P=document.createElement("a");P.href=D,P.download=`${L.id}-1.0.0.zip`,P.click(),URL.revokeObjectURL(D)},className:"px-3 py-1.5 rounded-lg border border-theme text-main text-xs font-medium flex items-center gap-1.5 hover:bg-surface-secondary cursor-pointer",children:[r.jsx($s,{size:14}),n==="zh"?"导出为 .zip 包":"Export .zip"]}),r.jsxs("button",{onClick:Z,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium flex items-center gap-1.5 cursor-pointer",children:[w?r.jsx(Xe,{size:14}):r.jsx(Un,{size:14}),w?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>x("none"),className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main cursor-pointer",children:n==="zh"?"取消":"Cancel"}),r.jsx("button",{onClick:F,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 e2({isOpen:e,onClose:t,lang:n="zh",isAdmin:s=!1}){const i=b.useRef(null),o=b.useRef(null),a=Ie(S=>S.theme),l=Ie(S=>S.catalog),c=Ie(S=>S.installedVersion),u=Ie(S=>S.latestVersion),d=Ie(S=>S.upgradeAvailable),f=Ie(S=>S.upgradeChangelog),m=Ie(S=>S.colorMode),h=Ie(S=>S.appearanceOverrides),y=Ie(S=>S.previewState),p=Ie(S=>S.refreshCatalog),x=Ie(S=>S.installThemeZip),g=Ie(S=>S.selectTheme),v=Ie(S=>S.setColorMode),w=Ie(S=>S.setAppearanceOverrides),E=Ie(S=>S.upgradeCurrentTheme),N=Ie(S=>S.startPreview),j=Ie(S=>S.cancelPreview),I=Ie(S=>S.resetToSafeDefault),[z,$]=b.useState(!1),[V,B]=b.useState(null),[_,U]=b.useState(null);b.useEffect(()=>{const S=i.current;S&&(e?(typeof S.showModal=="function"&&!S.open?S.showModal():S.setAttribute("open","true"),p()):S.open&&(typeof S.close=="function"?S.close():S.removeAttribute("open")))},[e,p]);const k=()=>{y&&j(),t()},F=async S=>{const R=S.target.files?.[0];if(S.target.value="",!!R){$(!0),U(null);try{const D=await x(R);U({type:"ok",text:n==="zh"?`已安装第三方主题「${D.name}」(v${D.latestVersion})`:`Installed theme "${D.name}" (v${D.latestVersion})`})}catch(D){U({type:"err",text:D instanceof Error?D.message:n==="zh"?"主题包校验或安装失败":"Failed to install theme package"})}finally{$(!1)}}},Z=async S=>{B(S.id),U(null);try{const R=await Bv(S.id,S.latestVersion);if(!R?.bundle){U({type:"err",text:n==="zh"?"无法加载主题包预览数据":"Unable to load theme preview"});return}N({themeId:S.id,bundle:R.bundle,mode:m,appearanceOverrides:h})}finally{B(null)}},M=async S=>{B(S.id),U(null);try{await g(S.id,{version:S.latestVersion}),U({type:"ok",text:n==="zh"?`已切换至主题「${S.name}」`:`Switched to "${S.name}"`})}catch(R){U({type:"err",text:R instanceof Error?R.message:"应用主题失败"})}finally{B(null)}},A=async S=>{B(S.id),U(null);try{S.status==="disabled"?await $v(S.id):await Dv(S.id),await p(),a===S.id&&S.status!=="disabled"&&await I()}catch(R){U({type:"err",text:R instanceof Error?R.message:"操作失败"})}finally{B(null)}},L=async S=>{B(S.id),U(null);try{await Mv(S.id),await p(),a===S.id&&await I()}catch(R){U({type:"err",text:R instanceof Error?R.message:"删除主题失败"})}finally{B(null)}};return e?r.jsx("dialog",{ref:i,onCancel:S=>{S.preventDefault(),k()},"aria-labelledby":"theme-center-title",className:"fixed inset-0 m-auto max-w-4xl w-[94vw] max-h-[88vh] p-0 rounded-2xl border border-theme bg-surface text-main shadow-2xl backdrop:bg-black/60 backdrop:backdrop-blur-xs overflow-hidden",children:r.jsxs("div",{className:"flex flex-col max-h-[88vh]",children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme bg-surface-secondary/50 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx(ut,{size:20,className:"text-primary-theme"}),r.jsxs("div",{children:[r.jsx("h2",{id:"theme-center-title",className:"text-base font-bold text-main",children:n==="zh"?"主题中心 · 第三方主题与外观定制":"Theme Center · Third-Party Themes"}),r.jsx("p",{className:"text-xs text-muted",children:n==="zh"?"导入安全沙盒校验的 .zip 主题包,支持深浅模式、基础外观覆盖与版本独立升级":"Install declarative .zip theme packages with per-account isolation and live preview"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:()=>void I(),className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium text-main hover:bg-surface-secondary flex items-center gap-1.5 cursor-pointer",children:[r.jsx(Vl,{size:13}),n==="zh"?"恢复默认":"Reset Safe"]}),r.jsx("button",{type:"button",onClick:k,"aria-label":n==="zh"?"关闭":"Close",className:"p-1.5 rounded-lg text-muted hover:text-main hover:bg-surface-secondary cursor-pointer",children:r.jsx(De,{size:18})})]})]}),r.jsxs("div",{className:"p-6 overflow-y-auto space-y-6 flex-1",children:[_&&r.jsxs("div",{role:"status",className:`rounded-xl px-4 py-2.5 text-xs font-medium flex items-center justify-between border ${_.type==="ok"?"bg-emerald-500/10 border-emerald-500/30 text-emerald-700 dark:text-emerald-300":"bg-rose-500/10 border-rose-500/30 text-rose-700 dark:text-rose-300"}`,children:[r.jsx("span",{children:_.text}),r.jsx("button",{type:"button",onClick:()=>U(null),className:"opacity-70 hover:opacity-100",children:r.jsx(De,{size:14})})]}),d&&u&&r.jsxs("div",{className:"rounded-xl border border-amber-500/40 bg-amber-500/10 p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-bold text-amber-800 dark:text-amber-300",children:n==="zh"?`当前主题有新版本可用:v${c} → v${u}`:`Theme upgrade available: v${c} -> v${u}`}),f&&r.jsx("p",{className:"text-xs text-muted mt-1",children:f})]}),r.jsx("button",{type:"button","data-testid":"theme-upgrade-confirm",onClick:()=>void E(),className:"px-3.5 py-2 rounded-lg bg-amber-600 hover:bg-amber-700 text-white text-xs font-semibold shrink-0 cursor-pointer",children:n==="zh"?`确认升级到 v${u}`:`Upgrade to v${u}`})]}),r.jsxs("section",{className:"rounded-xl border border-theme bg-surface-secondary/30 p-4 space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[r.jsx("h3",{className:"text-xs font-bold uppercase tracking-wider text-main",children:n==="zh"?"当前账号基础外观覆盖(独立持久保存)":"Account Appearance Overrides"}),r.jsx("div",{className:"flex items-center gap-1 bg-surface border border-theme rounded-lg p-0.5",children:[{id:"light",label:n==="zh"?"浅色":"Light",icon:af},{id:"dark",label:n==="zh"?"深色":"Dark",icon:lf},{id:"auto",label:n==="zh"?"自动":"Auto",icon:b0}].map(({id:S,label:R,icon:D})=>r.jsxs("button",{type:"button",onClick:()=>void v(S),className:`px-2.5 py-1 rounded-md text-xs font-medium flex items-center gap-1 cursor-pointer transition-colors ${m===S?"bg-primary-theme text-white":"text-muted hover:text-main"}`,children:[r.jsx(D,{size:12}),R]},S))})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3 text-xs",children:[r.jsxs("label",{className:"space-y-1",children:[r.jsx("span",{className:"text-muted font-medium block",children:n==="zh"?"强调色覆盖":"Accent Color"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"color","aria-label":n==="zh"?"强调色覆盖":"Accent color override",value:h.primaryColor||"#4f46e5",onChange:S=>void w({...h,primaryColor:S.target.value}),className:"h-8 w-10 rounded border border-theme bg-surface cursor-pointer"}),h.primaryColor&&r.jsx("button",{type:"button",onClick:()=>{const S={...h};delete S.primaryColor,w(S)},className:"text-xs text-muted hover:text-main underline cursor-pointer",children:n==="zh"?"清除":"Clear"})]})]}),r.jsxs("label",{className:"space-y-1",children:[r.jsx("span",{className:"text-muted font-medium block",children:n==="zh"?"组件圆角":"Corner Radius"}),r.jsxs("select",{value:h.borderRadius||"",onChange:S=>{const R=S.target.value,D={...h};R?D.borderRadius=R:delete D.borderRadius,w(D)},className:"w-full px-2.5 py-1.5 rounded-lg border border-theme bg-surface text-main text-xs",children:[r.jsx("option",{value:"",children:n==="zh"?"跟随主题包默认":"Theme Default"}),r.jsx("option",{value:"sharp",children:n==="zh"?"利落直角 (sharp)":"Sharp"}),r.jsx("option",{value:"rounded",children:n==="zh"?"标准圆角 (rounded)":"Rounded"}),r.jsx("option",{value:"pill",children:n==="zh"?"柔和胶囊 (pill)":"Pill"})]})]}),r.jsxs("label",{className:"space-y-1",children:[r.jsx("span",{className:"text-muted font-medium block",children:n==="zh"?"界面密度":"Layout Density"}),r.jsxs("select",{value:h.density||"",onChange:S=>{const R=S.target.value,D={...h};R?D.density=R:delete D.density,w(D)},className:"w-full px-2.5 py-1.5 rounded-lg border border-theme bg-surface text-main text-xs",children:[r.jsx("option",{value:"",children:n==="zh"?"跟随主题包默认":"Theme Default"}),r.jsx("option",{value:"compact",children:n==="zh"?"紧凑 (compact)":"Compact"}),r.jsx("option",{value:"comfortable",children:n==="zh"?"舒适 (comfortable)":"Comfortable"}),r.jsx("option",{value:"spacious",children:n==="zh"?"宽松 (spacious)":"Spacious"})]})]}),r.jsxs("label",{className:"space-y-1",children:[r.jsxs("span",{className:"text-muted font-medium block",children:[n==="zh"?"字号比例":"Font Scale"," (",h.fontScale||1,"×)"]}),r.jsx("input",{type:"range",min:"0.85",max:"1.25",step:"0.05",value:h.fontScale||1,onChange:S=>void w({...h,fontScale:Number(S.target.value)}),className:"w-full accent-indigo-600 cursor-pointer"})]})]})]}),r.jsxs("section",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-xl border border-dashed border-theme p-4 bg-surface",children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(cf,{size:20,className:"text-primary-theme shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-bold text-main",children:n==="zh"?"安装或更新第三方主题包 (.zip)":"Install / Update Theme Package (.zip)"}),r.jsx("p",{className:"text-xs text-muted mt-0.5",children:n==="zh"?"所有登录账号均可上传主题包至共享目录;同一主题 ID 仅限原上传者提交更高版本更新。":"Any authenticated user may install packages; only the original author can publish version bumps."})]})]}),r.jsxs("div",{children:[r.jsx("input",{ref:o,type:"file",accept:".zip,application/zip","data-testid":"theme-zip-upload-input",onChange:F,className:"hidden"}),r.jsxs("button",{type:"button",disabled:z,onClick:()=>o.current?.click(),className:"px-4 py-2 rounded-xl bg-primary-theme text-white text-xs font-semibold flex items-center gap-1.5 cursor-pointer disabled:opacity-50",children:[r.jsx(Ua,{size:14}),z?n==="zh"?"校验并安装中...":"Installing...":n==="zh"?"上传主题包 (.zip)":"Upload .zip"]})]})]}),r.jsxs("section",{className:"space-y-2.5",children:[r.jsx("h3",{className:"text-xs font-bold uppercase tracking-wider text-muted",children:n==="zh"?"系统内置主题":"Built-in Themes"}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:Vf.map(S=>{const R=a===S.id;return r.jsxs("button",{type:"button",onClick:()=>void g(S.id),className:`p-3 rounded-xl border text-left transition-all cursor-pointer ${R?"border-primary-theme bg-primary-theme/10 ring-1 ring-primary-theme/40":"border-theme bg-surface hover:bg-surface-secondary"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/15",style:{backgroundColor:S.previewPrimary}}),R&&r.jsx(Xe,{size:14,className:"text-primary-theme"})]}),r.jsx("div",{className:"text-xs font-bold text-main mt-2",children:S.label}),r.jsx("div",{className:"text-xs text-muted mt-1 line-clamp-2",children:S.description})]},S.id)})})]}),r.jsxs("section",{className:"space-y-2.5",children:[r.jsx("h3",{className:"text-xs font-bold uppercase tracking-wider text-muted",children:n==="zh"?`平台共享第三方主题目录 (${l.length})`:`Shared Theme Catalog (${l.length})`}),l.length===0?r.jsx("div",{className:"rounded-xl border border-theme p-6 text-center text-xs text-muted bg-surface-secondary/20",children:n==="zh"?"暂无已安装的第三方主题包。上传符合规范的 .zip 主题包即可实时预览与应用。":"No third-party themes installed yet. Upload a .zip package above to get started."}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:l.map(S=>{const R=a===S.id,D=y?.themeId===S.id,P=S.status==="disabled";return r.jsxs("div",{"data-testid":`theme-catalog-card-${S.id}`,className:`rounded-xl border p-4 flex flex-col justify-between gap-3 ${R?"border-primary-theme bg-primary-theme/5":"border-theme bg-surface"}`,children:[r.jsxs("div",{className:"flex items-start gap-3",children:[S.previewImageUrl?r.jsx("img",{src:S.previewImageUrl,alt:S.name,className:"w-12 h-12 rounded-xl object-cover border border-theme shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded-xl border border-theme bg-surface-secondary flex items-center justify-center shrink-0",children:r.jsx(ut,{size:18,className:"text-primary-theme"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"text-sm font-bold text-main truncate",children:S.name}),r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-surface-secondary text-muted font-mono",children:["v",S.latestVersion]}),R&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-primary-theme text-white font-semibold",children:n==="zh"?"使用中":"Active"}),P&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-rose-500/15 text-rose-600 font-semibold flex items-center gap-1",children:[r.jsx(Kh,{size:11}),n==="zh"?"已停用":"Disabled"]})]}),r.jsxs("div",{className:"text-xs text-muted mt-0.5",children:[S.author," · ",S.supportsModes.join(" / "),S.isOwner&&r.jsxs("span",{className:"ml-2 text-primary-theme font-medium",children:["(",n==="zh"?"我上传的":"Yours",")"]})]}),r.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2",children:S.description})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap pt-2 border-t border-theme-subtle",children:[r.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[!P&&S.compatible&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",disabled:V===S.id,onClick:()=>D?j():void Z(S),className:"px-2.5 py-1.5 rounded-lg border border-theme text-xs font-medium text-main hover:bg-surface-secondary flex items-center gap-1 cursor-pointer",children:[r.jsx(kn,{size:13}),D?n==="zh"?"退出预览":"Stop Preview":n==="zh"?"预览":"Preview"]}),r.jsxs("button",{type:"button",disabled:V===S.id,onClick:()=>void M(S),className:"px-2.5 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-semibold flex items-center gap-1 cursor-pointer",children:[r.jsx(Xe,{size:13}),n==="zh"?"应用":"Apply"]})]}),r.jsxs("a",{href:Fv(S.id,S.latestVersion),download:!0,className:"px-2.5 py-1.5 rounded-lg border border-theme text-xs font-medium text-muted hover:text-main hover:bg-surface-secondary flex items-center gap-1",children:[r.jsx($s,{size:13}),n==="zh"?"导出":"Export"]})]}),s&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("button",{type:"button",disabled:V===S.id,onClick:()=>void A(S),className:"px-2.5 py-1 rounded-lg border border-amber-500/40 text-xs font-medium text-amber-700 dark:text-amber-300 hover:bg-amber-500/10 cursor-pointer",children:P?n==="zh"?"恢复启用":"Enable":n==="zh"?"停用":"Disable"}),r.jsx("button",{type:"button",disabled:V===S.id,onClick:()=>void L(S),"aria-label":n==="zh"?`删除 ${S.name}`:`Delete ${S.name}`,className:"p-1.5 rounded-lg border border-rose-500/30 text-rose-600 hover:bg-rose-500/10 cursor-pointer",children:r.jsx(Jn,{size:13})})]})]})]},S.id)})})]})]})]})}):null}function t2({lang:e="zh"}){const[t,n]=b.useState(!1),[s,i]=b.useState(!1),[o,a]=b.useState(!1),l=b.useRef(null),u=ke(w=>w.session)?.subRole==="administrator",d=Ie(w=>w.theme),f=Ie(w=>w.availableThemes),m=Ie(w=>w.catalog),h=Ie(w=>w.upgradeAvailable),y=Ie(w=>w.selectTheme),p=Ie(w=>w.setTheme);b.useEffect(()=>{function w(E){l.current&&!l.current.contains(E.target)&&n(!1)}return t&&document.addEventListener("mousedown",w),()=>{document.removeEventListener("mousedown",w)}},[t]);const x=w=>{switch(w){case"dark":return r.jsx(lf,{size:16,className:"text-indigo-400"});case"eyecare":return r.jsx(kn,{size:16,className:"text-emerald-500"});case"chalkboard":return r.jsx(Ba,{size:16,className:"text-green-400"});case"light":return r.jsx(af,{size:16,className:"text-amber-500"});default:return r.jsx(ut,{size:16,className:"text-primary-theme"})}},g=m.filter(w=>w.status==="active"),v=w=>{if(n(!1),f.some(N=>N.id===w&&N.category==="custom")){p(w);return}y(w)};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"relative",ref:l,children:[r.jsxs("button",{type:"button",onClick:()=>n(!t),title:e==="zh"?"切换教学界面主题":"Switch Theme",className:"relative 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:[x(d),h&&r.jsx("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full bg-amber-500 border border-surface",title:e==="zh"?"当前主题有可用更新":"Theme update available"})]}),t&&r.jsxs("div",{className:"absolute right-0 mt-2 w-72 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.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[f.map(w=>{const E=d===w.id;return r.jsxs("button",{type:"button",onClick:()=>v(w.id),className:`w-full flex items-center justify-between px-3 py-2 rounded-lg text-left text-xs transition-all cursor-pointer ${E?"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:w.previewPrimary}}),r.jsxs("div",{children:[r.jsx("div",{className:"font-medium text-main leading-none",children:w.label}),r.jsx("div",{className:"text-xs text-muted mt-1 leading-tight opacity-80",children:w.description})]})]}),E&&r.jsx(Xe,{size:14,className:"text-primary-theme shrink-0"})]},w.id)}),g.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 pt-2 pb-1 text-[11px] font-bold text-muted uppercase tracking-wider border-t border-theme-subtle mt-1",children:e==="zh"?"第三方主题包":"Third-Party Themes"}),g.map(w=>{const E=d===w.id;return r.jsxs("button",{type:"button",onClick:()=>v(w.id),className:`w-full flex items-center justify-between px-3 py-2 rounded-lg text-left text-xs transition-all cursor-pointer ${E?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[r.jsxs("div",{className:"min-w-0 pr-2",children:[r.jsxs("div",{className:"font-medium text-main leading-none flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"text-[10px] font-mono text-muted",children:["v",w.latestVersion]})]}),r.jsx("div",{className:"text-xs text-muted mt-1 truncate opacity-80",children:w.author})]}),E&&r.jsx(Xe,{size:14,className:"text-primary-theme shrink-0"})]},w.id)})]})]}),r.jsxs("div",{className:"pt-2 mt-1 border-t border-theme-subtle space-y-1",children:[r.jsxs("button",{type:"button","data-testid":"open-theme-center-btn",onClick:()=>{n(!1),a(!0)},className:"w-full flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium text-primary-theme hover:bg-primary-theme/10 transition-colors cursor-pointer",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(cf,{size:14}),r.jsx("span",{children:e==="zh"?"第三方主题中心 (.zip)...":"Theme Center (.zip)..."})]}),h&&r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-700 dark:text-amber-300 font-bold",children:e==="zh"?"可更新":"Update"})]}),r.jsxs("button",{type:"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-main hover:bg-surface-secondary transition-colors cursor-pointer",children:[r.jsx(ut,{size:14}),r.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})]})]})]}),r.jsx(e2,{isOpen:o,onClose:()=>a(!1),lang:e,isAdmin:u}),r.jsx(XE,{isOpen:s,onClose:()=>i(!1),lang:e})]})}function Um({lang:e="zh"}){const[t,n]=b.useState(!1),s=b.useRef(null),{scale:i,minScale:o,maxScale:a,setScale:l,increaseScale:c,decreaseScale:u,resetScale:d}=Fn();b.useEffect(()=>{function h(y){s.current&&!s.current.contains(y.target)&&n(!1)}return t&&document.addEventListener("mousedown",h),()=>{document.removeEventListener("mousedown",h)}},[t]);const f=oh.find(h=>h.scale===i),m=i===Qr;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 ${m?"bg-surface border-theme text-main":"bg-primary-theme-light border-primary-theme text-primary-theme font-bold"}`,"aria-label":"Font size selector","aria-expanded":t,children:[r.jsx(y0,{size:16}),!m&&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"})]}),!m&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1 text-xs text-muted hover:text-primary-theme transition-colors cursor-pointer px-1.5 py-0.5 rounded hover:bg-surface-secondary",title:e==="zh"?"恢复默认 100%":"Reset to 100%",children:[r.jsx(Vl,{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:u,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(w0,{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:f?e==="zh"?f.labelZh.split(" ")[0]:f.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(tr,{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:oh.map(h=>{const y=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 ${y?"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})]}),y&&r.jsx(Xe,{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 n2(e){const t=Ot(),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,u=e.setIsFollowingTeacher??t?.setIsFollowingTeacher??(()=>{}),d=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(f=>f.id===s)?.name||s}`:"学生端"}),r.jsx("span",{children:"•"}),r.jsx("span",{children:o?`课节: ${a.find(f=>f.id===o)?.title||o}`:"等待教师推流课节..."})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{type:"button",onClick:()=>{if(l){d();return}u(!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(Ci,{size:12,className:c?"animate-spin":""}),r.jsx("span",{children:n==="zh"?`跟随教师步调: ${c?"开":"关"}`:`Follow Teacher: ${c?"ON":"OFF"}`})]}),r.jsx(Um,{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(Bl,{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 s2(e){const t=Ot(),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,u=e.students??t?.students??[],d=e.studentDashboardData??t?.studentDashboardData??null,f=e.isNotificationsOpen??t?.isNotificationsOpen??!1,m=e.studentNotifications??t?.studentNotifications??[],h=e.unreadNotifications??t?.unreadNotifications??[],y=e.readNotifications??t?.readNotifications??new Set;e.selectedNotificationForModal!==void 0?e.selectedNotificationForModal:t?.selectedNotificationForModal;const p=e.dbConnected??t?.dbConnected??!1,x=e.dbStatus??t?.dbStatus??"normal",g=e.siteInfo??t?.siteInfo,v=e.setActiveStudentId??t?.setActiveStudentId??(()=>{}),w=e.setReadNotifications??t?.setReadNotifications??(()=>{}),E=e.setIsSystemResourceLibraryOpen??t?.setIsSystemResourceLibraryOpen??(()=>{}),N=e.setProfileOpen??t?.setProfileOpen??(()=>{}),j=e.setTeacherTab??t?.setTeacherTab??(()=>{}),I=e.setStudentViewStatus??t?.setStudentViewStatus??(()=>{}),z=e.setIsNotificationsOpen??t?.setIsNotificationsOpen??(()=>{}),$=e.setSelectedNotificationForModal??t?.setSelectedNotificationForModal??(()=>{}),V=e.handleLogout??t?.handleLogout??t?.onLogout??(()=>{}),B=e.toggleLanguage??t?.toggleLanguage??(()=>{}),_=e.setActiveRole??t?.setActiveRole??(()=>{}),U=e.isStudentLocked??t?.isNavigationLocked??t?.isStudentLocked??!1,k=e.onBlockedNavigate??t?.notifyLockedNavigation,F=GE(L=>L.timetableOcrTask);if(t?.isStudentLiveMode)return r.jsx(n2,{});const Z=n==="student"&&U,M=()=>{if(Z){k?.();return}n==="teacher"?j("live_class"):n==="student"&&I("dashboard")},A=()=>{if(Z){k?.();return}n==="teacher"?j("dashboard"):n==="student"&&I("dashboard")};return r.jsxs("header",{className:"h-16 border-b border-theme bg-surface text-main flex items-center px-6 justify-between shrink-0 shadow-sm relative z-20 transition-colors duration-200",children:[r.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[r.jsxs("button",{onClick:M,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:Z?i==="zh"?"全班专注锁定中,无法返回首页":"Class focus locked — cannot return to home":i==="zh"?"返回首页":"Back to Home",children:[g.logoUrl?r.jsx("img",{src:g.logoUrl,alt:"site logo",width:32,height:32,decoding:"async",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:g.siteName||"OpenLearn Next"}),r.jsxs("span",{className:"text-xs font-medium text-subtle tracking-tight",children:["v","0.7.16"]}),g.slogan&&r.jsx("span",{className:"hidden md:inline text-xs text-subtle font-normal truncate max-w-[200px]",children:g.slogan})]})]}),r.jsx(qe,{slot:"header.status_pill",slotProps:{dbConnected:p,dbStatus:x,lang:i}}),F?.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(dt,{size:13,className:"animate-spin text-violet-600"}),r.jsx("span",{children:i==="zh"?"后台识别课表中...":"Timetable OCR Running..."})]}),F?.status==="completed"&&o!=="timetable"&&r.jsxs("button",{type:"button",onClick:()=>{j("timetable"),Ge.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(bt,{size:13,className:"text-emerald-600"}),r.jsx("span",{children:i==="zh"?`课表识别已完成 (${F.result?.entries.length||0}节) · 查看`:`Timetable Ready (${F.result?.entries.length||0})`})]}),r.jsx(qe,{slot:"header.async_task.item",slotProps:{lang:i,activeRole:n,teacherTab:o,setTeacherTab:j}}),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"} ${Z?"opacity-50":""}`,children:[Z?r.jsx(Da,{size:16}):r.jsx(df,{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(uf,{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(kn,{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:L=>v(L.target.value),children:[r.jsxs("option",{value:"",children:["-- ",i==="zh"?"选择学生":"Select Student"," --"]}),u.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))]}),r.jsxs("button",{type:"button",onClick:()=>{if(s){window.close();return}_?.("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(De,{size:12}):r.jsx(ki,{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&&d&&r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>z(!f),"aria-label":i==="zh"?`通知${h.length>0?`(${h.length} 条未读)`:""}`:`Notifications${h.length>0?` (${h.length} unread)`:""}`,"aria-expanded":f,className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[r.jsx(ui,{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})]}),f&&r.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden",children:[r.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[r.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),h.length>0&&r.jsx("button",{onClick:async()=>{if(c){try{const L=m.filter(S=>!y.has(S.id)).map(S=>fetch(`/api/students/${c}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:S.id})}));await Promise.all(L)}catch(L){console.error(L)}w(L=>{const S=new Set(L);return m.forEach(R=>S.add(R.id)),S})}},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:m.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:m.map(L=>{const S=!y.has(L.id);return r.jsx("button",{type:"button",className:`w-full text-left p-3 hover:bg-gray-50 cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-indigo-500 ${S?"bg-indigo-50/30":""}`,onClick:()=>{S&&(c&&fetch(`/api/students/${c}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:L.id})}).catch(console.error),w(D=>new Set(D).add(L.id)));const R=d?.assignments?.find(D=>D.id===L.relatedId);$({...L,assignment:R}),z(!1)},children:r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"mt-0.5","aria-hidden":"true",children:L.type==="new_assignment"?r.jsx(Zn,{size:16,className:"text-indigo-500"}):r.jsx(bt,{size:16,className:"text-green-500"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:`text-sm ${S?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:L.title}),r.jsx("div",{className:`text-xs mt-0.5 ${S?"text-gray-600":"text-gray-500"}`,children:L.message})]}),S&&r.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1","aria-hidden":"true"})]})},L.id)})})})]})]}),r.jsx("div",{id:"app-header-plugin-actions",className:"flex items-center gap-2 empty:hidden",children:r.jsx(qe,{slot:"header.action",lang:i,fallback:r.jsx(r.Fragment,{}),slotProps:{session:l,currentRole:n,lang:i}})}),r.jsxs("button",{onClick:()=>E(!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(hi,{size:14,className:"text-emerald-500 animate-pulse"}),i==="zh"?"系统资源库":"System Resource Library"]}),r.jsx("button",{onClick:B,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(hi,{size:16})}),r.jsx(Um,{lang:i}),r.jsx(t2,{lang:i}),n!=="student"&&(()=>{const L=x==="error"||!p?{bg:"bg-rose-50 border-rose-200 text-rose-600 hover:bg-rose-100 animate-pulse",dot:"bg-rose-500",ping:"bg-rose-400",label:i==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:x==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:i==="zh"?"SQLite 数据库存在状态警告":"SQLite DB Warning"}:{bg:"bg-emerald-50 border-emerald-200 text-emerald-600 hover:bg-emerald-100",dot:"bg-emerald-500",ping:"bg-emerald-400",label:i==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return r.jsxs("div",{id:"db-connection-status-badge",className:`w-8 h-8 rounded-lg border flex items-center justify-center relative select-none shrink-0 cursor-pointer transition-colors shadow-3xs ${L.bg}`,title:L.label,children:[r.jsx(v0,{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 ${L.ping}`}),r.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${L.dot}`})]})]})})(),r.jsx(ZE,{session:l,lang:i,onLogout:V,onProfile:()=>N(!0)})]})]})}function r2(){const[e,t]=b.useState(()=>typeof navigator>"u"?!0:navigator.onLine);return b.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 i2(){const e=Ot(),t=r2(),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(qe,{slot:"statusbar.item",lang:n,fallback:r.jsx(r.Fragment,{}),slotProps:{session:i,currentRole:s,lang:n,isOnline:t}})})}const o2='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function vh(e,t,n){const s=e.getBoundingClientRect();return!(s.top<=n&&n<=s.top+s.height&&s.left<=t&&t<=s.left+s.width)}function yi({open:e,onClose:t,ariaLabelledBy:n,ariaLabel:s,closedBy:i="closerequest",className:o="",children:a}){const l=b.useRef(null),c=b.useRef(t);if(c.current=t,b.useLayoutEffect(()=>{if(!e)return;const d=l.current;if(!d)return;const f=document.activeElement instanceof HTMLElement?document.activeElement:null,m=typeof d.showModal=="function";m?d.open||d.showModal():(d.setAttribute("open",""),d.contains(document.activeElement)||(d.querySelector("[autofocus]")??d.querySelector(o2))?.focus());let h=!1;const y=()=>{d.returnValue="",!h&&!d.open&&c.current()};return d.addEventListener("close",y),()=>{h=!0,d.removeEventListener("close",y),m?d.open&&typeof d.close=="function"&&d.close():(d.removeAttribute("open"),f&&f.isConnected&&f.focus())}},[e]),b.useLayoutEffect(()=>{if(!e)return;const d=l.current;if(!d)return;const f=typeof d.showModal=="function",m=w=>{w.preventDefault(),i!=="none"&&c.current()},h=w=>{w.key==="Escape"&&i!=="none"&&(w.preventDefault(),c.current())};let y=!1,p=!1;const x=i==="any"&&!("closedBy"in HTMLDialogElement.prototype),g=w=>{y=!0,p=w.target===d&&vh(d,w.clientX,w.clientY)},v=w=>{if(w.target!==d){y=!1,p=!1;return}const E=vh(d,w.clientX,w.clientY),N=y?p&&E:E;y=!1,p=!1,N&&c.current()};return d.addEventListener("cancel",m),f||d.addEventListener("keydown",h),x&&(d.addEventListener("pointerdown",g),d.addEventListener("click",v)),()=>{d.removeEventListener("cancel",m),f||d.removeEventListener("keydown",h),x&&(d.removeEventListener("pointerdown",g),d.removeEventListener("click",v))}},[e,i]),!e)return null;const u=i?{closedby:i}:{};return r.jsx("dialog",{ref:l,"aria-labelledby":n,"aria-label":s,...u,className:`openlearn-dialog ${o}`.trim(),children:a})}function Vm({labelledBy:e,label:t,className:n="",children:s}){return r.jsx("div",{tabIndex:0,role:"region","aria-labelledby":e,"aria-label":e?void 0:t,className:`table-scroll-region ${n}`.trim(),children:s})}const Na=["administrator","teacher","student"];function Sh(e){const t=e.split(",").map(n=>n.trim()).filter(Boolean);return t.length>0?t:void 0}function Ln(e,t){return e==="administrator"?t==="zh"?"管理员":"Admin":e==="teacher"?t==="zh"?"教师":"Teacher":t==="zh"?"学生":"Student"}function a2({lang:e,aiProviders:t=[]}){const n=t.filter(K=>!!K.is_shared),[s,i]=b.useState([]),[o,a]=b.useState(!0),[l,c]=b.useState(""),[u,d]=b.useState(""),[f,m]=b.useState(!1),[h,y]=b.useState(null),[p,x]=b.useState(null),[g,v]=b.useState(!1),[w,E]=b.useState(""),[N,j]=b.useState(""),[I,z]=b.useState(""),[$,V]=b.useState(""),[B,_]=b.useState(""),[U,k]=b.useState("🤖"),[F,Z]=b.useState(!0),[M,A]=b.useState(""),[L,S]=b.useState("overlay"),[R,D]=b.useState("inherit"),[P,Y]=b.useState([]),[H,ee]=b.useState([]),[le,ae]=b.useState(""),[fe,be]=b.useState(""),[ye,Se]=b.useState(""),[me,C]=b.useState(""),[J,se]=b.useState("5"),[W,T]=b.useState(!1),[q,X]=b.useState(""),ne=b.useCallback(async()=>{a(!0);try{const K=await fetch("/api/agent/personas?scope=all"),we=await K.json();K.ok&&we?.success&&Array.isArray(we.personas)&&i(we.personas)}catch{d(e==="zh"?"加载 AI 角色模板失败":"Failed to load AI persona templates.")}finally{a(!1)}},[e]);b.useEffect(()=>{ne()},[ne]);const Q=()=>{y(null),E(""),j(""),z(""),V(""),_(""),k("🎯"),Z(!0),A(""),S("overlay"),D("inherit"),Y([]),ee([]),ae(""),be(""),Se(""),C(""),se("5"),X(""),m(!0)},re=K=>{y(K),E(K.id),j(K.nameZh),z(K.nameEn),V(K.descriptionZh||""),_(K.descriptionEn||""),k(K.icon||"🤖"),Z(K.enabled!==!1),A(K.preferredProviderId||""),S(K.mode??"overlay"),D(K.basePolicy??(K.mode==="replace"?"drop":"inherit")),Y(Array.isArray(K.visibility)?K.visibility:[]),ee(Array.isArray(K.defaultForRole)?K.defaultForRole:[]),ae(K.instructionZh||""),be(K.instructionEn||""),Se(Array.isArray(K.toolPolicy?.allow)?K.toolPolicy.allow.join(", "):""),C(Array.isArray(K.toolPolicy?.deny)?K.toolPolicy.deny.join(", "):""),se(String(K.maxTurns??5)),X(""),m(!0)},de=(K,we,oe)=>{we.includes(K)?oe(we.filter(ce=>ce!==K)):oe([...we,K])},te=async K=>{K.preventDefault(),X(""),d("");const we=Number(J);if(!Number.isFinite(we)||we<1||we>20){X(e==="zh"?"最大推理轮次需在 1 到 20 之间。":"Max turns must be between 1 and 20.");return}const oe=Sh(ye),ce=Sh(me),pe=oe||ce?{...oe?{allow:oe}:{},...ce?{deny:ce}:{}}:void 0,xe={id:w.trim(),nameZh:N.trim(),nameEn:I.trim(),descriptionZh:$.trim(),descriptionEn:B.trim(),enabled:h?.id==="plain_assistant"?!0:F,preferredProviderId:M.trim()||void 0,icon:U.trim()||void 0,mode:L,basePolicy:R,visibility:P.length>0&&P.length<Na.length?P:void 0,defaultForRole:H.length>0?H:void 0,instructionZh:le,instructionEn:fe,toolPolicy:pe,maxTurns:Math.trunc(we)};T(!0);try{const ve=h?`/api/agent/personas/${encodeURIComponent(h.id)}`:"/api/agent/personas",je=await fetch(ve,{method:h?"PATCH":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(xe)}),Me=await je.json().catch(()=>({}));if(!je.ok||Me?.success===!1){X(Me?.message||Me?.error||(e==="zh"?"保存失败":"Failed to save persona"));return}m(!1),y(null),c(h?e==="zh"?`已更新角色「${xe.nameZh}」,新会话与侧栏刷新立即生效。`:`Updated persona "${xe.nameEn}". Effective immediately for new requests.`:e==="zh"?`已创建角色「${xe.nameZh}」,新会话与侧栏刷新立即生效。`:`Created persona "${xe.nameEn}". Effective immediately for new requests.`),await ne(),window.dispatchEvent(new CustomEvent("openlearn:personas-updated"))}catch{X(e==="zh"?"网络请求失败,请重试":"Network request failed")}finally{T(!1)}},O=async(K,we,oe=!1)=>{d("");try{const ce=oe?"?force=true":"",pe=await fetch(`/api/agent/personas/${encodeURIComponent(K.id)}${ce}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:we,...oe?{force:!0}:{}})}),xe=await pe.json().catch(()=>({}));if(pe.status===409&&xe?.error==="PERSONA_IN_USE"&&!oe){const ve=Array.isArray(xe?.references?.defaultForRoles)?xe.references.defaultForRoles:K.defaultForRole??[];x({action:"deactivate",persona:K,referencedRoles:ve});return}if(!pe.ok||xe?.success===!1){d(xe?.message||xe?.error||(e==="zh"?"状态切换失败":"Status update failed"));return}c(we?e==="zh"?`已启用角色「${K.nameZh}」`:`Enabled persona "${K.nameEn}"`:e==="zh"?`已停用角色「${K.nameZh}」,引用已自动回退至可用默认角色。`:`Deactivated persona "${K.nameEn}". Active references automatically fall back cleanly.`),await ne(),window.dispatchEvent(new CustomEvent("openlearn:personas-updated"))}catch{d(e==="zh"?"状态切换请求失败":"Failed to update persona status")}},G=K=>{const we=K.enabled===!1,oe=K.references?.defaultForRoles??K.defaultForRole??[];if(!we&&oe.length>0){x({action:"deactivate",persona:K,referencedRoles:oe});return}O(K,we,!1)},ie=async(K,we=!1)=>{d("");try{const oe=we?"?force=true":"",ce=await fetch(`/api/agent/personas/${encodeURIComponent(K.id)}${oe}`,{method:"DELETE"}),pe=await ce.json().catch(()=>({}));if(ce.status===409&&pe?.error==="PERSONA_IN_USE"&&!we){const xe=Array.isArray(pe?.references?.defaultForRoles)?pe.references.defaultForRoles:K.defaultForRole??[];x({action:"delete",persona:K,referencedRoles:xe});return}if(!ce.ok||pe?.success===!1){d(pe?.message||pe?.error||(e==="zh"?"删除失败":"Delete failed"));return}c(e==="zh"?`已删除角色模板「${K.nameZh}」,正在使用的默认引用已自动回退。`:`Deleted persona "${K.nameEn}" cleanly.`),await ne(),window.dispatchEvent(new CustomEvent("openlearn:personas-updated"))}catch{d(e==="zh"?"删除请求失败":"Delete request failed")}},ue=K=>{const we=K.references?.defaultForRoles??K.defaultForRole??[];if(we.length>0){x({action:"delete",persona:K,referencedRoles:we});return}ie(K,!1)},he=async()=>{if(p){v(!0);try{p.action==="deactivate"?await O(p.persona,!1,!0):await ie(p.persona,!0),x(null)}finally{v(!1)}}};return r.jsxs("section",{"aria-labelledby":"ai-personas-section-heading",className:"bg-white rounded-2xl border border-gray-200 shadow-xs overflow-hidden text-left",children:[r.jsxs("div",{className:"p-5 border-b border-gray-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-slate-50/70",children:[r.jsxs("div",{children:[r.jsxs("h3",{id:"ai-personas-section-heading",className:"font-bold text-gray-800 flex items-center gap-2 text-base",children:[r.jsx(Jc,{className:"text-indigo-600",size:18}),e==="zh"?"内核 AI 助教角色配置":"Kernel AI Assistant Personas"]}),r.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:e==="zh"?"管理内置与自定义 AI 助教角色(支持用途说明、启停状态、平台共享模型绑定、作用范围与默认角色)。保存后立即对新对话与侧栏生效。":"Manage built-in and custom AI assistant personas (purpose, enable/disable, shared provider binding, role scope & defaults). Changes take effect immediately for new requests."})]}),r.jsxs("button",{type:"button",onClick:Q,className:"px-3.5 py-2 bg-indigo-600 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 hover:bg-indigo-700 transition-colors cursor-pointer shrink-0 shadow-xs",children:[r.jsx(tr,{size:14}),r.jsx("span",{children:e==="zh"?"新建角色模板":"New Persona"})]})]}),r.jsxs("div",{className:"mx-5 mt-4 p-3 rounded-xl bg-slate-50 border border-slate-200/80 text-[11px] text-slate-600 leading-relaxed",children:[r.jsx("strong",{className:"text-slate-700",children:e==="zh"?"配置说明与生效规则:":"Scope & Lifecycle Guide: "}),e==="zh"?"「可见角色」限定哪些身份可在 AI 侧栏选取;「默认角色」决定未切换时的初始角色;「绑定共享模型」仅允许绑定平台共享 AI 提供商(个人私有配置不会被暴露);停用或删除被设为默认的角色时会自动解除绑定并回退至「普通助教(默认)」,保障助手始终可用。":"Visibility limits which user roles see each persona; Default For sets initial selection; Shared Provider Binding accepts only platform-shared providers; deactivating or deleting a referenced default cleanly clears bindings and falls back to Plain Assistant."]}),l&&r.jsx("div",{role:"status","aria-live":"polite",className:"mx-5 mt-4 p-2.5 bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs rounded-xl font-medium",children:l}),u&&r.jsx("div",{role:"alert",className:"mx-5 mt-4 p-2.5 bg-rose-50 border border-rose-200 text-rose-800 text-xs rounded-xl font-medium",children:u}),r.jsx("div",{className:"p-5",children:o?r.jsxs("div",{className:"flex items-center justify-center py-8 text-xs text-gray-500 gap-2",children:[r.jsx(dt,{size:14,className:"animate-spin"}),r.jsx("span",{children:e==="zh"?"正在加载角色模板...":"Loading personas..."})]}):r.jsx(Vm,{labelledBy:"ai-personas-table-caption",children:r.jsxs("table",{className:"w-full text-left text-xs border-collapse",children:[r.jsx("caption",{id:"ai-personas-table-caption",className:"sr-only",children:e==="zh"?"AI Agent 角色模板配置列表":"AI Agent Persona Templates List"}),r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-gray-200 text-gray-500 bg-gray-50/60",children:[r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold",children:e==="zh"?"角色 / ID":"Persona / ID"}),r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold",children:e==="zh"?"用途说明":"Purpose"}),r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold",children:e==="zh"?"来源 / 绑定模型":"Source / Provider"}),r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold",children:e==="zh"?"可见范围 / 默认":"Scope / Default"}),r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold",children:e==="zh"?"状态":"Status"}),r.jsx("th",{scope:"col",className:"py-2.5 px-3 font-semibold text-right",children:e==="zh"?"操作":"Actions"})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100",children:s.map(K=>{const we=e==="zh"?K.nameZh:K.nameEn,oe=e==="zh"?K.descriptionZh||K.instructionZh||"系统默认全能助教":K.descriptionEn||K.instructionEn||"Default assistant",ce=K.mode==="replace"?"replace":"overlay",pe=K.basePolicy??(ce==="replace"?"drop":"inherit"),xe=K.visibility&&K.visibility.length>0?K.visibility.map(ft=>Ln(ft,e)).join(", "):e==="zh"?"全角色":"All roles",ve=K.defaultForRole&&K.defaultForRole.length>0?K.defaultForRole.map(ft=>Ln(ft,e)).join(", "):"—",_e=K.preferredProviderId?n.find(ft=>ft.id===K.preferredProviderId):void 0,je=K.preferredProviderName||_e?.name||(K.preferredProviderId?e==="zh"?"绑定提供商已失效(自动回退)":"Bound provider missing (fallback)":e==="zh"?"跟随默认":"Follow default"),Me=K.source==="plugin",et=K.source==="admin",Be=K.enabled!==!1,st=K.id==="plain_assistant";return r.jsxs("tr",{className:`hover:bg-slate-50/80 transition-colors ${Be?"":"opacity-65 bg-slate-50/50"}`,children:[r.jsx("th",{scope:"row",className:"py-2.5 px-3 font-medium text-gray-800",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{"aria-hidden":"true",children:K.icon||"🤖"}),r.jsxs("div",{children:[r.jsxs("div",{className:"font-semibold text-gray-800 flex items-center gap-1.5",children:[r.jsx("span",{children:we}),st&&r.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded bg-amber-50 text-amber-700 border border-amber-200 font-medium",children:e==="zh"?"兜底":"Fallback"})]}),r.jsxs("div",{className:"text-[11px] text-gray-400 font-mono",children:[K.id," · ",ce,"/",pe," · ",K.maxTurns??5,"t"]})]})]})}),r.jsx("td",{className:"py-2.5 px-3 text-gray-600 max-w-[240px]",children:r.jsx("p",{className:"line-clamp-2 leading-snug",title:oe,children:oe})}),r.jsx("td",{className:"py-2.5 px-3",children:r.jsxs("div",{className:"flex flex-col gap-1 items-start",children:[r.jsx("span",{className:`inline-block px-2 py-0.5 rounded-full text-[11px] font-medium ${K.source==="builtin"?"bg-slate-100 text-slate-700":et?"bg-indigo-50 text-indigo-700":"bg-purple-50 text-purple-700"}`,children:K.source}),r.jsx("span",{className:"text-[11px] text-gray-500",children:je})]})}),r.jsxs("td",{className:"py-2.5 px-3 text-gray-600",children:[r.jsx("div",{children:xe}),ve!=="—"&&r.jsx("div",{className:"text-[11px] text-indigo-700 font-medium mt-0.5",children:e==="zh"?`默认: ${ve}`:`Default: ${ve}`})]}),r.jsx("td",{className:"py-2.5 px-3 whitespace-nowrap",children:r.jsx("span",{className:`inline-block px-2 py-0.5 rounded-full text-[11px] font-semibold ${Be?"bg-emerald-50 text-emerald-700":"bg-gray-100 text-gray-500"}`,children:Be?e==="zh"?"已启用":"Active":e==="zh"?"已停用":"Disabled"})}),r.jsx("td",{className:"py-2.5 px-3 text-right",children:r.jsxs("div",{className:"inline-flex items-center gap-1.5 flex-wrap justify-end",children:[Me?r.jsx("span",{className:"text-[11px] text-gray-400",children:e==="zh"?"插件托管":"Plugin managed"}):r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:()=>re(K),"aria-label":e==="zh"?`编辑角色模板 ${we} (${K.id})`:`Edit persona ${we} (${K.id})`,className:"px-2 py-1 text-indigo-600 bg-indigo-50 hover:bg-indigo-100 rounded-md font-semibold transition-colors cursor-pointer inline-flex items-center gap-1",children:[r.jsx(S0,{size:12}),r.jsx("span",{children:e==="zh"?"编辑":"Edit"})]}),!st&&r.jsxs("button",{type:"button",onClick:()=>G(K),"aria-label":Be?e==="zh"?`停用角色模板 ${we} (${K.id})`:`Deactivate persona ${we} (${K.id})`:e==="zh"?`启用角色模板 ${we} (${K.id})`:`Activate persona ${we} (${K.id})`,className:`px-2 py-1 rounded-md font-semibold transition-colors cursor-pointer inline-flex items-center gap-1 ${Be?"text-amber-700 bg-amber-50 hover:bg-amber-100":"text-emerald-700 bg-emerald-50 hover:bg-emerald-100"}`,children:[r.jsx(k0,{size:12}),r.jsx("span",{children:Be?e==="zh"?"停用":"Disable":e==="zh"?"启用":"Enable"})]})]}),et&&r.jsxs("button",{type:"button",onClick:()=>ue(K),"aria-label":e==="zh"?`删除角色模板 ${we} (${K.id})`:`Delete persona ${we} (${K.id})`,className:"px-2 py-1 text-rose-600 bg-rose-50 hover:bg-rose-100 rounded-md font-semibold transition-colors cursor-pointer inline-flex items-center gap-1",children:[r.jsx(Jn,{size:12}),r.jsx("span",{children:e==="zh"?"删除":"Delete"})]})]})})]},K.id)})})]})})}),r.jsxs(yi,{open:f,onClose:()=>{m(!1),y(null)},ariaLabelledBy:"ai-persona-modal-title",className:"rounded-2xl shadow-xl border border-gray-200/60 w-full max-w-xl p-0 bg-white text-gray-800 backdrop:bg-gray-900/40",children:[r.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-gray-100 bg-slate-50/70",children:[r.jsxs("h4",{id:"ai-persona-modal-title",className:"font-extrabold text-sm sm:text-base text-gray-800 flex items-center gap-2",children:[r.jsx(Jc,{className:"text-indigo-600",size:18}),h?e==="zh"?"编辑 AI 角色模板":"Edit AI Persona":e==="zh"?"新建 AI 角色模板":"Create AI Persona"]}),r.jsx("button",{type:"button",onClick:()=>{m(!1),y(null)},"aria-label":e==="zh"?"关闭角色配置对话框":"Close persona dialog",className:"p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition-colors cursor-pointer",children:r.jsx(De,{size:16})})]}),r.jsxs("form",{onSubmit:te,className:"p-5 space-y-4 text-left max-h-[75vh] overflow-y-auto",children:[q&&r.jsx("div",{role:"alert",className:"p-2.5 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-lg",children:q}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[r.jsxs("div",{className:"sm:col-span-2",children:[r.jsx("label",{htmlFor:"persona-form-id",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"唯一 ID *":"Persona ID *"}),r.jsx("input",{id:"persona-form-id",name:"id",type:"text",required:!0,disabled:!!h,value:w,onChange:K=>E(K.target.value),placeholder:"e.g. chemistry_lab_tutor",className:"w-full text-xs bg-gray-50 disabled:bg-gray-100 border border-gray-200 rounded-lg px-3 py-2 font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-icon",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"图标":"Icon"}),r.jsx("input",{id:"persona-form-icon",name:"icon",type:"text",value:U,onChange:K=>k(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-name-zh",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"中文名称 *":"Chinese Name *"}),r.jsx("input",{id:"persona-form-name-zh",name:"nameZh",type:"text",required:!0,value:N,onChange:K=>j(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-name-en",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"英文名称 *":"English Name *"}),r.jsx("input",{id:"persona-form-name-en",name:"nameEn",type:"text",required:!0,value:I,onChange:K=>z(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-desc-zh",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"用途说明(中文)":"Purpose Description (ZH)"}),r.jsx("input",{id:"persona-form-desc-zh",name:"descriptionZh",type:"text",value:$,onChange:K=>V(K.target.value),placeholder:e==="zh"?"简述该助教适用教学场景":"Briefly describe purpose in Chinese",className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-desc-en",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"用途说明(英文)":"Purpose Description (EN)"}),r.jsx("input",{id:"persona-form-desc-en",name:"descriptionEn",type:"text",value:B,onChange:K=>_(K.target.value),placeholder:"Brief purpose summary",className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 items-end",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-provider",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"绑定平台共享 AI 提供商(可选)":"Bind Shared AI Provider (Optional)"}),r.jsxs("select",{id:"persona-form-provider",name:"preferredProviderId",value:M,onChange:K=>A(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500",children:[r.jsx("option",{value:"",children:e==="zh"?"不绑定(跟随当前用户选择 / 平台默认)":"None (follow active user/default provider)"}),n.map(K=>r.jsxs("option",{value:K.id,children:[K.name," (",K.model_name,")"]},K.id))]})]}),r.jsxs("label",{className:"inline-flex items-center gap-2 text-xs font-semibold text-gray-700 border border-gray-200 rounded-lg px-3 py-2 bg-gray-50 cursor-pointer",children:[r.jsx("input",{type:"checkbox",name:"enabled",disabled:h?.id==="plain_assistant",checked:h?.id==="plain_assistant"?!0:F,onChange:K=>Z(K.target.checked),className:"rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"}),r.jsx("span",{children:h?.id==="plain_assistant"?e==="zh"?"启用中(系统兜底角色常驻)":"Active (System fallback)":e==="zh"?"启用该角色模板":"Enable this persona"})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-mode",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"提示词模式":"Mode"}),r.jsxs("select",{id:"persona-form-mode",name:"mode",value:L,onChange:K=>{const we=K.target.value==="replace"?"replace":"overlay";S(we),D(we==="replace"?"drop":"inherit")},className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500",children:[r.jsxs("option",{value:"overlay",children:["overlay (",e==="zh"?"叠加":"Overlay",")"]}),r.jsxs("option",{value:"replace",children:["replace (",e==="zh"?"替换":"Replace",")"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-base-policy",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"基础指令策略":"Base Policy"}),r.jsxs("select",{id:"persona-form-base-policy",name:"basePolicy",value:R,onChange:K=>D(K.target.value==="drop"?"drop":"inherit"),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500",children:[r.jsxs("option",{value:"inherit",children:["inherit (",e==="zh"?"保留内置":"Inherit",")"]}),r.jsxs("option",{value:"drop",children:["drop (",e==="zh"?"丢弃内置":"Drop",")"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-max-turns",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"最大轮次 (1-20)":"Max Turns (1-20)"}),r.jsx("input",{id:"persona-form-max-turns",name:"maxTurns",type:"number",min:1,max:20,value:J,onChange:K=>se(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsxs("fieldset",{className:"border border-gray-200 rounded-lg p-3",children:[r.jsx("legend",{className:"text-xs font-bold text-gray-600 px-1",children:e==="zh"?"可见角色(空选 = 全角色)":"Visibility (empty = all)"}),r.jsx("div",{className:"flex flex-wrap gap-3 mt-1",children:Na.map(K=>r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-gray-700 cursor-pointer",children:[r.jsx("input",{type:"checkbox",name:`visibility_${K}`,checked:P.includes(K),onChange:()=>de(K,P,Y),className:"rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"}),r.jsx("span",{children:Ln(K,e)})]},`vis-${K}`))})]}),r.jsxs("fieldset",{className:"border border-gray-200 rounded-lg p-3",children:[r.jsx("legend",{className:"text-xs font-bold text-gray-600 px-1",children:e==="zh"?"设为默认角色":"Default For Roles"}),r.jsx("div",{className:"flex flex-wrap gap-3 mt-1",children:Na.map(K=>r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-gray-700 cursor-pointer",children:[r.jsx("input",{type:"checkbox",name:`default_for_${K}`,checked:H.includes(K),onChange:()=>de(K,H,ee),className:"rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"}),r.jsx("span",{children:Ln(K,e)})]},`def-${K}`))})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-allow-tools",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"工具白名单(逗号分隔)":"Allow Tools (comma-separated)"}),r.jsx("input",{id:"persona-form-allow-tools",name:"toolAllow",type:"text",value:ye,onChange:K=>Se(K.target.value),placeholder:"e.g. vfs.*, lesson.*",className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-deny-tools",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"工具黑名单(逗号分隔)":"Deny Tools (comma-separated)"}),r.jsx("input",{id:"persona-form-deny-tools",name:"toolDeny",type:"text",value:me,onChange:K=>C(K.target.value),placeholder:"e.g. process.*, class_create",className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-inst-zh",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"中文系统指令":"Chinese System Instruction"}),r.jsx("textarea",{id:"persona-form-inst-zh",name:"instructionZh",rows:3,required:w.trim()!=="plain_assistant",value:le,onChange:K=>ae(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"persona-form-inst-en",className:"block text-xs font-bold text-gray-600 mb-1",children:e==="zh"?"英文系统指令":"English System Instruction"}),r.jsx("textarea",{id:"persona-form-inst-en",name:"instructionEn",rows:3,required:w.trim()!=="plain_assistant",value:fe,onChange:K=>be(K.target.value),className:"w-full text-xs bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"})]}),r.jsxs("div",{className:"flex items-center justify-end gap-3 pt-3 border-t border-gray-100",children:[r.jsx("button",{type:"button",onClick:()=>{m(!1),y(null)},className:"px-4 py-2 text-xs font-bold text-gray-600 bg-slate-100 hover:bg-slate-200 rounded-lg cursor-pointer transition-colors",children:e==="zh"?"取消":"Cancel"}),r.jsxs("button",{type:"submit",disabled:W,className:"px-4 py-2 text-xs font-bold text-white bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded-lg shadow-sm transition-all cursor-pointer inline-flex items-center gap-1.5",children:[W?r.jsx(dt,{size:13,className:"animate-spin"}):r.jsx(Xe,{size:14}),r.jsx("span",{children:e==="zh"?"保存角色模板":"Save Persona"})]})]})]})]}),r.jsx(yi,{open:!!p,onClose:()=>{g||x(null)},ariaLabelledBy:"persona-confirm-dialog-title",className:"rounded-2xl shadow-xl border border-gray-200/60 w-full max-w-md p-0 bg-white text-gray-800 backdrop:bg-gray-900/40",children:p&&r.jsxs("div",{className:"p-5 space-y-4 text-left",children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:"p-2 rounded-xl bg-amber-50 text-amber-600 shrink-0",children:r.jsx(Bt,{size:18})}),r.jsxs("div",{children:[r.jsx("h4",{id:"persona-confirm-dialog-title",className:"font-bold text-sm text-gray-900",children:p.action==="deactivate"?e==="zh"?"确认停用正在引用的助教角色":"Confirm Deactivating Referenced Persona":e==="zh"?"确认删除正在引用的助教角色":"Confirm Deleting Referenced Persona"}),r.jsx("p",{className:"text-xs text-gray-600 mt-1.5 leading-relaxed",children:e==="zh"?`角色「${p.persona.nameZh}」(${p.persona.id})当前被设为「${p.referencedRoles.map(K=>Ln(K,"zh")).join("、")}」的默认助教。继续${p.action==="deactivate"?"停用":"删除"}后,系统将自动清除这些默认绑定并回退至「普通助教(默认)」,已打开侧栏的会话将在下次刷新或发送消息时自动平滑切换,不会影响助手正常使用。`:`Persona "${p.persona.nameEn}" (${p.persona.id}) is currently set as default for: ${p.referencedRoles.map(K=>Ln(K,"en")).join(", ")}. Proceeding will automatically clear those default bindings and fall back to "Plain Assistant" so assistant service stays available.`})]})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2.5 pt-2 border-t border-gray-100",children:[r.jsx("button",{type:"button",autoFocus:!0,disabled:g,onClick:()=>x(null),className:"px-3.5 py-2 text-xs font-bold text-gray-600 bg-slate-100 hover:bg-slate-200 rounded-lg cursor-pointer transition-colors",children:e==="zh"?"取消":"Cancel"}),r.jsx("button",{type:"button",disabled:g,onClick:()=>void he(),className:"px-3.5 py-2 text-xs font-bold text-white bg-amber-600 hover:bg-amber-700 disabled:opacity-50 rounded-lg cursor-pointer transition-colors",children:p.action==="deactivate"?e==="zh"?"确认停用并自动回退":"Deactivate & Fall Back":e==="zh"?"确认删除并自动回退":"Delete & Fall Back"})]})]})})]})}const l2=new Set(["metadata.google.internal","metadata.goog"]);function Wm(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Ec(e){if(e.length!==4||e.some(i=>!Number.isInteger(i)||i<0||i>255))return null;const t=e[0]??-1,n=e[1]??-1,s=e[2]??-1;return t===127?"loopback":t===169&&n===254?"link-local":t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===100&&n>=64&&n<=127?"private":t===0||t===192&&n===0&&(s===0||s===2)||t===198&&(n===18||n===19)||t===198&&n===51&&s===100||t===203&&n===0&&s===113||t>=224?"blocked":"public"}function c2(e){let t=Wm(e).toLowerCase();const n=t.lastIndexOf(":"),s=n>=0?t.slice(n+1):"";if(s.includes(".")){const d=s.split(".").map(y=>Number(y));if(!Ec(d))return null;const m=(d[0]<<8|d[1]).toString(16),h=(d[2]<<8|d[3]).toString(16);t=`${t.slice(0,n+1)}${m}:${h}`}const i=t.split("::");if(i.length>2)return null;const o=i[0]?i[0].split(":"):[],a=i.length===2?i[1]?i[1].split(":"):[]:[];if(i.length===1&&o.length!==8)return null;const l=8-o.length-a.length;if(l<0)return null;const c=[...o,...Array.from({length:l},()=>"0"),...a];if(c.length!==8)return null;const u=c.map(d=>/^[0-9a-f]{1,4}$/.test(d)?parseInt(d,16):Number.NaN);return u.some(d=>Number.isNaN(d))?null:u}function d2(e){const t=c2(e);if(!t)return"invalid";if(t.every(o=>o===0))return"blocked";if(t.slice(0,7).every(o=>o===0)&&t[7]===1)return"loopback";const n=t.slice(0,5).every(o=>o===0)&&t[5]===65535,s=t.slice(0,6).every(o=>o===0);if(n||s){const o=t[6]??0,a=t[7]??0;return Ec([o>>8&255,o&255,a>>8&255,a&255])??"invalid"}const i=t[0]??0;return(i&65024)===64512?"private":(i&65472)===65152?"link-local":(i&65280)===65280?"blocked":"public"}function u2(e){const t=Wm(e).toLowerCase().replace(/\.$/,"");return t?l2.has(t)?"metadata":t==="localhost"||t.endsWith(".localhost")?"loopback":t.endsWith(".local")?"private":/^\d{1,3}(\.\d{1,3}){3}$/.test(t)?Ec(t.split(".").map(n=>Number(n)))??"invalid":t.includes(":")?d2(t):"public":"invalid"}const gt={EMPTY_URL:{zh:"API 端点 URL 不能为空。",en:"API endpoint URL is required."},MISSING_PROTOCOL:{zh:"API 端点 URL 必须以 http:// 或 https:// 开头(例如 http://192.168.1.10:11434/v1 或 https://api.deepseek.com/v1)。",en:"API endpoint URL must start with http:// or https:// (e.g. http://192.168.1.10:11434/v1 or https://api.deepseek.com/v1)."},UNSUPPORTED_PROTOCOL:{zh:"仅支持 http:// 或 https:// 协议。",en:"Only http:// and https:// protocols are allowed."},INVALID_URL:{zh:"URL 格式无效,请检查协议、主机名/IP、端口与路径。",en:"Invalid URL format. Please check the protocol, host/IP, port, and path."},INVALID_HOST:{zh:"URL 中包含无效的主机名或 IP 地址。",en:"URL contains an invalid hostname or IP address."},CREDENTIALS_NOT_ALLOWED:{zh:"安全策略禁止在 API URL 中直接携带用户名或密码凭据。",en:"Security policy forbids embedding username/password credentials in the API URL."},BLOCKED_LINK_LOCAL:{zh:"安全策略禁止访问链路本地地址(如 169.254.x.x、fe80::)。",en:"Security policy forbids link-local addresses (e.g. 169.254.x.x, fe80::)."},BLOCKED_METADATA:{zh:"安全策略禁止访问云元数据服务主机名。",en:"Security policy forbids cloud metadata hostnames."},BLOCKED_RESERVED:{zh:"安全策略禁止访问未指定、组播或保留网段地址(如 0.0.0.0、::、224.0.0.0/4)。",en:"Security policy forbids unspecified, multicast, or reserved network addresses (e.g. 0.0.0.0, ::, 224.0.0.0/4)."}};function h2(e,t="zh"){return e.code&>[e.code]?gt[e.code][t]:e.reason||gt.INVALID_URL[t]}function f2(e){const t=typeof e=="string"?e.trim():"";if(!t)return{valid:!1,code:"EMPTY_URL",reason:gt.EMPTY_URL.en};if(!/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(t))return{valid:!1,code:"MISSING_PROTOCOL",reason:gt.MISSING_PROTOCOL.en};let n;try{n=new URL(t)}catch{return{valid:!1,code:"INVALID_URL",reason:gt.INVALID_URL.en}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{valid:!1,code:"UNSUPPORTED_PROTOCOL",reason:gt.UNSUPPORTED_PROTOCOL.en};if(!n.hostname)return{valid:!1,code:"INVALID_HOST",reason:gt.INVALID_HOST.en};if(n.username||n.password)return{valid:!1,code:"CREDENTIALS_NOT_ALLOWED",reason:gt.CREDENTIALS_NOT_ALLOWED.en};const s=u2(n.hostname);return s==="link-local"?{valid:!1,code:"BLOCKED_LINK_LOCAL",reason:gt.BLOCKED_LINK_LOCAL.en}:s==="metadata"?{valid:!1,code:"BLOCKED_METADATA",reason:gt.BLOCKED_METADATA.en}:s==="blocked"?{valid:!1,code:"BLOCKED_RESERVED",reason:gt.BLOCKED_RESERVED.en}:s==="invalid"?{valid:!1,code:"INVALID_HOST",reason:gt.INVALID_HOST.en}:{valid:!0,normalizedUrl:t,hostKind:s}}function m2({lang:e,aiProviders:t,onAIProvidersChanged:n,currentUserId:s,currentUserRole:i}){const[o,a]=b.useState(!1),[l,c]=b.useState(null),[u,d]=b.useState(""),[f,m]=b.useState(""),[h,y]=b.useState(""),[p,x]=b.useState(""),[g,v]=b.useState(!1),[w,E]=b.useState(!1),[N,j]=b.useState(null),[I,z]=b.useState(null),[$,V]=b.useState(null),[B,_]=b.useState(null),[U,k]=b.useState(null),F=b.useRef(null),Z=b.useRef(null),M=b.useRef(null),A=()=>{z(null),V(null),_(null),k(null)},L=()=>{c(null),d(""),m(""),y(""),x(""),v(!1),A(),a(!0)},S=H=>{c(H),d(H.name),m(H.api_url),y(H.api_key||""),x(H.model_name),v(!!H.is_shared),A(),a(!0)},R=H=>{const ee=f2(H);return ee.valid?null:h2(ee,e)},D=async H=>{H.preventDefault(),k(null);const ee=u.trim()?null:e==="zh"?"服务商名称不可为空。":"Provider name is required.",le=R(f),ae=p.trim()?null:e==="zh"?"模型代号不可为空。":"Model identifier is required.";if(z(ee),V(le),_(ae),ee){F.current?.focus();return}if(le){Z.current?.focus();return}if(ae){M.current?.focus();return}try{E(!0);const fe=!!l,be=fe?`/api/ai-providers/${l.id}`:"/api/ai-providers",ye=fe?"PUT":"POST",Se={name:u.trim(),api_url:f.trim(),api_key:h,model_name:p.trim()};i==="administrator"&&(Se.is_shared=g?1:0);const me=await fetch(be,{method:ye,headers:{"Content-Type":"application/json"},body:JSON.stringify(Se)});if(me.ok)a(!1),c(null),A(),n();else{const J=(await me.json().catch(()=>({}))).error||(e==="zh"?"保存失败,请检查配置参数。":"Failed to save provider.");k(J)}}catch(fe){const be=fe instanceof Error?fe.message:String(fe);k(be||"Error")}finally{E(!1)}},P=async(H,ee)=>{if(confirm(e==="zh"?`确认要删除 AI 提供商 [${ee}] 吗?`:`Confirm deleting AI Provider [${ee}]?`))try{(await fetch(`/api/ai-providers/${H}`,{method:"DELETE"})).ok?n():alert("Delete failed")}catch(le){const ae=le instanceof Error?le.message:String(le);alert(ae||"Error")}},Y=async H=>{if(!N){j(H.id);try{const ee=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:H.id,api_url:H.api_url,api_key:H.api_key,model_name:H.model_name})});if(ee.ok)alert(e==="zh"?`[${H.name}] 连接测试成功!`:`[${H.name}] Connection test successful!`);else{const le=await ee.json().catch(()=>({}));alert(e==="zh"?`测试失败: ${le.error||"未知错误"}`:`Test failed: ${le.error||"Unknown error"}`)}}catch(ee){const le=ee instanceof Error?ee.message:String(ee);alert(e==="zh"?`网络异常: ${le}`:`Network error: ${le}`)}finally{j(null)}}};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 animate-fade-in text-gray-800",children:[i==="administrator"&&r.jsx("div",{className:"bg-indigo-50/70 border border-indigo-200/70 rounded-xl px-5 py-4 flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:r.jsxs("div",{children:[r.jsx("h2",{className:"font-extrabold text-gray-900 text-base sm:text-lg tracking-tight",children:e==="zh"?"AI 配置":"AI Configuration"}),r.jsx("p",{className:"text-xs text-gray-600 mt-0.5",children:e==="zh"?"统一管理 AI 模型服务与内核 AI 助教角色;个人私有提供商仍仅限所属账号可见与使用。":"Unified management for OpenAI-compatible AI model providers and kernel AI assistant personas. Private providers remain strictly user-scoped."})]})}),r.jsxs("div",{className:"bg-white border border-gray-200 rounded-xl shadow-3xs overflow-hidden",children:[r.jsxs("div",{className:"p-4 sm:p-5 border-b border-gray-100 flex items-center justify-between bg-gray-50/60",children:[r.jsxs("div",{children:[r.jsxs("h3",{className:"font-bold text-gray-800 flex items-center gap-2 text-sm sm:text-base",children:[r.jsx(hf,{className:"text-indigo-600",size:18}),e==="zh"?"OpenAI 兼容 / 自定义模型 AI 提供商列表":"AI Providers List (OpenAI-Compatible)"]}),r.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:e==="zh"?"支持 OpenAI 兼容 API。私有模型仅您个人可用,平台共享模型供全校教师共用。":"OpenAI-compatible APIs. Private models are exclusive to your account; shared models are available to all teachers."})]}),r.jsxs("button",{onClick:L,className:"flex items-center gap-1.5 px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg shadow-sm transition-all text-xs cursor-pointer",children:[r.jsx(tr,{size:14}),e==="zh"?"添加 AI 提供商":"Add AI Provider"]})]}),r.jsx("div",{className:"p-4 sm:p-5",children:t.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-400 text-center",children:[r.jsx(ji,{size:40,className:"mb-3 opacity-30 text-indigo-500"}),r.jsx("span",{className:"font-semibold text-sm",children:e==="zh"?"暂未配置任何 AI 提供商":"No AI Providers Registered"}),r.jsx("p",{className:"text-xs text-gray-400 mt-1 max-w-xs",children:e==="zh"?"点击右上角按钮新建。":"Click the button above to add one."})]}):r.jsx(Vm,{labelledBy:"ai-providers-table-caption",className:"border border-gray-100 rounded-xl",children:r.jsxs("table",{className:"responsive-data-table w-full text-left border-collapse","data-stack-mobile":"true",children:[r.jsx("caption",{id:"ai-providers-table-caption",className:"sr-only",children:e==="zh"?"AI 提供商配置列表":"AI Providers List"}),r.jsx("thead",{children:r.jsxs("tr",{className:"bg-slate-50/70 border-b border-gray-100 text-gray-500 font-bold text-xs uppercase tracking-wider",children:[r.jsx("th",{scope:"col",className:"py-3.5 px-4",children:e==="zh"?"名称":"Name"}),r.jsx("th",{scope:"col",className:"py-3.5 px-4",children:e==="zh"?"类型 / 范围":"Scope"}),r.jsx("th",{scope:"col",className:"py-3.5 px-4",children:e==="zh"?"API 端点 URL":"API Endpoint URL"}),r.jsx("th",{scope:"col",className:"py-3.5 px-4",children:e==="zh"?"模型代号":"Model Identifier"}),r.jsx("th",{scope:"col",className:"py-3.5 px-4",children:e==="zh"?"密钥状态":"API Key"}),r.jsx("th",{scope:"col",className:"py-3.5 px-4 text-center",children:e==="zh"?"操作":"Actions"})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 text-xs text-gray-700",children:t.map(H=>{const ee=!!H.is_shared,le=ee?i==="administrator":!H.owner_id||!s||H.owner_id===s;return r.jsxs("tr",{className:"hover:bg-slate-50/50 transition-colors",children:[r.jsx("th",{scope:"row","data-label":e==="zh"?"名称":"Name",className:"py-4 px-4 text-left",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${ee?"bg-purple-500":"bg-indigo-500"}`}),r.jsx("span",{className:"font-extrabold text-gray-800 text-sm",children:H.name})]})}),r.jsx("td",{"data-label":e==="zh"?"类型 / 范围":"Scope",className:"py-4 px-4 whitespace-nowrap",children:ee?r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold bg-purple-50 text-purple-700 border border-purple-200",children:[r.jsx(Xc,{size:12}),e==="zh"?"平台共享":"Platform Shared"]}):r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200",children:[r.jsx(wn,{size:12}),e==="zh"?"个人私有":"Private"]})}),r.jsx("td",{"data-label":e==="zh"?"API 端点 URL":"API Endpoint URL",className:"py-4 px-4 font-mono text-gray-550 truncate max-w-[220px]",children:H.api_url}),r.jsx("td",{"data-label":e==="zh"?"模型代号":"Model Identifier",className:"py-4 px-4",children:r.jsx("span",{className:"bg-slate-100 text-slate-800 font-bold px-2 py-1 rounded font-mono text-xs border border-slate-200",children:H.model_name})}),r.jsx("td",{"data-label":e==="zh"?"密钥状态":"API Key",className:"py-4 px-4",children:H.api_key?r.jsxs("span",{className:"text-emerald-600 font-bold flex items-center gap-1 font-mono",children:[r.jsx(Xe,{size:12})," Key Saved"]}):r.jsx("span",{className:"text-amber-500/90 font-mono italic",children:"Not Set"})}),r.jsx("td",{"data-label":e==="zh"?"操作":"Actions",className:"py-4 px-4 text-center",children:r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsxs("button",{onClick:()=>Y(H),disabled:N===H.id,className:"px-2.5 py-1 text-xs font-semibold rounded-lg border transition-all cursor-pointer flex items-center gap-1.5 shadow-3xs bg-emerald-50 border-emerald-200 text-emerald-700 hover:bg-emerald-100 disabled:opacity-60",title:e==="zh"?"测试连通性":"Test Connection",children:[N===H.id?r.jsx(dt,{size:11,className:"animate-spin"}):r.jsx(hi,{size:11}),r.jsx("span",{children:e==="zh"?"测试":"Test"})]}),r.jsx("button",{onClick:()=>S(H),disabled:!le,className:`px-2.5 py-1 rounded-lg border font-semibold transition-all shadow-3xs ${le?"text-indigo-700 hover:bg-indigo-100 border-indigo-200 bg-indigo-50 cursor-pointer":"text-gray-400 border-gray-200 bg-gray-50 opacity-50 cursor-not-allowed"}`,title:le?e==="zh"?"编辑配置":"Edit":e==="zh"?"平台共享配置仅管理员可修改":"Shared provider can only be modified by administrator",children:e==="zh"?"编辑":"Edit"}),r.jsx("button",{onClick:()=>P(H.id,H.name),disabled:!le,className:`px-2.5 py-1 rounded-lg border font-semibold transition-all shadow-3xs ${le?"text-rose-600 hover:bg-rose-100 border-rose-200 bg-rose-50 cursor-pointer":"text-gray-400 border-gray-200 bg-gray-50 opacity-50 cursor-not-allowed"}`,title:le?e==="zh"?"删除":"Delete":e==="zh"?"平台共享配置仅管理员可修改":"Shared provider can only be modified by administrator",children:e==="zh"?"删除":"Delete"})]})})]},H.id)})})]})})})]}),i==="administrator"&&r.jsx(a2,{lang:e,aiProviders:t})]}),o&&r.jsx("div",{className:"fixed inset-0 bg-gray-900/40 backdrop-blur-xs flex items-center justify-center p-4 z-[60] overflow-y-auto",children:r.jsxs("div",{className:"bg-white rounded-2xl shadow-xl border border-gray-200/60 w-full max-w-md overflow-hidden text-gray-800 text-left",children:[r.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-gray-100 bg-slate-50/70",children:[r.jsxs("h3",{className:"font-extrabold text-sm sm:text-base text-gray-800 flex items-center gap-2",children:[r.jsx(j0,{className:"text-indigo-600",size:18}),l?e==="zh"?"编辑 AI 提供商配置":"Edit AI Provider":e==="zh"?"添加全新 AI 提供商":"Add New AI Provider"]}),r.jsx("button",{onClick:()=>{a(!1),c(null)},className:"p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition-colors cursor-pointer",children:r.jsx(De,{size:16})})]}),r.jsxs("form",{noValidate:!0,onSubmit:D,className:"p-5 space-y-4 text-left",children:[U&&r.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700",children:[r.jsx(Pt,{size:14,className:"mt-0.5 shrink-0"}),r.jsx("span",{children:U})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"ai-provider-name",className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1 text-left",children:e==="zh"?"服务商名称 *":"Provider Name *"}),r.jsx("input",{ref:F,id:"ai-provider-name",name:"provider_name",type:"text",required:!0,placeholder:"e.g. Deepseek, Minimax",value:u,"aria-invalid":I?"true":"false","aria-describedby":I?"ai-provider-name-error":void 0,onChange:H=>{d(H.target.value),I&&z(null)},className:`w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:border-transparent transition-all font-semibold ${I?"border-rose-400 focus:ring-rose-500 bg-rose-50/40":"border-gray-200 focus:ring-indigo-500"}`}),I&&r.jsxs("p",{id:"ai-provider-name-error",className:"mt-1 text-xs text-rose-600 flex items-center gap-1",children:[r.jsx(Pt,{size:12,className:"shrink-0"}),r.jsx("span",{children:I})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"ai-provider-url",className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1 text-left",children:e==="zh"?"API 端点 URL *":"API Endpoint URL *"}),r.jsx("span",{id:"ai-provider-url-hint",className:"text-xs text-gray-500 mb-1.5 block",children:e==="zh"?"支持公网域名、内网/本地 IP(如 http://192.168.1.10:11434/v1)、自定义端口与基础路径。":"Supports domains, LAN/local IPs (e.g. http://192.168.1.10:11434/v1), custom ports, and base paths."}),r.jsx("input",{ref:Z,id:"ai-provider-url",name:"provider_api_url",type:"url",required:!0,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:"https://api.deepseek.com/v1",value:f,"aria-invalid":$?"true":"false","aria-describedby":$?"ai-provider-url-hint ai-provider-url-error":"ai-provider-url-hint",onChange:H=>{m(H.target.value),$&&V(null)},onBlur:()=>{f.trim()&&V(R(f))},className:`w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:border-transparent transition-all font-mono ${$?"border-rose-400 focus:ring-rose-500 bg-rose-50/40":"border-gray-200 focus:ring-indigo-500"}`}),$&&r.jsxs("p",{id:"ai-provider-url-error",className:"mt-1 text-xs text-rose-600 flex items-start gap-1",children:[r.jsx(Pt,{size:12,className:"mt-0.5 shrink-0"}),r.jsx("span",{children:$})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"ai-provider-model",className:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1 text-left",children:e==="zh"?"模型代号 *":"Model Identifier *"}),r.jsx("input",{ref:M,id:"ai-provider-model",name:"provider_model_name",type:"text",required:!0,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:"e.g. deepseek-chat",value:p,"aria-invalid":B?"true":"false","aria-describedby":B?"ai-provider-model-error":void 0,onChange:H=>{x(H.target.value),B&&_(null)},className:`w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:border-transparent transition-all font-mono ${B?"border-rose-400 focus:ring-rose-500 bg-rose-50/40":"border-gray-200 focus:ring-indigo-500"}`}),B&&r.jsxs("p",{id:"ai-provider-model-error",className:"mt-1 text-xs text-rose-600 flex items-center gap-1",children:[r.jsx(Pt,{size:12,className:"shrink-0"}),r.jsx("span",{children:B})]})]}),r.jsx(bn,{id:"ai-provider-key",name:"provider_api_key",label:e==="zh"?"API Key (可选)":"API Key (Optional)",labelClassName:"block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5 text-left",placeholder:e==="zh"?"不修改请留空":"Leave empty to keep existing",value:h,onChange:y,autoComplete:"off",lang:e,className:"w-full text-xs sm:text-sm bg-gray-50 hover:bg-gray-100/50 focus:bg-white border border-gray-200 rounded-lg px-3 py-2 pr-10 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all font-mono"}),i==="administrator"&&r.jsx("div",{className:"pt-2 border-t border-gray-100",children:r.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:g,onChange:H=>v(H.target.checked),className:"mt-0.5 w-4 h-4 text-indigo-600 rounded border-gray-300 focus:ring-indigo-500 cursor-pointer"}),r.jsxs("div",{children:[r.jsxs("span",{className:"text-xs font-bold text-gray-800 flex items-center gap-1.5",children:[r.jsx(Xc,{size:14,className:"text-purple-600"}),e==="zh"?"设为平台共享模型 (全校教师可用)":"Set as Platform Shared (All teachers)"]}),r.jsx("span",{className:"text-xs text-gray-400 mt-0.5 block leading-relaxed",children:e==="zh"?"勾选后,所有教师可直接在侧栏与课表中使用该模型,但无法查看或篡改您的 API Key。不勾选则仅为您个人私有。":"If enabled, all teachers can use this model without seeing your API key. Otherwise it remains private."})]})]})}),r.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4 border-t border-gray-100",children:[r.jsx("button",{type:"button",onClick:()=>{a(!1),c(null)},className:"px-4 py-2 text-xs font-bold text-gray-500 bg-slate-100 hover:bg-slate-200 rounded-lg cursor-pointer transition-colors",children:e==="zh"?"取消":"Cancel"}),r.jsxs("button",{type:"submit",disabled:w,className:"px-4 py-2 text-xs font-bold text-white bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded-lg shadow-sm transition-all cursor-pointer flex items-center gap-1.5",children:[w?r.jsx(dt,{size:13,className:"animate-spin"}):r.jsx(Xe,{size:14}),r.jsx("span",{children:w?e==="zh"?"保存中...":"Saving...":e==="zh"?"保存至数据库":"Save Connection"})]})]})]})]})})]})}function p2({open:e,session:t,lang:n,onClose:s,onSaved:i,onAvatar:o}){const[a,l]=b.useState("profile"),[c,u]=b.useState(t.name),[d,f]=b.useState(!1),[m,h]=b.useState(null),y=Ot(),[p,x]=b.useState([]),g=b.useCallback(async()=>{try{const re=await fetch("/api/ai-providers");if(re.ok){const de=await re.json();x(Array.isArray(de)?de:[])}}catch{}},[]);b.useEffect(()=>{e&&a==="ai_providers"&&g()},[e,a,g]);const v=y?.aiProviders&&y.aiProviders.length>0?y.aiProviders:p,w=()=>{y?.onAIProvidersChanged&&y.onAIProvidersChanged(),g()},E=t.userId||t.id,N=t.subRole==="administrator"?"administrator":t.role,j=b.useRef(null),[I,z]=b.useState(!1),[$,V]=b.useState(null),B=b.useRef(null),_=b.useRef(null),U=b.useRef(null),k=b.useRef(null),[F,Z]=b.useState(!1),[M,A]=b.useState(""),[L,S]=b.useState(""),[R,D]=b.useState(""),[P,Y]=b.useState(!1),[H,ee]=b.useState(null),[le,ae]=b.useState(null),[fe,be]=b.useState(null),[ye,Se]=b.useState(null),[me,C]=b.useState(!1);if(!e)return null;const J=(re,de)=>n==="zh"?re:de,se=t.role==="teacher"?t.subRole==="administrator"?J("管理员","Administrator"):J("教师","Teacher"):J("学生","Student"),W=c.trim(),T=W.length>0&&W!==t.name,q=async re=>{if(re?.preventDefault(),!d){if(!W){h(n==="zh"?"显示名称不能为空":"Display name is required"),B.current?.focus();return}if(!T){h(n==="zh"?"显示名称未发生变化":"Display name is unchanged"),B.current?.focus();return}f(!0),h(null);try{const de=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:W})}),te=await de.json();if(!de.ok){h(te.error||(n==="zh"?"保存失败":"Save failed"));return}i(te.name??W)}catch{h(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{f(!1)}}},X=async re=>{if(re?.preventDefault(),P)return;ee(null);let de=null,te=null,O=null;if(M||(de=n==="zh"?"请输入当前密码":"Enter your current password"),(L.length<8||!/[a-zA-Z]/.test(L)||!/[0-9]/.test(L))&&(te=n==="zh"?"新密码至少 8 位且须包含字母和数字":"Use at least 8 characters with letters and numbers"),R?L!==R&&(O=n==="zh"?"两次输入的新密码不一致":"New passwords do not match"):O=n==="zh"?"请再次输入新密码":"Confirm your new password",ae(de),be(te),Se(O),de){_.current?.focus();return}if(te){U.current?.focus();return}if(O){k.current?.focus();return}Y(!0);try{const G=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:M,newPassword:L})}),ie=await G.json();if(!G.ok){ee(ie.error||(n==="zh"?"修改失败":"Change failed"));return}C(!0),A(""),S(""),D(""),ae(null),be(null),Se(null),Z(!1)}catch{ee(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{Y(!1)}},ne=async re=>{const de=re.target.files?.[0];if(re.target.value="",!!de){z(!0),V(null);try{const te=await new Promise((ie,ue)=>{const he=new FileReader;he.onload=()=>ie(he.result),he.onerror=()=>ue(he.error),he.readAsDataURL(de)}),O=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:de.name,base64Data:te})}),G=await O.json();if(!O.ok){V(G.error||(n==="zh"?"上传失败":"Upload failed"));return}o?.(G.avatar)}catch{V(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{z(!1)}}},Q=async()=>{z(!0),V(null);try{const re=await fetch("/api/auth/avatar",{method:"DELETE"}),de=await re.json().catch(()=>({}));if(!re.ok){V(de.error||(n==="zh"?"移除失败":"Remove failed"));return}o?.(null)}catch{V(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{z(!1)}};return r.jsxs(yi,{open:e,onClose:s,ariaLabel:J("个人资料与 AI 设置","Profile & AI Settings"),closedBy:"any",className:`bg-white rounded-2xl shadow-xl overflow-hidden ${a==="ai_providers"?"max-w-4xl max-h-[88vh]":"max-w-md"}`,children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5 border-b border-gray-100 bg-slate-50/50 shrink-0",children:[t.role!=="student"?r.jsxs("div",{className:"flex items-center gap-1.5 bg-gray-200/70 p-1 rounded-xl",children:[r.jsxs("button",{type:"button",onClick:()=>l("profile"),className:`px-3 py-1.5 text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${a==="profile"?"bg-white text-indigo-700 shadow-3xs":"text-gray-600 hover:text-gray-900"}`,children:[r.jsx(wn,{size:13}),J("个人资料","Profile")]}),r.jsxs("button",{type:"button",onClick:()=>l("ai_providers"),className:`px-3 py-1.5 text-xs font-bold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${a==="ai_providers"?"bg-white text-indigo-700 shadow-3xs":"text-gray-600 hover:text-gray-900"}`,children:[r.jsx(hf,{size:13}),J("AI 模型设置","AI Providers")]})]}):r.jsx("h3",{className:"font-semibold text-gray-800",children:J("个人资料","Profile")}),r.jsx("button",{type:"button",onClick:s,"aria-label":J("关闭弹窗","Close dialog"),className:"text-gray-400 hover:text-gray-600 cursor-pointer p-1 rounded-full hover:bg-gray-100 transition-colors",children:r.jsx(De,{size:18})})]}),a==="ai_providers"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(m2,{lang:n==="zh"?"zh":"en",aiProviders:v,onAIProvidersChanged:w,currentUserId:E,currentUserRole:N})}):r.jsxs("div",{className:"p-5 space-y-5 overflow-y-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:t.avatar?r.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):r.jsx(wn,{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:se}),r.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:()=>j.current?.click(),disabled:I,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:I?J("上传中…","Uploading…"):t.avatar?J("更换头像","Change avatar"):J("上传头像","Upload avatar")}),t.avatar&&r.jsx("button",{type:"button",onClick:Q,disabled:I,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:J("移除","Remove")})]}),r.jsx("input",{ref:j,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:ne})]})]}),$&&r.jsx("p",{className:"text-xs text-rose-500",children:$}),r.jsxs("form",{noValidate:!0,onSubmit:re=>void q(re),children:[r.jsx("label",{htmlFor:"profile-display-name",className:"block text-sm text-gray-500 mb-1",children:J("显示名称","Display Name")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{ref:B,id:"profile-display-name",name:"displayName",type:"text",autoComplete:"name",required:!0,value:c,onChange:re=>{u(re.target.value),m&&h(null)},maxLength:50,"aria-invalid":m?"true":"false","aria-describedby":m?"profile-display-name-error":void 0,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",{type:"submit",disabled: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 shrink-0",children:d?J("保存中…","Saving…"):J("保存","Save")})]}),m&&r.jsx("p",{id:"profile-display-name-error",role:"alert",className:"text-xs text-rose-500 mt-1",children:m})]}),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(Si,{size:16,className:"text-gray-400","aria-hidden":"true"}),J("修改密码","Change Password")]}),!F&&!me&&r.jsx("button",{type:"button",onClick:()=>{Z(!0),ee(null),ae(null),be(null),Se(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:J("修改","Edit")})]}),me&&r.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[r.jsx(bt,{size:16,"aria-hidden":"true"}),J("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),F&&r.jsxs("form",{noValidate:!0,onSubmit:re=>void X(re),className:"mt-3 space-y-3",children:[r.jsx(bn,{id:"profile-old-password",name:"currentPassword",label:J("当前密码","Current password"),value:M,onChange:re=>{A(re),le&&ae(null)},autoComplete:"current-password",required:!0,enterKeyHint:"next",error:le,inputRef:_,lang:n,placeholder:J("当前密码","Current password"),className:"w-full border border-gray-300 rounded-lg pl-3 pr-10 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200",labelClassName:"block text-xs font-medium text-gray-600 mb-1"}),r.jsx(bn,{id:"profile-new-password",name:"newPassword",label:J("新密码","New password"),hint:J("至少 8 位,需同时包含字母和数字","At least 8 characters with letters and numbers"),value:L,onChange:re=>{S(re),fe&&be(null)},autoComplete:"new-password",required:!0,minLength:8,enterKeyHint:"next",error:fe,inputRef:U,lang:n,placeholder:J("输入新密码","Enter new password"),className:"w-full border border-gray-300 rounded-lg pl-3 pr-10 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200",labelClassName:"block text-xs font-medium text-gray-600 mb-0.5"}),r.jsx(bn,{id:"profile-confirm-password",name:"confirmPassword",label:J("确认新密码","Confirm new password"),value:R,onChange:re=>{D(re),ye&&Se(null)},autoComplete:"new-password",required:!0,minLength:8,enterKeyHint:"done",error:ye,inputRef:k,lang:n,placeholder:J("再次输入新密码","Re-enter new password"),className:"w-full border border-gray-300 rounded-lg pl-3 pr-10 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200",labelClassName:"block text-xs font-medium text-gray-600 mb-1"}),H&&r.jsx("p",{role:"alert",className:"text-xs text-rose-500",children:H}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx("button",{type:"button",onClick:()=>{Z(!1),A(""),S(""),D(""),ee(null),ae(null),be(null),Se(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:J("取消","Cancel")}),r.jsx("button",{type:"submit",disabled:P,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:P?J("提交中…","Submitting…"):J("提交","Submit")})]})]})]}),r.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-gray-400",children:J("用户名(登录账号)","Username (login)")}),r.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title: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:J("角色","Role")}),r.jsx("span",{className:"text-sm font-medium text-gray-700",children:se})]})]})]})]})}const g2=b.lazy(()=>Ye(()=>import("./student-workspace-BFPfR77J.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(e=>({default:e.StudentWorkspace}))),Hm="studentShell",qm="workspace";function Gm(e){try{const t=e??(typeof window<"u"?window.location.search:"");return new URLSearchParams(t).get(Hm)===qm}catch{return!1}}function kh(){const e=Ot(),t=e?.session??null,n=e?.activeStudentId||t?.studentId||t?.userId||"";if(!t||!n)return r.jsx("div",{className:"flex-1 flex items-center justify-center p-8 text-sm text-subtle",children:r.jsx("span",{children:"学生身份未就绪,无法打开 Student Workspace 预览。"})});const s=e?.lang==="en"?"en":"zh";return r.jsxs("div",{"data-testid":"student-workspace-preview",className:"flex-1 min-h-0 flex flex-col",children:[r.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold bg-amber-50 text-amber-800 border-b border-amber-200",children:"Student Workspace 预览壳(C 组迁移中,功能不等价于现有学生端)"}),r.jsx(b.Suspense,{fallback:r.jsxs("div",{className:"flex-1 flex items-center justify-center gap-2 text-subtle",children:[r.jsx(dt,{className:"w-5 h-5 animate-spin"}),r.jsx("span",{className:"text-sm",children:"正在加载预览壳…"})]}),children:r.jsx(g2,{student:{id:n,name:t.name??""},lessonId:e?.selectedLesson??void 0,lang:s})})]})}const x2=Object.freeze(Object.defineProperty({__proto__:null,STUDENT_WORKSPACE_PREVIEW_QUERY:Hm,STUDENT_WORKSPACE_PREVIEW_VALUE:qm,StudentWorkspacePreview:kh,default:kh,isStudentWorkspacePreviewEnabled:Gm},Symbol.toStringTag,{value:"Module"})),b2=b.lazy(()=>Ye(()=>import("./StudentView-mMwGPiiF.js").then(e=>e.S),__vite__mapDeps([10,1,2,6,8])).then(e=>({default:e.StudentView}))),y2=b.lazy(()=>Ye(()=>import("./TeacherView-ofB-3SEJ.js").then(e=>e.T),__vite__mapDeps([11,1,2,6])).then(e=>({default:e.TeacherView}))),w2=b.lazy(()=>Ye(()=>Promise.resolve().then(()=>x2),void 0).then(e=>({default:e.StudentWorkspacePreview})));function v2(e){const{activeRole:t}=e,n=t==="student"&&Gm();return r.jsx(b.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(dt,{className:"w-8 h-8 animate-spin text-indigo-500"}),r.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?n?r.jsx(w2,{}):r.jsx(b2,{}):r.jsx(y2,{})})}const ti="openlearn_agent_persona_id";function S2(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:i,expandedClassId:o,fetchLessons:a,fetchClasses:l,fetchStudents:c,fetchClassStudents:u,fetchClassProgress:d,fetchClassDashboard:f,fetchElements:m}=e,[h,y]=b.useState([{role:"agent",content:n.agentIntro||""}]),[p,x]=b.useState(""),[g,v]=b.useState(!1),[w,E]=b.useState([]),[N,j]=b.useState(()=>{try{return localStorage.getItem(ti)||""}catch{return""}}),I=b.useCallback(U=>{j(U);try{U?localStorage.setItem(ti,U):localStorage.removeItem(ti)}catch{}},[]);b.useEffect(()=>{h.length===1&&h[0].role==="agent"&&y([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const z=b.useCallback(async U=>{try{const k=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(U||"")}`);if(!k.ok)return;const F=await k.json(),Z=Array.isArray(F.messages)?F.messages:[];Z.length>0?y(Z.map(M=>({role:M.role==="assistant"?"agent":"user",content:M.content??""}))):y([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),$=b.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(s||"")}`,{method:"DELETE"})}catch{}y([{role:"agent",content:n.agentIntro}])},[s,n.agentIntro]);return b.useEffect(()=>{z(s)},[s,z]),{personaId:N,setPersonaId:I,chatLog:h,setChatLog:y,input:p,setInput:x,loading:g,setLoading:v,chatAttachments:w,setChatAttachments:E,handleChatFileChange:U=>{U.target.files&&Array.from(U.target.files).forEach(k=>{const F=new FileReader;F.onload=Z=>{Z.target?.result&&E(M=>[...M,{name:k.name,content:Z.target.result}])},k.name.endsWith(".zip")?F.readAsDataURL(k):F.readAsText(k)})},handleChatDrop:U=>{U.preventDefault(),U.dataTransfer.files&&Array.from(U.dataTransfer.files).forEach(k=>{const F=new FileReader;F.onload=Z=>{Z.target?.result&&E(M=>[...M,{name:k.name,content:Z.target.result}])},k.name.endsWith(".zip")?F.readAsDataURL(k):F.readAsText(k)})},handleSend:async U=>{if(U.preventDefault(),!p.trim()||g)return;const k=[...w];let F=p;k.length>0&&(F+=`
|
|
106
|
+
(📁 ${t==="zh"?"附件":"Attachments"}: ${k.map(Z=>Z.name).join(", ")})`),y(Z=>[...Z,{role:"user",content:F}]),x(""),E([]),v(!0);try{const Z=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:p,lang:t,currentLessonId:s,attachments:k,providerId:i||null,personaId:N||null})}),M=await Z.json();let A="";if(!Z.ok||M.success===!1)A=`⚠️ ${M.message||M.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`;else{if(M.personaFallback){const L=typeof M.personaFallback.fallbackPersonaId=="string"?M.personaFallback.fallbackPersonaId:"";I(L),window.dispatchEvent(new CustomEvent("openlearn:personas-updated")),A+=t==="zh"?`ℹ️ 当前选定的助教角色已停用或被删除,系统已自动回退至可用默认角色继续为您服务。
|
|
107
|
+
|
|
108
|
+
`:`ℹ️ The previously selected assistant persona was disabled or removed. Automatically switched to an active default persona.
|
|
109
|
+
|
|
110
|
+
`}A+=M.agentText||"",M.toolResults&&M.toolResults.length>0&&(A+=`
|
|
111
|
+
|
|
112
|
+
${n.executedCommands}`+M.toolResults.map(L=>L.callName).join(", "))}y(L=>[...L,{role:"agent",content:A}]),await a(),await l(),await c(),o&&(await u(o),await d(o),await f(o)),s&&await m(s)}catch{y(Z=>[...Z,{role:"agent",content:n.simulationError}])}finally{v(!1)}},handleClearAgentMemory:$,restoreAgentMemory:z}}const k2=(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 j2({setInput:e,currentInput:t,lang:n="zh"}){const s=Re(y=>y.extensionPoints),[i,o]=b.useState(!1),[a,l]=b.useState(null),[c,u]=b.useState({}),d=b.useMemo(()=>s.get("ai.prompt.template")??[],[s]),f=n==="zh",m=d.find(y=>y.id===a);if(d.length===0)return null;const h=(y,p)=>{const x=y.slotProps?.prompt??"",g=k2(x,y.slotProps?.parameters,p);e(t?`${t.trimEnd()}
|
|
113
|
+
|
|
114
|
+
${g}`:g),o(!1),l(null),u({})};return r.jsxs("div",{className:"relative shrink-0",children:[r.jsx("button",{type:"button",onClick:()=>o(!i),disabled:a!==null&&!!m,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:f?"插件提示词模板":"Plugin prompt templates",children:r.jsx(N0,{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:f?"插件提示词模板":"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(De,{size:12})})]}),m?r.jsxs("div",{className:"p-3 space-y-2",children:[r.jsx("div",{className:"font-medium text-gray-800",children:m.slotProps?.title||m.id}),(m.slotProps?.parameters??[]).map(y=>r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"text-[11px] text-gray-500",children:y.label||y.name}),r.jsx("input",{value:c[y.name]??"",onChange:p=>u(x=>({...x,[y.name]:p.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:y.default||y.name})]},y.name)),r.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[r.jsx("button",{type:"button",onClick:()=>h(m,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:f?"插入到输入框":"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:f?"返回":"Back"})]})]}):r.jsx("div",{className:"py-1",children:d.map(y=>{const p=y.slotProps?.title||y.id,x=y.slotProps?.description;return r.jsxs("button",{type:"button",onClick:()=>{const g=y.slotProps?.parameters??[];if(g.length>0){const v={};for(const w of g)w.default&&(v[w.name]=w.default);u(v),l(y.id)}else h(y,{})},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:p}),x&&r.jsx("div",{className:"text-[11px] text-gray-500 mt-0.5 line-clamp-2",children:x})]},y.id)})})]})]})}function N2(e={}){const t=Ot(),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??"",u=e.setPersonaId??t?.setPersonaId??(()=>{}),d=e.aiProviders??t?.aiProviders??[],f=e.selectedAgentProvider!==void 0?e.selectedAgentProvider:t?.selectedAgentProvider??null,m=e.chatLog??t?.chatLog??[],h=e.loading??t?.loading??!1,y=e.input??t?.input??"",p=e.setInput??t?.setInput??(()=>{}),x=e.handleSend??t?.handleSend??(async()=>{}),g=e.chatAttachments??t?.chatAttachments??[],v=e.setChatAttachments??t?.setChatAttachments??(()=>{}),w=e.handleChatFileChange??t?.handleChatFileChange??(()=>{}),E=e.handleChatDrop??t?.handleChatDrop??(()=>{}),N=e.onClearAgentMemory??t?.handleClearAgentMemory??(()=>{}),j=e.events??t?.events??[],I=e.lang??t?.lang??"zh",z=e.t??t?.t??{},$=b.useRef(null);b.useEffect(()=>{$.current?.scrollIntoView?.({behavior:"smooth"})},[m]);const[V,B]=b.useState([]),[_,U]=b.useState(0);return b.useEffect(()=>{const k=()=>U(F=>F+1);return window.addEventListener("openlearn:personas-updated",k),()=>window.removeEventListener("openlearn:personas-updated",k)},[]),b.useEffect(()=>{if(!n)return;let k=!1;return fetch("/api/agent/personas").then(F=>F.ok?F.json():null).then(F=>{if(k||!F?.success||!Array.isArray(F.personas))return;const Z=F.personas;if(B(Z),!u)return;const M=Z.some(R=>R.id==="plain_assistant"),A=typeof F.defaultPersonaId=="string"?F.defaultPersonaId:"";let L="";try{L=localStorage.getItem(ti)||""}catch{}const S=L||c;if(S)if(Z.some(R=>R.id===S))S!==c&&u(S);else{const R=A&&(A!=="plain_assistant"||!M)?A:M?"":Z[0]?.id||"";u(R)}else A&&(A!=="plain_assistant"||!M)&&u(A)}).catch(()=>{}),()=>{k=!0}},[n,_]),r.jsx("aside",{"aria-label":I==="zh"?"AI 与扩展侧栏":"AI & Extensions Sidebar",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 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(Zi,{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(Wr,{size:14})," Shell"]}),r.jsx(qe,{slot:"ai_sidebar.tab",slotProps:{renderType:"button",activeTab:i,setActiveTab:o,lang:I}}),r.jsx("button",{type:"button",onClick:()=>s(!1),"aria-label":I==="zh"?"收起右侧栏":"Collapse sidebar",className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:r.jsx(C0,{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(Zi,{size:16})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:z.agentTitle}),r.jsx("p",{className:"text-xs text-gray-500",children:z.agentSubtitle}),r.jsxs("button",{onClick:N,title:I==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",I==="zh"?"清除记忆":"Clear memory"]})]})]}),r.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[r.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-gray-400",children:I==="zh"?"AI 提供商":"AI Provider"}),r.jsxs("div",{className:"relative w-full",children:[d.length===0?r.jsx("select",{disabled:!0,value:"",className:"w-full appearance-none rounded-xl border border-amber-200 bg-amber-50/50 px-3 py-2 pr-9 text-xs font-medium text-amber-700 shadow-xs outline-none cursor-not-allowed",children:r.jsx("option",{value:"",children:I==="zh"?"未配置 AI 提供商":"No AI Provider"})}):r.jsx("select",{value:a,onChange:k=>l(k.target.value),className:"w-full appearance-none rounded-xl border border-gray-200 bg-gradient-to-b from-white to-gray-50 px-3 py-2 pr-9 text-xs font-medium text-gray-700 shadow-xs outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:d.map(k=>{const F=k.is_shared?I==="zh"?"· 平台共享":"· Shared":I==="zh"?"· 私有":"· Private";return r.jsxs("option",{value:k.id,children:[k.name," (",F.trim(),")"]},k.id)})}),r.jsx(Gn,{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:f?.model_name||"",children:f?`${f.model_name}`:I==="zh"?"未配置提供商":"No Provider"})]})]})}),u&&V.length>0&&(()=>{const k=V.find(Z=>Z.id===(c||"plain_assistant"))??V.find(Z=>Z.id===c),F=k&&(I==="zh"?k.descriptionZh:k.descriptionEn)||"";return r.jsxs("div",{className:"mx-4 mb-3",children:[r.jsx("label",{htmlFor:"right-sidebar-persona-select",className:"sr-only",children:I==="zh"?"选择 AI 助教角色":"Select AI Assistant Persona"}),r.jsxs("select",{id:"right-sidebar-persona-select",name:"personaId",value:c||"",onChange:Z=>{const M=Z.target.value;u(M);const A=V.find(L=>L.id===(M||"plain_assistant"));A?.preferredProviderId&&d.some(L=>L.id===A.preferredProviderId)&&l(A.preferredProviderId)},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:[V.some(Z=>Z.id==="plain_assistant")&&r.jsx("option",{value:"",children:I==="zh"?"🤖 助教角色:默认":"🤖 Persona: Default"}),V.filter(Z=>Z.id!=="plain_assistant").map(Z=>r.jsxs("option",{value:Z.id,children:[Z.icon||"🎯"," ",I==="zh"?Z.nameZh:Z.nameEn]},Z.id))]}),(F||k?.preferredProviderName)&&r.jsxs("p",{className:"mt-1 px-1 text-[11px] leading-snug text-gray-500",children:[F,k?.preferredProviderName&&r.jsx("span",{className:"ml-1 inline-block text-indigo-600 font-medium",children:I==="zh"?`(推荐模型:${k.preferredProviderName})`:`(Recommended model: ${k.preferredProviderName})`})]})]})})(),d.length===0&&r.jsxs("div",{className:"mx-4 mt-3 p-3 bg-amber-50 border border-amber-200/80 rounded-xl text-xs text-amber-900 flex items-start gap-2 shadow-xs shrink-0",children:[r.jsx(Bt,{size:15,className:"shrink-0 text-amber-600 mt-0.5"}),r.jsxs("div",{className:"flex-1 leading-relaxed",children:[r.jsx("span",{className:"font-semibold",children:I==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),r.jsx("p",{className:"mt-0.5 text-amber-700",children:I==="zh"?"请前往「系统管理 -> AI 配置」添加大模型服务(如 DeepSeek、Qwen、OpenAI 等)。":'Please configure an AI provider in "System Management -> AI Config" to use the AI assistant.'})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[m.map((k,F)=>r.jsx("div",{className:`flex flex-col ${k.role==="user"?"items-end":"items-start"}`,children:r.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${k.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:k.content})},F)),h&&r.jsx("div",{className:"flex items-start",children:r.jsxs("div",{className:"px-4 py-2.5 rounded-2xl max-w-[85%] text-xs bg-gray-100 text-gray-500 rounded-bl-none flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),r.jsx("div",{ref:$})]}),r.jsxs("form",{onSubmit:x,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:k=>k.preventDefault(),onDrop:E,children:[g.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:g.map((k,F)=>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(nf,{size:10,className:"shrink-0"}),r.jsx("span",{className:"truncate max-w-[100px]",title:k.name,children:k.name}),r.jsx("button",{type:"button",onClick:()=>v(Z=>Z.filter((M,A)=>A!==F)),className:"hover:bg-indigo-200 rounded-full p-0.5 cursor-pointer ml-0.5 transition-colors text-indigo-400 hover:text-indigo-600",children:r.jsx(De,{size:10})})]},F))}),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(E0,{size:14}),r.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:w,accept:".csv,.txt,.json,.md"})]}),r.jsx(j2,{setInput:p,currentInput:y,lang:I}),r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"text",value:y,disabled:d.length===0,onChange:k=>p(k.target.value),placeholder:d.length===0?I==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":z.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||!y.trim()||d.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(sf,{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(Wr,{size:14}),r.jsx("span",{className:"text-xs",children:z.eventStream})]})}),r.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:j.length===0?r.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):j.map((k,F)=>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(k.timestamp).toLocaleTimeString(),"]"]}),r.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:k.source,children:k.source})]}),r.jsx("div",{className:"text-green-300 font-bold",children:k.type}),r.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:k.payload})]},F))})]}):r.jsx("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-4",children:r.jsx(qe,{slot:"ai_sidebar.tab",slotProps:{renderType:"panel",activeTab:i,lang:I}})})]}):r.jsxs("button",{type:"button",onClick:()=>s(!0),"aria-label":I==="zh"?"OS Core Options · 展开 AI 与扩展侧栏":"OS Core Options · Expand AI & Extensions Sidebar",className:"flex flex-col items-center py-6 h-full text-subtle w-full cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:[r.jsx(Zi,{size:18,className:"mb-6 hover:text-indigo-500","aria-hidden":"true"}),r.jsx(Wr,{size:18,className:"hover:text-indigo-500","aria-hidden":"true"}),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 C2=b.lazy(()=>Ye(()=>import("./ImportModal-DNaPHV0I.js"),__vite__mapDeps([12,1,2,6,8,9])).then(e=>({default:e.ImportModal}))),E2=b.lazy(()=>Ye(()=>import("./CourseWizardModal-DmQu237c.js"),__vite__mapDeps([13,1,2,6,8,9])).then(e=>({default:e.CourseWizardModal}))),I2=b.lazy(()=>Ye(()=>import("./ImportLessonsModal-p8Uc1U_h.js"),__vite__mapDeps([14,1,2,6,8,9])).then(e=>({default:e.ImportLessonsModal}))),A2=b.lazy(()=>Ye(()=>import("./QuizGeneratorModal-Lf5QMvkq.js"),__vite__mapDeps([15,1,2,6,8,9])).then(e=>({default:e.QuizGeneratorModal}))),T2=b.lazy(()=>Ye(()=>import("./ProcessLogsModal-D-Ez_YZA.js"),__vite__mapDeps([16,1,2,6,8,9])).then(e=>({default:e.ProcessLogsModal}))),_2=b.lazy(()=>Ye(()=>import("./CloudDriveModal-GNZzWVCP.js"),__vite__mapDeps([17,1,2,18,6,8,9])).then(e=>({default:e.CloudDriveModal}))),P2=b.lazy(()=>Ye(()=>import("./SystemResourceLibraryModal-LUDNOwgW.js"),__vite__mapDeps([19,1,2,17,18,6,8,9])).then(e=>({default:e.SystemResourceLibraryModal}))),z2=b.lazy(()=>Ye(()=>import("./BatchPickerModal-Cw4OZqOJ.js"),__vite__mapDeps([20,1,2,6,8,9])).then(e=>({default:e.BatchPickerModal}))),R2=b.lazy(()=>Ye(()=>import("./ExportWeightModal-C0SuUhHM.js"),__vite__mapDeps([21,1,2,6,8,9])).then(e=>({default:e.ExportWeightModal}))),L2=b.lazy(()=>Ye(()=>import("./NotificationDetailModal-BVYuS4uR.js"),__vite__mapDeps([22,1,2,6,8,9])).then(e=>({default:e.NotificationDetailModal}))),O2=b.lazy(()=>Ye(()=>import("./HelpTour-D8hVFA6N.js"),__vite__mapDeps([23,1,2,6])).then(e=>({default:e.HelpTour}))),D2=b.lazy(()=>Ye(()=>import("./CoursewareHubPanel-Xn5WbXg9.js"),__vite__mapDeps([24,1,2,6,8,9])).then(e=>({default:e.CoursewareHubPanel})));function $2(e={}){const t=Ot(),{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:u=t?.isImporting??!1,downloadCSVTemplate:d=t?.downloadCSVTemplate??(()=>{}),addToast:f=t?.addToast??(()=>{}),isImportLessonsOpen:m=t?.isImportLessonsOpen??!1,setIsImportLessonsOpen:h=t?.setIsImportLessonsOpen??(()=>{}),importStatus:y=t?.importStatus??"idle",setIsDraggingImport:p=t?.setIsDraggingImport??(()=>{}),handleCSVFileChange:x=t?.handleCSVFileChange??(()=>{}),handleImportFileChange:g=t?.handleImportFileChange??(()=>{}),downloadCsvTemplate:v=t?.downloadCsvTemplate??(()=>{}),downloadCourseTemplate:w=t?.downloadCourseTemplate??(()=>{}),packagePreview:E=t?.packagePreview??null,handlePackageImportSubmit:N=t?.handlePackageImportSubmit??(()=>{}),packageDuplicate:j=t?.packageDuplicate??null,handlePackageDuplicateDismiss:I=t?.handlePackageDuplicateDismiss??(()=>{}),isDraggingImport:z=t?.isDraggingImport??!1,previewImportData:$=t?.previewImportData??[],setPreviewImportData:V=t?.setPreviewImportData??(()=>{}),setImportStatus:B=t?.setImportStatus??(()=>{}),importProgress:_=t?.importProgress??0,importProgressTotal:U=t?.importProgressTotal??0,importErrorMsg:k=t?.importErrorMsg??"",setImportErrorMsg:F=t?.setImportErrorMsg??(()=>{}),handleCSVImportSubmit:Z=t?.handleCSVImportSubmit??(()=>{}),lessons:M=t?.lessons??[],fetchClassDashboard:A=t?.fetchClassDashboard??(()=>{}),currentVfsParent:L=t?.currentVfsParent??null,setCurrentVfsParent:S=t?.setCurrentVfsParent??(()=>{}),vfsNodes:R=t?.vfsNodes??[],showProcessLogs:D=t?.showProcessLogs??null,setShowProcessLogs:P=t?.setShowProcessLogs??(()=>{}),processLogsContent:Y=t?.processLogsContent??"",isCloudDriveOpen:H=t?.isCloudDriveOpen??!1,setIsCloudDriveOpen:ee=t?.setIsCloudDriveOpen??(()=>{}),cloudDrivePreviewNode:le=t?.cloudDrivePreviewNode??null,setCloudDrivePreviewNode:ae=t?.setCloudDrivePreviewNode??(()=>{}),isSystemResourceLibraryOpen:fe=t?.isSystemResourceLibraryOpen??!1,setIsSystemResourceLibraryOpen:be=t?.setIsSystemResourceLibraryOpen??(()=>{}),systemResourceTab:ye=t?.systemResourceTab??"system",setSystemResourceTab:Se=t?.setSystemResourceTab??(()=>{}),selectedLibraryResourceId:me=t?.selectedLibraryResourceId??null,setSelectedLibraryResourceId:C=t?.setSelectedLibraryResourceId??(()=>{}),loadingLibraryResources:J=t?.loadingLibraryResources??!1,libraryResources:se=t?.libraryResources??[],fetchLibraryResources:W=t?.fetchLibraryResources??(()=>{}),classes:T=t?.classes??[],expandedClassId:q=t?.expandedClassId??null,isExportWeightModalOpen:X=t?.isExportWeightModalOpen??!1,setIsExportWeightModalOpen:ne=t?.setIsExportWeightModalOpen??(()=>{}),quizzesWeight:Q=t?.quizzesWeight??40,setQuizzesWeight:re=t?.setQuizzesWeight??(()=>{}),assignmentsWeight:de=t?.assignmentsWeight??60,setAssignmentsWeight:te=t?.setAssignmentsWeight??(()=>{}),handleQuizzesWeightChange:O=t?.handleQuizzesWeightChange??(()=>{}),handleAssignmentsWeightChange:G=t?.handleAssignmentsWeightChange??(()=>{}),customCategoryOverrides:ie=t?.customCategoryOverrides??{},setCustomCategoryOverrides:ue=t?.setCustomCategoryOverrides??(()=>{}),classDashboardMap:he=t?.classDashboardMap??{},exportClassId:K=t?.exportClassId??"",exportClassName:we=t?.exportClassName??"",csvPreviewData:oe=t?.csvPreviewData??null,handleExportGrades:ce=t?.handleExportGrades??(()=>{}),setSelectedAssignment:pe=t?.setSelectedAssignment??(()=>{}),setStudentViewStatus:xe=t?.setStudentViewStatus??(()=>{}),setQuizStudentAnswers:ve=t?.setQuizStudentAnswers??(()=>{}),setSubAssignmentTab:_e=t?.setSubAssignmentTab??(()=>{}),isTourOpen:je=t?.isTourOpen??!1,setIsTourOpen:Me=t?.setIsTourOpen??(()=>{}),dismissTour:et=t?.dismissTour,handleSeedSuccess:Be=t?.handleSeedSuccess??(()=>{}),setTeacherTab:st=t?.setTeacherTab??(()=>{}),showCoursewareHub:ft=t?.showCoursewareHub??!1,setShowCoursewareHub:Cn=t?.setShowCoursewareHub??(()=>{})}=e,Ve=e.courseWizard??t,ns=Ve?.isCourseWizardOpen??e.isCourseWizardOpen??!1,ss=Ve?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),rs=Ve?.wizardStep??e.wizardStep??1,En=Ve?.setWizardStep??e.setWizardStep??(()=>{}),is=Ve?.wizardIsSubmitting??e.wizardIsSubmitting??!1,In=Ve?.wizardCourseTitle??e.wizardCourseTitle??"",os=Ve?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),as=Ve?.wizardCourseDescription??e.wizardCourseDescription??"",ls=Ve?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Ut=Ve?.wizardCourseCategory??e.wizardCourseCategory??"",An=Ve?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),rn=Ve?.wizardCourseTimeline??e.wizardCourseTimeline??[],cs=Ve?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),ds=Ve?.wizardCourseContent??e.wizardCourseContent??"",Vt=Ve?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),Tn=Ve?.wizardIsGeneratingOutline??e.wizardIsGeneratingOutline??!1,_n=Ve?.handleGenerateOutline??e.handleGenerateOutline??(async()=>{}),us=Ve?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),We=e.quizGenerator??t,hs=We?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,fs=We?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),ms=We?.quizGenMode??e.quizGenMode??"scan_lesson",ps=We?.setQuizGenMode??e.setQuizGenMode??(()=>{}),gs=We?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",xs=We?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),bs=We?.quizGenTopic??e.quizGenTopic??"",ys=We?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),ws=We?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,vs=We?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),Ss=We?.suggestedObjectives??e.suggestedObjectives??[],ks=We?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),Pe=We?.suggestedQuestions??e.suggestedQuestions??[],rt=We?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),on=We?.quizGenTimeLimit??e.quizGenTimeLimit??0,Ae=We?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),tt=We?.savingQuiz??e.savingQuiz??!1,at=We?.setSavingQuiz??e.setSavingQuiz??(()=>{}),an=We?.quizGeneratorClassId??e.quizGeneratorClassId??null,Qe=e.classBatch??t,mt=Qe?.batchPicker??e.batchPicker??null,ln=Qe?.setBatchPicker??e.setBatchPicker??(()=>{}),Wt=Qe?.batchPickerLesson??e.batchPickerLesson??"",Fi=Qe?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),dr=Qe?.batchPickerDate??e.batchPickerDate??"",Bi=Qe?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),ur=Qe?.batchPickerTargetClass??e.batchPickerTargetClass??"",Ui=Qe?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Vi=Qe?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),hr=e.studentNotificationsHook??t,Wi=hr?.selectedNotificationForModal??e.selectedNotificationForModal??null,Hi=hr?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return r.jsxs(b.Suspense,{fallback:null,children:[r.jsx(C2,{show:i,onClose:()=>o(!1),lang:n,handleImportFile:a,importError:l,importSuccess:c,isImporting:u,downloadCSVTemplate:d}),r.jsx(E2,{isCourseWizardOpen:ns,setIsCourseWizardOpen:ss,lang:n,wizardStep:rs,setWizardStep:En,wizardIsSubmitting:is,wizardCourseTitle:In,setWizardCourseTitle:os,wizardCourseDescription:as,setWizardCourseDescription:ls,wizardCourseCategory:Ut,setWizardCourseCategory:An,wizardCourseTimeline:rn,setWizardCourseTimeline:cs,wizardCourseContent:ds,setWizardCourseContent:Vt,addToast:f,wizardIsGeneratingOutline:Tn,handleGenerateOutline:_n,handleDeployWizardCourse:us}),r.jsx(I2,{isImportLessonsOpen:m,setIsImportLessonsOpen:h,lang:n,importStatus:y,setIsDraggingImport:p,handleCSVFileChange:x,handleImportFileChange:g,downloadCsvTemplate:v,downloadCourseTemplate:w,packagePreview:E,handlePackageImportSubmit:N,packageDuplicate:j,handlePackageDuplicateDismiss:I,isDraggingImport:z,previewImportData:$,setPreviewImportData:V,setImportStatus:B,importProgress:_,importProgressTotal:U,importErrorMsg:k,setImportErrorMsg:F,handleCSVImportSubmit:Z}),r.jsx(A2,{isQuizGeneratorOpen:hs,setIsQuizGeneratorOpen:fs,lessons:M,quizGenMode:ms,setQuizGenMode:ps,quizGenSelectedLessonId:gs,setQuizGenSelectedLessonId:xs,quizGenTopic:bs,setQuizGenTopic:ys,isGeneratingSuggestions:ws,setIsGeneratingSuggestions:vs,suggestedObjectives:Ss,setSuggestedObjectives:ks,suggestedQuestions:Pe,setSuggestedQuestions:rt,quizGenTimeLimit:on,setQuizGenTimeLimit:Ae,savingQuiz:tt,setSavingQuiz:at,quizGeneratorClassId:an,fetchClassDashboard:A}),r.jsx(T2,{showProcessLogs:D,setShowProcessLogs:P,processLogsContent:Y,t:s}),r.jsx(_2,{isOpen:H,onClose:()=>ee(!1),vfsNodes:R,currentVfsParent:L,setCurrentVfsParent:S,cloudDrivePreviewNode:le,setCloudDrivePreviewNode:ae}),r.jsx(P2,{isSystemResourceLibraryOpen:fe,setIsSystemResourceLibraryOpen:be,lang:n,systemResourceTab:ye,setSystemResourceTab:Se,selectedLibraryResourceId:me,setSelectedLibraryResourceId:C,vfsNodes:R,currentVfsParent:L,setCurrentVfsParent:S,cloudDrivePreviewNode:le,setCloudDrivePreviewNode:ae,loadingLibraryResources:J,libraryResources:se,fetchLibraryResources:W}),r.jsx(z2,{batchPicker:mt,setBatchPicker:ln,batchPickerLesson:Wt,setBatchPickerLesson:Je=>Fi(typeof Je=="function"?Je(Wt):Je),batchPickerDate:dr,setBatchPickerDate:Je=>Bi(typeof Je=="function"?Je(dr):Je),batchPickerTargetClass:ur,setBatchPickerTargetClass:Je=>Ui(typeof Je=="function"?Je(ur):Je),lessons:M,classes:T,expandedClassId:q,confirmBatchPicker:Vi,lang:n}),r.jsx(R2,{isExportWeightModalOpen:X,setIsExportWeightModalOpen:ne,lang:n,quizzesWeight:Q,setQuizzesWeight:re,assignmentsWeight:de,setAssignmentsWeight:te,handleQuizzesWeightChange:O,handleAssignmentsWeightChange:G,customCategoryOverrides:ie,setCustomCategoryOverrides:ue,classDashboardMap:he,exportClassId:K,exportClassName:we,csvPreviewData:oe,handleExportGrades:ce}),r.jsx(L2,{notification:Wi,onClose:()=>Hi(null),lang:n,onOpenWorkspace:Je=>{pe(Je),xe("assignment"),ve({}),_e("quiz")}}),r.jsx(O2,{isOpen:je,onClose:()=>Me(!1),onDismiss:et,lang:n,onSeedSuccess:Be,onJumpTab:Je=>st(Je)}),ft&&r.jsx(D2,{onClose:()=>Cn(!1),lang:n})]})}const Zm="openlearn_live_classroom_sync";class Ic{constructor(t=Zm,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=jc(()=>this.ensureSocketBound())}ensureSocketBound(){if(this.isDestroyed)return;const t=yt();!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=yt();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=yt();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=yt();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=yt();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=yt();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=yt();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=yt();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=yt();i&&s&&i.emit("teacher-broadcast-fullscreen",{elementId:t,lessonId:s,classId:this.classId})}broadcastShowcaseDiff(t){this.postMessage({type:"TEACHER_SHOWCASE_DIFF_SYNC",payload:{lessonId:this.lessonId,selectedIds:t.selectedIds,layout:t.layout,works:t.works,anonymous:t.anonymous,timestamp:Date.now()}})}broadcastMacroNotification(t,n){this.postMessage({type:"TEACHER_MACRO_NOTIFICATION",payload:{lessonId:this.lessonId,title:n,message:t,timestamp:Date.now()}})}broadcastGroupCollabUpdated(t){this.postMessage({type:"GROUP_COLLAB_UPDATED",payload:{lessonId:this.lessonId,classId:this.classId,updatedAt:Date.now(),galleryMode:t}})}acknowledgePick(t){this.postMessage({type:"STUDENT_ACKNOWLEDGE_PICK",payload:{studentId:t}});const n=yt();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 M2(e){const t=await fetch(`/api/students/${e}/read_notifications`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function F2(e,t){await fetch(`/api/students/${e}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:t})})}async function B2(e,t){await fetch(`/api/students/${e}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function U2(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 V2(e){const t=await fetch(`/api/students/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}function W2(e,t,n=typeof window<"u"?window:null){const s=b.useRef(t);s.current=t,b.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 H2(){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);let o=!1;const a=()=>{o||(o=!0,t.close().catch(()=>{}))};s.onended=a,setTimeout(a,1100),s.start(n),s.stop(n+.8)}catch{}}function q2({lessonId:e,lang:t="zh",syncChannel:n}){const[s,i]=b.useState(null),[o,a]=b.useState(!1),[l,c]=b.useState(!0),[u,d]=b.useState(!1),f=b.useRef(s);f.current=s,b.useEffect(()=>{if(!e)return;let v=null,w;try{v=n||new Ic,w=v.onMessage(I=>{I.type==="TEACHER_BROADCAST_COUNTDOWN"?i(I.payload):I.type==="TEACHER_SYNC_TIMER"&&i(z=>z?{...z,timeRemaining:I.payload.timeRemaining,isRunning:I.payload.isRunning,endsAt:I.payload.isRunning?Date.now()+I.payload.timeRemaining*1e3:null}:{lessonId:e,totalDuration:Math.max(300,I.payload.timeRemaining),timeRemaining:I.payload.timeRemaining,isRunning:I.payload.isRunning,isPaused:!1,label:t==="zh"?"⏱️ 课堂限时任务":"⏱️ Timed Task",endsAt:I.payload.isRunning?Date.now()+I.payload.timeRemaining*1e3:null,updatedAt:Date.now()})})}catch{}(async()=>{try{const I=await fetch(`/api/classroom/sessions/${e}/countdown`);if(I.ok){const z=await I.json();z.success&&z.countdown&&i(z.countdown)}}catch{}})();let N=null;const j=jc(I=>{const z=$=>{!$||$.lessonId&&$.lessonId!==e||i($)};N?.(),I.on("classroom:countdown_updated",z),N=()=>I.off("classroom:countdown_updated",z)});return()=>{w?.(),j(),N?.(),!n&&typeof v?.destroy=="function"&&v.destroy()}},[e,t]),W2("openlearn:countdown:updated",v=>{v&&i(v)});const m=b.useRef(null);if(b.useEffect(()=>{!s?.isRunning||!s.endsAt||m.current!==s.endsAt&&(m.current=s.endsAt,d(!1))},[s?.isRunning,s?.endsAt]),b.useEffect(()=>{if(!s||!s.isRunning||!s.endsAt)return;const v=setInterval(()=>{const w=f.current;if(!w||!w.isRunning||!w.endsAt)return;const E=Date.now(),N=Math.max(0,Math.round((w.endsAt-E)/1e3));if(N!==w.timeRemaining){const j={...w,timeRemaining:N,updatedAt:E};N<=0&&(j.isRunning=!1,j.isPaused=!1,j.endsAt=null,l&&!u&&(H2(),d(!0))),i(j);try{window.dispatchEvent(new CustomEvent("openlearn:student:countdown_tick",{detail:{timeRemaining:N,totalDuration:w.totalDuration,label:w.label}}))}catch{}}},500);return()=>clearInterval(v)},[s?.isRunning,s?.endsAt,l,u]),!s||s.timeRemaining===0&&!s.isRunning&&!u)return null;const h=v=>{const w=Math.floor(v/60),E=v%60,N=j=>j.toString().padStart(2,"0");return`${N(w)}:${N(E)}`},y=s.totalDuration>0?Math.min(100,Math.max(0,s.timeRemaining/s.totalDuration*100)):0,p=s.timeRemaining>0&&s.timeRemaining<=60,x=s.timeRemaining>60&&s.timeRemaining<=180,g=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 ${p?"border-rose-500/80 shadow-rose-500/20":x?"border-amber-500/80 shadow-amber-500/20":g?"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 ${p?"bg-rose-500 animate-pulse":x?"bg-amber-500":g?"bg-emerald-500":"bg-primary-theme"}`,children:r.jsx(er,{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(I0,{size:12}):r.jsx(A0,{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(Gn,{size:12}):r.jsx(Qh,{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 ${p?"text-rose-500 animate-pulse":x?"text-amber-500":g?"text-emerald-500":"text-primary-theme"}`,children:h(s.timeRemaining)}),r.jsx("span",{className:"text-[11px] font-semibold text-muted",children:g?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 ${p?"bg-rose-500":x?"bg-amber-500":g?"bg-emerald-500":"bg-primary-theme"}`,style:{width:`${y}%`}})}),r.jsx(qe,{slot:"student.classroom.countdown",slotProps:{countdown:s,lang:t}})]})]})})}const G2=({isOpen:e,onClose:t,lessonId:n,studentName:s="我",lang:i="zh",coreQuestion:o,challengeQuestion:a,onSubmitSuccess:l})=>{const[c,u]=b.useState(null),[d,f]=b.useState(!1),[m,h]=b.useState(null),y=!!o,p=y&&!!a,[x,g]=b.useState(null),[v,w]=b.useState(5),[E,N]=b.useState(""),[j,I]=b.useState(""),[z,$]=b.useState(!1),[V,B]=b.useState(!1),_=()=>{if(!c||!o)return;const F=c===o.correctOption;h(F),f(!0)},U=async()=>{if(z)return;$(!0);const F=y?m?x?"challenge_done":"passed":"remediation":null;try{n&&await fetch(`/api/classroom/sessions/${n}/exit-ticket`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rating:v,puzzledConcept:E.trim(),feedback:j.trim(),...y?{coreAnswer:c,isCorrect:m,tierLevel:F,challengeAnswer:x}:{}})}),B(!0),l?.()}catch{B(!0),l?.()}finally{$(!1)}},k=()=>{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(bt,{size:20}),r.jsx("span",{children:i==="zh"?"60 秒自适应结课通票 (Adaptive Exit Ticket)":"60s Adaptive Exit Ticket"})]}),r.jsx("button",{onClick:k,className:"text-muted hover:text-main rounded-lg p-1 cursor-pointer","aria-label":"Close",children:r.jsx(De,{size:18})})]}),V?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(bt,{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:k,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. 核心概念过关题"})]}),d&&r.jsx("span",{className:`text-2xs font-bold px-2 py-0.5 rounded-full ${m?"bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300":"bg-rose-100 text-rose-700 dark:bg-rose-950 dark:text-rose-300"}`,children:m?"✓ 概念通关":"需巩固"})]}),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(F=>r.jsxs("button",{type:"button",disabled:d,onClick:()=>u(F.key),className:`w-full p-2.5 rounded-xl border text-left flex items-start gap-2.5 transition-all cursor-pointer ${c===F.key?"border-indigo-500 bg-indigo-50/50 dark:bg-indigo-950/40 font-bold text-indigo-700 dark:text-indigo-300":"border-border/60 hover:bg-surface text-main"} ${d?"cursor-default opacity-90":""}`,children:[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:F.key}),r.jsx("span",{className:"text-2xs leading-relaxed",children:F.text})]},F.key))}),!d&&r.jsxs("button",{type:"button",disabled:!c,onClick:_,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(qn,{size:12})]}),d&&m&&p&&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(ut,{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(F=>r.jsxs("button",{type:"button",onClick:()=>g(F.key),className:`p-2 rounded-lg border text-left text-2xs transition-colors ${x===F.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:[F.key,"."]}),r.jsx("span",{children:F.text})]},F.key))})]}),d&&!m&&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(Xs,{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(F=>r.jsx("button",{type:"button",onClick:()=>w(F),"aria-label":`${F} 星`,"aria-pressed":F===v,className:"p-0.5 text-xl transition-transform hover:scale-125 cursor-pointer",children:r.jsx(di,{size:20,className:F<=v?"text-amber-400 fill-amber-400":"text-slate-300"})},F)),r.jsxs("span",{className:"text-2xs font-bold text-amber-700 dark:text-amber-400 font-mono ml-1",children:[v,".0 星"]})]})]}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsx("label",{className:"text-2xs font-bold text-main",children:i==="zh"?"3. 今天最困惑或没完全搞懂的知识点/卡点是什么?":"Most Confused Concept"}),r.jsx("input",{type:"text",value:E,onChange:F=>N(F.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:j,onChange:F=>I(F.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:z,onClick:U,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:z?i==="zh"?"正在提交...":"Submitting...":i==="zh"?"提交自适应结课通票":"Submit Exit Ticket"})})]})]})}):null};class kl extends Error{constructor(t,n){super(n),this.name="ApiError",this.status=t}}async function Oe(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 kl(n.status,i?.error||`HTTP ${n.status}`);return i}const Xt={listQuestionTypes:()=>Oe("/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 Oe(`/api/assessments${n?`?${n}`:""}`)},get:e=>Oe(`/api/assessments/${encodeURIComponent(e)}`),create:e=>Oe("/api/assessments",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>Oe(`/api/assessments/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)}),remove:e=>Oe(`/api/assessments/${encodeURIComponent(e)}`,{method:"DELETE"}),replaceItems:(e,t)=>Oe(`/api/assessments/${encodeURIComponent(e)}/items`,{method:"PUT",body:JSON.stringify({items:t})}),listBank:e=>Oe(`/api/question-bank${e?`?type=${encodeURIComponent(e)}`:""}`),createBankItem:e=>Oe("/api/question-bank",{method:"POST",body:JSON.stringify(e)}),removeBankItem:e=>Oe(`/api/question-bank/${encodeURIComponent(e)}`,{method:"DELETE"}),getAssignments:e=>Oe(`/api/assessments/${encodeURIComponent(e)}/assignments`),getTeacherView:e=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/teacher-view`),publish:(e,t)=>Oe(`/api/assessments/${encodeURIComponent(e)}/publish`,{method:"POST",body:JSON.stringify(t)}),closeAssignment:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/close`,{method:"POST"}),releaseScores:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/release`,{method:"POST"}),syncGradebook:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/sync-gradebook`,{method:"POST"}),getAssignmentProgress:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/progress`),listAttempts:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`),stats:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/stats`),gradeAnswer:(e,t,n)=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/grade`,{method:"PUT",body:JSON.stringify(n)}),aiSuggestGrade:(e,t)=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}/ai-suggest`,{method:"POST"}),regrade:e=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/regrade`,{method:"POST"}),exportCsvUrl:e=>`/api/assessment-assignments/${encodeURIComponent(e)}/export?format=csv`,startClassroomAssessment:(e,t)=>Oe(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment`,{method:"POST",body:JSON.stringify(t)}),getClassroomAssessmentProgress:(e,t)=>Oe(`/api/classroom/sessions/${encodeURIComponent(e)}/assessment-progress${t?`?assignmentId=${encodeURIComponent(t)}`:""}`),myAssessments:()=>Oe("/api/me/assessments"),startAttempt:e=>Oe(`/api/assessment-assignments/${encodeURIComponent(e)}/attempts`,{method:"POST"}),reportProctor:(e,t)=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/proctor`,{method:"PUT",body:JSON.stringify(t)}),saveAnswer:(e,t,n)=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/answers/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({answer:n})}),submitAttempt:e=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/submit`,{method:"POST"}),attemptResult:e=>Oe(`/api/assessment-attempts/${encodeURIComponent(e)}/result`)},Js="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 Z2(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function wi({htmlFor:e,children:t}){return r.jsx("label",{htmlFor:e,className:"block text-xs font-semibold text-muted mb-1",children:t})}function Km({config:e,answerKey:t,onChange:n,lang:s,disabled:i,multiple:o,idPrefix:a}){const l=Z2(e),c=o?Array.isArray(t?.indexes)?t.indexes.map(Number).filter(m=>Number.isInteger(m)):[]:typeof t?.index=="number"?[t.index]:[],u=m=>n({config:{...e,options:m},answerKey:t}),d=(m,h)=>{if(o){const y=h?[...new Set([...c,m])].sort((p,x)=>p-x):c.filter(p=>p!==m);n({config:e,answerKey:y.length>0?{indexes:y}:null})}else n({config:e,answerKey:{index:m}})},f=m=>String.fromCharCode(65+m);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((m,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:y=>d(h,y.target.checked),"aria-label":`${s==="zh"?"把选项":"Mark option"} ${f(h)} ${s==="zh"?"标为正确答案":"as correct"}`,className:"shrink-0 accent-indigo-600"}),r.jsx("label",{htmlFor:`${a}-opt-${h}`,className:"sr-only",children:s==="zh"?`选项 ${f(h)}`:`Option ${f(h)}`}),r.jsx("span",{className:"text-xs font-bold text-muted w-4 shrink-0",children:f(h)}),r.jsx("input",{type:"text",value:m,disabled:i,"aria-label":s==="zh"?`选项 ${f(h)} 内容`:`Option ${f(h)} text`,onChange:y=>{const p=[...l];p[h]=y.target.value,u(p)},className:Js}),r.jsx("button",{type:"button",disabled:i||l.length<=2,onClick:()=>{const y=l.filter((p,x)=>x!==h);u(y),n({config:{...e,options:y},answerKey:null})},"aria-label":s==="zh"?`删除选项 ${f(h)}`:`Delete option ${f(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(Jn,{size:13})})]},h))]}),r.jsxs("button",{type:"button",disabled:i,onClick:()=>u([...l,s==="zh"?`选项 ${f(l.length)}`:`Option ${f(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(tr,{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 K2=e=>r.jsx(Km,{...e,multiple:!1,idPrefix:`sc-${e.lang}`}),Y2=e=>r.jsx(Km,{...e,multiple:!0,idPrefix:`mc-${e.lang}`}),Q2=({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 J2(e){const t=e.blanks;return Array.isArray(t)?t:[]}function X2(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 eI=({config:e,answerKey:t,onChange:n,lang:s,disabled:i})=>{const o=J2(e),a=X2(t,o.length),l=(c,u)=>{const d=u.map(h=>h.split("|").map(y=>y.trim()).filter(Boolean)),f=d.some(h=>h.length>0),m=c.map((h,y)=>d[y]??[]);n({config:{...e,blanks:c},answerKey:f&&m.every(h=>h.length>0)?{blanks:m}: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,u)=>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(wi,{htmlFor:`fb-accepted-${c.id}`,children:s==="zh"?`第 ${u+1} 空的可接受答案`:`Accepted answers for blank ${u+1}`}),r.jsx("input",{id:`fb-accepted-${c.id}`,type:"text",value:a[u]??"",disabled:i,onChange:d=>{const f=[...a];f[u]=d.target.value,l(o,f)},placeholder:s==="zh"?"光合作用 | photosynthesis":"photosynthesis",className:Js})]}),r.jsxs("div",{children:[r.jsx(wi,{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:d=>{const f=o.map((m,h)=>h===u?{...m,inputType:d.target.value}:m);l(f,a)},className:Js,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 d=o.filter((f,m)=>m!==u);l(d,a.filter((f,m)=>m!==u))},"aria-label":s==="zh"?`删除第 ${u+1} 空`:`Delete blank ${u+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(Jn,{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(tr,{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."})]})},tI=({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(wi,{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:Js})]}),r.jsxs("div",{children:[r.jsx(wi,{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:Js})]}),r.jsx("p",{className:"col-span-2 text-xs text-muted",children:n==="zh"?"简答题不自动判分,交卷后进入人工批改队列。":"Short answers are always graded manually."})]}),Ac="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 nI(e){const t=e.options;return Array.isArray(t)?t.map(n=>String(n)):[]}function sI(e){return String.fromCharCode(65+e)}const Ym=({config:e,value:t,onChange:n,lang:s,readOnly:i,multiple:o,name:a})=>{const l=nI(e),c=typeof t=="number"?t:null,u=Array.isArray(t)?t.map(Number).filter(d=>Number.isInteger(d)):[];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((d,f)=>{const m=o?u.includes(f):c===f;return r.jsxs("label",{className:`flex items-start gap-2.5 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${m?"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:m,disabled:i,onChange:h=>{if(!i)if(o){const y=h.target.checked?[...new Set([...u,f])].sort((p,x)=>p-x):u.filter(p=>p!==f);n(y)}else n(f)},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:[sI(f),"."]}),d]})]},f)}),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"})]})},rI=e=>r.jsx(Ym,{...e,multiple:!1,name:"answer-single"}),iI=e=>r.jsx(Ym,{...e,multiple:!0,name:"answer-multi"}),oI=({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)))]})},aI=({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:u=>{const d=o.map((f,m)=>m===c?u.target.value:String(a[m]??""));n(d)},className:Ac})]},l.id))})},lI=({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:`${Ac} resize-y`}),r.jsxs("p",{className:"text-2xs text-muted mt-1 text-right",children:[a.length,"/",o]})]})},cI=({value:e,onChange:t,lang:n,readOnly:s})=>{const[i,o]=Ue.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:`${Ac} resize-y font-mono`})]})},jh=["选项 A","选项 B","选项 C","选项 D"];let Nh=!1;function dI(){Nh||(Nh=!0,$t.register({type:"single_choice",label:{zh:"单选题",en:"Single choice"},category:"objective",supports:["quiz","exam","survey"],Editor:K2,Answer:rI,createDefaultConfig:()=>({options:[...jh]}),createDefaultAnswerKey:()=>({index:0})}),$t.register({type:"multiple_choice",label:{zh:"多选题",en:"Multiple choice"},category:"objective",supports:["quiz","exam","survey"],Editor:Y2,Answer:iI,createDefaultConfig:()=>({options:[...jh]}),createDefaultAnswerKey:()=>({indexes:[0]})}),$t.register({type:"true_false",label:{zh:"判断题",en:"True / false"},category:"objective",supports:["quiz","exam","survey"],Editor:Q2,Answer:oI,createDefaultConfig:()=>({trueLabel:"正确",falseLabel:"错误"}),createDefaultAnswerKey:()=>({value:!0})}),$t.register({type:"fill_blank",label:{zh:"填空题",en:"Fill in the blank"},category:"objective",supports:["quiz","exam","survey"],Editor:eI,Answer:aI,createDefaultConfig:()=>({blanks:[{id:"b1",inputType:"text"}]}),createDefaultAnswerKey:()=>null}),$t.register({type:"short_answer",label:{zh:"简答/论述",en:"Short answer"},category:"subjective",supports:["quiz","exam","survey"],Editor:tI,Answer:lI,createDefaultConfig:()=>({placeholder:"请输入你的作答",maxLength:2e3}),createDefaultAnswerKey:()=>null}))}dI();const uI=1500;function hI(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 Ch(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 fI({lang:e,onExit:t}){const n=e==="zh",[s,i]=b.useState({mode:"list"}),[o,a]=b.useState(null),[l,c]=b.useState(!1),[u,d]=b.useState(null),f=b.useCallback(async()=>{c(!0),d(null);try{const p=await Xt.myAssessments();a(p.items)}catch(p){d(p instanceof kl?p.message:String(p?.message??p))}finally{c(!1)}},[]);b.useEffect(()=>{s.mode==="list"&&f()},[s.mode,f]);const m=async p=>{d(null),c(!0);try{if(p.completed&&p.attempt){const x=await Xt.attemptResult(p.attempt.id);i({mode:"result",result:x})}else{const x=await Xt.startAttempt(p.assignmentId);i({mode:"answering",payload:x,answers:{...x.answers}})}}catch(x){d(x instanceof kl?x.message:String(x?.message??x))}finally{c(!1)}};if(s.mode==="answering")return r.jsx(Tc,{lang:e,payload:s.payload,initialAnswers:s.answers,onSubmitted:p=>i({mode:"result",result:p}),onExit:()=>i({mode:"list"})});if(s.mode==="result")return r.jsx(_c,{lang:e,result:s.result,onBack:()=>{i({mode:"list"}),f()}});const h=(o??[]).filter(p=>!p.completed),y=(o??[]).filter(p=>p.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(Wl,{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(Zn,{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 f(),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(Ci,{size:13,className:l?"animate-spin":""}),n?"刷新":"Refresh"]})]}),u&&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:u}),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(dt,{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(Zn,{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(p=>r.jsx("li",{children:r.jsx(Eh,{entry:p,lang:e,disabled:l,onOpen:()=>void m(p)})},p.assignmentId))})]}),y.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","(",y.length,")"]}),r.jsx("ul",{"data-testid":"student-completed-list",className:"space-y-2",children:y.map(p=>r.jsx("li",{children:r.jsx(Eh,{entry:p,lang:e,disabled:l,onOpen:()=>void m(p)})},p.assignmentId))})]})]})})]})}function Eh({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(er,{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($l,{size:12}),l?o?i?"已截止":"Closed":i?"未开始":"Not open":e.completed?i?"查看结果":"View result":i?"开始作答":"Start"]})]})}function Tc({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,u]=b.useState(n),[d,f]=b.useState(new Set),[m,h]=b.useState(t.attempt.remainingSeconds??null),[y,p]=b.useState(!1),[x,g]=b.useState(null),[v,w]=b.useState(null),[E,N]=b.useState(!!document.fullscreenElement),[j,I]=b.useState(0),[z,$]=b.useState(null),V=b.useRef({}),B=b.useRef(c),_=b.useRef(!1);B.current=c;const U=b.useCallback(async S=>{if(!(!l||_.current))try{I(D=>D+1),$({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!"}[S]),await Xt.reportProctor(a,{type:S})}catch{}},[a,l,o]);b.useEffect(()=>{if(!l)return;const S=()=>{document.visibilityState==="hidden"&&U("visibility_hidden")},R=()=>{U("blur")},D=()=>{const H=!!document.fullscreenElement;N(H),!H&&!_.current&&U("fullscreen_exit")},P=H=>{H.preventDefault()},Y=H=>{H.preventDefault()};return document.addEventListener("visibilitychange",S),window.addEventListener("blur",R),document.addEventListener("fullscreenchange",D),document.addEventListener("contextmenu",P),document.addEventListener("copy",Y),document.addEventListener("cut",Y),document.addEventListener("paste",Y),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("blur",R),document.removeEventListener("fullscreenchange",D),document.removeEventListener("contextmenu",P),document.removeEventListener("copy",Y),document.removeEventListener("cut",Y),document.removeEventListener("paste",Y)}},[l,U]);const k=async()=>{try{document.fullscreenElement||await document.documentElement.requestFullscreen()}catch{}},F=b.useCallback(async S=>{try{await Xt.saveAnswer(a,S,B.current[S]??null),w(Date.now()),f(R=>{const D=new Set(R);return D.delete(S),D})}catch(R){g(R?.message??String(R))}},[a]),Z=(S,R)=>{u(D=>({...D,[S]:R})),f(D=>new Set(D).add(S)),V.current[S]&&clearTimeout(V.current[S]),V.current[S]=setTimeout(()=>void F(S),uI)},M=b.useCallback(async()=>{if(!_.current){_.current=!0,p(!0),g(null);try{for(const D of Object.keys(V.current))V.current[D]&&clearTimeout(V.current[D]);const S=[...d];await Promise.all(S.map(D=>Xt.saveAnswer(a,D,B.current[D]??null)));const R=await Xt.submitAttempt(a);document.fullscreenElement&&document.exitFullscreen().catch(()=>{}),s(R)}catch(S){_.current=!1,g(S?.message??String(S))}finally{p(!1)}}},[a,d,s]);b.useEffect(()=>{if(m===null)return;if(m<=0){M();return}const S=setTimeout(()=>h(R=>R===null?null:R-1),1e3);return()=>clearTimeout(S)},[m,M]),b.useEffect(()=>()=>{Object.values(V.current).forEach(S=>clearTimeout(S))},[]);const A=b.useMemo(()=>[...t.items].sort((S,R)=>S.sortOrder-R.sortOrder),[t.items]),L=A.filter(S=>{const R=c[S.id];return R==null||R===""?!1:Array.isArray(R)?R.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((S,R)=>r.jsxs("div",{className:"transform -rotate-25 text-xs font-mono font-bold tracking-widest text-main",children:[t.assignment.title," · #",a.slice(-6)]},R))}),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(Wl,{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"," ",L,"/",A.length,v&&` · ${o?"已自动保存":"autosaved"}`,d.size>0&&` · ${o?"保存中…":"saving…"}`,l&&j>0&&r.jsx("span",{className:"text-rose-600 font-semibold ml-2",children:o?`异常记录 ${j} 次`:`Violations: ${j}`})]})]}),l&&!E&&r.jsx("button",{type:"button",onClick:()=>void k(),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"}),m!==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 ${m<=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(er,{size:12}),hI(m)]}),r.jsxs("button",{type:"button",onClick:()=>void M(),disabled:y,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:[y?r.jsx(dt,{size:13,className:"animate-spin"}):r.jsx(bt,{size:13}),o?"提交交卷":"Submit"]}),r.jsx(qe,{slot:"assessment.attempt.toolbar",slotProps:{assignmentId:t.assignment.id,attemptId:a,lang:e},lang:e})]}),z&&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:["⚠️ ",z]}),r.jsx("button",{type:"button",onClick:()=>$(null),className:"text-2xs font-bold underline cursor-pointer",children:o?"知道了":"Dismiss"})]}),x&&r.jsx("p",{role:"alert",className:"relative z-10 mx-5 mt-3 px-3 py-2 rounded-xl border border-rose-200 bg-rose-50 text-rose-700 text-xs",children:x}),r.jsx("div",{className:"relative z-10 flex-1 overflow-y-auto p-5",children:r.jsx("ol",{className:"space-y-4 max-w-3xl mx-auto",children:A.map((S,R)=>{const P=$t.get(S.type)?.Answer??cI;return r.jsxs("li",{"data-testid":`answer-item-${S.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:["#",R+1]}),r.jsx("p",{className:"text-sm font-semibold text-main whitespace-pre-wrap break-words flex-1",children:S.stem}),r.jsxs("span",{className:"text-2xs text-muted shrink-0",children:[S.maxScore," 分"]})]}),r.jsx(P,{config:S.config,value:c[S.id],onChange:Y=>Z(S.id,Y),lang:e})]},S.id)})})})]})}function _c({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(Wl,{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(bt,{size:15,className:"text-emerald-600 shrink-0","aria-label":s?"正确":"Correct"}):r.jsx(T0,{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:"}),Ch(a.answer)]}),t.showAnalysis&&a.answerKey!==void 0&&a.answerKey!==null&&r.jsxs("p",{className:"text-2xs text-muted",children:[s?"参考答案:":"Reference answer:"," ",Ch(a.answerKey)]}),t.showAnalysis&&a.feedback&&r.jsxs("p",{className:"text-2xs text-indigo-700 dark:text-indigo-300",children:[s?"教师评语:":"Feedback:"," ",a.feedback]}),t.showAnalysis&&a.score!==null&&r.jsxs("p",{className:"text-2xs text-muted",children:[s?"本题得分":"Item score",":",a.score,"/",a.maxScore]})]},a.itemId))}),!o.scoreReleased&&t.showScore&&r.jsxs("p",{className:"text-2xs text-muted flex items-center gap-1",children:[r.jsx(Bt,{size:11}),s?"成绩尚未正式发布。":"Scores are not officially released yet."]})]})]})}const t_=Object.freeze(Object.defineProperty({__proto__:null,AssessmentRunner:Tc,ResultView:_c,StudentAssessmentsView:fI},Symbol.toStringTag,{value:"Module"}));function mI({lessonId:e,studentId:t,studentName:n="我",classId:s,lang:i="zh",interactionLocked:o=!1}){const[a,l]=b.useState(null),[c,u]=b.useState(null),[d,f]=b.useState("IN_CLASS_TEACHING"),[m,h]=b.useState(null),[y,p]=b.useState({}),[x,g]=b.useState(null),[v,w]=b.useState(null),[E,N]=b.useState(!1),[j,I]=b.useState("IDLE"),[z,$]=b.useState(null),[V,B]=b.useState(null),[_,U]=b.useState(!1),[k,F]=b.useState(!1),[Z,M]=b.useState(null),[A,L]=b.useState(null),[S,R]=b.useState(5),[D,P]=b.useState(""),[Y,H]=b.useState(""),[ee,le]=b.useState(null),[ae,fe]=b.useState("closed"),[be,ye]=b.useState(null),[Se,me]=b.useState(null),[C,J]=b.useState(!1),[se,W]=b.useState(null),[T,q]=b.useState(null),[X,ne]=b.useState(null),Q=b.useRef(Date.now()),re=b.useRef(null),de=b.useRef(0),te=b.useRef(0),O=b.useRef(null),G=b.useRef(null),ie=b.useRef(!1),ue=b.useRef(0);b.useEffect(()=>{if(!e)return;let ce=!0;const pe=async()=>{const ve=++de.current;try{const _e=await fetch(`/api/classroom/sessions/${e}`);if(_e.ok&&ce){const je=await _e.json();if(je.hasActiveSession){if(f(je.stage),je.session?.current_segment_id&&h(je.session.current_segment_id),je.stage==="WRAP_UP_EXIT_TICKET"&&!ie.current&&U(!0),je.exitTicketCoreQuestion!==void 0&&M(je.exitTicketCoreQuestion),je.exitTicketChallengeQuestion!==void 0&&L(je.exitTicketChallengeQuestion),je.activeCountdown)try{window.dispatchEvent(new CustomEvent("openlearn:countdown:updated",{detail:je.activeCountdown}))}catch{}je.activePoll&&(!O.current||O.current.id!==je.activePoll.id)?(O.current=je.activePoll,l(je.activePoll),w(null),N(!1)):!je.activePoll&&O.current&&(O.current=null,l(null));const Me=G.current;if(je.activeBuzzer)if(!Me||Me.id!==je.activeBuzzer.id)G.current=je.activeBuzzer,u(je.activeBuzzer),I("IDLE"),$(null),re.current=null,Q.current=Date.now();else if(je.activeBuzzer.status==="LOCKED"){const Be=re.current,st=Be&&Be.buzzerId===je.activeBuzzer.id?Be.status:t&&je.activeBuzzer.winner_student_id===t?"WINNER":"MISSED";re.current={buzzerId:je.activeBuzzer.id,status:st},G.current=je.activeBuzzer,I(st),u(je.activeBuzzer)}else je.activeBuzzer.status==="READY"&&!(ve<=te.current)&&re.current?.buzzerId===je.activeBuzzer.id&&(re.current=null,G.current=je.activeBuzzer,I("IDLE"),u(je.activeBuzzer),$(null),Q.current=Date.now());else Me&&(G.current=null,u(null),I("IDLE"),re.current=null)}}}catch{}};pe();const xe=setInterval(pe,2500);return()=>{ce=!1,clearInterval(xe)}},[e,t]),b.useEffect(()=>{const ce=yt();if(!ce||!e)return;const pe=ve=>{ve?.lessonId===e&&ve?.activeSegmentId&&h(ve.activeSegmentId)},xe=ve=>{ve?.lessonId===e&&ve?.assignmentId&&(le({assignmentId:ve.assignmentId,title:ve.title||(i==="zh"?"随堂测评":"Classroom Assessment"),kind:ve.kind||"quiz",durationSec:ve.durationSec??null,totalItems:ve.totalItems??0,maxScore:ve.maxScore??0}),fe("prompt"))};return ce.on("student-active-segment-changed",pe),ce.on("classroom:assessment_started",xe),()=>{typeof ce.off=="function"&&(ce.off("student-active-segment-changed",pe),ce.off("classroom:assessment_started",xe))}},[e,i]),b.useEffect(()=>{if(!e)return;const ce=new Ic(Zm,e,s);let pe=null;const xe=ce.onMessage(ve=>{if(ve.type==="TEACHER_MACRO_NOTIFICATION"){if(ve.payload.lessonId&&ve.payload.lessonId!==e)return;q({title:ve.payload.title,message:ve.payload.message}),pe&&clearTimeout(pe),pe=setTimeout(()=>q(null),8e3)}else if(ve.type==="TEACHER_SHOWCASE_DIFF_SYNC"){if(ve.payload.lessonId&&ve.payload.lessonId!==e)return;const _e=Array.isArray(ve.payload.works)?ve.payload.works:[];_e.length>0&&ne({layout:ve.payload.layout,works:_e,anonymous:ve.payload.anonymous})}});return()=>{pe&&clearTimeout(pe),xe(),ce.destroy()}},[e,s]);const he=async()=>{if(ee){J(!0),W(null);try{const ce=await Xt.startAttempt(ee.assignmentId);ye(ce),fe("answering")}catch(ce){W(ce?.message||String(ce))}finally{J(!1)}}};if(b.useEffect(()=>{e&&fetch(`/api/lessons/${e}`).then(ce=>ce.ok?ce.json():null).then(ce=>{if(ce?.timeline)try{const pe=typeof ce.timeline=="string"?JSON.parse(ce.timeline):ce.timeline;if(Array.isArray(pe)){const xe={};pe.forEach(ve=>{ve?.id&&ve?.title&&(xe[ve.id]=ve.title)}),p(xe)}}catch{}}).catch(()=>{})},[e]),b.useEffect(()=>{if(!e)return;fetch(`/api/classroom/sessions/${e}/pacing-summary?segmentId=${encodeURIComponent(m||"default")}`).then(pe=>pe.ok?pe.json():null).then(pe=>{pe?.success&&g(pe.mySignal||null)}).catch(()=>{})},[e,m]),!e)return null;const K=async ce=>{const pe=Date.now();if(!(pe-ue.current<300)){ue.current=pe;try{const xe=x===ce,ve=await fetch(`/api/classroom/sessions/${e}/pacing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signal:xe?null:ce,action:xe?"cancel":void 0,toggle:!0,segmentId:m||"default"})});if(ve.ok){const _e=await ve.json();g(_e.currentSignal??null),_e.currentSignal?B(ce==="TOO_FAST"?i==="zh"?"已反馈: 🐇 讲太快":"Pacing: Too Fast":ce==="SLOW"?i==="zh"?"已反馈: 🐢 讲太慢":"Pacing: Too Slow":ce==="CONFUSED"?i==="zh"?"已反馈: ❓ 有疑问":"Pacing: Confused":i==="zh"?"已反馈: 💡 听懂了":"Pacing: Clear"):B(i==="zh"?"已取消反馈":"Feedback cleared"),setTimeout(()=>B(null),2500)}}catch{}}},we=async ce=>{if(!(!a||E))try{w(ce),N(!0),await fetch(`/api/classroom/sessions/${e}/quick-poll/${a.id}/vote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({option:ce})})}catch{}},oe=async()=>{if(!c||c.status!=="READY"||j!=="IDLE")return;const ce=Date.now()-Q.current;te.current=de.current,I("BUZZED");try{const pe=await fetch(`/api/classroom/sessions/${e}/buzzer/${c.id}/buzz`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentName:n,responseTimeMs:ce})});if(pe.ok){const xe=await pe.json(),ve=xe.won??xe.winner===!0,_e=ve?"WINNER":"MISSED";if(re.current={buzzerId:c.id,status:_e},I(_e),!ve&&xe.winner){const je={...c,status:"LOCKED",winner_student_id:xe.winner.studentId??null,winner_student_name:xe.winner.studentName??null,winner_response_time_ms:xe.winner.responseTimeMs??null};G.current=je,u(je)}}else I("IDLE")}catch{I("IDLE")}};return r.jsxs(r.Fragment,{children:[r.jsx(q2,{lessonId:e,lang:i}),T&&r.jsxs("div",{"data-testid":"student-macro-notification-banner",className:"fixed top-20 left-1/2 -translate-x-1/2 z-[75] max-w-lg w-[calc(100%-2rem)] bg-indigo-600 text-white px-4 py-2.5 rounded-2xl shadow-xl border border-indigo-400/50 flex items-center justify-between gap-3 animate-in fade-in slide-in-from-top-2 duration-200",role:"status",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(ui,{size:16,className:"shrink-0 text-amber-200"}),r.jsxs("div",{className:"min-w-0",children:[T.title&&r.jsx("div",{className:"text-[11px] font-bold text-indigo-100 truncate",children:T.title}),r.jsx("div",{className:"text-xs font-extrabold truncate",children:T.message})]})]}),r.jsx("button",{type:"button",onClick:()=>q(null),className:"p-1 rounded-lg hover:bg-white/20 text-white/80 hover:text-white cursor-pointer shrink-0","aria-label":i==="zh"?"关闭广播提示":"Dismiss notification",children:r.jsx(De,{size:14})})]}),X&&r.jsx("div",{"data-testid":"student-synced-diff-modal",className:"fixed inset-0 z-[80] bg-black/70 backdrop-blur-xs flex items-center justify-center p-4",role:"dialog","aria-modal":"true","aria-label":i==="zh"?"教师推送的作业对比展示":"Teacher Broadcasted Showcase Diff",children:r.jsxs("div",{className:"bg-surface border border-theme rounded-2xl shadow-2xl max-w-5xl w-full max-h-[85vh] flex flex-col overflow-hidden text-main",children:[r.jsxs("div",{className:"px-4 py-3 border-b border-theme bg-surface-secondary flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ut,{size:16,className:"text-purple-500"}),r.jsx("span",{className:"text-sm font-black",children:i==="zh"?"教师大屏同屏对比讲评":"Live Teacher Showcase Comparison"})]}),r.jsx("button",{type:"button",onClick:()=>ne(null),className:"p-1.5 rounded-lg hover:bg-surface text-muted hover:text-main cursor-pointer","aria-label":i==="zh"?"关闭对比视窗":"Close comparison view",children:r.jsx(De,{size:16})})]}),r.jsx("div",{className:`p-4 overflow-y-auto grid gap-3 ${X.works.length<=2,"grid-cols-1 md:grid-cols-2"}`,children:X.works.map((ce,pe)=>r.jsxs("div",{className:"border border-theme rounded-xl p-3 bg-surface-secondary/40 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-xs font-extrabold text-main",children:X.anonymous?`${i==="zh"?"作答方案":"Solution"} ${String.fromCharCode(65+pe)}`:ce.studentName}),typeof ce.accuracyScore=="number"&&r.jsxs("span",{className:"text-[11px] font-mono font-bold text-primary-ink px-2 py-0.5 rounded-full bg-primary-theme/10",children:[ce.accuracyScore," pts"]})]}),r.jsx("div",{className:"text-xs font-bold text-muted",children:ce.title}),r.jsx("pre",{className:"text-xs whitespace-pre-wrap break-words bg-surface p-2.5 rounded-lg border border-theme/70 max-h-60 overflow-y-auto font-mono",children:ce.content})]},ce.studentId))})]})}),r.jsx(qe,{slot:"student.classroom.overlay",slotProps:{studentId:t,studentName:n,lessonId:e,classId:s},locked:o}),r.jsx(qe,{slot:"student.fullscreen",slotProps:{studentId:t,studentName:n,lessonId:e}}),r.jsxs("aside",{"aria-label":i==="zh"?"课堂互动工具栏":"Classroom interaction toolbar",className:"fixed bottom-6 right-6 z-40 flex items-center gap-2.5 bg-surface/95 backdrop-blur-md border border-theme p-2 rounded-2xl shadow-2xl transition-all",children:[r.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-surface-secondary/70 rounded-xl border border-theme text-2xs font-bold text-muted",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary-theme animate-pulse"}),r.jsx("span",{className:"truncate max-w-[120px]",children:m&&y[m]?y[m]:i==="zh"?"当前环节":"Current Segment"})]}),V&&r.jsx("span",{className:"text-2xs font-bold text-primary-ink px-1.5 py-0.5 animate-fade-in whitespace-nowrap",children:V}),o&&r.jsxs("span",{"data-testid":"student-overlay-lock-chip",className:"px-2 py-1 rounded-xl bg-slate-900/70 text-white text-2xs font-bold whitespace-nowrap",title:i==="zh"?"老师已开启全班专注锁定,互动组件已暂停":"Classroom focus lock is on — interactions are paused",children:["🔒 ",i==="zh"?"专注锁定中":"Focus locked"]}),r.jsxs("div",{className:`flex items-center gap-1${o?" pointer-events-none opacity-40":""}`,"aria-disabled":o||void 0,children:[r.jsxs("button",{type:"button",disabled:o,"aria-pressed":x==="CLEAR",onClick:()=>K("CLEAR"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="CLEAR"?"bg-emerald-500/20 text-emerald-700 dark:text-emerald-300 ring-2 ring-emerald-500/60 shadow-xs":"hover:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"}`,title:i==="zh"?"听懂了,节奏适宜(再次点击取消)":"Clear & Optimal (Click again to cancel)",children:[r.jsx("span",{children:"💡"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"听懂了":"Clear"}),x==="CLEAR"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,"aria-pressed":x==="CONFUSED",onClick:()=>K("CONFUSED"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="CONFUSED"?"bg-amber-500/20 text-amber-700 dark:text-amber-300 ring-2 ring-amber-500/60 shadow-xs":"hover:bg-amber-500/10 text-amber-700 dark:text-amber-400"}`,title:i==="zh"?"有点困惑,希望老师点拨(再次点击取消)":"Confused (Click again to cancel)",children:[r.jsx("span",{children:"❓"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"有疑问":"Confused"}),x==="CONFUSED"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,"aria-pressed":x==="TOO_FAST",onClick:()=>K("TOO_FAST"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="TOO_FAST"?"bg-rose-500/20 text-rose-700 dark:text-rose-300 ring-2 ring-rose-500/60 shadow-xs":"hover:bg-rose-500/10 text-rose-700 dark:text-rose-400"}`,title:i==="zh"?"讲得太快了,希望能慢一点(再次点击取消)":"Too fast (Click again to cancel)",children:[r.jsx("span",{children:"🐇"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"讲太快":"Too Fast"}),x==="TOO_FAST"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]}),r.jsxs("button",{type:"button",disabled:o,"aria-pressed":x==="SLOW",onClick:()=>K("SLOW"),className:`px-2.5 py-1.5 rounded-xl font-bold text-xs transition-all flex items-center gap-1 cursor-pointer ${x==="SLOW"?"bg-indigo-500/20 text-indigo-600 dark:text-indigo-300 ring-2 ring-indigo-500/60 shadow-xs":"hover:bg-indigo-500/10 text-indigo-600 dark:text-indigo-400"}`,title:i==="zh"?"讲太慢了,希望快一点(再次点击取消)":"Too slow (Click again to cancel)",children:[r.jsx("span",{children:"🐢"}),r.jsx("span",{className:"hidden sm:inline",children:i==="zh"?"讲太慢":"Too Slow"}),x==="SLOW"&&r.jsx("span",{className:"text-3xs ml-0.5 font-bold",children:"✓"})]})]})]}),a&&a.status==="ACTIVE"&&r.jsxs("div",{"data-testid":"student-quick-poll-card",className:"fixed bottom-20 right-6 z-50 bg-surface rounded-2xl border border-amber-500/40 p-5 shadow-2xl w-80 flex flex-col gap-3 animate-slide-up",children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 pb-2",children:[r.jsxs("span",{className:"text-xs font-extrabold text-amber-700 dark:text-amber-400 flex items-center gap-1.5",children:[r.jsx(ut,{size:14}),i==="zh"?"极速答题进行中":"Quick Poll Active"]}),E&&r.jsxs("span",{className:"text-[11px] text-emerald-700 dark:text-emerald-400 font-bold flex items-center gap-1",children:[r.jsx(bt,{size:12}),i==="zh"?"已提交":"Submitted"]})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:a.title}),r.jsx("div",{className:"grid grid-cols-2 gap-2 mt-1",children:(a.options||["A","B","C","D"]).map(ce=>{const pe=v===ce;return r.jsx("button",{disabled:E,onClick:()=>we(ce),className:`p-3 rounded-xl font-bold text-center text-sm transition-all cursor-pointer ${pe?"bg-primary-solid text-white ring-2 ring-primary-theme shadow-md scale-95":E?"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:ce},ce)})})]}),c&&z!==c.id&&r.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4",onClick:()=>$(c.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:ce=>ce.stopPropagation(),children:[r.jsx("button",{onClick:()=>$(c.id),"aria-label":i==="zh"?"关闭抢答":"Close buzzer",className:"absolute top-3 right-3 p-1.5 rounded-full text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:r.jsx(De,{size:18})}),r.jsxs("h3",{className:"text-xl font-black text-foreground flex items-center gap-2",children:[r.jsx(ui,{size:22,className:"text-rose-700 dark:text-rose-400 animate-bounce"}),r.jsx("span",{children:c.title||"全班极速抢答"})]}),j==="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:"请稍候,马上公布结果"})]}),j==="IDLE"&&c.status==="READY"&&r.jsxs("div",{className:"my-4 flex flex-col items-center gap-3",children:[r.jsxs("button",{onClick:oe,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(_0,{size:32,className:"mb-1"}),r.jsx("span",{children:"抢!"})]}),r.jsx("span",{className:"text-xs text-muted",children:"点击红色大按钮抢得首答权"})]}),j==="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:()=>$(c.id),className:"mt-3 px-4 py-1.5 rounded-xl text-xs font-bold text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:i==="zh"?"知道了,返回课堂":"Got it, back to class"})]}),j==="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:["已被 ",c.winner_student_name||"其他同学"," 抢先一步!"]}),r.jsx("span",{className:"text-xs text-muted mt-1",children:"下次手速要更快哦"}),r.jsx("button",{onClick:()=>$(c.id),className:"mt-3 px-4 py-1.5 rounded-xl text-xs font-bold text-muted hover:text-foreground hover:bg-surface-secondary transition-colors cursor-pointer",children:i==="zh"?"知道了,返回课堂":"Got it, back to class"})]})]})}),r.jsx(G2,{isOpen:_,onClose:()=>U(!1),lessonId:e,studentName:n,lang:i,coreQuestion:Z,challengeQuestion:A,onSubmitSuccess:()=>{ie.current=!0,F(!0)}}),ee&&ae==="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(Zn,{size:14}),i==="zh"?"随堂测评已发起":"Classroom Assessment"]}),r.jsx("button",{onClick:()=>fe("closed"),"aria-label":i==="zh"?"关闭":"Close",className:"p-1 rounded-lg text-muted hover:text-foreground cursor-pointer",children:r.jsx(De,{size:14})})]}),r.jsx("p",{className:"font-bold text-sm text-foreground",children:ee.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:ee.kind==="exam"?i==="zh"?"考试":"Exam":ee.kind==="survey"?i==="zh"?"问卷":"Survey":i==="zh"?"测试":"Quiz"}),r.jsxs("span",{children:[ee.totalItems," ",i==="zh"?"道题":"items"]}),r.jsxs("span",{children:[i==="zh"?"满分":"Total"," ",ee.maxScore]}),ee.durationSec&&r.jsxs("span",{className:"inline-flex items-center gap-1",children:[r.jsx(er,{size:11}),Math.round(ee.durationSec/60)," ",i==="zh"?"分钟":"min"]})]}),se&&r.jsx("p",{className:"text-2xs text-rose-600 bg-rose-50 dark:bg-rose-950/40 p-1.5 rounded-lg",children:se}),r.jsxs("button",{type:"button",onClick:()=>void he(),disabled:C,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:[C?r.jsx("span",{className:"animate-spin text-xs",children:"⏳"}):r.jsx($l,{size:13}),i==="zh"?"立即开始作答":"Start Assessment"]})]}),ae==="answering"&&be&&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(Tc,{lang:i,payload:be,initialAnswers:be.answers,onSubmitted:ce=>{me(ce),fe("result")},onExit:()=>fe("closed")})})}),ae==="result"&&Se&&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(_c,{lang:i,result:Se,onBack:()=>{fe("closed"),le(null),ye(null),me(null)}})})})]})}function pI(e){const t=Ot(),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,u=e.activeStudentId!==void 0?e.activeStudentId:t?.activeStudentId??null,d=e.students??t?.students??[],f=e.activeRole??t?.activeRole??"teacher",m=e.isStudentLiveMode??t?.isStudentLiveMode??!1,h=e.liveStudentParam!==void 0?e.liveStudentParam:t?.liveStudentParam??null,y=e.isInteractionLocked!==void 0?e.isInteractionLocked:t?.isInteractionLocked??!1,p=e.addToast??t?.addToast??(()=>{}),x=e.setReadNotifications??t?.setReadNotifications??(()=>{});return r.jsxs(r.Fragment,{children:[n&&!i&&r.jsx("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-[9990] animate-in slide-in-from-top-4 duration-300 pointer-events-auto max-w-lg w-auto",children:r.jsxs("div",{className:"flex items-center gap-3 px-5 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-full shadow-xl shadow-amber-500/25 backdrop-blur-xs text-sm font-bold border border-amber-300/40",children:[r.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-75"}),r.jsx("span",{className:"relative inline-flex rounded-full h-2.5 w-2.5 bg-white"})]}),r.jsx(ut,{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(De,{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(ut,{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 g=new Ic(void 0,l,c);if(g.acknowledgePick(i.studentId),g.destroy(),i.rollcallId){const v=i.rollcallId;u&&F2(u,v).catch(console.error),x(w=>new Set(w).add(v))}o?.(null),p(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(bt,{size:20}),r.jsx("span",{children:a==="zh"?"🙋♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋♂️ Ready / Acknowledge to Teacher"})]})})]})}),(f==="student"||m)&&r.jsx(mI,{lessonId:l,studentId:u||h||void 0,studentName:d.find(g=>g.id===(u||h))?.name||void 0,classId:c||d.find(g=>g.id===(u||h))?.class_id||d.find(g=>g.id===(u||h))?.classId||void 0,lang:a,interactionLocked:y})]})}function gI(){const e=yS(o=>o.toasts),[t,n]=b.useState(null),s=async(o,a)=>{o.stopPropagation();const l=`[${a.title}] ${a.message}`;await Qs(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(Pt,{size:16})};case"warning":return{border:"border-l-4 border-amber-500",iconBg:"bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400",icon:r.jsx(Bt,{size:16})};case"info":return{border:"border-l-4 border-blue-500",iconBg:"bg-blue-50 text-blue-600 dark:bg-blue-950/60 dark:text-blue-400",icon:r.jsx(rf,{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(bt,{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(wy,{children:e.map(o=>{const a=i(o.type),l=t===o.id;return r.jsxs(qa.div,{initial:{y:50,x:50,scale:.9},animate:{y:0,x:0,scale:1},exit:{scale:.85,transition:{duration:.2}},transition:{type:"spring",stiffness:300,damping:24},className:`pointer-events-auto w-full bg-white dark:bg-slate-900 ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 ${a.border} overflow-hidden text-gray-900 dark:text-gray-100`,id:`toast-${o.id}`,children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:`p-1 rounded-full shrink-0 ${a.iconBg}`,children:a.icon}),r.jsx("p",{className:"font-semibold text-sm font-sans truncate",children:o.title})]}),(o.type==="error"||o.type==="warning")&&r.jsxs("button",{type:"button",onClick: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(Xe,{size:11}):r.jsx(Un,{size:11}),r.jsx("span",{children:l?"已复制":"复制"})]})]}),r.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mt-2 leading-relaxed font-sans break-words",children:o.message}),o.action&&r.jsx("div",{className:"mt-2.5",children:r.jsx("button",{type:"button",onClick:()=>{o.action?.onClick(),Ge.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:()=>Ge.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(De,{size:14})})]},o.id)})})})}class xI{constructor(){this.commands=new Map,this.recents=[],this.favorites=new Set}register(t){if(!t||!t.id)throw new Error("CommandRegistry Error: Command descriptor must have a valid ID.");this.commands.set(t.id,t)}unregister(t){return this.recents=this.recents.filter(n=>n!==t),this.favorites.delete(t),this.commands.delete(t)}getCommand(t){return this.commands.get(t)}search(t="",n){const s=t.trim().toLowerCase(),i=Array.from(this.commands.values());return Object.freeze(i.filter(o=>{if(n&&o.category!==n)return!1;if(!s)return!0;const a=o.title.toLowerCase().includes(s),l=o.description?.toLowerCase().includes(s)??!1,c=o.keywords?.some(u=>u.toLowerCase().includes(s))??!1;return a||l||c}))}async executeCommand(t,n){const s=this.commands.get(t);if(!s)throw new Error(`CommandRegistry Error: Command '${t}' not found.`);this.recents=[t,...this.recents.filter(i=>i!==t)].slice(0,10),await s.execute(n)}getRecents(){const t=this.recents.map(n=>this.commands.get(n)).filter(n=>n!==void 0);return Object.freeze(t)}getFavorites(){const t=Array.from(this.favorites).map(n=>this.commands.get(n)).filter(n=>n!==void 0);return Object.freeze(t)}toggleFavorite(t){this.favorites.has(t)?this.favorites.delete(t):this.commands.has(t)&&this.favorites.add(t)}listAll(){return Object.freeze(Array.from(this.commands.values()))}clear(){this.commands.clear(),this.recents=[],this.favorites.clear()}}function bI(e){if(e==null)return{};const t={};for(const n of Object.keys(e))t[n]=Reflect.get(e,n);return t}function Mr(e,t){const n=e[t];return typeof n=="string"?n:void 0}function yI(e){if(!Array.isArray(e))return;const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];typeof s=="string"&&t.push(s)}return t.length>0?t:void 0}function wI(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t={};for(const n of Object.keys(e))t[n]=Reflect.get(e,n);return t}function vI(e,t,n){if(typeof e!="string")return n;for(const s of t)if(s===e)return s;return n}const SI=["Lesson","Whiteboard","Plugin","AI","Workspace","Analytics","Resource"],jl=new xI,kI=({isOpen:e,onClose:t,registry:n=jl})=>{const[s,i]=b.useState(""),[o,a]=b.useState("All"),[l,c]=b.useState(0),u=Re(m=>m.extensionPoints),d=b.useMemo(()=>{const m=o==="All"?void 0:o,h=n.search(s,m),p=(u.get("command_palette.item")??[]).map(x=>{const g=bI(x.slotProps),v=vI(g.category,SI,"Plugin"),w=Mr(g,"title"),E=Mr(g,"commandType"),N=wI(g.payload);return{id:x.id,title:x.label||w||x.id,description:Mr(g,"description"),icon:typeof x.icon=="string"?x.icon:void 0,category:v,keywords:yI(g.keywords),shortcut:Mr(g,"shortcut"),execute:async j=>{if(E){const I=await Fm.post("/api/plugins/execute-command",{type:E,payload:N??j});I.success||Ge.getState().addToast({id:`plugin-cmd-error-${Date.now()}`,type:"error",title:"插件命令执行失败",message:I.error||`命令 ${E} 未能执行`})}}}}).filter(x=>{if(m&&x.category!==m)return!1;if(!s.trim())return!0;const g=s.trim().toLowerCase(),v=x.title.toLowerCase().includes(g),w=x.description?.toLowerCase().includes(g)??!1,E=x.keywords?.some(N=>N.toLowerCase().includes(g))??!1;return v||w||E});return[...h,...p]},[n,s,o,u]),f=b.useCallback(m=>{if(m.key==="ArrowDown")m.preventDefault(),c(h=>h+1<d.length?h+1:0);else if(m.key==="ArrowUp")m.preventDefault(),c(h=>h-1>=0?h-1:d.length-1);else if(m.key==="Enter"){m.preventDefault();const h=d[l];h&&(n.getCommand?.(h.id)?n.executeCommand(h.id):h.execute(),t())}else m.key==="Escape"&&(m.preventDefault(),t())},[d,l,n,t]);return b.useEffect(()=>{c(0)},[s,o]),e?r.jsx("div",{className:"command-palette-backdrop fixed inset-0 bg-slate-950/70 backdrop-blur-sm z-50 flex items-start justify-center pt-24",onClick:t,"data-testid":"command-palette-backdrop",children:r.jsxs("div",{className:"command-palette-container w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-xl shadow-2xl overflow-hidden flex flex-col",onClick:m=>m.stopPropagation(),"data-testid":"command-palette-modal",children:[r.jsxs("div",{className:"flex items-center px-4 py-3 border-b border-slate-800 bg-slate-900/90",children:[r.jsx("input",{type:"text",className:"w-full bg-transparent text-slate-100 placeholder-slate-400 outline-none text-base font-medium",placeholder:"Type a command or search...",value:s,onChange:m=>i(m.target.value),onKeyDown:f,autoFocus:!0,"data-testid":"command-search-input"}),r.jsx("kbd",{className:"text-xs bg-slate-800 text-slate-400 px-2 py-1 rounded border border-slate-700 font-mono",children:"ESC"})]}),r.jsx("div",{className:"flex items-center space-x-1 px-3 py-2 border-b border-slate-800 bg-slate-900/50 overflow-x-auto",children:["All","Lesson","Whiteboard","Plugin","AI","Workspace","Analytics","Resource"].map(m=>r.jsx("button",{className:`px-2.5 py-1 text-xs rounded-md transition-colors font-medium ${o===m?"bg-indigo-600 text-white":"text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,onClick:()=>a(m),children:m},m))}),r.jsx("div",{className:"max-h-96 overflow-y-auto p-2 divide-y divide-slate-800/50",children:d.length===0?r.jsx("div",{className:"py-8 text-center text-slate-500 text-sm",children:"No commands found."}):d.map((m,h)=>r.jsxs("div",{className:`flex items-center justify-between px-3 py-2.5 rounded-lg cursor-pointer transition-colors ${h===l?"bg-indigo-600/20 text-white":"text-slate-300 hover:bg-slate-800/60"}`,onClick:()=>{n.getCommand?.(m.id)?n.executeCommand(m.id):m.execute(),t()},"data-testid":`command-item-${m.id}`,children:[r.jsxs("div",{className:"flex items-center space-x-3",children:[r.jsx("span",{className:"text-xs font-semibold px-2 py-0.5 rounded bg-slate-800 text-indigo-400 border border-slate-700",children:m.category}),r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-medium text-slate-100",children:m.title}),m.description&&r.jsx("div",{className:"text-xs text-slate-400",children:m.description})]})]}),m.shortcut&&r.jsx("kbd",{className:"text-xs font-mono text-slate-400 bg-slate-800 px-2 py-0.5 rounded border border-slate-700",children:m.shortcut})]},m.id))})]})}):null},vi={teaching:{key:"teaching",label:{zh:"教学工具",en:"TEACHING"},position:10},system:{key:"system",label:{zh:"系统管理",en:"SYSTEM MANAGEMENT"},position:20},extensions:{key:"extensions",label:{zh:"扩展应用",en:"EXTENSIONS"},position:30},support:{key:"support",label:{zh:"帮助支持",en:"HELP & SUPPORT"},position:40}},jI=[{id:"courses",tab:"courses",label:{zh:"课程管理",en:"Courses"},icon:Xs,group:"teaching",position:10},{id:"live_class",tab:"live_class",label:{zh:"互动课堂",en:"Live Class"},icon:Ni,group:"teaching",position:20,highlight:!0},{id:"classes",tab:"classes",label:{zh:"班级管理",en:"Classes & Students"},icon:Ol,group:"teaching",position:30},{id:"assessments",tab:"assessments",label:{zh:"测评中心",en:"Assessment Center"},icon:Zn,group:"teaching",position:40},{id:"timetable",tab:"timetable",label:{zh:"课表管理",en:"Timetable Routine"},icon:P0,group:"system",position:10},{id:"computer_labs",tab:"computer_labs",label:{zh:"机房管理",en:"Computer Lab Seating"},icon:uf,group:"system",position:20},{id:"plugins",tab:"plugins",label:{zh:"插件中心",en:"App Store / Plugins"},icon:ji,group:"system",position:30},{id:"admin_directory",tab:"admin_directory",label:{zh:"管理后台",en:"⭐ Admin Center"},icon:Zh,group:"system",position:40,administratorOnly:!0},{id:"help",tab:"help",label:{zh:"帮助文档",en:"System Commands / Help"},icon:Dl,group:"support",position:10}];function NI(e,t){return jI.filter(n=>!n.administratorOnly||e==="administrator").map(n=>({id:n.id,tab:n.tab,label:n.label[t]??n.label.zh,labelZh:n.label.zh,labelEn:n.label.en,icon:n.icon,group:n.group,position:n.position,administratorOnly:n.administratorOnly??!1,highlight:n.highlight??!1})).sort((n,s)=>{const i=vi[n.group].position,o=vi[s.group].position;return i!==o?i-o:n.position-s.position})}function n_(e,t){return vi[e].label[t]??vi[e].label.zh}const CI=e=>e==="zh",pn="builtin.";function EI(e){const t=CI(e.lang),n=[];for(const i of NI(e.role,e.lang))n.push({id:`${pn}goto.${i.id}`,title:t?`前往${i.labelZh}`:`Go to ${i.labelEn}`,description:t?"切换到左侧导航中的对应工作区":"Switch to the matching workspace",category:"Workspace",keywords:t?[i.labelZh,"跳转","导航"]:[i.labelEn,"go","navigate"],execute:()=>e.setTeacherTab(i.tab)});n.push({id:`${pn}ui.toggleSidebar`,title:t?"折叠 / 展开左侧导航":"Collapse / expand sidebar",description:t?"切换左侧导航栏的宽度":"Toggle the left navigation width",category:"Workspace",keywords:t?["侧边栏","折叠","展开"]:["sidebar","collapse","expand"],execute:()=>e.toggleSidebar()}),n.push({id:`${pn}ui.toggleLanguage`,title:t?"切换界面语言(中 / 英)":"Toggle interface language (ZH / EN)",category:"Workspace",keywords:t?["语言","中英文"]:["language","locale","i18n"],execute:()=>e.toggleLanguage()}),n.push({id:`${pn}ui.openNotifications`,title:t?"打开通知中心":"Open notifications",category:"Workspace",keywords:t?["通知","消息"]:["notification","inbox"],execute:()=>e.openNotifications()}),n.push({id:`${pn}ui.openSystemResourceLibrary`,title:t?"打开系统资源库":"Open system resource library",category:"Resource",keywords:t?["资源库","素材"]:["resource","library","material"],execute:()=>e.openSystemResourceLibrary()}),n.push({id:`${pn}ui.openProfile`,title:t?"打开个人资料":"Open profile",category:"Workspace",keywords:t?["个人","资料","头像"]:["profile","account","avatar"],execute:()=>e.openProfile()});const s=[{id:"light",zh:"浅色",en:"Light"},{id:"dark",zh:"深色",en:"Dark"},{id:"eyecare",zh:"护眼",en:"Eyecare"},{id:"chalkboard",zh:"黑板",en:"Chalkboard"}];for(const i of s)n.push({id:`${pn}theme.${i.id}`,title:t?`切换主题:${i.zh}`:`Switch theme: ${i.en}`,category:"Workspace",keywords:t?["主题","配色",i.zh]:["theme","appearance",i.en],execute:()=>e.setTheme(i.id)});return n}function II(e,t){for(const n of EI(t))e.register(n)}function AI(){const[e,t]=b.useState(!1),n=Ot(),s=ke(c=>c.lang),i=ke(c=>c.setTeacherTab),o=Ie(c=>c.setTheme),a=n?.session?.subRole==="administrator"?"administrator":"teacher";b.useEffect(()=>{II(jl,{setTeacherTab:i,role:a,lang:s,toggleSidebar:()=>{const c=n?.mainNavCollapsed;c!==void 0&&n?.setMainNavCollapsed?.(!c)},toggleLanguage:()=>n?.toggleLanguage?.(),setTheme:o,openNotifications:()=>n?.setIsNotificationsOpen?.(!0),openSystemResourceLibrary:()=>n?.setIsSystemResourceLibraryOpen?.(!0),openProfile:()=>n?.setProfileOpen?.(!0)})},[n,s,a,i,o]);const l=b.useCallback(()=>t(!1),[]);return b.useEffect(()=>{const c=u=>{!u.metaKey&&!u.ctrlKey||typeof u.key!="string"||u.key.toLowerCase()!=="k"||(u.preventDefault(),t(d=>!d))};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[]),b.useEffect(()=>{if(!e)return;const c=u=>{u.key==="Escape"&&t(!1)};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),e?r.jsx(kI,{isOpen:e,onClose:l,registry:jl}):null}const Nl=new Set;function TI(e){return Nl.add(e),()=>{Nl.delete(e)}}const Ih=30,Ah=(e,t)=>Math.min(e,t.length);function Pc(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(`
|
|
115
|
+
`)}function Qm(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(`
|
|
116
|
+
`)}function _I(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 系统诊断报告
|
|
117
|
+
- 生成时间: ${n}
|
|
118
|
+
- 暂无记录的系统异常。`;const o=e.length+t.length,a=["# 🛠️ OpenLearn 系统异常诊断报告",`- **生成时间**: ${n}`,`- **当前页面**: ${s}`,`- **异常总数**: ${o} 项`,`- **本机异常数**: ${e.length} 项`,`- **学生端异常数**: ${t.length} 项`,`- **运行环境**: ${i}`,"","---",""].join(`
|
|
119
|
+
`),l=e.length>0?`## 💻 本机异常记录 (${e.length})
|
|
120
|
+
|
|
121
|
+
`+e.map((u,d)=>`#### 错误 #${d+1} (${u.type.toUpperCase()})
|
|
122
|
+
`+Pc(u)).join(`
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
`):"",c=t.length>0?`## 🎒 学生端异常记录 (${t.length})
|
|
127
|
+
|
|
128
|
+
`+t.map((u,d)=>`#### 学生异常 #${d+1}
|
|
129
|
+
`+Qm(u)).join(`
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
`):"";return[a,l,c].filter(Boolean).join(`
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
`)}const gn=Lt((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 u=[l,...c.errors].slice(0,Ih);return{errors:u,unreadCount:Ah(c.unreadCount+1,u)}}),Nl.forEach(c=>{try{c(l)}catch(u){console.error("[ErrorStore] Error in errorListener:",u)}}),l},removeError:n=>e(s=>{const i=s.errors.filter(o=>o.id!==n);return{errors:i,unreadCount:Ah(s.unreadCount,i)}}),clearErrors:()=>e({errors:[],unreadCount:0}),addStudentError:n=>{const s=Date.now(),i=n.timestamp||s;e(o=>o.studentErrors.some(u=>u.studentId===n.studentId&&u.type===n.type&&u.message===n.message&&Math.abs(i-u.timestamp)<2e3)?o:{studentErrors:[{...n,id:n.id||`st_err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:i},...o.studentErrors].slice(0,Ih)})},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 It(e){return tn(gn,e||(t=>t))}function PI(){const e=ke(B=>B.session),t=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),n=e?.role==="student"||t,s=It(B=>B.errors),i=It(B=>B.studentErrors),o=It(B=>B.activeTab),a=It(B=>B.setActiveTab),l=It(B=>B.isErrorCenterOpen),c=It(B=>B.setIsErrorCenterOpen),u=It(B=>B.clearErrors),d=It(B=>B.clearStudentErrors),f=It(B=>B.removeError),m=It(B=>B.removeStudentError),[h,y]=b.useState(!1),[p,x]=b.useState(null),[g,v]=b.useState(new Set),[w,E]=b.useState(!1),N=s.length+(n?0:i.length),j=s.length>0||!n&&i.length>0,I=B=>{v(_=>{const U=new Set(_);return U.has(B)?U.delete(B):U.add(B),U})},z=async()=>{const B=_I(s,n?[]:i);await Qs(B)&&(y(!0),setTimeout(()=>y(!1),2500))},$=async(B,_,U=!1)=>{B.stopPropagation();const k=U?Qm(_):Pc(_);await Qs(k)&&(x(_.id),setTimeout(()=>x(null),2500))},V=B=>{switch(B){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:[j&&!l&&!w&&(n?r.jsxs(qa.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(Bt,{size:15}),r.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center leading-none shadow-xs border border-slate-900",children:s.length})]}):r.jsxs(qa.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(Bt,{size:15,className:"text-rose-400 group-hover:scale-110 transition-transform"}),r.jsxs("div",{className:"text-xs font-semibold flex items-center gap-1.5",children:[r.jsx("span",{children:"捕获到"}),r.jsx("span",{className:"bg-rose-500/80 text-white font-mono px-1.5 py-0.2 rounded-md text-xs font-bold",children:N}),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:B=>{B.stopPropagation(),E(!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(De,{size:13})})]})),r.jsxs(yi,{open:l,onClose:()=>c(!1),ariaLabelledBy:"system-error-center-dialog-title",closedBy:"any",className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-2xl shadow-2xl max-w-3xl max-h-[85vh] overflow-hidden text-gray-900 dark:text-gray-100 select-text",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(z0,{size:18})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("h2",{id:"system-error-center-dialog-title",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:["(",N," 项记录)"]})]})}),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:z,disabled:N===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(Xe,{size:13}):r.jsx(Un,{size:13}),r.jsx("span",{children:h?"已复制全部!":"一键复制全部诊断日志"})]}),r.jsx("button",{type:"button",onClick:()=>{!n&&o==="student"?d():u()},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(Jn,{size:16})}),r.jsx("button",{type:"button",onClick:()=>c(!1),"aria-label":"关闭弹窗",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(De,{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(R0,{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(Oa,{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(Xe,{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((B,_)=>{const U=g.has(B.id),k=p===B.id;return r.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[r.jsxs("div",{onClick:()=>I(B.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:U?r.jsx(Gn,{size:15}):r.jsx(qn,{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(Oa,{size:11}),r.jsx("span",{children:B.studentName||B.studentId})]}),V(B.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",i.length-_," ",B.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(B.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:B.message}),r.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[r.jsxs("span",{children:["学生学号/ID: ",B.studentId]}),B.lessonId&&r.jsxs("span",{children:["课节: ",B.lessonId]}),B.classId&&r.jsxs("span",{children:["班级: ",B.classId]}),B.endpoint&&r.jsxs("span",{children:["接口: ",B.endpoint]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:F=>$(F,B,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${k?"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:[k?r.jsx(Xe,{size:11}):r.jsx(Un,{size:11}),r.jsx("span",{children:k?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),m(B.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(De,{size:13})})]})]}),U&&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:["学生: ",B.studentName||"未知"," (",B.studentId,")"]}),r.jsxs("span",{children:["页面地址: ",B.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(B.timestamp).toLocaleString()]})]}),B.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:B.stack})]}),B.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:B.componentStack})]})]})]},B.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(Xe,{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((B,_)=>{const U=g.has(B.id),k=p===B.id;return r.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[r.jsxs("div",{onClick:()=>I(B.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:U?r.jsx(Gn,{size:15}):r.jsx(qn,{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:[V(B.type),r.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-_," ",B.title]}),r.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(B.timestamp).toLocaleTimeString()})]}),r.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:B.message}),B.endpoint&&r.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",B.endpoint]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[r.jsxs("button",{type:"button",onClick:F=>$(F,B,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${k?"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:[k?r.jsx(Xe,{size:11}):r.jsx(Un,{size:11}),r.jsx("span",{children:k?"已复制":"复制"})]}),r.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),f(B.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:r.jsx(De,{size:13})})]})]}),U&&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:["页面地址: ",B.url||"未知"]}),r.jsxs("span",{children:["时间: ",new Date(B.timestamp).toLocaleString()]})]}),B.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:B.stack})]}),B.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:B.componentStack})]})]})]},B.id)})})]})]})}function Ca({lang:e="zh"}){const t=Ie(d=>d.theme),n=Ie(d=>d.activeBundle),s=Ie(d=>d.previewState),i=Ie(d=>d.appearanceOverrides),o=Ie(d=>d.fallbackNotice),a=Ie(d=>d.cancelPreview),l=Ie(d=>d.resetToSafeDefault),c=Ie(d=>d.clearFallbackNotice),u=!!n||!qr(t)||!!s||Object.keys(i||{}).length>0;return!u&&!o?null:r.jsxs("div",{"data-testid":"theme-failsafe-overlay",role:"region","aria-label":e==="zh"?"主题安全恢复栏":"Theme Failsafe Recovery",style:{position:"fixed",left:"14px",bottom:"14px",zIndex:2147483e3,display:"flex",flexDirection:"column",gap:"8px",maxWidth:"340px",pointerEvents:"auto",visibility:"visible",opacity:1,fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'},children:[o&&r.jsxs("div",{role:"status","data-testid":"theme-fallback-notice",style:{backgroundColor:"#fef3c7",color:"#78350f",border:"1px solid #f59e0b",borderRadius:"10px",padding:"8px 12px",fontSize:"12px",lineHeight:1.45,boxShadow:"0 8px 24px rgba(15, 23, 42, 0.22)",display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"8px"},children:[r.jsx("span",{children:o}),r.jsx("button",{type:"button",onClick:c,"aria-label":e==="zh"?"关闭提示":"Dismiss notice",style:{backgroundColor:"transparent",color:"#78350f",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:700,padding:"0 4px",lineHeight:1},children:"×"})]}),u&&r.jsxs("div",{style:{backgroundColor:"#0f172a",color:"#f8fafc",border:"1px solid #475569",borderRadius:"10px",padding:"6px 10px",fontSize:"12px",boxShadow:"0 8px 24px rgba(15, 23, 42, 0.3)",display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{color:"#fde68a",fontWeight:600},children:e==="zh"?`预览中: ${s.bundle?.manifest.name||s.themeId}`:`Previewing: ${s.bundle?.manifest.name||s.themeId}`}),r.jsx("button",{type:"button","data-testid":"theme-cancel-preview",onClick:a,style:{backgroundColor:"#334155",color:"#f8fafc",border:"1px solid #64748b",borderRadius:"6px",padding:"3px 8px",fontSize:"11px",fontWeight:600,cursor:"pointer"},children:e==="zh"?"退出预览":"Exit Preview"})]}),r.jsx("button",{type:"button","data-testid":"theme-failsafe-recovery",onClick:()=>void l(),style:{backgroundColor:"#dc2626",color:"#ffffff",border:"1px solid #f87171",borderRadius:"6px",padding:"4px 10px",fontSize:"11px",fontWeight:700,cursor:"pointer"},children:e==="zh"?"一键恢复默认主题":"Reset to Safe Default Theme"})]})]})}let Th=!1;function zI(){if(Th)return;Th=!0;const e=()=>Ye(()=>import("./ActivityWorkspaceWidget-KJQdLnvf.js"),__vite__mapDeps([7,1,2,6,8,9])).then(t=>({default:()=>r.jsx(t.ActivityWorkspaceWidget,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,Re.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}function RI(){return{addToast:b.useCallback((t,n,s="info")=>{const i=Math.random().toString(36).substring(2,9);Te.getState().addToast({id:i,title:t,message:n,type:s}),setTimeout(()=>{Te.getState().removeToast(i)},6e3)},[])}}function _h(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 Ph(e,t){if(t?.aborted)return!0;if(!e||typeof e!="object")return!1;const n=e;return n.name==="AbortError"||n.code===20}function LI(e){const t=e[1];return t?t instanceof Request?t.signal:t.signal??null:null}function OI(){b.useEffect(()=>{if(typeof window>"u")return;const e=o=>{const a=o.reason;if(Ph(a)){console.warn("[GlobalErrorCapture] Ignored aborted request rejection:",a);return}const l=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",c=a instanceof Error?a.stack:void 0;gn.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:l,stack:c}),_h({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;gn.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:l}),_h({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 u="";try{const m=JSON.parse(c);u=m.error||m.message||m.details||c}catch{u=c.slice(0,300)}const d=o[0],f=typeof d=="string"?d:d instanceof Request?d.url:String(d);gn.getState().addError({type:"api",title:`服务端接口错误 (HTTP ${a.status})`,message:u||`Request failed with status ${a.status}`,endpoint:f,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!Ph(a,LI(o))&&c&&(c.startsWith("/api")||c.includes("/api/"))&&gn.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:c,stack:a?.stack}),a}},i=TI(o=>{try{const a=Te.getState(),l=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||l))return;const u=typeof window<"u"?new URLSearchParams(window.location.search):null,d=a.session?.userId||u?.get("studentId")||"anonymous_student",f=a.session?.name||a.session?.username||u?.get("studentName")||d,m=a.selectedLesson||u?.get("lessonId")||null,h=a.liveClassSelectedClassId||u?.get("classId")||null,y={studentId:d,studentName:f,lessonId:m,classId:h,error:o},p=yt();if(p&&p.connected)p.emit("student-client-error",y);else{const x="/api/diagnostics/report",g=JSON.stringify(y);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(x,new Blob([g],{type:"application/json"})):fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:g}).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 DI(e){const{fetchStudents:t}=e,n=ke(w=>w.session),s=ke(w=>w.setSession),i=ke(w=>w.lang),o=ke(w=>w.setLang),[a,l]=b.useState("teacher"),[c,u]=b.useState(!0),[d,f]=b.useState("normal"),[m,h]=b.useState(null),[y,p]=b.useState(!1);return b.useEffect(()=>{if(!n||n.role!=="teacher")return;const w=async()=>{try{const{ok:N,status:j,data:I}=await Aw();N?(I.status==="warning"||I.warning?f("warning"):f("normal"),u(!0)):j===429||j===503?(f("warning"),u(!0)):(f("error"),u(!1))}catch{f("error"),u(!1)}};w();const E=setInterval(w,5e3);return()=>clearInterval(E)},[n]),b.useEffect(()=>{(async()=>{try{const{ok:E,data:N}=await Rf();E&&Te.getState().setSiteInfo({siteName:N.siteName||"",slogan:N.slogan||"",logoUrl:N.logoUrl||null})}catch(E){console.warn("Failed to fetch site settings:",E)}})()},[]),{session:n,setSession:s,lang:i,setLang:o,activeRole:a,setActiveRole:l,setActiveStudentId:h,activeStudentId:m,dbConnected:c,dbStatus:d,profileOpen:y,setProfileOpen:p,handleLoginSuccess:w=>{if(s(w),w.role==="teacher"){l("teacher");const E=typeof window<"u"?Fs(window.location.hash):null;Te.getState().setTeacherTab(E||"live_class")}else l("student"),h(w.studentId),t()},handleLogout:async()=>{try{await _w()}catch(w){console.error("Logout failed",w)}s(null)},toggleLanguage:()=>{o(i==="zh"?"en":"zh")}}}function $I(e){const{activeStudentId:t,activeRole:n,students:s,liveClassFocusLocked:i,setIsFollowingTeacher:o,lang:a,addToast:l}=e,[c,u]=b.useState("dashboard"),d=s.find(U=>U.id===t),f=n==="student"&&(!!t&&!!d?.locked_lesson_id||i),m=d?.lock_mode||"full",h=f,y=f&&m==="full",p=(()=>{if(!d?.lock_target)return null;try{return typeof d.lock_target=="string"?JSON.parse(d.lock_target):d.lock_target}catch{return null}})(),x=b.useRef(h),g=b.useRef(m),v=b.useRef(c);b.useEffect(()=>{x.current=h,g.current=m,v.current=c},[h,m,c]),b.useEffect(()=>{h&&(o(!0),u("lesson"))},[h,o]);const[w,E]=b.useState("whiteboard");b.useEffect(()=>{h&&p?.tab&&E(p.tab)},[h,p?.tab]);const N=U=>{const k=typeof U=="function"?U(v.current):U;if(x.current&&k!=="lesson"){j();return}u(k)},j=()=>{const U=g.current==="navigation";l(a==="zh"?U?"🔒 答题锁定":"🔒 全班专注锁定":U?"🔒 Answer Locked":"🔒 Class Focus Locked",a==="zh"?U?"老师已开启答题锁定,请在当前页面完成作答并提交,暂时无法离开本页。":"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":U?"The teacher locked the screen for answering. Please complete your work on this page before leaving.":"The teacher locked the class focus. Navigation is disabled — please follow the current lesson.","warning")},[I,z]=b.useState(null),[$,V]=b.useState("none"),[B,_]=b.useState(!0);return b.useEffect(()=>{c!=="lesson"&&_(!0)},[c]),{studentViewStatus:c,setStudentViewStatus:N,isStudentLocked:f,isNavigationLocked:h,isInteractionLocked:y,studentLockMode:m,studentLockTarget:p,studentLessonTab:w,setStudentLessonTab:E,studentSelectedCourseware:I,setStudentSelectedCourseware:z,studentFullscreenPanel:$,setStudentFullscreenPanel:V,isStudentLessonContentCollapsed:B,setIsStudentLessonContentCollapsed:_,notifyLockedNavigation:j}}const MI="edu_os_tour_completed",Jm="edu_os_tour_status:";function Ea(e){return e&&(e.userId||e.id||e.username)||null}function FI(e){if(typeof window>"u"||!window.localStorage)return null;try{if(e){const t=window.localStorage.getItem(`${Jm}${e}`);if(t==="completed"||t==="skipped")return t}if(window.localStorage.getItem(MI)==="true")return"completed"}catch{}return null}function BI(e,t){if(typeof window>"u"||!window.localStorage||!e)return!1;try{return window.localStorage.setItem(`${Jm}${e}`,t),!0}catch{return!1}}function UI({lang:e,addToast:t,fetchStudents:n}){const[s,i]=b.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,u=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="stage_display"||window.location.hash.includes("stage_display")),d=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null,f=typeof window<"u"?new URLSearchParams(window.location.search).get("title"):null,m=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")),y=o||h,[p,x]=b.useState(!0),[g,v]=b.useState(!1);b.useEffect(()=>{Ie.getState().initTheme(),Fn.getState().initFontSize();const ue=he=>{(he.ctrlKey||he.metaKey)&&he.altKey&&(he.key==="+"||he.key==="="?(he.preventDefault(),Fn.getState().increaseScale()):he.key==="-"||he.key==="_"?(he.preventDefault(),Fn.getState().decreaseScale()):he.key==="0"&&(he.preventDefault(),Fn.getState().resetScale()))};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[]);const w=ke(ue=>ue.session),E=ke(ue=>ue.setSession),[N,j]=b.useState(!0),I=DI({fetchStudents:n}),{activeRole:z,setActiveRole:$,activeStudentId:V,setActiveStudentId:B,dbConnected:_,dbStatus:U,profileOpen:k,setProfileOpen:F,handleLoginSuccess:Z,handleLogout:M,toggleLanguage:A}=I,L=ke(ue=>ue.students);ke(ue=>ue.dataVersion);const S=ke(ue=>ue.setSelectedLesson),R=$I({activeStudentId:V,activeRole:z,students:L,liveClassFocusLocked:g,setIsFollowingTeacher:x,lang:e,addToast:t}),{studentViewStatus:D,setStudentViewStatus:P,isStudentLocked:Y,isNavigationLocked:H,isInteractionLocked:ee,studentLockMode:le,studentLockTarget:ae,studentLessonTab:fe,setStudentLessonTab:be,studentSelectedCourseware:ye,setStudentSelectedCourseware:Se,studentFullscreenPanel:me,setStudentFullscreenPanel:C,isStudentLessonContentCollapsed:J,setIsStudentLessonContentCollapsed:se,notifyLockedNavigation:W}=R;b.useEffect(()=>{(async()=>{try{const{ok:he,data:K}=await Tw();if(he&&K&&K.session)if(E(K.session),y){$("student"),P("lesson");const we=a||K.session.studentId;we&&B(we),l&&S(l),n()}else $(K.session.role),l&&S(l),K.session.role==="student"&&K.session.studentId&&(B(K.session.studentId),n())}catch(he){console.warn("Session check failed",he)}finally{j(!1)}})()},[]),b.useEffect(()=>{N||Ie.getState().syncWithSession(w?{userId:w.userId,studentId:w.studentId,role:w.role}:null)},[N,w?.userId,w?.studentId,w?.role]);const T=ke(ue=>ue.teacherTab),q=ke(ue=>ue.setTeacherTab),X=b.useRef(!0);b.useEffect(()=>{if(y||u)return;const ue=()=>{const K=Fs(window.location.hash);K&&K!==Te.getState().teacherTab&&q(K)};window.addEventListener("hashchange",ue);const he=Fs(window.location.hash);return he&&he!==Te.getState().teacherTab&&q(he),()=>window.removeEventListener("hashchange",ue)},[q,y,u]),b.useEffect(()=>{if(y||u)return;if(X.current){X.current=!1;const he=Fs(window.location.hash);if(he&&he!==T)return}const ue=Hf(T);window.location.hash!==ue&&(window.location.hash=ue)},[T,q,y,u]);const[ne,Q]=b.useState(!1),re=b.useRef(new Set),[de,te]=b.useState(!1),[O,G]=b.useState(!1),ie=b.useCallback(async ue=>{const he=Te.getState().session,K=Ea(he),we=K??"__anonymous__";if(re.current.add(we),Q(!1),!he)return;const oe=BI(K,ue);let ce=!1;try{ce=!!(await Pw(ue)).ok}catch{ce=!1}if(ce){const pe=Te.getState().session;pe&&Ea(pe)===K&&E({...pe,tourStatus:ue});return}t(e==="zh"?oe?"向导状态已在本地保存,但同步至服务器失败,切换设备或清理存储后可能会再次提示。":"向导状态未能保存到服务器与本地存储,本次会话内已为您抑制重复弹出。":oe?"Tour state was saved locally, but syncing to the server failed.":"Failed to save tour status to the server or local storage; suppressed for this session.","warning")},[t,e,E]);return b.useEffect(()=>{if(!w||w.mustChangePassword){Q(!1);return}if(N||y||w.subRole!=="administrator")return;const ue=Ea(w),he=ue??"__anonymous__";re.current.has(he)||w.tourStatus==="completed"||w.tourStatus==="skipped"||FI(ue)===null&&Q(!0)},[N,w,y]),b.useEffect(()=>{T==="live_class"&&i(!0)},[T]),{mainNavCollapsed:s,setMainNavCollapsed:i,isStudentLiveMode:o,liveStudentParam:a,liveLessonParam:l,liveClassParam:c,isStageDisplayMode:u,stageLessonParam:d,stageTitleParam:f,stageLangParam:m,isStudentPreviewMode:h,isStudentTabMode:y,isFollowingTeacher:p,setIsFollowingTeacher:x,liveClassFocusLocked:g,setLiveClassFocusLocked:v,session:w,setSession:E,sessionLoading:N,fetchStudents:n,sessionBootstrapData:I,activeRole:z,setActiveRole:$,activeStudentId:V,setActiveStudentId:B,dbConnected:_,dbStatus:U,profileOpen:k,setProfileOpen:F,handleLoginSuccess:Z,handleLogout:M,toggleLanguage:A,students:L,setSelectedLesson:S,studentViewStateData:R,studentViewStatus:D,setStudentViewStatus:P,isStudentLocked:Y,isNavigationLocked:H,isInteractionLocked:ee,studentLockMode:le,studentLockTarget:ae,studentLessonTab:fe,setStudentLessonTab:be,studentSelectedCourseware:ye,setStudentSelectedCourseware:Se,studentFullscreenPanel:me,setStudentFullscreenPanel:C,isStudentLessonContentCollapsed:J,setIsStudentLessonContentCollapsed:se,notifyLockedNavigation:W,teacherTab:T,setTeacherTab:q,isTourOpen:ne,setIsTourOpen:Q,dismissTour:ie,isApprovalsCollapsed:de,setIsApprovalsCollapsed:te,isProcessesCollapsed:O,setIsProcessesCollapsed:G}}function VI(e){const[t,n]=b.useState(""),[s,i]=b.useState("recent"),[o,a]=b.useState(!1),[l,c]=b.useState(!1),[u,d]=b.useState(!1),[f,m]=b.useState(null),h=b.useMemo(()=>{let y=[...e];if(t.trim()){const p=t.toLowerCase();y=y.filter(x=>x.title.toLowerCase().includes(p)||x.content.toLowerCase().includes(p))}if(o&&(y=y.filter(p=>(p.enrollment_count||0)>0)),l&&(y=y.filter(p=>p.content&&p.content.trim().length>0)),u){const p=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();y=y.filter(x=>(x.created_at||0)>=p)}return s==="recent"?y.sort((p,x)=>(x.created_at||0)-(p.created_at||0)):s==="alphabetical"?y.sort((p,x)=>p.title.localeCompare(x.title)):s==="enrollment"&&y.sort((p,x)=>(x.enrollment_count||0)-(p.enrollment_count||0)),y},[e,t,s,o,l,u]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:i,filterEnrollment:o,setFilterEnrollment:a,filterHasContent:l,setFilterHasContent:c,filterThisMonth:u,setFilterThisMonth:d,copyingLessonId:f,setCopyingLessonId:m,filteredAndSortedLessons:h}}function cr(e=new Date){const t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${s}`}function WI(){const e=Ow(),t=e?.academicYear==="all"?null:e?.academicYear??null,[n,s]=b.useState([]),[i,o]=b.useState(!1),[a,l]=b.useState({lab_id:null,seats:[]}),[c,u]=b.useState(!1),[d,f]=b.useState([]),[m,h]=b.useState({}),[y,p]=b.useState({}),[x,g]=b.useState(null),[v,w]=b.useState(""),[E,N]=b.useState(""),j=b.useCallback(async()=>{try{o(!0);const B=await fetch("/api/labs");B.ok&&s(await B.json())}catch(B){console.error(B)}finally{o(!1)}},[]),I=b.useCallback(async B=>{try{const _=await fetch(`/api/classes/${B}/seats`);if(_.ok){const U=await _.json();l(U)}}catch(_){console.error(_)}},[]),z=b.useCallback(async()=>{try{const B=cr(),_=await fetch(`/api/schedules/today?date=${B}`);if(_.ok){const U=await _.json();U.success&&U.schedules&&f(U.schedules)}}catch(B){console.warn("Failed to fetch today schedules",B)}},[]),$=b.useCallback(async B=>{try{const _=await fetch(`/api/classes/${B}/schedules${t?`?academicYear=${encodeURIComponent(t)}`:""}`);if(_.ok){const U=await _.json();h(k=>({...k,[B]:U}))}}catch{}},[t]),V=b.useCallback(async B=>{try{const _=await fetch(`/api/schedules/${B}/attendance`);if(_.ok){const U=await _.json();p(k=>({...k,[B]:U}))}}catch{}},[]);return{computerLabs:n,setComputerLabs:s,loadingLabs:i,setLoadingLabs:o,fetchLabs:j,classSeats:a,setClassSeats:l,savingSeats:c,setSavingSeats:u,fetchClassSeats:I,todaySchedules:d,setTodaySchedules:f,fetchTodaySchedules:z,classSchedulesMap:m,setClassSchedulesMap:h,fetchClassSchedules:$,scheduleAttendanceMap:y,setScheduleAttendanceMap:p,fetchScheduleAttendance:V,expandedScheduleId:x,setExpandedScheduleId:g,newScheduleDate:v,setNewScheduleDate:w,newScheduleLessonId:E,setNewScheduleLessonId:N}}function HI(e){const{lang:t,addToast:n,setCopyingLessonId:s}=e,i=ke(h=>h.selectedLesson),o=ke(h=>h.setSelectedLesson),a=ke(h=>h.setElements),l=b.useRef(new Map),c=async()=>{await Te.getState().loadLessons()};return{fetchLessons:c,handleQuickCreateLesson:async(h,y)=>{try{const{ok:p,data:x}=await nS({title:h,content:y});if(p)return await c(),x.id||"lesson-created"}catch(p){console.error("Quick create lesson failed",p)}return""},handleDeleteCourse:async h=>{const{ok:y,data:p}=await sS(h);if(!y)throw new Error(p.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:y,data:p}=await rS(h);if(!y)throw new Error(p.error||"Failed to copy course");await c(),n(t==="zh"?"复制成功":"Course Copied",t==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(y){n(t==="zh"?"复制失败":"Copy Failed",y.message||(t==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{s(null)}},fetchElements:async h=>{try{const{ok:y,data:p}=await iS(h);if(!y)return;const x=JSON.stringify(p);x!==l.current.get(h)&&(l.current.set(h,x),a(p))}catch{}},lastElementsJsonByRoomRef:l}}async function qI(){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 GI(e){const t=await fetch(`/api/vfs${e?`?parentId=${e}`:""}`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function ZI(){const e=await fetch("/api/processes");return e.ok?{ok:!0,data:await e.json()}:{ok:!1}}async function KI(e){const t=await fetch(`/api/processes/${e}/logs`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function YI(e,t){return{ok:(await fetch(`/api/classes/${e}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function QI(e,t){return{ok:(await fetch(`/api/assignments/${e}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}}async function JI(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 XI(e){const t=await fetch(`/api/classes/${e}/progress`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function eA(e){const t=await fetch(`/api/classes/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function tA(e){const t=await fetch(`/api/students/${e}/dashboard`);return t.ok?{ok:!0,data:await t.json()}:{ok:!1}}async function s_(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 nA(e){const{fetchClassSchedules:t}=e,[n,s]=b.useState({}),[i,o]=b.useState({}),[a,l]=b.useState({}),[c,u]=b.useState({}),[d,f]=b.useState({}),[m,h]=b.useState([]),y=async E=>{try{const{ok:N,data:j}=await dS(E);N&&s(I=>({...I,[E]:j}))}catch{}},p=async E=>{try{const{ok:N,data:j}=await XI(E);N&&o(I=>({...I,[E]:j}))}catch{}},x=async E=>{try{const{ok:N,data:j}=await eA(E);N&&l(I=>({...I,[E]:j}))}catch{}};return{classStudentsMap:n,setClassStudentsMap:s,classProgressMap:i,setClassProgressMap:o,classDashboardMap:a,setClassDashboardMap:l,classAssignmentsMap:c,setClassAssignmentsMap:u,assignmentSubmissionsMap:d,setAssignmentSubmissionsMap:f,liveClassStudentProgress:m,setLiveClassStudentProgress:h,fetchClassStudents:y,fetchClassProgress:p,fetchClassDashboard:x,fetchLiveClassStudentProgress:async(E,N)=>{try{const{ok:j,data:I}=await U2(E,N);j&&h(I)}catch{}},handleQuickScheduleClass:async(E,N,j)=>{try{const{ok:I}=await YI(E,{lessonId:N,scheduledDate:j});if(I)return await t(E),!0}catch(I){console.error("Quick schedule class failed",I)}return!1},handleQuickGenerateAssignment:async(E,N,j)=>{const I=N||j||"Assignment";try{const{ok:z,data:$}=await JI(E,I);if(z)return await x(E),$.id||"assignment-created"}catch(z){console.error("Quick generate assignment failed",z)}return null}}}function sA(e){const[t,n]=b.useState([]),[s,i]=b.useState([]),[o,a]=b.useState([]),[l,c]=b.useState(null),[u,d]=b.useState(""),[f,m]=b.useState(!1),[h,y]=b.useState(null);return{registeredCommands:t,setRegisteredCommands:n,vfsNodes:s,setVfsNodes:i,processes:o,setProcesses:a,showProcessLogs:l,setShowProcessLogs:c,processLogsContent:u,setProcessLogsContent:d,showLogs:f,setShowLogs:m,currentVfsParent:h,setCurrentVfsParent:y,fetchRegisteredCommands:async()=>{try{const{ok:w,data:E,contentType:N}=await qI();w&&N&&N.includes("application/json")&&Array.isArray(E)&&n(E)}catch(w){console.warn("Failed to fetch registered commands",w)}},fetchVfs:async w=>{if(e)try{const{ok:E,data:N}=await GI(w);E&&i(N)}catch(E){console.warn("Failed to fetch VFS nodes",E)}},fetchProcesses:async()=>{try{const{ok:w,data:E}=await ZI();w&&a(E)}catch{}},fetchProcessLogs:async w=>{try{const{ok:E,data:N}=await KI(w);E&&(d(N.logs||""),c(w))}catch{}}}}function Hs(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 rA(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+`
|
|
138
|
+
`+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 Yt(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 zh(e){return{name:e?.name||e?.studentName||e?.student_name||"",email:e?.email||e?.studentEmail||e?.student_email||"",student_number:e?.student_number||e?.studentNumber||e?.studentNo||"",password:e?.password||e?.initialPassword||e?.initial_password||"",private_notes:e?.private_notes||e?.privateNotes||e?.notes||e?.note||"",gender:e?.gender||e?.sex||""}}function Rh(e,t){if(!e||e.length===0)return"";const n=e.map(s=>`${s.student_number||"-"} / ${s.name} / ${s.initial_password}`).join(`
|
|
139
|
+
`);return t==="zh"?`
|
|
140
|
+
|
|
141
|
+
🔑 以下 ${e.length} 名学生使用系统生成的初始密码(仅本次显示,请及时分发):
|
|
142
|
+
${n}`:`
|
|
143
|
+
|
|
144
|
+
🔑 Initial passwords for ${e.length} student(s) (shown once — distribute them now):
|
|
145
|
+
${n}`}const iA={zh:{className:"班级名称",classDesc:"班级描述",studentNumber:"学生学号",studentName:"学生姓名",studentEmail:"学生邮箱",password:"初始密码",notes:"学生备注",gender:"性别"},en:{className:"Class Name",classDesc:"Class Desc",studentNumber:"Student Number",studentName:"Student Name",studentEmail:"Student Email",password:"Initial Password",notes:"Student Notes",gender:"Gender"}};function At(e){return e.map(t=>{const n=t??"";return/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}).join(",")}function Lh(e,t){const n=iA[t==="zh"?"zh":"en"];let s,i,o;e==="class"?(s=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",i=At([n.className,n.classDesc,n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes,n.gender]),o=t==="zh"?[At(["高一A班","基础英语课程","20260101","李明","liming@example.com","","","男"]),At(["高一A班","基础英语课程","20260102","王华","wanghua@example.com","","数学较弱","女"])]:[At(["Class 101","Introduction to English","20260101","John Doe","john@example.com","","","Male"]),At(["Class 101","Introduction to English","20260102","Jane Smith","jane@example.com","","","Female"])]):(s=t==="zh"?"学生批量导入模板.csv":"student_import_template.csv",i=At([n.studentNumber,n.studentName,n.studentEmail,n.password,n.notes,n.gender]),o=t==="zh"?[At(["20260101","张三","zhangsan@example.com","","","男"]),At(["20260102","李四","lisi@example.com","","","女"])]:[At(["20260101","Alice Cooper","alice@example.com","","","Male"]),At(["20260102","Bob Dylan","bob@example.com","","","Female"])]);const a=new Blob(["\uFEFF"+i+`
|
|
146
|
+
`+o.join(`
|
|
147
|
+
`)+`
|
|
148
|
+
`],{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 oA(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 u=c.target?.result;if(!u)throw new Error("File content is empty");let d=[],f=[],m=!0;if(e.name.endsWith(".json")){const h=JSON.parse(u);if(!Array.isArray(h))throw new Error("JSON structure must be an array");h.some(p=>p.className||p.name&&(p.students||p.classDescription))?(m=!0,d=h.map(p=>{const x=p.name||p.className||p.class_name,g=p.description||p.classDescription||"",v=p.students||p.studentList||[],w=(Array.isArray(v)?v:[]).map(zh).filter(E=>E.name);return{name:x,description:g,students:w}}).filter(p=>p.name)):(m=!1,f=h.map(zh).filter(p=>p.name))}else{const h=u.split(/\r?\n/);if(h.length<2)throw new Error("CSV has empty or insufficient data");const y=Hs(h[0]).map(z=>z.trim().toLowerCase()),p=Yt(y,["班级名称","class name","classname","class_name","班级"]),x=Yt(y,["班级描述","class desc","classdesc","class_desc","描述"]),g=Yt(y,["学生学号","student number","studentnumber","student_number","student no","学号","编号"]),v=Yt(y,["学生姓名","student name","studentname","student_name","姓名","学生"]),w=Yt(y,["学生邮箱","student email","studentemail","student_email","邮箱","email","mail"]),E=Yt(y,["初始密码","initial password","password","passwd","pwd","密码"]),N=Yt(y,["学生备注","student notes","private_notes","备注","note","remark"]),j=Yt(y,["性别","gender","sex","学生性别"]);if(v===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');const I=z=>({name:z[v]||"",email:w!==-1&&z[w]||"",student_number:g!==-1&&z[g]||"",password:E!==-1&&z[E]||"",private_notes:N!==-1&&z[N]||"",gender:j!==-1&&z[j]||""});if(p!==-1){m=!0;const z={};for(let $=1;$<h.length;$++){const V=h[$].trim();if(!V)continue;const B=Hs(V),_=B[p];if(!_)continue;const U=x!==-1&&B[x]||"",k=I(B);z[_]||(z[_]={name:_,description:U,students:[]}),k.name&&z[_].students.push(k)}d=Object.values(z)}else{m=!1;for(let z=1;z<h.length;z++){const $=h[z].trim();if(!$)continue;const V=I(Hs($));V.name&&f.push(V)}}}if(m){if(d.length===0)throw new Error("No valid class elements found inside file.");const h=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:d})});if(!h.ok){const v=await h.json();throw new Error(v.error||"Server importation failed")}const y=await h.json();await s(),await i();const p=y.imported.length,x=y.imported.reduce((v,w)=>v+(w.studentsCount||0),0),g=Rh(y.credentials,n);o({success:!0,message:n==="zh"?`成功导入 ${p} 个班级、${x} 名学生。${g}`:`Imported ${p} class(es) and ${x} student(s).${g}`})}else{if(f.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:f})});if(!h.ok){const w=await h.json();throw new Error(w.error||"Server student importation failed")}const y=await h.json();await i();const p=y.created??y.imported.filter(w=>w.new).length,x=y.existing??y.imported.filter(w=>!w.new).length,g=(y.imported||[]).filter(w=>w.created&&w.initial_password).map(w=>({student_number:w.student_number,name:w.name,initial_password:w.initial_password})),v=Rh(g,n);o({success:!0,message:n==="zh"?`成功导入 ${p} 名新学生${x?`,${x} 名已存在(按邮箱或学号匹配,已跳过重复创建)`:""}。${v}`:`Imported ${p} new student(s)${x?`, skipped ${x} existing one(s) matched by email or student number`:""}.${v}`})}}catch(u){a(u)}},l.onerror=()=>{a(new Error("Failed to read file from disk."))},l.readAsText(e)})}function aA(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=Hs(l[0]).map(h=>h.trim().toLowerCase()),u=c.findIndex(h=>h.includes("title")||h.includes("标题")||h.includes("课程")),d=c.findIndex(h=>h.includes("content")||h.includes("内容")||h.includes("正文"));if(u===-1||d===-1)throw new Error(t==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const f=rA(l.slice(1)),m=[];for(const h of f){if(!h.trim())continue;const y=Hs(h),p=y[u]?.trim(),x=y[d]?.trim();p&&x&&m.push({title:p,content:x})}if(m.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(m)}catch(a){s(a)}},i.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},i.readAsText(e)})}async function lA(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 u=await c.json();console.warn(`Failed to import item ${a+1}:`,u)}}catch(c){console.warn(`Error importing item ${a+1}:`,c)}s(a+1)}return 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 Oh="openlearn.course-package",zc=20*1024*1024,Cl=Math.round(zc/(1024*1024));function El(e){return`${(e/(1024*1024)).toFixed(1)}MB`}async function cA(){try{const e=await fetch("/api/course-packages/template");if(!e.ok){let n="";try{n=(await e.json())?.error||""}catch{}return{ok:!1,error:n||`模板下载失败(HTTP ${e.status})`}}const t=await e.blob();return Xm(t,"openlearn-course-template.json"),{ok:!0}}catch(e){return{ok:!1,error:e?.message||String(e)}}}async function dA(e){try{const t=await fetch(`/api/lessons/${encodeURIComponent(e)}/export-package`);if(!t.ok){let l="";try{l=(await t.json())?.error||""}catch{}return{ok:!1,error:l||`课程包导出失败(HTTP ${t.status})`}}const n=t.headers.get("X-Course-Package-Filename");let s="course-package.openlearn-package.json";if(n)try{s=decodeURIComponent(n)}catch{}const i=await t.blob();Xm(i,s);const o=Number(t.headers.get("X-Course-Package-Assets")||"0"),a=Number(t.headers.get("X-Course-Package-Skipped")||"0");return{ok:!0,filename:s,assets:Number.isFinite(o)?o:0,skipped:Number.isFinite(a)?a:0}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}function Xm(e,t){const n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.setAttribute("download",t),document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}async function uA(e){if(e.size>zc)return{ok:!1,error:`课程包文件 ${El(e.size)} 超过 ${Cl}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!==Oh)return{ok:!1,error:`不是 OpenLearn 课程包文件(format 应为 "${Oh}")`};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 hA(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 fA=zc;function mA(e){const{lang:t,fetchClasses:n,fetchStudents:s,fetchLessons:i,addToast:o}=e,[a,l]=b.useState(!1),[c,u]=b.useState(null),[d,f]=b.useState(!1),[m,h]=b.useState("system"),[y,p]=b.useState(null),[x,g]=b.useState([]),[v,w]=b.useState(!1),[E,N]=b.useState(!1),j=async()=>{try{w(!0);const{ok:te,data:O}=await Iw();te&&g(O)}catch(te){console.warn("Error fetching library resources:",te)}finally{w(!1)}};b.useEffect(()=>{d&&j()},[d]);const[I,z]=b.useState(!1),[$,V]=b.useState("idle"),[B,_]=b.useState(0),[U,k]=b.useState(0),[F,Z]=b.useState(""),[M,A]=b.useState([]),[L,S]=b.useState(!1),[R,D]=b.useState(null),[P,Y]=b.useState(null),[H,ee]=b.useState(null),le=()=>{Lh("class",t)},ae=async te=>{if(te){if(!te.name.toLowerCase().endsWith(".csv")){V("error"),Z(t==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}V("parsing"),Z("");try{const O=await aA(te,t);A(O)}catch(O){V("error"),Z(O.message||String(O))}}},fe=async te=>{if(!te)return;if(te.size>fA){V("error"),Z(t==="zh"?`文件 ${El(te.size)} 超过 ${Cl}MB 上限,请精简后重试。`:`File is ${El(te.size)}, over the ${Cl}MB limit.`),D(null),Y(null);return}if(te.name.toLowerCase().endsWith(".json")){Z("");try{const G=await uA(te);if(!G.ok){D(null),Y(null),V("error"),Z(G.error);return}Y(G.package),D(G.preview),A([]),V("parsing")}catch(G){V("error"),Z(G?.message||String(G))}return}D(null),Y(null),await ae(te)},be=async()=>{const te=await cA();if(!te.ok){V("error"),Z(te.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")},ye=async te=>{const O=await dA(te);if(!O.ok)return o(t==="zh"?"课程包导出失败":"Course package export failed",O.error||(t==="zh"?"请稍后重试":"Please try again later"),"error"),O;const G=O.skipped??0;return o(t==="zh"?"课程包已导出":"Course package exported",t==="zh"?`${O.filename}(内联 ${O.assets??0} 个附件${G>0?`,${G} 个引用未内联`:""})可直接拖回导入框复用。`:`${O.filename} (${O.assets??0} embedded assets${G>0?`, ${G} reference(s) skipped`:""}). Drop it back into the import dialog to reuse.`,G>0?"warning":"success"),O},Se=async(te=!1)=>{if(!P)return;V("importing"),Z("");const O=await hA(P,{allowDuplicate:te});if(O.ok&&O.result){V("success"),ee(null),await i(),o(t==="zh"?"课程包导入成功":"Course package imported",t==="zh"?`已导入「${O.result.title}」:${O.result.segments} 个教学环节、${O.result.elements} 个白板元素、${O.result.assets} 份课件附件。`:`Imported "${O.result.title}": ${O.result.segments} segments, ${O.result.elements} elements, ${O.result.assets} assets.`,"success");return}if(O.duplicate){ee(O.duplicate),V("error"),Z(O.error||"");return}V("error"),Z(O.error||(t==="zh"?"课程包导入失败":"Course package import failed"))},me=()=>{ee(null),Z(""),V("parsing")},C=async()=>{if(M.length===0)return;V("importing"),_(0),k(M.length);const te=await lA(M,{lang:t,setImportProgress:_,fetchLessons:i});te.success?V("success"):(V("error"),Z(te.errorMsg||""))},[J,se]=b.useState(!1),[W,T]=b.useState(!1),[q,X]=b.useState(null),[ne,Q]=b.useState(null);return{isCloudDriveOpen:a,setIsCloudDriveOpen:l,cloudDrivePreviewNode:c,setCloudDrivePreviewNode:u,isSystemResourceLibraryOpen:d,setIsSystemResourceLibraryOpen:f,systemResourceTab:m,setSystemResourceTab:h,selectedLibraryResourceId:y,setSelectedLibraryResourceId:p,libraryResources:x,setLibraryResources:g,loadingLibraryResources:v,setLoadingLibraryResources:w,showCoursewareHub:E,setShowCoursewareHub:N,fetchLibraryResources:j,isImportLessonsOpen:I,setIsImportLessonsOpen:z,importStatus:$,setImportStatus:V,importProgress:B,setImportProgress:_,importProgressTotal:U,setImportProgressTotal:k,importErrorMsg:F,setImportErrorMsg:Z,previewImportData:M,setPreviewImportData:A,isDraggingImport:L,setIsDraggingImport:S,downloadCsvTemplate:le,handleCSVFileChange:ae,handleCSVImportSubmit:C,packagePreview:R,setPackagePreview:D,pendingCoursePackage:P,packageDuplicate:H,handlePackageDuplicateDismiss:me,handleImportFileChange:fe,handlePackageImportSubmit:Se,downloadCourseTemplate:be,exportCoursePackage:ye,showImportModal:J,setShowImportModal:se,isImporting:W,setIsImporting:T,importError:q,setImportError:X,importSuccess:ne,setImportSuccess:Q,downloadCSVTemplate:te=>{Lh(te,t)},handleImportFile:async te=>{T(!0),X(null),Q(null);try{const O=await oA(te,{lang:t,fetchClasses:n,fetchStudents:s});Q(O.message)}catch(O){X(O.message||String(O))}finally{T(!1)}}}}function Dh(e,t="seg-w"){const n=e==="zh";return[{id:`${t}1`,title:n?"课堂导入":"Course Orientation",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100",notes:n?"明确本课学习目标与情境导入":"Introduce basic goals"},{id:`${t}2`,title:n?"核心精讲":"Subject Core Lecture",type:"lecture",duration:"15m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100",notes:n?"讲解核心概念与重点内容":"Present major content frameworks"},{id:`${t}3`,title:n?"互动演练":"Interactive Lab Work",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100",notes:n?"开展随堂练习与协作实践":"Provide collaborative assignments on terminal or board"},{id:`${t}4`,title:n?"课堂总结":"Lesson Wrap-up",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100",notes:n?"回顾重点知识并安排课后任务":"Reflect and assign task"}]}function pA(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:i,setTeacherTab:o}=e,[a,l]=b.useState(!1),[c,u]=b.useState(1),[d,f]=b.useState(""),[m,h]=b.useState("Mathematics"),[y,p]=b.useState(""),[x,g]=b.useState(""),[v,w]=b.useState(()=>Dh(t)),[E,N]=b.useState(!1),[j,I]=b.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:l,wizardStep:c,setWizardStep:u,wizardCourseTitle:d,setWizardCourseTitle:f,wizardCourseCategory:m,setWizardCourseCategory:h,wizardCourseDescription:y,setWizardCourseDescription:p,wizardCourseContent:x,setWizardCourseContent:g,wizardCourseTimeline:v,setWizardCourseTimeline:w,wizardIsSubmitting:E,setWizardIsSubmitting:N,wizardIsGeneratingOutline:j,handleGenerateOutline:async()=>{if(!j){if(!d.trim()){n(t==="zh"?"请先填写课程课题":"Course Title Required",t==="zh"?"AI 需要课题名称才能生成大纲。":"AI needs a course title to generate the outline.","warning");return}I(!0);try{const V=await fetch("/api/lessons/generate-outline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,category:m,description:y,timeline:v,lang:t})}),B=await V.json().catch(()=>null);if(!V.ok||!B?.success)throw new Error(B?.error||B?.message||`HTTP ${V.status}`);const _=(B.content||"").trim();if(!_)throw new Error(t==="zh"?"AI 返回了空内容":"AI returned empty content");g(_),n(t==="zh"?"✨ AI 大纲生成成功":"✨ AI Outline Generated",t==="zh"?`已根据《${d}》生成 ${_.length} 字的专家级教学大纲。`:`Generated a ${_.length}-character outline for "${d}".`,"success")}catch(V){console.error(V),n(t==="zh"?"AI 大纲生成失败":"AI Outline Generation Failed",V?.message||(t==="zh"?"请确认「系统管理 -> AI 配置」中已配置可用的模型服务。":"Please configure a working AI Provider in System Management -> AI Config."),"error")}finally{I(!1)}}},handleDeployWizardCourse:async()=>{if(!d.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}N(!0);try{const V=x.trim()||`Course outline for ${d} (${m})`,B=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,content:V})});if(B.ok){const U=(await B.json()).result?.lessonId;U&&await fetch(`/api/lessons/${U}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:v})}),await s(),U&&(i(U),o("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${d}》已成功保存到核心SQLite并已自动激活!`:`Course "${d}" is now live in SQLite and auto-activated.`,"success"),l(!1),f(""),h("Mathematics"),p(""),g(""),w(Dh(t)),u(1)}else n("Error","SQLite save failed","warning")}catch(V){console.error(V),n("Error","Launch Exception","warning")}finally{N(!1)}}}}const gA=`exports.default = {
|
|
149
|
+
manifest: {
|
|
150
|
+
id: "@my-scope/hello-world",
|
|
151
|
+
name: "Hello World Plugin",
|
|
152
|
+
version: "1.0.0",
|
|
153
|
+
capabilitiesProposed: ["lesson:read"]
|
|
154
|
+
},
|
|
155
|
+
activate: async (ctx) => {
|
|
156
|
+
ctx.log.info('Hello World plugin activated');
|
|
157
|
+
}
|
|
158
|
+
};`;function xA(e){const{session:t,host:n,lang:s,addToast:i,setChatLog:o,setTeacherTab:a,fetchLessons:l}=e,[c,u]=b.useState([]),[d,f]=b.useState([]),[m,h]=b.useState(!1),[y,p]=b.useState(null),[x,g]=b.useState(""),[v,w]=b.useState(""),[E,N]=b.useState(""),[j,I]=b.useState(""),[z,$]=b.useState(null),[V,B]=b.useState(!1),[_,U]=b.useState("store"),[k,F]=b.useState(gA),[Z,M]=b.useState(!1),[A,L]=b.useState([]),[S,R]=b.useState([]),[D,P]=b.useState({}),[Y,H]=b.useState([]),[ee,le]=b.useState(!1),ae=b.useCallback(async()=>{le(!0);try{const O=await fetch("/api/plugins/orphan-data");if(O.ok){const G=await O.json();H(Array.isArray(G.items)?G.items:[])}}catch(O){console.warn("Failed to fetch plugin orphan data",O)}finally{le(!1)}},[]),fe=b.useCallback(async O=>{try{const G=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(O.pluginId)}/export`,{method:"POST"}),ie=await G.json().catch(()=>({}));G.ok&&ie?.success?(i(s==="zh"?"导出完成":"Export finished",s==="zh"?`已导出 ${ie.tables?.length??0} 张表 / ${ie.rowCount??0} 行到 ${ie.file}`:`Exported ${ie.tables?.length??0} tables / ${ie.rowCount??0} rows to ${ie.file}`,"success"),await ae()):i(s==="zh"?"导出失败":"Export failed",ie?.error||"Unknown error","error")}catch(G){i(s==="zh"?"导出失败":"Export failed",String(G?.message??G),"error")}},[i,ae,s]),be=b.useCallback(async O=>{try{const G=await fetch(`/api/plugins/orphan-data/${encodeURIComponent(O.pluginId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:O.pluginId})}),ie=await G.json().catch(()=>({}));G.ok&&ie?.success?(i(s==="zh"?"已清除插件数据":"Plugin data purged",s==="zh"?`删除 ${ie.droppedTables?.length??0} 张表;归档:${ie.exportFile??"(无)"}`:`Dropped ${ie.droppedTables?.length??0} tables; archive: ${ie.exportFile??"(none)"}`,"success"),await ae()):i(s==="zh"?"清除失败":"Purge failed",ie?.error||"Unknown error","error")}catch(G){i(s==="zh"?"清除失败":"Purge failed",String(G?.message??G),"error")}},[i,ae,s]),ye=b.useCallback(O=>{window.open(`/api/plugins/orphan-data/${encodeURIComponent(O.pluginId)}/archive`,"_blank")},[]),Se=b.useRef(new Set),me=b.useCallback(async()=>{try{const O=await fetch("/api/plugins");if(O.ok){const G=await O.json();u(G)}}catch(O){console.warn("Failed to fetch plugins",O)}},[]),C=b.useCallback(async()=>{try{const O=await fetch("/api/ai-providers");if(O.ok){const G=await O.json();f(G)}}catch(O){console.warn("Failed to fetch AI Providers",O)}},[]);b.useEffect(()=>{me(),t&&t.role!=="student"&&C()},[me,C,t?.role]);const J=b.useCallback(async()=>{try{const O=await fetch("/api/events");O.ok&&L(await O.json())}catch{}},[]),se=b.useCallback(async()=>{try{const O=await fetch("/api/approvals");O.ok&&R(await O.json())}catch{}},[]);return{plugins:c,setPlugins:u,fetchPlugins:me,aiProviders:d,setAiProviders:f,fetchAIProviders:C,isAIProviderModalOpen:m,setIsAIProviderModalOpen:h,editingAIProvider:y,setEditingAIProvider:p,providerName:x,setProviderName:g,providerApiUrl:v,setProviderApiUrl:w,providerApiKey:E,setProviderApiKey:N,providerModelName:j,setProviderModelName:I,testingProviderId:z,setTestingProviderId:$,showPluginModal:V,setShowPluginModal:B,storeTab:_,setStoreTab:U,pluginCode:k,setPluginCode:F,installingPlugin:Z,setInstallingPlugin:M,events:A,setEvents:L,fetchEvents:J,approvals:S,setApprovals:R,fetchApprovals:se,scoreOverrides:D,setScoreOverrides:P,handleSaveAIProvider:async()=>{if(!x.trim()||!v.trim()||!j.trim()){i(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let O;if(y?O=await fetch(`/api/ai-providers/${y.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:v,api_key:E,model_name:j})}):O=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:v,api_key:E,model_name:j})}),O.ok)i(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${x}] 已保存。`:`AI Provider [${x}] has been updated.`,"success"),h(!1),p(null),g(""),w(""),N(""),I(""),C();else{const G=await O.json().catch(()=>({}));i(s==="zh"?"保存失败":"Failed to Save",G.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(O){console.error(O),i(s==="zh"?"保存异常":"Execution Error",O.message||"Error occurred","warning")}},handleDeleteAIProvider:async(O,G)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${G}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${G}]?`))try{(await fetch(`/api/ai-providers/${O}`,{method:"DELETE"})).ok?(i(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${G}] 已经被清除。`:`AI Provider [${G}] has been removed.`,"success"),C()):i(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(ie){console.error(ie),i(s==="zh"?"操作异常":"Execution Error",ie.message||"Error occurred","warning")}},handleTestAIProvider:async O=>{$(O.id);try{const G=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:O.id,api_url:O.api_url,api_key:O.api_key,model_name:O.model_name})}),ie=await G.json();G.ok&&ie.success?i(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${O.name}]。${ie.message}`:`Successfully connected to [${O.name}]. ${ie.message}`,"success"):i(s==="zh"?"测试失败":"Test Failed",ie.error||"Connection error","warning")}catch(G){console.error(G),i(s==="zh"?"连接异常":"Connection Exception",G.message||"Error occurred","warning")}finally{$(null)}},handleInstallPlugin:async()=>{if(k.trim()){M(!0);try{const G=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:k})})).json();G.success?(await me(),B(!1),o(ie=>[...ie,{role:"agent",content:`[System] Plugin "${G.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+G.error)}catch(O){alert("Error: "+O.message)}finally{M(!1)}}},handleZipPluginUpload:async(O,G,ie)=>{M(!0);const ue=ie?.mode==="update";try{const he={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(O.name),"X-Execution-Mode":G,"X-Install-Mode":ue?"update":"install","X-Allow-Downgrade":ie?.allowDowngrade?"true":"false"};ie?.approvePublicRoutes&&(he["X-Approve-Public-Routes"]="true"),ie?.approveCapabilities&&(he["X-Approve-Capabilities"]="true"),ie?.approveNetworkHosts&&(he["X-Approve-Network-Hosts"]="true"),ie?.allowUnsigned&&(he["x-allow-unsigned"]="true"),ue&&(he["X-Acknowledge-Risk"]="true"),ie?.targetPluginId&&(he["X-Target-Plugin-Id"]=encodeURIComponent(ie.targetPluginId));const K=ue&&ie?.targetPluginId?`/api/plugins/${encodeURIComponent(ie.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",we=await fetch(K,{method:"POST",headers:he,body:O}),oe=await we.json().catch(()=>({}));if(!we.ok||!oe.success){const Me=oe.error||"Unknown error";throw i(s==="zh"?ue?"更新失败":"安装失败":ue?"Update Failed":"Installation Failed",Me,"error"),new Error(Me)}const ce=oe.pluginId||oe.manifest?.pluginId||oe.manifest?.id,pe=!!(oe.updated||ue);if(!pe&&ce)await fetch(`/api/plugins/${encodeURIComponent(ce)}/toggle`,{method:"POST"}).catch(()=>{});else if(pe&&oe.wasActive&&ce)try{await n.deactivatePlugin(ce)}catch{}a("plugins"),U("store"),await me(),setTimeout(()=>{me()},1e3);const xe=oe.manifest?.name||ce||O.name,ve=typeof oe.executionMode=="string"?oe.executionMode:G,_e=ve==="process"?s==="zh"?"子进程隔离":"process isolation":ve==="worker"?s==="zh"?"Worker 线程":"worker thread":ve==="inline"?s==="zh"?"主进程":"in-process":ve,je=oe.executionModeCoerced===!0?s==="zh"?"(未受信任插件已强制改为子进程,清单里的 inline/worker 不会生效)":" (untrusted plugin was forced into a child process)":"";if(pe){const Me=oe.oldVersion||"?",et=oe.newVersion||oe.manifest?.version||"?";i(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${xe}" 已从 v${Me} 更新到 v${et}(配置与数据已保留)`:`"${xe}" updated v${Me} → v${et} (config & data preserved)`,"success"),o(Be=>[...Be,{role:"agent",content:`[System] Plugin "${xe}" updated ${Me} → ${et}.`}])}else i(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${xe}" 已上传,实际运行模式为 [${_e}]${je}`:`Plugin "${xe}" installed in [${_e}] mode${je}`,"success"),o(Me=>[...Me,{role:"agent",content:`[System] Plugin "${xe}" installed successfully from ZIP file.`}])}catch(he){const K=he?.message?String(he.message):"";throw K&&K!=="Failed to fetch"&&K!=="Network error"||i(s==="zh"?"网络错误":"Network Error",K||"Network error","error"),he}finally{M(!1)}},handleTogglePlugin:async O=>{if(!Se.current.has(O)){Se.current.add(O);try{const G=await fetch(`/api/plugins/${encodeURIComponent(O)}/toggle`,{method:"POST"}),ie=await G.json().catch(()=>({}));if(G.ok)await me();else{const ue=ie.error||"Unknown error";ue.includes("requires human approval")||ue.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await se()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+ue)}}catch(G){console.error("Failed to toggle plugin:",G),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{Se.current.delete(O)}}},handleDeletePlugin:async(O,G="keep")=>{try{const ie=G==="purge"?`/api/plugins/${encodeURIComponent(O)}?dataPolicy=purge&confirm=purge`:`/api/plugins/${encodeURIComponent(O)}`,ue=await fetch(ie,{method:"DELETE"});if(ue.ok){const he=await ue.json().catch(()=>({}));a("plugins"),U("store"),await me();const K=G==="purge"?s==="zh"?`插件已卸载,数据已清除(归档:${he.exportFile??"无数据需归档"})。`:`Plugin uninstalled and data purged (archive: ${he.exportFile??"nothing to archive"}).`:s==="zh"?`插件已卸载,数据已保留(${he.keptTables?.length??0} 张表),可在「插件数据」中管理。`:`Plugin uninstalled with data kept (${he.keptTables?.length??0} tables). Manage it under Plugin Data.`;o(we=>[...we,{role:"agent",content:`[System] ${K}`}]),i(s==="zh"?"卸载完成":"Uninstalled",K,"success")}else{const he=await ue.json().catch(()=>({}));alert(he.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(ie){console.error("Failed to delete plugin:",ie),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},orphanData:Y,orphanDataLoading:ee,fetchOrphanData:ae,handleExportOrphanData:fe,handlePurgeOrphanData:be,handleDownloadOrphanArchive:ye,handleApprove:async(O,G)=>{try{const ue=await(await fetch(`/api/approvals/${O}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:G})})).json();ue.success?(await se(),await l(),await me()):alert("Action failed: "+ue.error)}catch(ie){console.error(ie)}},handleReject:async O=>{try{await fetch(`/api/approvals/${O}/reject`,{method:"POST"}),await se(),await me()}catch(G){console.error(G)}}}}function bA(){const[e,t]=b.useState(!1),[n,s]=b.useState(null),[i,o]=b.useState("scan_lesson"),[a,l]=b.useState(""),[c,u]=b.useState(""),[d,f]=b.useState(!1),[m,h]=b.useState([]),[y,p]=b.useState([]),[x,g]=b.useState(!1),[v,w]=b.useState({}),[E,N]=b.useState(10),[j,I]=b.useState("quiz"),z=b.useRef(v);return b.useEffect(()=>{z.current=v},[v]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:i,setQuizGenMode:o,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:l,quizGenTopic:c,setQuizGenTopic:u,isGeneratingSuggestions:d,setIsGeneratingSuggestions:f,suggestedObjectives:m,setSuggestedObjectives:h,suggestedQuestions:y,setSuggestedQuestions:p,savingQuiz:x,setSavingQuiz:g,quizStudentAnswers:v,setQuizStudentAnswers:w,quizGenTimeLimit:E,setQuizGenTimeLimit:N,quizStudentAnswersRef:z,subAssignmentTab:j,setSubAssignmentTab:I}}function yA(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:i,fetchClassStudents:o,handleExportAllClassesCombined:a}=e,[l,c]=b.useState(!1),[u,d]=b.useState(new Set),[f,m]=b.useState(new Set),[h,y]=b.useState(null),[p,x]=b.useState(""),[g,v]=b.useState(""),[w,E]=b.useState("");return{batchMode:l,setBatchMode:c,selectedClassIds:u,setSelectedClassIds:d,selectedStudentIds:f,setSelectedStudentIds:m,batchPicker:h,setBatchPicker:y,batchPickerLesson:p,setBatchPickerLesson:x,batchPickerDate:g,setBatchPickerDate:v,batchPickerTargetClass:w,setBatchPickerTargetClass:E,toggleClassSelection:A=>{d(L=>{const S=new Set(L);return S.has(A)?S.delete(A):S.add(A),S})},toggleSelectAllClasses:()=>{d(A=>A.size===n.length&&n.length>0?new Set:new Set(n.map(L=>L.id)))},toggleStudentSelection:A=>{m(L=>{const S=new Set(L);return S.has(A)?S.delete(A):S.add(A),S})},toggleSelectAllStudents:A=>{m(L=>L.size===A.length&&A.length>0?new Set:new Set(A.map(S=>S.id)))},handleBatchDeleteClasses:async()=>{if(u.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${u.size} 个班级吗?该操作不可恢复。`:`Delete ${u.size} selected classes permanently?`)){for(const A of u)await fetch(`/api/classes/${A}`,{method:"DELETE"});d(new Set),await i()}},handleBatchExportClasses:async()=>{u.size!==0&&await a(n.filter(A=>u.has(A.id)))},handleBatchSetPasscode:async()=>{if(u.size===0)return;const A=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(A!==null){for(const L of u)await fetch(`/api/classes/${L}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:A===""?null:A})});d(new Set),await i()}},handleBatchScheduleClasses:()=>{u.size!==0&&(x(""),v(cr()),y("schedule"))},handleBatchDeleteStudents:async()=>{if(!(f.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${f.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${f.size} selected student accounts?`)){for(const A of f)await fetch(`/api/students/${A}`,{method:"DELETE"});m(new Set),await o(s)}},handleBatchResetPassword:async()=>{if(f.size===0||!s)return;const A=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(A===null||A.trim()==="")){for(const L of f)await fetch(`/api/students/${L}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:A})});m(new Set),await o(s)}},handleBatchTransferStudents:()=>{f.size===0||!s||(E(""),y("transfer"))},handleBatchSetLockedLesson:()=>{f.size===0||!s||(x(""),y("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(h==="schedule"){if(!p){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const A of u)await fetch(`/api/classes/${A}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:p,scheduledDate:g+" 09:00:00",status:"scheduled"})});d(new Set)}else if(h==="lockedLesson"){if(!p){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const A of f)await fetch(`/api/students/${A}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:p})});m(new Set)}else if(h==="transfer"){if(!w||w===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const A of f)await fetch(`/api/classes/${s}/students/${A}`,{method:"DELETE"}),await fetch(`/api/classes/${w}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:A})});m(new Set)}y(null),s&&await o(s)}}}}function wA(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[i,o]=b.useState([]),[a,l]=b.useState("seg-1"),[c,u]=b.useState(null),[d,f]=b.useState(null),[m,h]=b.useState("none"),[y,p]=b.useState(null),[x,g]=b.useState(!1),v=b.useRef(null),w=async(E,N)=>{h("saving");try{(await fetch(`/api/lessons/${E}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:N})})).ok?(s(I=>I.map(z=>z.id===E?{...z,timeline:JSON.stringify(N)}:z)),o(N),h("saved"),p(new Date)):h("error")}catch(j){console.error("Failed to save timeline:",j),h("error")}};return b.useEffect(()=>{if(t){const E=n.find(N=>N.id===t);if(E){let N=[];if(E.timeline)try{N=typeof E.timeline=="string"?JSON.parse(E.timeline):E.timeline}catch{N=[{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 N=[{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(N);const j=v.current!==t;v.current=t,N.length>0?(j||!N.some(I=>I.id===a))&&l(N[0].id):l(null)}}},[t,n]),{timelineSegments:i,setTimelineSegments:o,activeSegmentId:a,setActiveSegmentId:l,segmentToEdit:c,setSegmentToEdit:u,draggedSegmentIdx:d,setDraggedSegmentIdx:f,editorSaveStatus:m,setEditorSaveStatus:h,editorLastSavedTime:y,setEditorLastSavedTime:p,editorPanelsExpanded:x,setEditorPanelsExpanded:g,saveTimeline:w}}function ep(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
|
|
159
|
+
`)?`"${t.replace(/"/g,'""')}"`:t}async function vA(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||[],u=i.assignments||[],d={};s.forEach(A=>{d[A.id]={id:A.id,name:A.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(A=>{const L=A.student_id;d[L]&&(d[L].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&d[L].submittedCount++,A.score!==null&&A.score!==void 0&&(d[L].totalGradesSum+=A.score,d[L].gradedCount++))});const f=Object.values(d).map(A=>{const L=A.gradedCount>0?A.totalGradesSum/A.gradedCount:0,S=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avgScore:L,submissionRate:S}});f.sort((A,L)=>L.avgScore-A.avgScore);let m=0,h=0,y=0,p=0;c.forEach(A=>{p++,(A.submission_status==="submitted"||A.submission_status==="graded")&&y++,A.score!==null&&A.score!==void 0&&(m+=A.score,h++)});const x=h>0?m/h:0,g=p>0?y/p*100:0,v={};u.forEach(A=>{v[A.id]={id:A.id,title:A.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(A=>{const L=A.assignment_id;v[L]&&(v[L].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&v[L].submittedCount++,A.score!==null&&A.score!==void 0&&v[L].scores.push(A.score))});const w=Object.values(v).map(A=>{const L=A.scores.length,S=A.scores.reduce((H,ee)=>H+ee,0),R=L>0?S/L:0,D=L>0?Math.max(...A.scores):0,P=L>0?Math.min(...A.scores):0,Y=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avg:R,max:D,min:P,subRate:Y}}),{jsPDF:E}=await Ye(async()=>{const{jsPDF:A}=await import("./vendor-pdf-DNexfcCO.js").then(L=>L.j);return{jsPDF:A}},[]),{applyPlugin:N}=await Ye(async()=>{const{applyPlugin:A}=await import("./vendor-pdf-DNexfcCO.js").then(L=>L.b);return{applyPlugin:A}},[]);N(E);const j=new E({orientation:"p",unit:"mm",format:"a4"}),I=[15,23,42],z=[79,70,229],$=[51,65,85],V=[226,232,240],B=A=>{j.setDrawColor(V[0],V[1],V[2]),j.setLineWidth(.3),j.line(14,A,196,A)};j.setFillColor(I[0],I[1],I[2]),j.rect(0,0,210,42,"F"),j.setTextColor(255,255,255),j.setFont("helvetica","bold"),j.setFontSize(20),j.text("CLASS PERFORMANCE REPORT",14,18),j.setFont("helvetica","normal"),j.setFontSize(10),j.setTextColor(194,205,225),j.text("Academic Insights • Generative Report Summary",14,25),j.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),j.setFillColor(z[0],z[1],z[2]),j.rect(172,10,24,24,"F"),j.setFont("helvetica","bold"),j.setFontSize(14),j.setTextColor(255,255,255),j.text("OS",180,26);let _=52;j.setTextColor(I[0],I[1],I[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("I. EXECUTIVE OVERVIEW",14,_),_+=6;const U=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${u.length} items`],["Global Assignment Submission Rate",`${g.toFixed(1)}%`],["Class Average Performance Score",`${x.toFixed(1)}%`]];j.autoTable({startY:_,head:[["Metric Indicator","Class-wide Metric Value"]],body:U,theme:"striped",headStyles:{fillColor:I,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:$,fontSize:9.5},margin:{left:14,right:14}}),_=j.lastAutoTable.finalY+12,j.setTextColor(I[0],I[1],I[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("II. STUDENT RANKING DISTRIBUTION",14,_),_+=6;const k=f.map((A,L)=>{let S="Excellent";return A.avgScore>=90?S="Excellent (A)":A.avgScore>=75?S="Good (B)":A.avgScore>=60?S="Satisfactory (C)":S="Needs Improvement (D)",[`${L+1}`,A.name,`${A.submittedCount}/${A.totalCount} (${A.submissionRate.toFixed(0)}%)`,`${A.avgScore.toFixed(1)}%`,S]});j.autoTable({startY:_,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:k,theme:"grid",headStyles:{fillColor:z,textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:$,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}}),_=j.lastAutoTable.finalY+12,_>210&&(j.addPage(),_=20),j.setTextColor(I[0],I[1],I[2]),j.setFont("helvetica","bold"),j.setFontSize(12),j.text("III. ASSIGNMENT PERFORMANCE METRICS",14,_),_+=6;const F=w.map(A=>[A.title,`${A.subRate.toFixed(0)}%`,`${A.avg.toFixed(1)}%`,`${A.min.toFixed(0)}% - ${A.max.toFixed(0)}%`]);j.autoTable({startY:_,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:F.length>0?F:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:$,fontSize:9.5},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),_=j.lastAutoTable.finalY+15,B(275),j.setFontSize(8),j.setTextColor(148,163,184),j.text("Generated by OpenLearn Next • Educational Operating System",14,282),j.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const Z=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),M=cr();j.save(`Class_Report_${Z}_${M}.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 SA(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||[],u=l.map(w=>{let E="assignment";if(a[w.id])E=a[w.id];else{const N=w.content&&w.content.startsWith('{"quizType":"mcq_learning_objectives"'),j=w.title&&(w.title.toLowerCase().includes("quiz")||w.title.toLowerCase().includes("test")||w.title.includes("测验")||w.title.includes("测试"));E=N||j?"quiz":"assignment"}return{...w,category:E}}),d=["Student Name","Student Email"];u.forEach(w=>{const E=w.category==="quiz"?"Quiz":"Assignment";d.push(`${E}: ${w.title}`)}),d.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${o}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const f=[d];n.forEach(w=>{const E=[w.name,w.email];let N=0,j=0,I=0,z=0,$=0,V=0,B=0;u.forEach(A=>{const L=c.find(S=>S.assignment_id===A.id&&S.student_id===w.id);if(L&&L.score!==null&&L.score!==void 0){E.push(`${L.score}%`);const S=Number(L.score);A.category==="quiz"?(N+=S,j++):(I+=S,z++),$+=S,V++,B++}else L&&L.submission_status==="submitted"?(E.push("Pending Grade"),B++):E.push("Not Submitted")});const _=j>0?Math.round(N/j):null,U=z>0?Math.round(I/z):null;let k="N/A";if(_!==null&&U!==null){const A=_*(i/100)+U*(o/100);k=`${Math.round(A)}%`}else _!==null?k=`${_}%`:U!==null&&(k=`${U}%`);const F=_!==null?`${_}%`:"N/A",Z=U!==null?`${U}%`:"N/A",M=V>0?`${Math.round($/V)}%`:"N/A";E.push(F,Z,k,M,`${B}`,`${l.length}`),f.push(E.map(ep))});const m=f.map(w=>w.join(",")).join(`
|
|
160
|
+
`),h=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8;"}),y=URL.createObjectURL(h),p=document.createElement("a"),x=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),g=cr(),v=`${x}_grades_report_${g}.csv`;p.setAttribute("href",y),p.setAttribute("download",v),p.style.visibility="hidden",document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(y)}function kA(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]||[],u=s[t];if(!u||!u.assignments||c.length===0)return null;const d=u.assignments||[],f=u.performance||[],m=d.map(x=>{let g="assignment";if(a[x.id])g=a[x.id];else{const v=x.content&&x.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=x.title&&(x.title.toLowerCase().includes("quiz")||x.title.toLowerCase().includes("test")||x.title.includes("测验")||x.title.includes("测试"));g=v||w?"quiz":"assignment"}return{...x,category:g}}),h=["Student Name","Student Email"];m.forEach(x=>{const g=x.category==="quiz"?"Quiz":"Assignment";h.push(`${g}: ${x.title}`)}),h.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${o}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const y=[];return c.slice(0,5).forEach(x=>{const g=[x.name,x.email];let v=0,w=0,E=0,N=0,j=0,I=0,z=0;m.forEach(F=>{const Z=f.find(M=>M.assignment_id===F.id&&M.student_id===x.id);if(Z&&Z.score!==null&&Z.score!==void 0){g.push(`${Z.score}%`);const M=Number(Z.score);F.category==="quiz"?(v+=M,w++):(E+=M,N++),j+=M,I++,z++}else Z&&Z.submission_status==="submitted"?(g.push(l==="zh"?"待评分":"Pending Grade"),z++):g.push(l==="zh"?"未提交":"Not Submitted")});const $=w>0?Math.round(v/w):null,V=N>0?Math.round(E/N):null;let B="N/A";if($!==null&&V!==null){const F=$*(i/100)+V*(o/100);B=`${Math.round(F)}%`}else $!==null?B=`${$}%`:V!==null&&(B=`${V}%`);const _=$!==null?`${$}%`:"N/A",U=V!==null?`${V}%`:"N/A",k=I>0?`${Math.round(j/I)}%`:"N/A";g.push(_,U,B,k,`${z}`,`${d.length}`),y.push(g)}),{headers:h,rows:y,totalStudents:c.length}}function jA(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(d=>{const f=n[d.id]||[],m=s[d.id];if(!m||!m.assignments||f.length===0)return;const h=m.assignments||[],y=h.map(p=>{const x=p.content&&p.content.startsWith('{"quizType":"mcq_learning_objectives"'),g=p.title&&(p.title.toLowerCase().includes("quiz")||p.title.toLowerCase().includes("test")||p.title.includes("测验")||p.title.includes("测试"));return{...p,category:x||g?"quiz":"assignment"}});f.forEach(p=>{let x=0,g=0,v=0,w=0,E=0,N=0;y.forEach(B=>{const _=m.performance?.find(U=>U.student_id===p.id&&U.assignment_id===B.id&&U.submission_status==="graded"&&U.score!==null);if(_){const U=Number(_.score);E+=U,N++,B.category==="quiz"?(x+=U,g++):(v+=U,w++)}});const j=g>0?Math.round(x/g):null,I=w>0?Math.round(v/w):null;let z=0;j!==null&&I!==null?z=Math.round(j*.4+I*.6):j!==null?z=Math.round(j):I!==null&&(z=Math.round(I));const $=N>0?Math.round(E/N):0,V=[d.name,p.name,p.email,j!==null?`${j}%`:"N/A",I!==null?`${I}%`:"N/A",`${z}%`,`${$}%`,`${N}`,`${h.length}`];a.push(V)})}),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(d=>d.map(ep).join(",")).join(`
|
|
161
|
+
`),c=encodeURI(l),u=document.createElement("a");u.setAttribute("href",c),u.setAttribute("download",`All_Classes_Combined_Grades_${cr()}.csv`),document.body.appendChild(u),u.click(),document.body.removeChild(u)}function NA(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:i,fetchClassStudents:o,fetchClassDashboard:a,fetchClassProgress:l,addToast:c=()=>{}}=e,[u,d]=b.useState(!1),[f,m]=b.useState(""),[h,y]=b.useState(""),[p,x]=b.useState(40),[g,v]=b.useState(60),[w,E]=b.useState({}),[N,j]=b.useState(!1),[I,z]=b.useState(!1),[$,V]=b.useState(null),[B,_]=b.useState(!1),[U,k]=b.useState({}),F=b.useCallback(P=>{const Y=Math.min(100,Math.max(0,P));x(Y),v(100-Y)},[]),Z=b.useCallback(P=>{const Y=Math.min(100,Math.max(0,P));v(Y),x(100-Y)},[]),M=b.useMemo(()=>kA({exportClassId:f,classStudentsMap:s,classDashboardMap:i,quizzesWeight:p,assignmentsWeight:g,customCategoryOverrides:w,lang:t}),[f,p,g,w,s,i,t]),A=b.useCallback(async(P,Y)=>{V(P);try{await o(P),await a(P),await l(P),m(P),y(Y),x(40),v(60),E({}),d(!0)}catch(H){console.error(H)}finally{V(null),j(!1)}},[o,a,l]),L=b.useCallback((P,Y,H=40,ee=60,le={})=>{SA({className:Y,students:s[P]||[],dashData:i[P],qWeight:H,aWeight:ee,overrides:le})},[s,i]),S=b.useCallback(async(P,Y)=>{await o(P),await a(P),await l(P),await vA({classId:P,className:Y,students:s[P]||[],dashData:i[P],lang:t,addToast:c,setIsGeneratingPDFReport:k})},[s,i,t,c,o,a,l]),R=b.useCallback(async()=>{_(!0);try{await jA({classes:n,classStudentsMap:s,classDashboardMap:i,lang:t})}catch(P){console.error("Export all classes error:",P)}finally{_(!1),j(!1)}},[n,s,i,t]),D=b.useCallback((P,Y)=>{const H=i[Y];if(!H||!H.performance)return null;const ee=Date.now()-2592e6,ae=H.performance.filter(ye=>ye.student_id===P).filter(ye=>ye.submitted_at&&ye.submitted_at>=ee&&ye.score!==null&&ye.score!==void 0);if(ae.length===0)return null;const be=ae.reduce((ye,Se)=>ye+Number(Se.score),0)/ae.length;return be<60?Math.round(be):null},[i]);return{isExportWeightModalOpen:u,setIsExportWeightModalOpen:d,exportClassId:f,setExportClassId:m,exportClassName:h,setExportClassName:y,quizzesWeight:p,setQuizzesWeight:x,assignmentsWeight:g,setAssignmentsWeight:v,customCategoryOverrides:w,setCustomCategoryOverrides:E,exportDropdownOpen:N,setExportDropdownOpen:j,exportTooltipOpen:I,setExportTooltipOpen:z,loadingExportClassId:$,setLoadingExportClassId:V,isExportingAllCombined:B,setIsExportingAllCombined:_,isGeneratingPDFReport:U,setIsGeneratingPDFReport:k,handleQuizzesWeightChange:F,handleAssignmentsWeightChange:Z,csvPreviewData:M,triggerExportForClass:A,handleExportGrades:L,handleGeneratePDFReport:S,handleExportAllClassesCombined:R,get30DayAverageWarning:D}}const r_={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"}},i_=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],CA=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:Ni,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
|
|
162
|
+
---
|
|
163
|
+
## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
|
|
164
|
+
---
|
|
165
|
+
## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:Wr,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:Ul,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:hi,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
|
|
166
|
+
<div style='padding:20px; text-align:center;'>
|
|
167
|
+
<h2>Interactive Web Courseware</h2>
|
|
168
|
+
<p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
|
|
169
|
+
</div>`},editFields:[{key:"title",labelZh:"标题",labelEn:"Title",kind:"input",placeholderZh:"课件标题",placeholderEn:"Courseware title"},{key:"coursewareUuid",labelZh:"互动课件 (Courseware)",labelEn:"Courseware",kind:"select",loadOptions:async()=>{try{return(await(await fetch("/api/courseware")).json()).map(n=>({value:n.uuid,label:n.name}))}catch{return[]}}},{key:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:ji,color:"amber",group:"assess",defaultData:{question:"New Quiz",options:["A","B","C","D"]},editFields:[{key:"question",labelZh:"题目",labelEn:"Question",kind:"input",placeholderZh:"请输入题目"},{key:"options",labelZh:"选项 (A/B/C/D)",labelEn:"Options (A/B/C/D)",kind:"options"}]},{type:"assignment",labelZh:"作业提交",labelEn:"Assignment",descriptionZh:"布置与提交",descriptionEn:"Submit work",icon:Zn,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:ef,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:ut,color:"pink",group:"manage",defaultData:{},editFields:[]}],EA=CA.reduce((e,t)=>(e[t.type]=t,e),{});function IA(e){return EA[e]||Wn.get(e)}const $h="openlearnv2.agentProviderId";function AA({lang:e,addToast:t,host:n,session:s,fetchStudents:i,fetchClasses:o,chatLogRef:a}){const l=ke(Ne=>Ne.lessons),c=ke(Ne=>Ne.setLessons),u=VI(l),{lessonsSearchQuery:d,setLessonsSearchQuery:f,lessonsSortOrder:m,setLessonsSortOrder:h,filterEnrollment:y,setFilterEnrollment:p,filterHasContent:x,setFilterHasContent:g,filterThisMonth:v,setFilterThisMonth:w,copyingLessonId:E,setCopyingLessonId:N,filteredAndSortedLessons:j}=u,I=ke(Ne=>Ne.selectedLesson),z=ke(Ne=>Ne.setSelectedLesson),$=ke(Ne=>Ne.elements),V=ke(Ne=>Ne.setElements),[B,_]=b.useState(!1),[U,k]=b.useState("agent"),F=ke(Ne=>Ne.classes),Z=ke(Ne=>Ne.setClasses),M=ke(Ne=>Ne.students),A=ke(Ne=>Ne.setStudents);ke(Ne=>Ne.dataVersion);const L=WI(),{computerLabs:S,setComputerLabs:R,loadingLabs:D,setLoadingLabs:P,fetchLabs:Y,classSeats:H,setClassSeats:ee,savingSeats:le,setSavingSeats:ae,fetchClassSeats:fe,todaySchedules:be,setTodaySchedules:ye,fetchTodaySchedules:Se,classSchedulesMap:me,setClassSchedulesMap:C,fetchClassSchedules:J,scheduleAttendanceMap:se,setScheduleAttendanceMap:W,fetchScheduleAttendance:T,expandedScheduleId:q,setExpandedScheduleId:X,newScheduleDate:ne,setNewScheduleDate:Q,newScheduleLessonId:re,setNewScheduleLessonId:de}=L,te=HI({lang:e,addToast:t,setCopyingLessonId:N}),{fetchLessons:O,handleQuickCreateLesson:G,handleDeleteCourse:ie,handleCopyCourse:ue,fetchElements:he}=te,K=nA({fetchClassSchedules:J}),{classStudentsMap:we,setClassStudentsMap:oe,classProgressMap:ce,setClassProgressMap:pe,classDashboardMap:xe,setClassDashboardMap:ve,classAssignmentsMap:_e,setClassAssignmentsMap:je,assignmentSubmissionsMap:Me,setAssignmentSubmissionsMap:et,liveClassStudentProgress:Be,setLiveClassStudentProgress:st,fetchClassStudents:ft,fetchClassProgress:Cn,fetchClassDashboard:Ve,fetchLiveClassStudentProgress:ns,handleQuickScheduleClass:ss,handleQuickGenerateAssignment:rs}=K,[En,is]=b.useState(null),In=Ne=>{is(Ne)},[os,as]=b.useState(null),ls=Ne=>{as(Ne)},Ut=b.useRef(null),[An,rn]=b.useState(null),cs=Ne=>{const js=IA(Ne);js&&rn({type:Ne,data:{...js.defaultData}})},ds=async Ne=>{const js=An;if(rn(null),!js)return;const Zb=Date.now()+15e3;for(;Date.now()<Zb;){const Zc=Ut.current?.addElementAtCenter;if(typeof Zc=="function"){await Zc(js.type,Ne);return}await new Promise(Kb=>setTimeout(Kb,50))}},Vt=ke(Ne=>Ne.siteInfo),Tn=ke(Ne=>Ne.setSiteInfo),_n=wA({selectedLesson:I,lessons:l,setLessons:c}),{timelineSegments:us,setTimelineSegments:We,activeSegmentId:hs,setActiveSegmentId:fs,segmentToEdit:ms,setSegmentToEdit:ps,draggedSegmentIdx:gs,setDraggedSegmentIdx:xs,editorSaveStatus:bs,setEditorSaveStatus:ys,editorLastSavedTime:ws,setEditorLastSavedTime:vs,editorPanelsExpanded:Ss,setEditorPanelsExpanded:ks,saveTimeline:Pe}=_n,rt=sA(s),{registeredCommands:on,setRegisteredCommands:Ae,vfsNodes:tt,setVfsNodes:at,processes:an,setProcesses:Qe,showProcessLogs:mt,setShowProcessLogs:ln,processLogsContent:Wt,setProcessLogsContent:Fi,showLogs:dr,setShowLogs:Bi,currentVfsParent:ur,setCurrentVfsParent:Ui,fetchRegisteredCommands:Vi,fetchVfs:hr,fetchProcesses:Wi,fetchProcessLogs:Hi}=rt,Je=mA({lang:e,fetchClasses:o,fetchStudents:i,fetchLessons:O,addToast:t}),{isCloudDriveOpen:gp,setIsCloudDriveOpen:xp,cloudDrivePreviewNode:bp,setCloudDrivePreviewNode:yp,isSystemResourceLibraryOpen:wp,setIsSystemResourceLibraryOpen:vp,systemResourceTab:Sp,setSystemResourceTab:kp,selectedLibraryResourceId:jp,setSelectedLibraryResourceId:Np,libraryResources:Cp,setLibraryResources:Ep,loadingLibraryResources:Ip,setLoadingLibraryResources:Ap,showCoursewareHub:Tp,setShowCoursewareHub:_p,fetchLibraryResources:Pp,isImportLessonsOpen:zp,setIsImportLessonsOpen:Rp,importStatus:Lp,setImportStatus:Op,importProgress:Dp,setImportProgress:$p,importProgressTotal:Mp,setImportProgressTotal:Fp,importErrorMsg:Bp,setImportErrorMsg:Up,previewImportData:Vp,setPreviewImportData:Wp,isDraggingImport:Hp,setIsDraggingImport:qp,downloadCsvTemplate:Gp,handleCSVFileChange:Zp,handleCSVImportSubmit:Kp,showImportModal:Yp,setShowImportModal:Qp,isImporting:Jp,setIsImporting:Xp,importError:eg,setImportError:tg,importSuccess:ng,setImportSuccess:sg,downloadCSVTemplate:rg,handleImportFile:ig}=Je,Mc=ke(Ne=>Ne.setTeacherTab),Fc=pA({lang:e,addToast:t,fetchLessons:O,setSelectedLesson:z,setTeacherTab:Mc}),{isCourseWizardOpen:og,setIsCourseWizardOpen:ag,wizardStep:lg,setWizardStep:cg,wizardCourseTitle:dg,setWizardCourseTitle:ug,wizardCourseCategory:hg,setWizardCourseCategory:fg,wizardCourseDescription:mg,setWizardCourseDescription:pg,wizardCourseContent:gg,setWizardCourseContent:xg,wizardCourseTimeline:bg,setWizardCourseTimeline:yg,wizardIsSubmitting:wg,wizardIsGeneratingOutline:vg,handleGenerateOutline:Sg,handleDeployWizardCourse:kg}=Fc,Bc=xA({session:s,host:n,lang:e,addToast:t,setChatLog:Ne=>a.current(Ne),setTeacherTab:Mc,fetchLessons:O}),{plugins:jg,setPlugins:Ng,fetchPlugins:Cg,aiProviders:Ht,setAiProviders:Eg,fetchAIProviders:Ig,isAIProviderModalOpen:Ag,setIsAIProviderModalOpen:Tg,editingAIProvider:_g,setEditingAIProvider:Pg,providerName:zg,setProviderName:Rg,providerApiUrl:Lg,setProviderApiUrl:Og,providerApiKey:Dg,setProviderApiKey:$g,providerModelName:Mg,setProviderModelName:Fg,testingProviderId:Bg,setTestingProviderId:Ug,showPluginModal:Vg,setShowPluginModal:Wg,storeTab:Hg,setStoreTab:qg,pluginCode:Gg,setPluginCode:Zg,installingPlugin:Kg,setInstallingPlugin:Yg,events:Qg,setEvents:Jg,fetchEvents:Xg,approvals:ex,setApprovals:tx,fetchApprovals:nx,scoreOverrides:sx,setScoreOverrides:rx,handleSaveAIProvider:ix,handleDeleteAIProvider:ox,handleTestAIProvider:ax,handleInstallPlugin:lx,handleZipPluginUpload:cx,handleTogglePlugin:dx,handleDeletePlugin:ux,handleApprove:hx,handleReject:fx}=Bc,[cn,Uc]=b.useState(()=>typeof window>"u"?"":window.localStorage.getItem($h)||""),Vc=Ht.some(Ne=>Ne.id===cn)?cn:Ht[0]?.id||"",mx=Ht.find(Ne=>Ne.id===Vc)||null;b.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem($h,cn)},[cn]),b.useEffect(()=>{Ht.length>0&&!Ht.some(Ne=>Ne.id===cn)&&Uc(Ht[0].id)},[Ht,cn]);const Wc=bA(),{isQuizGeneratorOpen:px,setIsQuizGeneratorOpen:gx,quizGeneratorClassId:xx,setQuizGeneratorClassId:bx,quizGenMode:yx,setQuizGenMode:wx,quizGenSelectedLessonId:vx,setQuizGenSelectedLessonId:Sx,quizGenTopic:kx,setQuizGenTopic:jx,isGeneratingSuggestions:Nx,setIsGeneratingSuggestions:Cx,suggestedObjectives:Ex,setSuggestedObjectives:Ix,suggestedQuestions:Ax,setSuggestedQuestions:Tx,savingQuiz:_x,setSavingQuiz:Px,quizStudentAnswers:zx,setQuizStudentAnswers:Rx,quizGenTimeLimit:Lx,setQuizGenTimeLimit:Ox,quizStudentAnswersRef:Dx,subAssignmentTab:$x,setSubAssignmentTab:Mx}=Wc,[Fx,Bx]=b.useState(null),[Ux,Vx]=b.useState("dueDate"),[Wx,Hx]=b.useState({}),Hc=NA({lang:e,classes:F,classStudentsMap:we,classDashboardMap:xe,fetchClassStudents:ft,fetchClassDashboard:Ve,fetchClassProgress:Cn}),{isExportWeightModalOpen:qx,setIsExportWeightModalOpen:Gx,exportClassId:Zx,setExportClassId:Kx,exportClassName:Yx,setExportClassName:Qx,quizzesWeight:Jx,setQuizzesWeight:Xx,assignmentsWeight:eb,setAssignmentsWeight:tb,customCategoryOverrides:nb,setCustomCategoryOverrides:sb,exportDropdownOpen:rb,setExportDropdownOpen:ib,exportTooltipOpen:ob,setExportTooltipOpen:ab,loadingExportClassId:lb,setLoadingExportClassId:cb,isExportingAllCombined:db,setIsExportingAllCombined:ub,isGeneratingPDFReport:hb,setIsGeneratingPDFReport:fb,handleQuizzesWeightChange:mb,handleAssignmentsWeightChange:pb,csvPreviewData:gb,triggerExportForClass:xb,handleExportGrades:bb,handleGeneratePDFReport:yb,handleExportAllClassesCombined:qc,get30DayAverageWarning:wb}=Hc,Gc=yA({lang:e,classes:F,expandedClassId:En,fetchClasses:o,fetchClassStudents:ft,handleExportAllClassesCombined:qc}),{batchMode:vb,setBatchMode:Sb,selectedClassIds:kb,setSelectedClassIds:jb,selectedStudentIds:Nb,setSelectedStudentIds:Cb,batchPicker:Eb,setBatchPicker:Ib,batchPickerLesson:Ab,setBatchPickerLesson:Tb,batchPickerDate:_b,setBatchPickerDate:Pb,batchPickerTargetClass:zb,setBatchPickerTargetClass:Rb,toggleClassSelection:Lb,toggleSelectAllClasses:Ob,toggleStudentSelection:Db,toggleSelectAllStudents:$b,handleBatchDeleteClasses:Mb,handleBatchExportClasses:Fb,handleBatchSetPasscode:Bb,handleBatchScheduleClasses:Ub,handleBatchDeleteStudents:Vb,handleBatchResetPassword:Wb,handleBatchTransferStudents:Hb,handleBatchSetLockedLesson:qb,confirmBatchPicker:Gb}=Gc;return{lessons:l,setLessons:c,lessonFilteringData:u,lessonsSearchQuery:d,setLessonsSearchQuery:f,lessonsSortOrder:m,setLessonsSortOrder:h,filterEnrollment:y,setFilterEnrollment:p,filterHasContent:x,setFilterHasContent:g,filterThisMonth:v,setFilterThisMonth:w,copyingLessonId:E,setCopyingLessonId:N,filteredAndSortedLessons:j,selectedLesson:I,setSelectedLesson:z,elements:$,setElements:V,showRightSidebar:B,setShowRightSidebar:_,rightSidebarTab:U,setRightSidebarTab:k,classes:F,setClasses:Z,students:M,setStudents:A,labAndScheduleData:L,computerLabs:S,setComputerLabs:R,loadingLabs:D,setLoadingLabs:P,fetchLabs:Y,classSeats:H,setClassSeats:ee,savingSeats:le,setSavingSeats:ae,fetchClassSeats:fe,todaySchedules:be,setTodaySchedules:ye,fetchTodaySchedules:Se,classSchedulesMap:me,setClassSchedulesMap:C,fetchClassSchedules:J,scheduleAttendanceMap:se,setScheduleAttendanceMap:W,fetchScheduleAttendance:T,expandedScheduleId:q,setExpandedScheduleId:X,newScheduleDate:ne,setNewScheduleDate:Q,newScheduleLessonId:re,setNewScheduleLessonId:de,lessonCrudData:te,fetchLessons:O,handleQuickCreateLesson:G,handleDeleteCourse:ie,handleCopyCourse:ue,fetchElements:he,classOpsData:K,classStudentsMap:we,setClassStudentsMap:oe,classProgressMap:ce,setClassProgressMap:pe,classDashboardMap:xe,setClassDashboardMap:ve,classAssignmentsMap:_e,setClassAssignmentsMap:je,assignmentSubmissionsMap:Me,setAssignmentSubmissionsMap:et,liveClassStudentProgress:Be,setLiveClassStudentProgress:st,fetchClassStudents:ft,fetchClassProgress:Cn,fetchClassDashboard:Ve,fetchLiveClassStudentProgress:ns,handleQuickScheduleClass:ss,handleQuickGenerateAssignment:rs,expandedClassId:En,setExpandedClassId:In,expandedStudentId:os,setExpandedStudentId:ls,whiteboardRef:Ut,paletteEdit:An,setPaletteEdit:rn,handlePaletteActivate:cs,handlePaletteConfirm:ds,siteInfo:Vt,setSiteInfo:Tn,lessonTimelineData:_n,timelineSegments:us,setTimelineSegments:We,activeSegmentId:hs,setActiveSegmentId:fs,segmentToEdit:ms,setSegmentToEdit:ps,draggedSegmentIdx:gs,setDraggedSegmentIdx:xs,editorSaveStatus:bs,setEditorSaveStatus:ys,editorLastSavedTime:ws,setEditorLastSavedTime:vs,editorPanelsExpanded:Ss,setEditorPanelsExpanded:ks,saveTimeline:Pe,systemData:rt,registeredCommands:on,setRegisteredCommands:Ae,vfsNodes:tt,setVfsNodes:at,processes:an,setProcesses:Qe,showProcessLogs:mt,setShowProcessLogs:ln,processLogsContent:Wt,setProcessLogsContent:Fi,showLogs:dr,setShowLogs:Bi,currentVfsParent:ur,setCurrentVfsParent:Ui,fetchRegisteredCommands:Vi,fetchVfs:hr,fetchProcesses:Wi,fetchProcessLogs:Hi,resourceLibraryData:Je,isCloudDriveOpen:gp,setIsCloudDriveOpen:xp,cloudDrivePreviewNode:bp,setCloudDrivePreviewNode:yp,isSystemResourceLibraryOpen:wp,setIsSystemResourceLibraryOpen:vp,systemResourceTab:Sp,setSystemResourceTab:kp,selectedLibraryResourceId:jp,setSelectedLibraryResourceId:Np,libraryResources:Cp,setLibraryResources:Ep,loadingLibraryResources:Ip,setLoadingLibraryResources:Ap,showCoursewareHub:Tp,setShowCoursewareHub:_p,fetchLibraryResources:Pp,isImportLessonsOpen:zp,setIsImportLessonsOpen:Rp,importStatus:Lp,setImportStatus:Op,importProgress:Dp,setImportProgress:$p,importProgressTotal:Mp,setImportProgressTotal:Fp,importErrorMsg:Bp,setImportErrorMsg:Up,previewImportData:Vp,setPreviewImportData:Wp,isDraggingImport:Hp,setIsDraggingImport:qp,downloadCsvTemplate:Gp,handleCSVFileChange:Zp,handleCSVImportSubmit:Kp,showImportModal:Yp,setShowImportModal:Qp,isImporting:Jp,setIsImporting:Xp,importError:eg,setImportError:tg,importSuccess:ng,setImportSuccess:sg,downloadCSVTemplate:rg,handleImportFile:ig,courseWizard:Fc,isCourseWizardOpen:og,setIsCourseWizardOpen:ag,wizardStep:lg,setWizardStep:cg,wizardCourseTitle:dg,setWizardCourseTitle:ug,wizardCourseCategory:hg,setWizardCourseCategory:fg,wizardCourseDescription:mg,setWizardCourseDescription:pg,wizardCourseContent:gg,setWizardCourseContent:xg,wizardCourseTimeline:bg,setWizardCourseTimeline:yg,wizardIsSubmitting:wg,wizardIsGeneratingOutline:vg,handleGenerateOutline:Sg,handleDeployWizardCourse:kg,pluginManagementData:Bc,plugins:jg,setPlugins:Ng,fetchPlugins:Cg,aiProviders:Ht,setAiProviders:Eg,fetchAIProviders:Ig,isAIProviderModalOpen:Ag,setIsAIProviderModalOpen:Tg,editingAIProvider:_g,setEditingAIProvider:Pg,providerName:zg,setProviderName:Rg,providerApiUrl:Lg,setProviderApiUrl:Og,providerApiKey:Dg,setProviderApiKey:$g,providerModelName:Mg,setProviderModelName:Fg,testingProviderId:Bg,setTestingProviderId:Ug,showPluginModal:Vg,setShowPluginModal:Wg,storeTab:Hg,setStoreTab:qg,pluginCode:Gg,setPluginCode:Zg,installingPlugin:Kg,setInstallingPlugin:Yg,events:Qg,setEvents:Jg,fetchEvents:Xg,approvals:ex,setApprovals:tx,fetchApprovals:nx,scoreOverrides:sx,setScoreOverrides:rx,handleSaveAIProvider:ix,handleDeleteAIProvider:ox,handleTestAIProvider:ax,handleInstallPlugin:lx,handleZipPluginUpload:cx,handleTogglePlugin:dx,handleDeletePlugin:ux,handleApprove:hx,handleReject:fx,agentProviderId:cn,setAgentProviderId:Uc,effectiveAgentProviderId:Vc,selectedAgentProvider:mx,quizGenerator:Wc,isQuizGeneratorOpen:px,setIsQuizGeneratorOpen:gx,quizGeneratorClassId:xx,setQuizGeneratorClassId:bx,quizGenMode:yx,setQuizGenMode:wx,quizGenSelectedLessonId:vx,setQuizGenSelectedLessonId:Sx,quizGenTopic:kx,setQuizGenTopic:jx,isGeneratingSuggestions:Nx,setIsGeneratingSuggestions:Cx,suggestedObjectives:Ex,setSuggestedObjectives:Ix,suggestedQuestions:Ax,setSuggestedQuestions:Tx,savingQuiz:_x,setSavingQuiz:Px,quizStudentAnswers:zx,setQuizStudentAnswers:Rx,quizGenTimeLimit:Lx,setQuizGenTimeLimit:Ox,quizStudentAnswersRef:Dx,subAssignmentTab:$x,setSubAssignmentTab:Mx,isGeneratingAssignment:Fx,setIsGeneratingAssignment:Bx,assignmentSortOrder:Ux,setAssignmentSortOrder:Vx,isGrading:Wx,setIsGrading:Hx,gradeExport:Hc,isExportWeightModalOpen:qx,setIsExportWeightModalOpen:Gx,exportClassId:Zx,setExportClassId:Kx,exportClassName:Yx,setExportClassName:Qx,quizzesWeight:Jx,setQuizzesWeight:Xx,assignmentsWeight:eb,setAssignmentsWeight:tb,customCategoryOverrides:nb,setCustomCategoryOverrides:sb,exportDropdownOpen:rb,setExportDropdownOpen:ib,exportTooltipOpen:ob,setExportTooltipOpen:ab,loadingExportClassId:lb,setLoadingExportClassId:cb,isExportingAllCombined:db,setIsExportingAllCombined:ub,isGeneratingPDFReport:hb,setIsGeneratingPDFReport:fb,handleQuizzesWeightChange:mb,handleAssignmentsWeightChange:pb,csvPreviewData:gb,triggerExportForClass:xb,handleExportGrades:bb,handleGeneratePDFReport:yb,handleExportAllClassesCombined:qc,get30DayAverageWarning:wb,classBatch:Gc,batchMode:vb,setBatchMode:Sb,selectedClassIds:kb,setSelectedClassIds:jb,selectedStudentIds:Nb,setSelectedStudentIds:Cb,batchPicker:Eb,setBatchPicker:Ib,batchPickerLesson:Ab,setBatchPickerLesson:Tb,batchPickerDate:_b,setBatchPickerDate:Pb,batchPickerTargetClass:zb,setBatchPickerTargetClass:Rb,toggleClassSelection:Lb,toggleSelectAllClasses:Ob,toggleStudentSelection:Db,toggleSelectAllStudents:$b,handleBatchDeleteClasses:Mb,handleBatchExportClasses:Fb,handleBatchSetPasscode:Bb,handleBatchScheduleClasses:Ub,handleBatchDeleteStudents:Vb,handleBatchResetPassword:Wb,handleBatchTransferStudents:Hb,handleBatchSetLockedLesson:qb,confirmBatchPicker:Gb,handleSeedSuccess:async Ne=>{await o(),await O(),await Se().catch(()=>{}),Te.getState().setLiveClassSelectedClassId(Ne.classId),z(Ne.lessonId),Te.getState().setLiveClassIsActive(!0),t(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")}}}function TA(){const[e,t]=b.useState(null),[n,s]=b.useState(null);b.useEffect(()=>{if(n){const h=setTimeout(()=>{s(null)},8e3);return()=>clearTimeout(h)}},[n]),b.useEffect(()=>{if(e)try{const h=window.AudioContext||window.webkitAudioContext;if(h){const y=new h,p=y.currentTime,x=y.createOscillator(),g=y.createGain();x.type="sine",x.frequency.setValueAtTime(587.33,p),x.frequency.exponentialRampToValueAtTime(880,p+.25),g.gain.setValueAtTime(.25,p),g.gain.exponentialRampToValueAtTime(.001,p+.8),x.connect(g),g.connect(y.destination);let v=!1;const w=()=>{v||(v=!0,y.close().catch(()=>{}))};x.onended=w,setTimeout(w,1100),x.start(p),x.stop(p+.8)}}catch{}},[e]);const[i,o]=b.useState([]),a=h=>{o(y=>{const p=typeof h=="function"?h(y):h;return Array.isArray(p)&&p.length>200?p.slice(0,200):p})},[l,c]=b.useState(new Map),[u,d]=b.useState([]),[f,m]=b.useState({});return{pickedAlertData:e,setPickedAlertData:t,pickedAnnouncement:n,setPickedAnnouncement:s,liveClassFeed:i,setLiveClassFeed:a,liveClassAcknowledgedMap:l,setLiveClassAcknowledgedMap:c,onlineStudentIds:u,setOnlineStudentIds:d,activeStudentLessons:f,setActiveStudentLessons:m}}function _A(e){const{activeStudentId:t,activeRole:n,selectedLesson:s,quizStudentAnswersRef:i,setStudentViewStatus:o}=e,a=ke(v=>v.session),l=ke(v=>v.setSelectedLesson),[c,u]=b.useState(null),[d,f]=b.useState({}),[m,h]=b.useState(null),y=async v=>{try{const{ok:w,data:E}=await tA(v);if(w){if(u(E),E.profile){const N=E.profile,j=Te.getState().students,I=j.findIndex(V=>V.id===E.profile.id),z=I>=0?j[I]:null;if(!z||z.locked_lesson_id!==N.locked_lesson_id||z.lock_mode!==N.lock_mode||JSON.stringify(z.lock_target)!==JSON.stringify(N.lock_target)||z.name!==N.name)if(I>=0){const V=[...j];V[I]={...V[I],...N},Te.getState().setStudents(V)}else Te.getState().setStudents([N])}E.profile&&E.profile.locked_lesson_id&&(l(E.profile.locked_lesson_id),o("lesson"))}}catch{}},p=async(v=!1)=>{if(!m||!t)return;const E=m?.content&&m.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(i.current):"Submitted via Whiteboard";try{const{ok:N}=await QI(m.id,{studentId:t,content:E});N&&(v&&alert("Time is up! Your assessment was successfully submitted automatically."),await y(t),o("dashboard"),h(null))}catch(N){console.error(N)}};return b.useEffect(()=>{a&&n==="student"&&t&&y(t)},[a,n,t]),{studentDashboardData:c,setStudentDashboardData:u,studentProgressMap:d,setStudentProgressMap:f,selectedAssignment:m,setSelectedAssignment:h,fetchStudentDashboard:y,fetchStudentProgress:async v=>{try{const{ok:w,data:E}=await V2(v);w&&f(N=>({...N,[v]:E}))}catch{}},updateStudentProgress:async v=>{if(n==="student"&&t&&s)try{await B2(t,{lessonId:s,completed:v===100,progressPercent:v})}catch(w){console.error("Failed to update student progress:",w)}},submitQuizAssignment:p}}function PA(e,t,n){const[s,i]=b.useState(new Set),[o,a]=b.useState(null),[l,c]=b.useState(!1),u=b.useMemo(()=>{if(e!=="student"||!t)return[];const f=[],m=t.assignments||[];for(const h of m)if(!h.submission_status)f.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 y=!!h.feedback;f.push({id:`graded-${h.id}`,type:"graded",title:y?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:y?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 f.sort((h,y)=>y.date-h.date)},[e,t,n]),d=b.useMemo(()=>u.filter(f=>!s.has(f.id)),[u,s]);return{studentNotifications:u,unreadNotifications:d,readNotifications:s,setReadNotifications:i,selectedNotificationForModal:o,setSelectedNotificationForModal:a,isNotificationsOpen:l,setIsNotificationsOpen:c}}function zA(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:i,selectedLesson:o,selectedAssignment:a,expandedClassId:l,fetchLessons:c,fetchPlugins:u,fetchRegisteredCommands:d,fetchEvents:f,fetchApprovals:m,fetchProcesses:h,fetchClasses:y,fetchTodaySchedules:p,fetchStudents:x,fetchLabs:g,fetchVfs:v,fetchProcessLogs:w,fetchClassStudents:E,fetchElements:N}=e,j=b.useRef(i),I=b.useRef(o),z=b.useRef(a),$=b.useRef(l);b.useEffect(()=>{j.current=i},[i]),b.useEffect(()=>{I.current=o},[o]),b.useEffect(()=>{z.current=a},[a]),b.useEffect(()=>{$.current=l},[l]);const V=t?.role,B=t?.subRole,_=t?.username,U=t?.userId;b.useEffect(()=>{if(!V)return;const F=V==="teacher",Z=F&&(B==="administrator"||_==="admin"||U==="usr_admin");c(),u(),d(),p().catch(()=>{}),Z&&(f(),m(),h()),F&&(y(),x(),g(),v(j.current));let M=!1;const A=setInterval(async()=>{if(!M){M=!0;try{if(Z&&(await f(),await m(),await h(),n&&await w(n)),await c(),await d(),await p().catch(()=>{}),F&&(await y(),await x(),await g(),await v(j.current),$.current&&await E($.current)),z.current){const L=s||z.current.student_id;await N(`assignment-${z.current.id}-student-${L}`)}else I.current&&await N(I.current)}finally{M=!1}}},2e3);return()=>clearInterval(A)},[t?.role,t?.subRole,t?.username,t?.userId,n,s]);const k=t?.role;b.useEffect(()=>{k&&k==="teacher"&&v(i)},[i,k]),b.useEffect(()=>{o&&N(o)},[o])}const Rt=Object.create(null);Rt.open="0";Rt.close="1";Rt.ping="2";Rt.pong="3";Rt.message="4";Rt.upgrade="5";Rt.noop="6";const ni=Object.create(null);Object.keys(Rt).forEach(e=>{ni[Rt[e]]=e});const Il={type:"error",data:"parser error"},tp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",np=typeof ArrayBuffer=="function",sp=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Rc=({type:e,data:t},n,s)=>tp&&t instanceof Blob?n?s(t):Mh(t,s):np&&(t instanceof ArrayBuffer||sp(t))?n?s(t):Mh(new Blob([t]),s):s(Rt[e]+(t||"")),Mh=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function Fh(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Ia;function RA(e,t){if(tp&&e.data instanceof Blob)return e.data.arrayBuffer().then(Fh).then(t);if(np&&(e.data instanceof ArrayBuffer||sp(e.data)))return t(Fh(e.data));Rc(e,!1,n=>{Ia||(Ia=new TextEncoder),t(Ia.encode(n))})}const Bh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ds=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Bh.length;e++)Ds[Bh.charCodeAt(e)]=e;const LA=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 u=new ArrayBuffer(t),d=new Uint8Array(u);for(s=0;s<n;s+=4)o=Ds[e.charCodeAt(s)],a=Ds[e.charCodeAt(s+1)],l=Ds[e.charCodeAt(s+2)],c=Ds[e.charCodeAt(s+3)],d[i++]=o<<2|a>>4,d[i++]=(a&15)<<4|l>>2,d[i++]=(l&3)<<6|c&63;return u},OA=typeof ArrayBuffer=="function",Lc=(e,t)=>{if(typeof e!="string")return{type:"message",data:rp(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:DA(e.substring(1),t)}:ni[n]?e.length>1?{type:ni[n],data:e.substring(1)}:{type:ni[n]}:Il},DA=(e,t)=>{if(OA){const n=LA(e);return rp(n,t)}else return{base64:!0,data:e}},rp=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},ip="",$A=(e,t)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((o,a)=>{Rc(o,!1,l=>{s[a]=l,++i===n&&t(s.join(ip))})})},MA=(e,t)=>{const n=e.split(ip),s=[];for(let i=0;i<n.length;i++){const o=Lc(n[i],t);if(s.push(o),o.type==="error")break}return s};function FA(){return new TransformStream({transform(e,t){RA(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 Aa;function Fr(e){return e.reduce((t,n)=>t+n.length,0)}function Br(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 BA(e,t){Aa||(Aa=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(Fr(n)<1)break;const c=Br(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(Fr(n)<2)break;const c=Br(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Fr(n)<8)break;const c=Br(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(Il);break}i=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(Fr(n)<i)break;const c=Br(n,i);l.enqueue(Lc(o?c:Aa.decode(c),t)),s=0}if(i===0||i>e){l.enqueue(Il);break}}}})}const op=4;function Ke(e){if(e)return UA(e)}function UA(e){for(var t in Ke.prototype)e[t]=Ke.prototype[t];return e}Ke.prototype.on=Ke.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Ke.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Ke.prototype.off=Ke.prototype.removeListener=Ke.prototype.removeAllListeners=Ke.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};Ke.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};Ke.prototype.emitReserved=Ke.prototype.emit;Ke.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Ke.prototype.hasListeners=function(e){return!!this.listeners(e).length};const $i=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),vt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),VA="arraybuffer";function ap(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const WA=vt.setTimeout,HA=vt.clearTimeout;function Mi(e,t){t.useNativeTimers?(e.setTimeoutFn=WA.bind(vt),e.clearTimeoutFn=HA.bind(vt)):(e.setTimeoutFn=vt.setTimeout.bind(vt),e.clearTimeoutFn=vt.clearTimeout.bind(vt))}const qA=1.33;function GA(e){return typeof e=="string"?ZA(e):Math.ceil((e.byteLength||e.size)*qA)}function ZA(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 lp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function KA(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function YA(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 QA extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class Oc extends Ke{constructor(t){super(),this.writable=!1,Mi(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 QA(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=Lc(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=KA(t);return n.length?"?"+n:""}}class JA extends Oc{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)};MA(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,$A(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]=lp()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let cp=!1;try{cp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const XA=cp;function eT(){}class tT extends JA{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 Hn=class si extends Ke{constructor(t,n,s){super(),this.createRequest=t,Mi(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=ap(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=si.requestsCount++,si.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=eT,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete si.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()}};Hn.requestsCount=0;Hn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Uh);else if(typeof addEventListener=="function"){const e="onpagehide"in vt?"pagehide":"unload";addEventListener(e,Uh,!1)}}function Uh(){for(let e in Hn.requests)Hn.requests.hasOwnProperty(e)&&Hn.requests[e].abort()}const nT=(function(){const e=dp({xdomain:!1});return e&&e.responseType!==null})();class sT extends tT{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=nT&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Hn(dp,this.uri(),t)}}function dp(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||XA))return new XMLHttpRequest}catch{}if(!t)try{return new vt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const up=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class rT extends Oc{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=up?{}:ap(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;Rc(s,this.supportsBinary,o=>{try{this.doWrite(s,o)}catch{}i&&$i(()=>{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]=lp()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Ta=vt.WebSocket||vt.MozWebSocket;class iT extends rT{createSocket(t,n,s){return up?new Ta(t,n,s):n?new Ta(t,n):new Ta(t)}doWrite(t,n){this.ws.send(n)}}class oT extends Oc{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=BA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),i=FA();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&&$i(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const aT={websocket:iT,webtransport:oT,polling:sT},lT=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,cT=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Al(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=lT.exec(e||""),o={},a=14;for(;a--;)o[cT[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=dT(o,o.path),o.queryKey=uT(o,o.query),o}function dT(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 uT(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,o){i&&(n[i]=o)}),n}const Tl=typeof addEventListener=="function"&&typeof removeEventListener=="function",ri=[];Tl&&addEventListener("offline",()=>{ri.forEach(e=>e())},!1);class en extends Ke{constructor(t,n){if(super(),this.binaryType=VA,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=Al(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=Al(n.host).host);Mi(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=YA(this.opts.query)),Tl&&(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"})},ri.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=op,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&&en.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",en.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+=GA(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,$i(()=>{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(en.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(),Tl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=ri.indexOf(this._offlineEventListener);s!==-1&&ri.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}en.protocol=op;class hT extends en{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;en.priorWebsocketSuccess=!1;const i=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",f=>{if(!s)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;en.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function o(){s||(s=!0,d(),n.close(),n=null)}const a=f=>{const m=new Error("probe error: "+f);m.transport=n.name,o(),this.emitReserved("upgradeError",m)};function l(){a("transport closed")}function c(){a("socket closed")}function u(f){n&&f.name!==n.name&&o()}const d=()=>{n.removeListener("open",i),n.removeListener("error",a),n.removeListener("close",l),this.off("close",c),this.off("upgrading",u)};n.once("open",i),n.once("error",a),n.once("close",l),this.once("close",c),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&n.push(t[s]);return n}}let fT=class extends hT{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=>aT[i]).filter(i=>!!i)),super(t,s)}};function mT(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=Al(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 pT=typeof ArrayBuffer=="function",gT=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,hp=Object.prototype.toString,xT=typeof Blob=="function"||typeof Blob<"u"&&hp.call(Blob)==="[object BlobConstructor]",bT=typeof File=="function"||typeof File<"u"&&hp.call(File)==="[object FileConstructor]";function Dc(e){return pT&&(e instanceof ArrayBuffer||gT(e))||xT&&e instanceof Blob||bT&&e instanceof File}function ii(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(ii(e[n]))return!0;return!1}if(Dc(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return ii(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&ii(e[n]))return!0;return!1}function yT(e){const t=[],n=e.data,s=e;return s.data=oi(n,t),s.attachments=t.length,{packet:s,buffers:t}}function oi(e,t,n){if(!e)return e;if(Dc(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]=oi(e[i],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return oi(e.toJSON(),t,!0);const s={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=oi(e[i],t));return s}return e}function wT(e,t){return e.data=_l(e.data,t),delete e.attachments,e}function _l(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]=_l(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=_l(e[n],t));return e}const vT=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ze;(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"})(ze||(ze={}));class ST{constructor(t){this.replacer=t}encode(t){return(t.type===ze.EVENT||t.type===ze.ACK)&&ii(t)?this.encodeAsBinary({type:t.type===ze.EVENT?ze.BINARY_EVENT:ze.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ze.BINARY_EVENT||t.type===ze.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=yT(t),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}class $c extends Ke{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===ze.BINARY_EVENT;s||n.type===ze.BINARY_ACK?(n.type=s?ze.EVENT:ze.ACK,this.reconstructor=new kT(n)):super.emitReserved("decoded",n)}else if(Dc(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(ze[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ze.BINARY_EVENT||s.type===ze.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(!jT(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($c.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 ze.CONNECT:return Vh(n);case ze.DISCONNECT:return n===void 0;case ze.CONNECT_ERROR:return typeof n=="string"||Vh(n);case ze.EVENT:case ze.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&vT.indexOf(n[0])===-1);case ze.ACK:case ze.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kT{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=wT(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const jT=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Vh(e){return Object.prototype.toString.call(e)==="[object Object]"}const NT=Object.freeze(Object.defineProperty({__proto__:null,Decoder:$c,Encoder:ST,get PacketType(){return ze}},Symbol.toStringTag,{value:"Module"}));function St(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const CT=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class fp extends Ke{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=[St(t,"open",this.onopen.bind(this)),St(t,"packet",this.onpacket.bind(this)),St(t,"error",this.onerror.bind(this)),St(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(CT.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:ze.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,f=n.pop();this._registerAckCallback(d,f),a.id=d}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:ze.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 ze.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 ze.EVENT:case ze.BINARY_EVENT:this.onevent(t);break;case ze.ACK:case ze.BINARY_ACK:this.onack(t);break;case ze.DISCONNECT:this.ondisconnect();break;case ze.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:ze.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:ze.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 ts(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}ts.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};ts.prototype.reset=function(){this.attempts=0};ts.prototype.setMin=function(e){this.ms=e};ts.prototype.setMax=function(e){this.max=e};ts.prototype.setJitter=function(e){this.jitter=e};class Pl extends Ke{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,Mi(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 ts({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||NT;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 fT(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=St(n,"open",function(){s.onopen(),t&&t()}),o=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=St(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(St(t,"ping",this.onping.bind(this)),St(t,"data",this.ondata.bind(this)),St(t,"error",this.onerror.bind(this)),St(t,"close",this.onclose.bind(this)),St(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){$i(()=>{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 fp(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 Ps={};function ai(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=mT(e,t.path||"/socket.io"),s=n.source,i=n.id,o=n.path,a=Ps[i]&&o in Ps[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let c;return l?c=new Pl(s,t):(Ps[i]||(Ps[i]=new Pl(s,t)),c=Ps[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(ai,{Manager:Pl,Socket:fp,io:ai,connect:ai});class ET{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 IT{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 zl=Lt(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null}),remoteBrowserFullscreenElementId:null,setRemoteBrowserFullscreenElementId:t=>e({remoteBrowserFullscreenElementId:t})})),a_=e=>tn(zl,e),_a=new Set,mp=Lt((e,t)=>({lastEvent:null,version:0,subscribe:n=>(_a.add(n),()=>{_a.delete(n)}),record:n=>{e({lastEvent:n,version:t().version+1});for(const s of _a)try{s(n)}catch(i){console.error("[pointsLedgerStore] listener error:",i)}},reset:()=>{e({lastEvent:null,version:0})}})),l_=e=>tn(mp,e),AT={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 Wh(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 c_(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 d_(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 u_(e,t=Math.random){if(!e||e.length===0)return null;if(e.length===1)return{student:e[0],weight:Wh(e[0])};const n=e.map(a=>Wh(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 TT(e){const{session:t,host:n,activeRole:s,activeStudentId:i,selectedLesson:o,activeSegmentId:a,studentViewStatus:l,lang:c,students:u,addToast:d,setOnlineStudentIds:f,setActiveStudentLessons:m,setLessons:h,setActiveSegmentId:y,setLiveClassStudentProgress:p,setLiveClassAcknowledgedMap:x,setLiveClassFeed:g,setSelectedLesson:v,setStudentViewStatus:w,studentLessonTab:E,setStudentLessonTab:N,selectedAssignment:j,setSelectedAssignment:I,setLocalProgressPercent:z,fetchStudentDashboard:$,fetchStudents:V,fetchElements:B,setPickedAlertData:_,setPickedAnnouncement:U,onStudentProgressUpdated:k}=e,F=b.useRef(null),Z=b.useRef(s),M=b.useRef(i),A=b.useRef(c),L=b.useRef(u),S=b.useRef(d),R=b.useRef(o),D=b.useRef(null),P=b.useRef(l),Y=b.useRef(new Map),H=b.useRef(E),ee=b.useRef(_),le=b.useRef(U),ae=b.useRef(k),fe=b.useRef(null);b.useEffect(()=>{Z.current=s},[s]),b.useEffect(()=>{M.current=i},[i]),b.useEffect(()=>{A.current=c},[c]),b.useEffect(()=>{L.current=u},[u]),b.useEffect(()=>{S.current=d},[d]),b.useEffect(()=>{R.current=o},[o]),b.useEffect(()=>{P.current=l},[l]),b.useEffect(()=>{H.current=E},[E]),b.useEffect(()=>{D.current=j},[j]),b.useEffect(()=>{ee.current=_},[_]),b.useEffect(()=>{le.current=U},[U]),b.useEffect(()=>{ae.current=k},[k]);const be=!!t,ye=t?.role,Se=t?`${t.role}:${t.userId??""}:${t.studentId??""}`:"";return b.useEffect(()=>{if(!be)return;const me=ai();F.current=me,Lm(me),n.isInitialized()||n.initialize(new Mm,new PC(me),new ET(S.current),new IT("__app__"));const C=()=>{me.emit("join-room","whiteboard-broadcast");const T=Te.getState().liveClassSelectedClassId;Z.current==="teacher"&&T&&me.emit("join-room",`class-${T}`),Z.current==="student"&&M.current?(me.emit("register-student",{studentId:M.current,name:L.current.find(q=>q.id===M.current)?.name||M.current}),P.current==="lesson"&&R.current&&me.emit("enter-lesson",{studentId:M.current,lessonId:R.current})):me.emit("request-presence")};C(),me.on("presence-update",T=>{f(T.onlineStudentIds),m(T.activeStudentLessons)}),me.on("lesson-progress-mode-changed",T=>{const{lessonId:q,progressMode:X,progressConditions:ne}=T;h(Q=>Q.map(re=>re.id===q?{...re,progress_mode:X,progress_conditions:ne}:re))}),me.on("student-active-segment-changed",T=>{const{activeSegmentId:q}=T;y(q)}),me.on("segment-gate-changed",T=>{window.dispatchEvent(new CustomEvent("openlearn:segment-gate-changed",{detail:T}))}),me.on("student-pinged",T=>{const q=T.message||(A.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");d(A.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",q,"warning")}),me.on("student-progress-updated",T=>{const{studentId:q,lessonId:X,progressPercent:ne,completed:Q}=T;p(re=>{const de=re.findIndex(te=>te.student_id===q);if(de!==-1){const te=[...re];return te[de]={...te[de],progress_percent:ne,completed:Q?1:0},te}else return[...re,{student_id:q,progress_percent:ne,completed:Q?1:0}]}),ae.current?.({studentId:q,lessonId:X,progressPercent:ne,completed:!!Q,verified:T.verified===!0})}),me.on("student-error-alert",T=>{if(!(!T||!T.error)&&(Z.current==="teacher"||t?.role==="administrator")){gn.getState().addStudentError({...T.error,studentId:T.studentId,studentName:T.studentName||T.studentId,lessonId:T.lessonId,classId:T.classId});const q=T.studentName?`${T.studentName} (${T.studentId})`:T.studentId;d(A.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${q}: ${T.error.title||T.error.message}`,"warning")}}),me.on("assignment-graded-toast",T=>{if(Z.current==="student"&&M.current&&T.studentId===M.current){const q=T.assignmentTitle||T.assignmentId,X=A.current==="zh"?`您的作业"${q}"已完成评分!得分:${T.score}%。建议反馈已收到,快去查看。`:`Your assignment "${q}" was graded. Score: ${T.score}%. Tutoring feedback has been posted.`;d(A.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",X,"success"),$(M.current)}}),me.on("student-picked",T=>{const q=`${T.studentId}:${T.pickedTime??""}`,X=Date.now(),ne=Y.current.get(q),Q=ne!==void 0&&X-ne<1e4;if(!Q){Y.current.set(q,X);for(const[te,O]of Y.current)X-O>=1e4&&Y.current.delete(te)}const re=M.current,de=Z.current==="student"&&re&&T.studentId===re;if(de&&re&&!Q){ee.current?.({studentId:T.studentId,studentName:T.studentName,rollcallId:T.rollcallId});const te=A.current==="zh"?"闪电警报!您已被老师在课程随机抽问中抽中!请立即集中注意力参与课堂回答。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";d(A.current==="zh"?"⚡️ 闪电抽问:老师抽中了你!":"⚡️ Classroom Pick Alert",te,"warning"),$(re)}else if(Z.current==="student"&&!de&&!Q){const te=T.studentName||"同学";le.current?.({studentName:te,studentId:T.studentId});const O=A.current==="zh"?`老师在课堂中随机抽中了【${te}】同学回答问题!`:`Teacher randomly selected [${te}] to answer!`;d(A.current==="zh"?"🎯 课堂随机抽问":"🎯 Classroom Random Pick",O,"info")}g(te=>[{id:`feed-pick-${T.studentId}-${T.pickedTime||Date.now()}`,time:new Date(T.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:A.current==="zh"?`点名互动:随机抽中学生【${T.studentName}】。`:`Classroom Pick: Randomly selected student "${T.studentName}".`},...te])}),me.on("rollcall:evaluated",T=>{if(Z.current!=="student"||T?.lessonId&&R.current&&T.lessonId!==R.current)return;const q=!!M.current&&T?.studentId===M.current,X=A.current==="zh",ne=AT[T?.rating];ne&&(q?(d(X?`${ne.badge} ${ne.label} +${T.rewardCoins} 金币`:`${ne.badge} ${ne.labelEn} +${T.rewardCoins} coins`,X?`老师在随机抽问中给了你「${ne.label}」的评价,成长金币 +${T.rewardCoins} 已到账!`:`The teacher rated you "${ne.labelEn}" in the random pick. +${T.rewardCoins} growth coins credited!`,"success"),M.current&&$(M.current)):d(X?`${ne.badge} 课堂表现评定`:`${ne.badge} Classroom Evaluation`,X?`老师给【${T.studentName||"某位同学"}】评了「${ne.label}」。`:`The teacher rated "${T.studentName||"a student"}" as "${ne.labelEn}".`,"info"),g(Q=>[{id:`feed-eval-${T.rollcallId||T.studentId}-${T.timestamp||Date.now()}`,time:new Date(T.timestamp||Date.now()).toLocaleTimeString(),type:"picked",message:X?`点名评价:${T.studentName||"学生"} 获评「${ne.label}」+${T.rewardCoins}金币。`:`Roll-call evaluation: "${T.studentName||"a student"}" rated ${ne.labelEn} +${T.rewardCoins} coins.`},...Q]))}),me.on("classroom:points_awarded",T=>{if(!T?.studentId)return;const q=A.current==="zh",X=Number(T.deltaPoints)||0;mp.getState().record({studentId:T.studentId,classId:T.classId??"",deltaPoints:X,reason:T.reason??"",dimensionId:T.dimensionId,createdAt:T.createdAt}),!!M.current&&T.studentId===M.current&&(d(q?X>=0?"🎁 获得成长积分":"📉 积分调整":X>=0?"Points earned":"Points adjusted",q?`${X>=0?"+":""}${X} 积分${T.reason?`:${T.reason}`:""}`:`${X>=0?"+":""}${X} points${T.reason?`: ${T.reason}`:""}`,X>=0?"success":"warning"),M.current&&$(M.current))}),me.on("student-acknowledged",T=>{const{studentId:q}=T;x(X=>{const ne=new Map(X);return ne.set(q,!0),ne}),g(X=>[{id:`feed-ack-${q}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:A.current==="zh"?`学生已确认收到提问点名(学生 ID: ${q})。`:`Student acknowledged the classroom call (Student ID: ${q}).`},...X]),V()}),me.on("class-lock-status-changed",T=>{const{lessonId:q,locked:X,mode:ne,target:Q}=T||{};if(Z.current==="student"&&M.current){const re=M.current,de=Te.getState().students,te=de.findIndex(G=>G.id===re),O=te>=0?{...de[te]}:{id:re,name:""};if(O.locked_lesson_id=X?q:null,O.lock_mode=X&&ne||"full",O.lock_target=X?Q:null,te>=0){const G=[...de];G[te]=O,Te.getState().setStudents(G)}else Te.getState().setStudents([O]);if(X&&q){v(q),w("lesson"),Q?.tab&&N(Q.tab);const G=ne==="navigation";d(A.current==="zh"?G?"🔒 答题锁定已开启":"🔒 课程已被锁定":G?"🔒 Answer Lock Active":"🔒 Lesson Locked",A.current==="zh"?G?"老师已开启答题锁定,请完成作答后提交,暂时无法离开本页。":"老师已锁定当前授课,您将无法切换到其他页面。":G?"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")}$(re)}else V()}),me.on("student-lesson-tab-changed",T=>{Z.current==="student"&&T?.tab&&(!T.lessonId||T.lessonId===R.current)&&N(T.tab)}),me.on("teacher-switched-lesson",T=>{Z.current==="student"&&T?.lessonId&&(v(T.lessonId),w("lesson"))}),me.on("whiteboard-sync",T=>{const{roomId:q,type:X}=T||{};if(X!=="refresh"||!q)return;const ne=R.current;ne&&ne!==q||(B(q),!ne&&Z.current==="student"&&(v(q),w("lesson")),me.emit("join-room",q))});const J=()=>{zl.getState().clearRemoteFullscreen();const T=fe.current;fe.current=null,T&&(N(T.lessonTab),T.viewStatus==="assignment"&&(I(T.assignment??null),T.lessonId&&v(T.lessonId),w("assignment")))};me.on("whiteboard-fullscreen-changed",T=>{if(Z.current!=="student")return;const q=T?.lessonId,X=T?.elementId??null,ne=T?.mode==="browser",Q=zl.getState();if(!X){if(ne){Q.setRemoteBrowserFullscreenElementId(null),Q.remoteFullscreenElementId||J();return}J();return}if(!q)return;const re=P.current;(re==="lesson"?R.current===q:re==="assignment")&&(!Q.remoteFullscreenElementId&&!Q.remoteBrowserFullscreenElementId&&(fe.current={viewStatus:re,lessonTab:H.current,lessonId:R.current,assignment:re==="assignment"?D.current:null}),ne?Q.setRemoteBrowserFullscreenElementId(X):Q.setRemoteFullscreenElementId(X),re==="assignment"&&I(null),v(q),B(q),w("lesson"),N("whiteboard"))}),me.on("connect",()=>{C(),J(),Promise.resolve(V()).catch(()=>{}),Z.current==="student"&&M.current&&Promise.resolve($(M.current)).catch(()=>{})});const se=()=>{C()};me.io?.on("reconnect",se);const W=T=>{try{if(!T)return;Jt.ingest({source:"widget.quiz",type:"quiz.answered",lessonId:T.lessonId,elementId:T.elementId,studentId:T.studentId,studentName:T.studentName,payload:{answer:T.answer,score:typeof T.score=="number"?T.score:void 0,isCorrect:!!T.isCorrect,correctAnswer:T.correctAnswer,correctIndex:typeof T.correctIndex=="number"?T.correctIndex:void 0,question:T.question,time:T.time},raw:T})}catch(q){console.error("[useClassroomSocket] quiz.answered ingest failed",q)}};return me.on("whiteboard-quiz-answered-staff",T=>{Z.current!=="teacher"&&ye!=="administrator"||W(T)}),me.on("whiteboard-quiz-answered",T=>{Z.current==="teacher"||ye==="administrator"||W(T)}),me.on("courseware-attempt-updated",T=>{try{if(!T||typeof T.attemptId!="string")return;const q=T.type==="log"?"courseware.event_logged":T.type==="submit"?"courseware.submitted":T.type==="promote"?"courseware.finished":"courseware.event_logged";Jt.ingest({source:"iframe.bridge",type:q,attemptId:T.attemptId,payload:{attemptId:T.attemptId,attemptType:T.type},raw:T})}catch(q){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",q)}}),()=>{me.io?.off("reconnect",se),me.disconnect(),F.current=null}},[be,Se,ye,s,i]),b.useEffect(()=>{F.current&&s==="student"&&i&&(l==="lesson"&&o?(F.current.emit("enter-lesson",{studentId:i,lessonId:o}),fetch(`/api/students/${i}/progress`).then(me=>me.json()).then(me=>{if(Array.isArray(me)){const C=me.find(J=>J.lesson_id===o);z(C?C.progress_percent:0)}}).catch(console.error)):F.current.emit("leave-lesson",{studentId:i}))},[l,o,s,i]),b.useEffect(()=>{s==="teacher"&&o&&a&&F.current&&F.current.emit("teacher-broadcast-segment",{lessonId:o,activeSegmentId:a})},[a,o,s]),{socketRef:F}}function Pa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Hh(e){if(!e||typeof e!="object")return[];const t=Pa(e.capabilitiesProposed);if(t.length>0)return t;const n=e.manifest;if(typeof n=="string"&&n.length>0)try{return Pa(JSON.parse(n)?.capabilitiesProposed)}catch{return[]}return n&&typeof n=="object"?Pa(n.capabilitiesProposed):[]}function _T(e){const t=e.isolation_mode??e.execution_mode;return t==="inline"||t==="worker"||t==="legacy"?t:"process"}function PT(e){const{lang:t,t:n,addToast:s,host:i,session:o,activeStudentId:a,activeRole:l,setStudentViewStatus:c,studentViewStatus:u,studentLessonTab:d,setStudentLessonTab:f,setLiveClassFocusLocked:m,isStudentLiveMode:h,isFollowingTeacher:y,liveStudentParam:p,fetchStudents:x,fetchLessons:g,fetchElements:v,fetchClasses:w,fetchClassStudents:E,fetchClassProgress:N,fetchClassDashboard:j,fetchLiveClassStudentProgress:I,setLiveClassStudentProgress:z,fetchRegisteredCommands:$,fetchVfs:V,fetchProcesses:B,fetchProcessLogs:_,fetchTodaySchedules:U,fetchLabs:k,fetchPlugins:F,fetchEvents:Z,fetchApprovals:M,showProcessLogs:A,currentVfsParent:L,expandedClassId:S,activeSegmentId:R,setActiveSegmentId:D,quizStudentAnswersRef:P,effectiveAgentProviderId:Y,plugins:H}=e,[ee,le]=b.useState(0),ae=TA(),{pickedAlertData:fe,setPickedAlertData:be,pickedAnnouncement:ye,setPickedAnnouncement:Se,liveClassFeed:me,setLiveClassFeed:C,liveClassAcknowledgedMap:J,setLiveClassAcknowledgedMap:se,onlineStudentIds:W,setOnlineStudentIds:T,activeStudentLessons:q,setActiveStudentLessons:X}=ae,ne=ke(Pe=>Pe.liveClassSelectedClassId),Q=ke(Pe=>Pe.setLiveClassSelectedClassId),re=ke(Pe=>Pe.liveClassIsActive),de=ke(Pe=>Pe.setLiveClassIsActive),te=ke(Pe=>Pe.selectedLesson),O=ke(Pe=>Pe.setSelectedLesson),G=ke(Pe=>Pe.setLessons),ie=ke(Pe=>Pe.students);ke(Pe=>Pe.dataVersion);const ue=_A({activeStudentId:a,activeRole:l,selectedLesson:te,quizStudentAnswersRef:P,setStudentViewStatus:c}),{studentDashboardData:he,setStudentDashboardData:K,studentProgressMap:we,setStudentProgressMap:oe,selectedAssignment:ce,setSelectedAssignment:pe,fetchStudentDashboard:xe,fetchStudentProgress:ve,updateStudentProgress:_e,submitQuizAssignment:je}=ue,[Me,et]=b.useState(""),[Be,st]=b.useState("all"),[ft,Cn]=b.useState("grid"),[Ve,ns]=b.useState({}),[ss,rs]=b.useState({}),[En,is]=b.useState({}),In=PA(l,he,t),{studentNotifications:os,unreadNotifications:as,readNotifications:ls,setReadNotifications:Ut,selectedNotificationForModal:An,setSelectedNotificationForModal:rn,isNotificationsOpen:cs,setIsNotificationsOpen:ds}=In;b.useEffect(()=>{a&&M2(a).then(({ok:Pe,data:rt})=>{Ut(Pe&&Array.isArray(rt)?new Set(rt):new Set)}).catch(Pe=>{console.warn("Failed to load read notifications from DB",Pe),Ut(new Set)})},[a]);const Vt=b.useRef(new Set);b.useEffect(()=>{if(!i.isInitialized()||H.length===0)return;const Pe=Re.getState(),rt=H.filter(Ae=>Ae.status==="active");for(const Ae of rt){if(Vt.current.has(Ae.id))continue;const tt=Pe.activePlugins.find(mt=>mt.id===Ae.id),at=!!(tt&&Ae.version&&tt.version!==Ae.version);if(!(!tt||at||tt.state!==He.ACTIVE&&tt.state!==He.ACTIVATING))continue;Vt.current.add(Ae.id);const Qe=()=>{if(!Pe.activePlugins.find(mt=>mt.id===Ae.id))Pe.addPlugin({id:Ae.id,name:Ae.name,version:Ae.version??"",state:He.INSTALLED,executionMode:_T(Ae),capabilitiesProposed:Hh(Ae),hasFrontend:Ae.has_frontend});else if(at)try{const mt=Hh(Ae);Re.setState(ln=>({activePlugins:ln.activePlugins.map(Wt=>Wt.id===Ae.id?{...Wt,version:Ae.version??"",name:Ae.name,capabilitiesProposed:mt,hasFrontend:Ae.has_frontend}:Wt)}))}catch{}try{const mt=JSON.parse(Ae.manifest);i.activateRemotePlugin(Ae.id,mt,{hasFrontend:Ae.has_frontend}).catch(ln=>{console.error(`[App] Failed to activate remote plugin "${Ae.name}":`,ln)}).finally(()=>{Vt.current.delete(Ae.id)})}catch(mt){Vt.current.delete(Ae.id),console.error(`[App] Failed to parse manifest for plugin "${Ae.name}":`,mt)}};tt&&tt.state===He.ACTIVE&&at?i.deactivatePlugin(Ae.id).catch(()=>{}).finally(Qe):Qe()}const on=H.filter(Ae=>Ae.status!=="active");for(const Ae of on){const tt=Pe.activePlugins.find(at=>at.id===Ae.id);tt&&tt.state===He.ACTIVE&&i.deactivatePlugin(Ae.id).catch(at=>{console.error(`[App] Failed to deactivate remote plugin "${Ae.name}":`,at)})}},[H,i]),b.useEffect(()=>{if(!i.isInitialized()||H.length===0)return;const Pe=Re.getState();for(const rt of H)rt.status==="active"&&(Pe.dashboardVisibility.has(rt.id)||Pe.setDashboardVisibility(rt.id,!0))},[H,i]),b.useEffect(()=>{ne&&te?I(ne,te):z([])},[ne,te]),b.useEffect(()=>{ne&&E(ne)},[ne]),Kw(o);const Tn=S2({lang:t,t:n,selectedLesson:te,effectiveAgentProviderId:Y,expandedClassId:S,fetchLessons:g,fetchClasses:w,fetchStudents:x,fetchClassStudents:E,fetchClassProgress:N,fetchClassDashboard:j,fetchElements:v}),{personaId:_n,setPersonaId:us,chatLog:We,setChatLog:hs,input:fs,setInput:ms,loading:ps,setLoading:gs,chatAttachments:xs,setChatAttachments:bs,handleChatFileChange:ys,handleChatDrop:ws,handleSend:vs,handleClearAgentMemory:Ss}=Tn;zA({session:o,showProcessLogs:A,activeStudentId:a,currentVfsParent:L,selectedLesson:te,selectedAssignment:ce,expandedClassId:S,fetchLessons:g,fetchPlugins:F,fetchRegisteredCommands:$,fetchEvents:Z,fetchApprovals:M,fetchProcesses:B,fetchClasses:w,fetchTodaySchedules:U,fetchStudents:x,fetchLabs:k,fetchVfs:V,fetchProcessLogs:_,fetchClassStudents:E,fetchElements:v});const{socketRef:ks}=TT({session:o,host:i,activeRole:l,activeStudentId:a,selectedLesson:te,activeSegmentId:R,studentViewStatus:u,lang:t,students:ie,addToast:s,setOnlineStudentIds:T,setActiveStudentLessons:X,setLessons:G,setActiveSegmentId:D,setLiveClassStudentProgress:z,setLiveClassAcknowledgedMap:se,setLiveClassFeed:C,setSelectedLesson:O,setStudentViewStatus:c,studentLessonTab:d,setStudentLessonTab:f,selectedAssignment:ce,setSelectedAssignment:pe,setLocalProgressPercent:le,fetchStudentDashboard:xe,fetchStudents:x,fetchElements:v,setPickedAlertData:be,setPickedAnnouncement:Se,onStudentProgressUpdated:({studentId:Pe,lessonId:rt,progressPercent:on,completed:Ae,verified:tt})=>{oe(at=>{const an=at[Pe];return an?{...at,[Pe]:an.map(Qe=>rt&&Qe.lesson_id!==rt?Qe:{...Qe,progress_percent:on,completed:Ae?1:0,...tt!==void 0?{verified:tt?1:0}:{}})}:at})}});return{localProgressPercent:ee,setLocalProgressPercent:le,classroomLiveData:ae,pickedAlertData:fe,setPickedAlertData:be,pickedAnnouncement:ye,setPickedAnnouncement:Se,liveClassFeed:me,setLiveClassFeed:C,liveClassAcknowledgedMap:J,setLiveClassAcknowledgedMap:se,onlineStudentIds:W,setOnlineStudentIds:T,activeStudentLessons:q,setActiveStudentLessons:X,liveClassSelectedClassId:ne,setLiveClassSelectedClassId:Q,liveClassIsActive:re,setLiveClassIsActive:de,studentOpsData:ue,studentDashboardData:he,setStudentDashboardData:K,studentProgressMap:we,setStudentProgressMap:oe,selectedAssignment:ce,setSelectedAssignment:pe,fetchStudentDashboard:xe,fetchStudentProgress:ve,updateStudentProgress:_e,submitQuizAssignment:je,rosterSearchQuery:Me,setRosterSearchQuery:et,rosterTagFilter:Be,setRosterTagFilter:st,rosterViewMode:ft,setRosterViewMode:Cn,classSubmissionFilters:Ve,setClassSubmissionFilters:ns,classActiveTabs:ss,setClassActiveTabs:rs,studentActiveTabs:En,setStudentActiveTabs:is,studentNotificationsHook:In,studentNotifications:os,unreadNotifications:as,readNotifications:ls,setReadNotifications:Ut,selectedNotificationForModal:An,setSelectedNotificationForModal:rn,isNotificationsOpen:cs,setIsNotificationsOpen:ds,agentChatData:Tn,personaId:_n,setPersonaId:us,chatLog:We,setChatLog:hs,input:fs,setInput:ms,loading:ps,setLoading:gs,chatAttachments:xs,setChatAttachments:bs,handleChatFileChange:ys,handleChatDrop:ws,handleSend:vs,handleClearAgentMemory:Ss,socketRef:ks}}zI();function zT(){OI();const e=ke(h=>h.lang),t=nl[e]??nl.zh,{addToast:n}=RI(),s=jS(),i=async()=>{await Te.getState().loadStudents()},o=async()=>{await Te.getState().loadClasses()},a=b.useRef(()=>{}),l=UI({lang:e,addToast:n,fetchStudents:i}),c=AA({lang:e,addToast:n,host:s,session:l.session,fetchStudents:i,fetchClasses:o,chatLogRef:a}),u=PT({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=u.setChatLog;const d=ke(h=>h.setSelectedLesson),f=ke(h=>h.setTeacherTab);return{appData:{addToast:n,...c.systemData,...c.resourceLibraryData,...c.lessonCrudData,...c.classOpsData,...l.studentViewStateData,...u.studentOpsData,...l.sessionBootstrapData,...u.classroomLiveData,...c.labAndScheduleData,...c.pluginManagementData,...u.agentChatData,...c.quizGenerator,...c.courseWizard,...c.classBatch,...c.lessonTimelineData,...u.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:u.rosterViewMode,setRosterViewMode:u.setRosterViewMode,rosterSearchQuery:u.rosterSearchQuery,setRosterSearchQuery:u.setRosterSearchQuery,rosterTagFilter:u.rosterTagFilter,setRosterTagFilter:u.setRosterTagFilter,classSubmissionFilters:u.classSubmissionFilters,setClassSubmissionFilters:u.setClassSubmissionFilters,classActiveTabs:u.classActiveTabs,setClassActiveTabs:u.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:u.studentActiveTabs,setStudentActiveTabs:u.setStudentActiveTabs,fetchStudents:i,fetchClasses:o,onLogout:l.handleLogout,onAIProvidersChanged:c.fetchAIProviders,onDeleteCourse:c.handleDeleteCourse,onCopyCourse:c.handleCopyCourse,socketRef:u.socketRef,liveClassSelectedClassId:u.liveClassSelectedClassId,setLiveClassSelectedClassId:u.setLiveClassSelectedClassId,liveClassIsActive:u.liveClassIsActive,setLiveClassIsActive:u.setLiveClassIsActive,setSelectedLesson:d,setTeacherTab:f,teacherTab:l.teacherTab,onViewCourse:h=>{f("lesson_editor"),d(h)},t,readNotifications:u.readNotifications,setReadNotifications:u.setReadNotifications,localProgressPercent:u.localProgressPercent,setLocalProgressPercent:u.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,dismissTour:l.dismissTour,handleSeedSuccess:c.handleSeedSuccess,wizardIsGeneratingOutline:c.wizardIsGeneratingOutline,handleGenerateOutline:c.handleGenerateOutline,activeRole:l.activeRole,setActiveRole:l.setActiveRole,isStudentPreviewMode:l.isStudentPreviewMode,isNotificationsOpen:u.isNotificationsOpen,setIsNotificationsOpen:u.setIsNotificationsOpen,selectedNotificationForModal:u.selectedNotificationForModal,setSelectedNotificationForModal:u.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 RT(){const{appData:e,sessionLoading:t,session:n,setSession:s,handleLoginSuccess:i,handleLogout:o,isStageDisplayMode:a,stageLessonParam:l,stageTitleParam:c,stageLangParam:u,activeRole:d,selectedLesson:f,lessons:m,profileOpen:h,setProfileOpen:y,lang:p}=zT();return Ue.useEffect(()=>{if(typeof document>"u")return;document.documentElement.lang=p==="en"?"en":"zh-CN";const x=e.siteInfo?.siteName?.trim()||"OpenLearn Next",g=n?n.mustChangePassword?p==="en"?"Change Default Password":"修改默认密码":a?p==="en"?"Stage Display":"大屏展台":d==="student"?p==="en"?"Student Space":"学生学习空间":p==="en"?"Teacher Workbench":"教师工作台":p==="en"?"Sign In":"登录";document.title=`${x} · ${g}`},[p,e.siteInfo?.siteName,n,a,d]),t?r.jsx(yr,{children:r.jsx(br,{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(dt,{size:48,className:"text-indigo-500 animate-spin"}),r.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:p==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]})})}):n?n.mustChangePassword?r.jsx(yr,{children:r.jsxs(br,{value:e,children:[r.jsx(eS,{lang:p,username:n.username,onDone:()=>s({...n,mustChangePassword:!1}),onLogout:o}),r.jsx(Ca,{lang:p})]})}):r.jsx(yr,{children:r.jsx(br,{value:e,children:r.jsxs(r.Fragment,{children:[a&&r.jsx(VE,{lessonId:l||f,lessonTitle:c||m.find(x=>x.id===(l||f))?.title,lang:u==="en"?"en":"zh"}),!a&&r.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[r.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[100] focus:px-4 focus:py-2 focus:rounded-lg focus:bg-indigo-600 focus:text-white focus:text-sm focus:font-semibold focus:shadow-lg focus:outline-none focus:ring-2 focus:ring-white",children:p==="zh"?"跳到主内容":"Skip to main content"}),r.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[r.jsx(WE,{}),n.role==="student"&&n.usedDefaultPassword&&r.jsx(HE,{userId:n.studentId||n.userId,lang:p,onOpenProfile:()=>y(!0)}),r.jsx(s2,{}),r.jsx(p2,{open:h,session:n,lang:p,onClose:()=>y(!1),onSaved:x=>{n&&s({...n,name:x}),y(!1)},onAvatar:x=>{n&&s({...n,avatar:x??void 0})}}),r.jsx("main",{id:"main-content",tabIndex:-1,className:"flex-1 flex flex-col min-h-0 min-w-0 overflow-hidden outline-none",children:r.jsx(v2,{activeRole:d})}),r.jsx(i2,{})]}),r.jsx(N2,{}),r.jsx($2,{}),r.jsx(pI,{}),r.jsx(gI,{}),r.jsx(AI,{}),r.jsx(PI,{}),r.jsx(Ca,{lang:p})]})]})})}):r.jsx(yr,{children:r.jsxs(br,{value:e,children:[r.jsx(Xv,{onLoginSuccess:i,lang:p}),r.jsx(Ca,{lang:p})]})})}const za=Symbol.for("openlearn.externalFontCspGuardInstalled"),qh="openlearn-local-font-fallback";function pp(e){if(!e.head||e.getElementById(qh))return;const t=e.createElement("style");t.id=qh,t.textContent=`:where(html, body) { font-family: ${Uf}; }`,HTMLHeadElement.prototype.appendChild.call(e.head,t)}function Ur(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.tagName!="string"||t.tagName.toUpperCase()!=="LINK")return null;const s=(typeof t.getAttribute=="function"?t.getAttribute("href"):null)||t.href||"";return Kn(s)?s:null}function Vr(e){const t=e.getAttribute("href")||e.href;t&&(e.setAttribute("data-openlearn-blocked-external-font",t),e.removeAttribute("href")),e.rel="openlearn-blocked-font",e.disabled=!0,e.ownerDocument&&pp(e.ownerDocument)}function LT(e=document){if(typeof e>"u"||typeof HTMLHeadElement>"u")return()=>{};const t=HTMLHeadElement.prototype;if(t[za])return()=>{};if(e.head)for(const l of Array.from(e.head.querySelectorAll("link")))Ur(l)&&(Vr(l),l.remove());const n=t.appendChild,s=t.insertBefore,i=typeof t.append=="function"?t.append:null,o=typeof HTMLLinkElement<"u"?HTMLLinkElement.prototype:null,a=o?o.setAttribute:null;return o&&a&&(o.setAttribute=function(l,c){if(l.toLowerCase()==="href"&&Kn(c)){a.call(this,"data-openlearn-blocked-external-font",c),this.removeAttribute("href"),this.rel="openlearn-blocked-font",this.disabled=!0,this.ownerDocument&&pp(this.ownerDocument);return}a.call(this,l,c)}),t.appendChild=function(l){return Ur(l)?(Vr(l),l):n.call(this,l)},t.insertBefore=function(l,c){return Ur(l)?(Vr(l),l):s.call(this,l,c)},i&&(t.append=function(...l){const c=[];for(const u of l)Ur(u)?Vr(u):c.push(u);c.length>0&&i.apply(this,c)}),t[za]=!0,()=>{t.appendChild=n,t.insertBefore=s,i&&(t.append=i),o&&a&&(o.setAttribute=a),delete t[za]}}class OT extends Ue.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=Pc({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 Qs(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}),gn.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(L0,{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(Gn,{size:14}):r.jsx(qn,{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(Xe,{size:14}):r.jsx(Un,{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(Ci,{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(df,{size:14}),r.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}LT();window.React=Ra;window.ReactDOM=La;window.HostSharedDeps={React:Ra,ReactDOM:La,ReactDOMClient:Yc,Recharts:od,LucideReact:ci,jsxRuntime:Kc,react:Ra,"react-dom":La,"react-dom/client":Yc,"react/jsx-runtime":Kc,recharts:od,"lucide-react":ci};const DT=new sE;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())});Qb.createRoot(document.getElementById("root")).render(r.jsx(b.StrictMode,{children:r.jsx(Ny,{reducedMotion:"user",children:r.jsx(OT,{children:r.jsx(kS,{host:DT,children:r.jsx(RT,{})})})})}));export{l_ as $,wy as A,Mr as B,zc as C,Rr as D,qe as E,wI as F,Fm as G,Ge as H,yI as I,CA as J,YT as K,i_ as L,wC as M,Bn as N,e_ as O,Rn as P,XT as Q,JT as R,QT as S,Sl as T,Ti as U,Gf as V,Ic as W,IA as X,yt as Y,wE as Z,LE as _,Xt as a,Qs as a0,Bm as a1,uh as a2,ep as a3,cr as a4,It as a5,xE as a6,yS as a7,UE as a8,Zs as a9,Wn as aA,ba as aB,KT as aC,Fn as aD,a_ as aE,zl as aF,_C as aG,MC as aH,Xr as aI,t_ as aJ,Zm as aa,Jf as ab,gn as ac,QE as ad,Ow as ae,Hs as af,Yt as ag,qE as ah,GE as ai,m2 as aj,Vf as ak,bn as al,e2 as am,ZT as an,GT as ao,MS as ap,kl as aq,$t as ar,Ww as as,Ql as at,ir as au,Jt as av,c_ as aw,d_ as ax,AT as ay,u_ as az,Ie as b,qT as c,Ot as d,Re as e,ke as f,s_ as g,n_ as h,Tr as i,Te as j,yi as k,Dh as l,qa as m,Vm as n,xS as o,kS as p,vn as q,NI as r,Jr as s,nl as t,W2 as u,ya as v,jc as w,r_ as x,bI as y,vI as z};
|