@mathwiz/ui-components 0.1.32 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),x=require("react"),Eh=require("@heroui/progress"),ao=require("@heroui/card"),Z=require("lucide-react"),H=require("@heroui/react"),Nh=require("katex"),Ic=require("jsxgraph"),Dn=require("zustand"),Pc=require("zustand/shallow"),bn=require("zustand/react/shallow"),Th=require("zustand/middleware");function Mh(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const et=Mh(x),Pt=({progress:t,variant:e="solid",size:n="md",radius:r="md",children:s,className:o="",loading:i,intent:a,useNewClassName:l=!1,...c})=>{const f=t!==void 0?(p=>{const y=l?"mathwiz-btn--":"button--";return p===0?`${y}primary`:p===100?`${y}success`:`${y}secondary`})(t):l?"mathwiz-btn--primary":"button--primary",g=l?"mathwiz-btn":"button",h=l?"mathwiz-btn--":"button--",m=[g,`${h}${n}`,`${h}${e}`,`${h}radius-${r}`,f,i&&`${h}loading`,a&&l?`mathwiz-btn--${a}`:null,o].filter(Boolean).join(" ");return u.jsx("button",{type:"button",className:m,"data-progress":t,disabled:i||c.disabled,...c,children:i?"加载中...":s})},xa=t=>t===0?"开始学习":t===100?"复习":"继续学习",$h=t=>{if(t.length===0)return 0;const e=t.reduce((n,r)=>n+r.progress,0);return Math.round(e/t.length)},jh=({knowledgeItem:t,onLearnAction:e})=>{const n=()=>{e(t)};return console.log("KnowledgeCard render:",{progress:t.progress,text:xa(t.progress)}),u.jsxs(ao.Card,{className:"content-accordion__knowledge-card",children:[u.jsxs(ao.CardBody,{children:[u.jsx("h3",{className:"content-accordion__knowledge-title",children:t.title}),u.jsx("p",{className:"content-accordion__knowledge-description",children:t.description})]}),u.jsxs(ao.CardFooter,{className:"content-accordion__knowledge-actions",children:[u.jsxs("div",{className:"content-accordion__progress-container",children:[u.jsx(Eh.Progress,{value:t.progress,size:"sm",color:"primary","aria-label":`${t.title} 进度`,className:"content-accordion__progress-bar"}),u.jsxs("span",{className:"content-accordion__progress-text",children:[t.progress,"%"]})]}),u.jsx(Pt,{size:"sm",radius:"md",onClick:n,progress:t.progress,variant:t.progress===100?"light":t.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:xa(t.progress)})]})]})},Oh=({lesson:t,isExpanded:e,onToggle:n,onLearnAction:r})=>{const s=()=>{n(t.id)},o=$h(t.knowledgeItems);return u.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header",onClick:s,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${t.title},点击${e?"收起":"展开"}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header-content",children:[u.jsx("h2",{className:"content-accordion__lesson-title",children:t.title}),u.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",t.duration," 分钟"]})]}),u.jsxs("div",{className:"content-accordion__lesson-actions",children:[u.jsxs("span",{className:"content-accordion__lesson-progress",children:[o,"%"]}),e?u.jsx(Z.ChevronDown,{className:"content-accordion__lesson-icon"}):u.jsx(Z.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&u.jsx("div",{className:"content-accordion__knowledge-list",children:t.knowledgeItems.map(i=>u.jsx(jh,{knowledgeItem:i,onLearnAction:r},i.id))})]})},Fc=({unit:t,activeLessonIds:e,onToggleLesson:n,onLearnAction:r,loading:s=!1,className:o="",emptyState:i})=>s?u.jsx("div",{className:"content-accordion content-accordion--loading",children:u.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):t?u.jsxs("div",{className:`content-accordion ${o}`,children:[u.jsxs("header",{className:"content-accordion__header",children:[u.jsx("h1",{className:"content-accordion__unit-title",children:t.title}),u.jsx("p",{className:"content-accordion__unit-description",children:t.description}),u.jsxs("div",{className:"content-accordion__unit-meta",children:[u.jsxs("span",{children:["总共 ",t.totalLessons," 节课"]}),u.jsx("span",{children:"•"}),u.jsxs("span",{children:["预计学习 ",t.estimatedDuration]})]})]}),u.jsx("div",{className:"content-accordion__lessons",children:t.lessons.map(a=>u.jsx(Oh,{lesson:a,isExpanded:e.includes(a.id),onToggle:n,onLearnAction:r},a.id))})]}):u.jsx("div",{className:"content-accordion content-accordion--empty",children:i||u.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),Ih=t=>{switch(t){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},Dc=({data:t,loading:e=!1,error:n=null,collapsed:r=!1,onToggleCollapse:s,activeUnitId:o=null,onUnitSelect:i,renderUnitItem:a,className:l="",unitItemClassName:c="",style:d={},unitItemStyle:f={}})=>{const g=(y,b)=>{b.preventDefault(),i?.(y)},h=()=>{s?.()},m=y=>u.jsxs("div",{className:`sidebar__unit-item ${c} ${o===y.unitId?"sidebar__unit-item--active":""} ${y.status?`sidebar__unit-item--${y.status}`:""}`,style:f,onClick:b=>g(y.unitId,b),role:"button",tabIndex:0,"aria-label":`${y.title},进度 ${y.progressPercentage}%`,children:[u.jsxs("div",{className:"sidebar__unit-item__content",children:[y.icon&&u.jsx("span",{className:"sidebar__unit-item__icon",children:y.icon}),!r&&u.jsx("span",{className:"sidebar__unit-item__title",children:y.title})]}),!r&&y.progressPercentage!==void 0&&u.jsxs("div",{className:"sidebar__unit-item__progress",children:[u.jsx(H.Progress,{value:y.progressPercentage,size:"sm",color:Ih(y.status),"aria-label":`${y.title} 进度`}),u.jsxs("span",{className:"progress-percentage",children:[y.progressPercentage,"%"]})]})]},y.unitId),p=()=>e?u.jsx("div",{className:"sidebar__loading",children:"加载中..."}):n?u.jsxs("div",{className:"sidebar__error",children:["加载失败: ",n.message]}):t?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar__header",children:[u.jsx("button",{className:"sidebar__toggle-btn",onClick:h,"aria-label":"切换侧边栏折叠状态",children:r?"→":"←"}),!r&&u.jsxs("div",{className:"sidebar__course-info",children:[u.jsx("h3",{className:"sidebar__course-title",children:t.courseTitle}),u.jsxs("span",{className:"sidebar__course-level",children:[t.courseLevel,"年级"]})]})]}),u.jsx("nav",{className:"sidebar__content",children:u.jsx("ul",{className:"sidebar__unit-list",children:t.units&&t.units.length>0?t.units.map(y=>u.jsx("li",{children:a?a(y,y):m(y)},y.unitId)):u.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):u.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return u.jsx("aside",{className:`sidebar ${l} ${r?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${n?"sidebar--error":""}`,style:d,"aria-label":"课程导航侧边栏",role:"complementary",children:p()})},wi=({trigger:t,items:e,position:n="bottom",alignment:r="start",openDelay:s=300,closeDelay:o=100,onOpen:i,onClose:a,renderItem:l,itemConfig:c={},className:d,menuClassName:f,itemClassName:g})=>{const[h,m]=x.useState(!1),p=x.useRef(null),y=x.useRef(null),b=()=>{p.current&&clearTimeout(p.current),y.current&&clearTimeout(y.current)},w=()=>{b(),p.current=setTimeout(()=>{m(!0),i?.()},s)},v=()=>{b(),y.current=setTimeout(()=>{m(!1),a?.()},o)},S=C=>{!C.disabled&&C.onClick&&C.onClick(C)};x.useEffect(()=>()=>b(),[]);const _=C=>u.jsxs("div",{className:`submenu-item ${C.disabled?"is-disabled":""} ${g||""}`,onClick:()=>S(C),children:[C.icon&&u.jsx("span",{className:"submenu-item-icon",children:C.icon}),u.jsx("span",{children:C.label})]},C.id),A=()=>{const C=["submenu-panel"];return f&&C.push(f),C.push(`position-${n}`),r!=="start"&&C.push(`alignment-${r}`),h&&C.push("is-open"),C.join(" ")};return u.jsxs("div",{className:`submenu-container ${d||""}`,onMouseEnter:w,onMouseLeave:v,children:[u.jsx("div",{className:"submenu-trigger",children:t}),u.jsx("div",{className:A(),children:e.map(C=>l?l(C,c):_(C))})]})};function Lc(t,e){return function(){return t.apply(e,arguments)}}const{toString:Ph}=Object.prototype,{getPrototypeOf:_i}=Object,{iterator:Ds,toStringTag:zc}=Symbol,Ls=(t=>e=>{const n=Ph.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),dt=t=>(t=t.toLowerCase(),e=>Ls(e)===t),zs=t=>e=>typeof e===t,{isArray:Ln}=Array,Mn=zs("undefined");function Cr(t){return t!==null&&!Mn(t)&&t.constructor!==null&&!Mn(t.constructor)&&Ke(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Vc=dt("ArrayBuffer");function Fh(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Vc(t.buffer),e}const Dh=zs("string"),Ke=zs("function"),Gc=zs("number"),Rr=t=>t!==null&&typeof t=="object",Lh=t=>t===!0||t===!1,fs=t=>{if(Ls(t)!=="object")return!1;const e=_i(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(zc in t)&&!(Ds in t)},zh=t=>{if(!Rr(t)||Cr(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Vh=dt("Date"),Gh=dt("File"),Uh=dt("Blob"),Bh=dt("FileList"),Hh=t=>Rr(t)&&Ke(t.pipe),Wh=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Ke(t.append)&&((e=Ls(t))==="formdata"||e==="object"&&Ke(t.toString)&&t.toString()==="[object FormData]"))},qh=dt("URLSearchParams"),[Yh,Kh,Xh,Jh]=["ReadableStream","Request","Response","Headers"].map(dt),Zh=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ar(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),Ln(t))for(r=0,s=t.length;r<s;r++)e.call(null,t[r],r,t);else{if(Cr(t))return;const o=n?Object.getOwnPropertyNames(t):Object.keys(t),i=o.length;let a;for(r=0;r<i;r++)a=o[r],e.call(null,t[a],a,t)}}function Uc(t,e){if(Cr(t))return null;e=e.toLowerCase();const n=Object.keys(t);let r=n.length,s;for(;r-- >0;)if(s=n[r],e===s.toLowerCase())return s;return null}const dn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Bc=t=>!Mn(t)&&t!==dn;function Go(){const{caseless:t,skipUndefined:e}=Bc(this)&&this||{},n={},r=(s,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const i=t&&Uc(n,o)||o;fs(n[i])&&fs(s)?n[i]=Go(n[i],s):fs(s)?n[i]=Go({},s):Ln(s)?n[i]=s.slice():(!e||!Mn(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&Ar(arguments[s],r);return n}const Qh=(t,e,n,{allOwnKeys:r}={})=>(Ar(e,(s,o)=>{n&&Ke(s)?Object.defineProperty(t,o,{value:Lc(s,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),t),eg=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),tg=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},ng=(t,e,n,r)=>{let s,o,i;const a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=n!==!1&&_i(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},rg=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},sg=t=>{if(!t)return null;if(Ln(t))return t;let e=t.length;if(!Gc(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},og=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&_i(Uint8Array)),ig=(t,e)=>{const r=(t&&t[Ds]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},ag=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},lg=dt("HTMLFormElement"),cg=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),va=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),dg=dt("RegExp"),Hc=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};Ar(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},ug=t=>{Hc(t,(e,n)=>{if(Ke(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(Ke(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},fg=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Ln(t)?r(t):r(String(t).split(e)),n},hg=()=>{},gg=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function mg(t){return!!(t&&Ke(t.append)&&t[zc]==="FormData"&&t[Ds])}const pg=t=>{const e=new Array(10),n=(r,s)=>{if(Rr(r)){if(e.indexOf(r)>=0)return;if(Cr(r))return r;if(!("toJSON"in r)){e[s]=r;const o=Ln(r)?[]:{};return Ar(r,(i,a)=>{const l=n(i,s+1);!Mn(l)&&(o[a]=l)}),e[s]=void 0,o}}return r};return n(t,0)},yg=dt("AsyncFunction"),bg=t=>t&&(Rr(t)||Ke(t))&&Ke(t.then)&&Ke(t.catch),Wc=((t,e)=>t?setImmediate:e?((n,r)=>(dn.addEventListener("message",({source:s,data:o})=>{s===dn&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),dn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ke(dn.postMessage)),xg=typeof queueMicrotask<"u"?queueMicrotask.bind(dn):typeof process<"u"&&process.nextTick||Wc,vg=t=>t!=null&&Ke(t[Ds]),E={isArray:Ln,isArrayBuffer:Vc,isBuffer:Cr,isFormData:Wh,isArrayBufferView:Fh,isString:Dh,isNumber:Gc,isBoolean:Lh,isObject:Rr,isPlainObject:fs,isEmptyObject:zh,isReadableStream:Yh,isRequest:Kh,isResponse:Xh,isHeaders:Jh,isUndefined:Mn,isDate:Vh,isFile:Gh,isBlob:Uh,isRegExp:dg,isFunction:Ke,isStream:Hh,isURLSearchParams:qh,isTypedArray:og,isFileList:Bh,forEach:Ar,merge:Go,extend:Qh,trim:Zh,stripBOM:eg,inherits:tg,toFlatObject:ng,kindOf:Ls,kindOfTest:dt,endsWith:rg,toArray:sg,forEachEntry:ig,matchAll:ag,isHTMLForm:lg,hasOwnProperty:va,hasOwnProp:va,reduceDescriptors:Hc,freezeMethods:ug,toObjectSet:fg,toCamelCase:cg,noop:hg,toFiniteNumber:gg,findKey:Uc,global:dn,isContextDefined:Bc,isSpecCompliantForm:mg,toJSONObject:pg,isAsyncFn:yg,isThenable:bg,setImmediate:Wc,asap:xg,isIterable:vg};let K=class qc extends Error{static from(e,n,r,s,o,i){const a=new qc(e.message,n||e.code,r,s,o);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,n,r,s,o){super(e),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),s&&(this.request=s),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:E.toJSONObject(this.config),code:this.code,status:this.status}}};K.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";K.ERR_BAD_OPTION="ERR_BAD_OPTION";K.ECONNABORTED="ECONNABORTED";K.ETIMEDOUT="ETIMEDOUT";K.ERR_NETWORK="ERR_NETWORK";K.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";K.ERR_DEPRECATED="ERR_DEPRECATED";K.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";K.ERR_BAD_REQUEST="ERR_BAD_REQUEST";K.ERR_CANCELED="ERR_CANCELED";K.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";K.ERR_INVALID_URL="ERR_INVALID_URL";const wg=null;function Uo(t){return E.isPlainObject(t)||E.isArray(t)}function Yc(t){return E.endsWith(t,"[]")?t.slice(0,-2):t}function wa(t,e,n){return t?t.concat(e).map(function(s,o){return s=Yc(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function _g(t){return E.isArray(t)&&!t.some(Uo)}const Sg=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function Vs(t,e,n){if(!E.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=E.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,y){return!E.isUndefined(y[p])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,i=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&E.isSpecCompliantForm(e);if(!E.isFunction(s))throw new TypeError("visitor must be a function");function c(m){if(m===null)return"";if(E.isDate(m))return m.toISOString();if(E.isBoolean(m))return m.toString();if(!l&&E.isBlob(m))throw new K("Blob is not supported. Use a Buffer instead.");return E.isArrayBuffer(m)||E.isTypedArray(m)?l&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function d(m,p,y){let b=m;if(m&&!y&&typeof m=="object"){if(E.endsWith(p,"{}"))p=r?p:p.slice(0,-2),m=JSON.stringify(m);else if(E.isArray(m)&&_g(m)||(E.isFileList(m)||E.endsWith(p,"[]"))&&(b=E.toArray(m)))return p=Yc(p),b.forEach(function(v,S){!(E.isUndefined(v)||v===null)&&e.append(i===!0?wa([p],S,o):i===null?p:p+"[]",c(v))}),!1}return Uo(m)?!0:(e.append(wa(y,p,o),c(m)),!1)}const f=[],g=Object.assign(Sg,{defaultVisitor:d,convertValue:c,isVisitable:Uo});function h(m,p){if(!E.isUndefined(m)){if(f.indexOf(m)!==-1)throw Error("Circular reference detected in "+p.join("."));f.push(m),E.forEach(m,function(b,w){(!(E.isUndefined(b)||b===null)&&s.call(e,b,E.isString(w)?w.trim():w,p,g))===!0&&h(b,p?p.concat(w):[w])}),f.pop()}}if(!E.isObject(t))throw new TypeError("data must be an object");return h(t),e}function _a(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Si(t,e){this._pairs=[],t&&Vs(t,this,e)}const Kc=Si.prototype;Kc.append=function(e,n){this._pairs.push([e,n])};Kc.toString=function(e){const n=e?function(r){return e.call(this,r,_a)}:_a;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Cg(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Xc(t,e,n){if(!e)return t;const r=n&&n.encode||Cg,s=E.isFunction(n)?{serialize:n}:n,o=s&&s.serialize;let i;if(o?i=o(e,s):i=E.isURLSearchParams(e)?e.toString():new Si(e,s).toString(r),i){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+i}return t}class Sa{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){E.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ci={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},Rg=typeof URLSearchParams<"u"?URLSearchParams:Si,Ag=typeof FormData<"u"?FormData:null,kg=typeof Blob<"u"?Blob:null,Eg={isBrowser:!0,classes:{URLSearchParams:Rg,FormData:Ag,Blob:kg},protocols:["http","https","file","blob","url","data"]},Ri=typeof window<"u"&&typeof document<"u",Bo=typeof navigator=="object"&&navigator||void 0,Ng=Ri&&(!Bo||["ReactNative","NativeScript","NS"].indexOf(Bo.product)<0),Tg=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Mg=Ri&&window.location.href||"http://localhost",$g=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ri,hasStandardBrowserEnv:Ng,hasStandardBrowserWebWorkerEnv:Tg,navigator:Bo,origin:Mg},Symbol.toStringTag,{value:"Module"})),Ve={...$g,...Eg};function jg(t,e){return Vs(t,new Ve.classes.URLSearchParams,{visitor:function(n,r,s,o){return Ve.isNode&&E.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Og(t){return E.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Ig(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],e[o]=t[o];return e}function Jc(t){function e(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),l=o>=n.length;return i=!i&&E.isArray(s)?s.length:i,l?(E.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!a):((!s[i]||!E.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&E.isArray(s[i])&&(s[i]=Ig(s[i])),!a)}if(E.isFormData(t)&&E.isFunction(t.entries)){const n={};return E.forEachEntry(t,(r,s)=>{e(Og(r),s,n,0)}),n}return null}function Pg(t,e,n){if(E.isString(t))try{return(e||JSON.parse)(t),E.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const kr={transitional:Ci,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=E.isObject(e);if(o&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return s?JSON.stringify(Jc(e)):e;if(E.isArrayBuffer(e)||E.isBuffer(e)||E.isStream(e)||E.isFile(e)||E.isBlob(e)||E.isReadableStream(e))return e;if(E.isArrayBufferView(e))return e.buffer;if(E.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return jg(e,this.formSerializer).toString();if((a=E.isFileList(e))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return Vs(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Pg(e)):e}],transformResponse:[function(e){const n=this.transitional||kr.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(E.isResponse(e)||E.isReadableStream(e))return e;if(e&&E.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?K.from(a,K.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ve.classes.FormData,Blob:Ve.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};E.forEach(["delete","get","head","post","put","patch"],t=>{kr.headers[t]={}});const Fg=E.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Dg=t=>{const e={};let n,r,s;return t&&t.split(`
2
- `).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&Fg[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Ca=Symbol("internals");function Yn(t){return t&&String(t).trim().toLowerCase()}function hs(t){return t===!1||t==null?t:E.isArray(t)?t.map(hs):String(t)}function Lg(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const zg=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function lo(t,e,n,r,s){if(E.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!E.isString(e)){if(E.isString(r))return e.indexOf(r)!==-1;if(E.isRegExp(r))return r.test(e)}}function Vg(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function Gg(t,e){const n=E.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let Xe=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(a,l,c){const d=Yn(l);if(!d)throw new Error("header name must be a non-empty string");const f=E.findKey(s,d);(!f||s[f]===void 0||c===!0||c===void 0&&s[f]!==!1)&&(s[f||l]=hs(a))}const i=(a,l)=>E.forEach(a,(c,d)=>o(c,d,l));if(E.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(E.isString(e)&&(e=e.trim())&&!zg(e))i(Dg(e),n);else if(E.isObject(e)&&E.isIterable(e)){let a={},l,c;for(const d of e){if(!E.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?E.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}i(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=Yn(e),e){const r=E.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return Lg(s);if(E.isFunction(n))return n.call(this,s,r);if(E.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=Yn(e),e){const r=E.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||lo(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=Yn(i),i){const a=E.findKey(r,i);a&&(!n||lo(r,r[a],a,n))&&(delete r[a],s=!0)}}return E.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||lo(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return E.forEach(this,(s,o)=>{const i=E.findKey(r,o);if(i){n[i]=hs(s),delete n[o];return}const a=e?Vg(o):String(o).trim();a!==o&&delete n[o],n[a]=hs(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return E.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&E.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(`
3
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[Ca]=this[Ca]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=Yn(i);r[a]||(Gg(s,i),r[a]=!0)}return E.isArray(e)?e.forEach(o):o(e),this}};Xe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);E.reduceDescriptors(Xe.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});E.freezeMethods(Xe);function co(t,e){const n=this||kr,r=e||n,s=Xe.from(r.headers);let o=r.data;return E.forEach(t,function(a){o=a.call(n,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Zc(t){return!!(t&&t.__CANCEL__)}let Er=class extends K{constructor(e,n,r){super(e??"canceled",K.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function Qc(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new K("Request failed with status code "+n.status,[K.ERR_BAD_REQUEST,K.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Ug(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Bg(t,e){t=t||10;const n=new Array(t),r=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(l){const c=Date.now(),d=r[o];i||(i=c),n[s]=l,r[s]=c;let f=o,g=0;for(;f!==s;)g+=n[f++],f=f%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),c-i<e)return;const h=d&&c-d;return h?Math.round(g*1e3/h):void 0}}function Hg(t,e){let n=0,r=1e3/e,s,o;const i=(c,d=Date.now())=>{n=d,s=null,o&&(clearTimeout(o),o=null),t(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(s=c,o||(o=setTimeout(()=>{o=null,i(s)},r-f)))},()=>s&&i(s)]}const Rs=(t,e,n=3)=>{let r=0;const s=Bg(50,250);return Hg(o=>{const i=o.loaded,a=o.lengthComputable?o.total:void 0,l=i-r,c=s(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(f)},n)},Ra=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},Aa=t=>(...e)=>E.asap(()=>t(...e)),Wg=Ve.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,Ve.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(Ve.origin),Ve.navigator&&/(msie|trident)/i.test(Ve.navigator.userAgent)):()=>!0,qg=Ve.hasStandardBrowserEnv?{write(t,e,n,r,s,o,i){if(typeof document>"u")return;const a=[`${t}=${encodeURIComponent(e)}`];E.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),E.isString(r)&&a.push(`path=${r}`),E.isString(s)&&a.push(`domain=${s}`),o===!0&&a.push("secure"),E.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Yg(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Kg(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function ed(t,e,n){let r=!Yg(e);return t&&(r||n==!1)?Kg(t,e):e}const ka=t=>t instanceof Xe?{...t}:t;function mn(t,e){e=e||{};const n={};function r(c,d,f,g){return E.isPlainObject(c)&&E.isPlainObject(d)?E.merge.call({caseless:g},c,d):E.isPlainObject(d)?E.merge({},d):E.isArray(d)?d.slice():d}function s(c,d,f,g){if(E.isUndefined(d)){if(!E.isUndefined(c))return r(void 0,c,f,g)}else return r(c,d,f,g)}function o(c,d){if(!E.isUndefined(d))return r(void 0,d)}function i(c,d){if(E.isUndefined(d)){if(!E.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in e)return r(c,d);if(f in t)return r(void 0,c)}const l={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>s(ka(c),ka(d),f,!0)};return E.forEach(Object.keys({...t,...e}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const f=E.hasOwnProp(l,d)?l[d]:s,g=f(t[d],e[d],d);E.isUndefined(g)&&f!==a||(n[d]=g)}),n}const td=t=>{const e=mn({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;if(e.headers=i=Xe.from(i),e.url=Xc(ed(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),E.isFormData(n)){if(Ve.hasStandardBrowserEnv||Ve.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(E.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Ve.hasStandardBrowserEnv&&(r&&E.isFunction(r)&&(r=r(e)),r||r!==!1&&Wg(e.url))){const l=s&&o&&qg.read(o);l&&i.set(s,l)}return e},Xg=typeof XMLHttpRequest<"u",Jg=Xg&&function(t){return new Promise(function(n,r){const s=td(t);let o=s.data;const i=Xe.from(s.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=s,d,f,g,h,m;function p(){h&&h(),m&&m(),s.cancelToken&&s.cancelToken.unsubscribe(d),s.signal&&s.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(s.method.toUpperCase(),s.url,!0),y.timeout=s.timeout;function b(){if(!y)return;const v=Xe.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),_={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:v,config:t,request:y};Qc(function(C){n(C),p()},function(C){r(C),p()},_),y=null}"onloadend"in y?y.onloadend=b:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(b)},y.onabort=function(){y&&(r(new K("Request aborted",K.ECONNABORTED,t,y)),y=null)},y.onerror=function(S){const _=S&&S.message?S.message:"Network Error",A=new K(_,K.ERR_NETWORK,t,y);A.event=S||null,r(A),y=null},y.ontimeout=function(){let S=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const _=s.transitional||Ci;s.timeoutErrorMessage&&(S=s.timeoutErrorMessage),r(new K(S,_.clarifyTimeoutError?K.ETIMEDOUT:K.ECONNABORTED,t,y)),y=null},o===void 0&&i.setContentType(null),"setRequestHeader"in y&&E.forEach(i.toJSON(),function(S,_){y.setRequestHeader(_,S)}),E.isUndefined(s.withCredentials)||(y.withCredentials=!!s.withCredentials),a&&a!=="json"&&(y.responseType=s.responseType),c&&([g,m]=Rs(c,!0),y.addEventListener("progress",g)),l&&y.upload&&([f,h]=Rs(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",h)),(s.cancelToken||s.signal)&&(d=v=>{y&&(r(!v||v.type?new Er(null,t,y):v),y.abort(),y=null)},s.cancelToken&&s.cancelToken.subscribe(d),s.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d)));const w=Ug(s.url);if(w&&Ve.protocols.indexOf(w)===-1){r(new K("Unsupported protocol "+w+":",K.ERR_BAD_REQUEST,t));return}y.send(o||null)})},Zg=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,s;const o=function(c){if(!s){s=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof K?d:new Er(d instanceof Error?d.message:d))}};let i=e&&setTimeout(()=>{i=null,o(new K(`timeout of ${e}ms exceeded`,K.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),t=null)};t.forEach(c=>c.addEventListener("abort",o));const{signal:l}=r;return l.unsubscribe=()=>E.asap(a),l}},Qg=function*(t,e){let n=t.byteLength;if(n<e){yield t;return}let r=0,s;for(;r<n;)s=r+e,yield t.slice(r,s),r=s},em=async function*(t,e){for await(const n of tm(t))yield*Qg(n,e)},tm=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{await e.cancel()}},Ea=(t,e,n,r)=>{const s=em(t,e);let o=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await s.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let g=o+=f;n(g)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),s.return()}},{highWaterMark:2})},Na=64*1024,{isFunction:Fr}=E,nm=(({Request:t,Response:e})=>({Request:t,Response:e}))(E.global),{ReadableStream:Ta,TextEncoder:Ma}=E.global,$a=(t,...e)=>{try{return!!t(...e)}catch{return!1}},rm=t=>{t=E.merge.call({skipUndefined:!0},nm,t);const{fetch:e,Request:n,Response:r}=t,s=e?Fr(e):typeof fetch=="function",o=Fr(n),i=Fr(r);if(!s)return!1;const a=s&&Fr(Ta),l=s&&(typeof Ma=="function"?(m=>p=>m.encode(p))(new Ma):async m=>new Uint8Array(await new n(m).arrayBuffer())),c=o&&a&&$a(()=>{let m=!1;const p=new n(Ve.origin,{body:new Ta,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!p}),d=i&&a&&$a(()=>E.isReadableStream(new r("").body)),f={stream:d&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(p,y)=>{let b=p&&p[m];if(b)return b.call(p);throw new K(`Response type '${m}' is not supported`,K.ERR_NOT_SUPPORT,y)})});const g=async m=>{if(m==null)return 0;if(E.isBlob(m))return m.size;if(E.isSpecCompliantForm(m))return(await new n(Ve.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(E.isArrayBufferView(m)||E.isArrayBuffer(m))return m.byteLength;if(E.isURLSearchParams(m)&&(m=m+""),E.isString(m))return(await l(m)).byteLength},h=async(m,p)=>{const y=E.toFiniteNumber(m.getContentLength());return y??g(p)};return async m=>{let{url:p,method:y,data:b,signal:w,cancelToken:v,timeout:S,onDownloadProgress:_,onUploadProgress:A,responseType:C,headers:R,withCredentials:k="same-origin",fetchOptions:M}=td(m),F=e||fetch;C=C?(C+"").toLowerCase():"text";let D=Zg([w,v&&v.toAbortSignal()],S),P=null;const j=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let O;try{if(A&&c&&y!=="get"&&y!=="head"&&(O=await h(R,b))!==0){let se=new n(p,{method:"POST",body:b,duplex:"half"}),ee;if(E.isFormData(b)&&(ee=se.headers.get("content-type"))&&R.setContentType(ee),se.body){const[L,X]=Ra(O,Rs(Aa(A)));b=Ea(se.body,Na,L,X)}}E.isString(k)||(k=k?"include":"omit");const T=o&&"credentials"in n.prototype,B={...M,signal:D,method:y.toUpperCase(),headers:R.normalize().toJSON(),body:b,duplex:"half",credentials:T?k:void 0};P=o&&new n(p,B);let $=await(o?F(P,M):F(p,B));const Q=d&&(C==="stream"||C==="response");if(d&&(_||Q&&j)){const se={};["status","statusText","headers"].forEach(ae=>{se[ae]=$[ae]});const ee=E.toFiniteNumber($.headers.get("content-length")),[L,X]=_&&Ra(ee,Rs(Aa(_),!0))||[];$=new r(Ea($.body,Na,L,()=>{X&&X(),j&&j()}),se)}C=C||"text";let oe=await f[E.findKey(f,C)||"text"]($,m);return!Q&&j&&j(),await new Promise((se,ee)=>{Qc(se,ee,{data:oe,headers:Xe.from($.headers),status:$.status,statusText:$.statusText,config:m,request:P})})}catch(T){throw j&&j(),T&&T.name==="TypeError"&&/Load failed|fetch/i.test(T.message)?Object.assign(new K("Network Error",K.ERR_NETWORK,m,P,T&&T.response),{cause:T.cause||T}):K.from(T,T&&T.code,m,P,T&&T.response)}}},sm=new Map,nd=t=>{let e=t&&t.env||{};const{fetch:n,Request:r,Response:s}=e,o=[r,s,n];let i=o.length,a=i,l,c,d=sm;for(;a--;)l=o[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:rm(e)),d=c;return c};nd();const Ai={http:wg,xhr:Jg,fetch:{get:nd}};E.forEach(Ai,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const ja=t=>`- ${t}`,om=t=>E.isFunction(t)||t===null||t===!1;function im(t,e){t=E.isArray(t)?t:[t];const{length:n}=t;let r,s;const o={};for(let i=0;i<n;i++){r=t[i];let a;if(s=r,!om(r)&&(s=Ai[(a=String(r)).toLowerCase()],s===void 0))throw new K(`Unknown adapter '${a}'`);if(s&&(E.isFunction(s)||(s=s.get(e))))break;o[a||"#"+i]=s}if(!s){const i=Object.entries(o).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
4
- `+i.map(ja).join(`
5
- `):" "+ja(i[0]):"as no adapter specified";throw new K("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const rd={getAdapter:im,adapters:Ai};function uo(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Er(null,t)}function Oa(t){return uo(t),t.headers=Xe.from(t.headers),t.data=co.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),rd.getAdapter(t.adapter||kr.adapter,t)(t).then(function(r){return uo(t),r.data=co.call(t,t.transformResponse,r),r.headers=Xe.from(r.headers),r},function(r){return Zc(r)||(uo(t),r&&r.response&&(r.response.data=co.call(t,t.transformResponse,r.response),r.response.headers=Xe.from(r.response.headers))),Promise.reject(r)})}const sd="1.13.5",Gs={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Gs[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Ia={};Gs.transitional=function(e,n,r){function s(o,i){return"[Axios v"+sd+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,a)=>{if(e===!1)throw new K(s(i," has been removed"+(n?" in "+n:"")),K.ERR_DEPRECATED);return n&&!Ia[i]&&(Ia[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,i,a):!0}};Gs.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function am(t,e,n){if(typeof t!="object")throw new K("options must be an object",K.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let s=r.length;for(;s-- >0;){const o=r[s],i=e[o];if(i){const a=t[o],l=a===void 0||i(a,o,t);if(l!==!0)throw new K("option "+o+" must be "+l,K.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new K("Unknown option "+o,K.ERR_BAD_OPTION)}}const gs={assertOptions:am,validators:Gs},st=gs.validators;let hn=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Sa,response:new Sa}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
- `+o):r.stack=o}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=mn(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&gs.assertOptions(r,{silentJSONParsing:st.transitional(st.boolean),forcedJSONParsing:st.transitional(st.boolean),clarifyTimeoutError:st.transitional(st.boolean),legacyInterceptorReqResOrdering:st.transitional(st.boolean)},!1),s!=null&&(E.isFunction(s)?n.paramsSerializer={serialize:s}:gs.assertOptions(s,{encode:st.function,serialize:st.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),gs.assertOptions(n,{baseUrl:st.spelling("baseURL"),withXsrfToken:st.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&E.merge(o.common,o[n.method]);o&&E.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),n.headers=Xe.concat(i,o);const a=[];let l=!0;this.interceptors.request.forEach(function(p){if(typeof p.runWhen=="function"&&p.runWhen(n)===!1)return;l=l&&p.synchronous;const y=n.transitional||Ci;y&&y.legacyInterceptorReqResOrdering?a.unshift(p.fulfilled,p.rejected):a.push(p.fulfilled,p.rejected)});const c=[];this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let d,f=0,g;if(!l){const m=[Oa.bind(this),void 0];for(m.unshift(...a),m.push(...c),g=m.length,d=Promise.resolve(n);f<g;)d=d.then(m[f++],m[f++]);return d}g=a.length;let h=n;for(;f<g;){const m=a[f++],p=a[f++];try{h=m(h)}catch(y){p.call(this,y);break}}try{d=Oa.call(this,h)}catch(m){return Promise.reject(m)}for(f=0,g=c.length;f<g;)d=d.then(c[f++],c[f++]);return d}getUri(e){e=mn(this.defaults,e);const n=ed(e.baseURL,e.url,e.allowAbsoluteUrls);return Xc(n,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],function(e){hn.prototype[e]=function(n,r){return this.request(mn(r||{},{method:e,url:n,data:(r||{}).data}))}});E.forEach(["post","put","patch"],function(e){function n(r){return function(o,i,a){return this.request(mn(a||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}hn.prototype[e]=n(),hn.prototype[e+"Form"]=n(!0)});let lm=class od{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{r.subscribe(a),o=a}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},e(function(o,i,a){r.reason||(r.reason=new Er(o,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new od(function(s){e=s}),cancel:e}}};function cm(t){return function(n){return t.apply(null,n)}}function dm(t){return E.isObject(t)&&t.isAxiosError===!0}const Ho={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Ho).forEach(([t,e])=>{Ho[e]=t});function id(t){const e=new hn(t),n=Lc(hn.prototype.request,e);return E.extend(n,hn.prototype,e,{allOwnKeys:!0}),E.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return id(mn(t,s))},n}const Se=id(kr);Se.Axios=hn;Se.CanceledError=Er;Se.CancelToken=lm;Se.isCancel=Zc;Se.VERSION=sd;Se.toFormData=Vs;Se.AxiosError=K;Se.Cancel=Se.CanceledError;Se.all=function(e){return Promise.all(e)};Se.spread=cm;Se.isAxiosError=dm;Se.mergeConfig=mn;Se.AxiosHeaders=Xe;Se.formToJSON=t=>Jc(E.isHTMLForm(t)?new FormData(t):t);Se.getAdapter=rd.getAdapter;Se.HttpStatusCode=Ho;Se.default=Se;const{Axios:c1,AxiosError:d1,CanceledError:u1,isCancel:f1,CancelToken:h1,VERSION:g1,all:m1,Cancel:p1,isAxiosError:y1,spread:b1,toFormData:x1,AxiosHeaders:v1,HttpStatusCode:w1,formToJSON:_1,getAdapter:S1,mergeConfig:C1}=Se,um=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),fm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),hm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),gm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),mm=[{id:"profile",label:"个人主页",icon:u.jsx(um,{})},{id:"settings",label:"设置",icon:u.jsx(fm,{})},{id:"help",label:"帮助",icon:u.jsx(hm,{})},{id:"logout",label:"退出",icon:u.jsx(gm,{})}],ad=({userId:t,userName:e,userAvatar:n,apiConfig:r,menuItems:s=mm,avatarSize:o="md",isLoading:i=!1,error:a=null,avatarClassName:l,userNameClassName:c,containerClassName:d,onMenuOpen:f,onMenuClose:g,onMenuItemClick:h,onLogout:m,renderMenuItem:p,renderUserInfo:y})=>{const[b,w]=x.useState({id:t||"",name:e||"",avatar:n||"",level:0,badges:[]}),[v,S]=x.useState(i),[_,A]=x.useState(a);x.useEffect(()=>{t&&r&&!e&&!n&&C()},[t,r,e,n]);const C=async()=>{S(!0),A(null);try{const P=r.endpoints.userProfile.replace(":userId",t),j=await Se.get(`${r.baseURL}${P}`,{headers:r.headers});w(j.data)}catch(P){A(P)}finally{S(!1)}},R=P=>{h?.(P.id),P.id==="logout"&&m?.()},k=()=>{f?.()},M=()=>{g?.()},F=()=>u.jsxs("div",{className:"user-profile-trigger",children:[u.jsx(H.Avatar,{src:b.avatar,size:o,className:l,alt:"用户头像"}),u.jsx("span",{className:`user-name ${c||""}`,children:b.name})]}),D=P=>u.jsxs("div",{className:"submenu-item",onClick:()=>R(P),children:[P.icon&&u.jsx("span",{className:"submenu-item-icon",children:P.icon}),u.jsx("span",{children:P.label})]},P.id);return v?u.jsx("div",{className:`user-profile-container ${d||""} is-loading`,children:u.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):_?u.jsx("div",{className:`user-profile-container ${d||""} has-error`,children:u.jsxs("div",{className:"user-profile-error",children:["错误: ",_.message]})}):b.name?u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx(wi,{trigger:y?y(b):F(),items:s.map(P=>({...P,onClick:()=>R(P)})),position:"bottom",alignment:"end",onOpen:k,onClose:M,renderItem:p?P=>p(P,b):D})}):u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx("div",{className:"user-profile-loading",children:"未登录"})})},pm=t=>u.jsxs("div",{className:"explore-menu-item",onClick:()=>t.onClick?.(t),children:[u.jsx("span",{className:"explore-item-label",children:t.label}),t.status&&u.jsx("span",{className:`explore-item-status status-${t.status.toLowerCase().replace("%","").replace(" ","-")}`,children:t.status})]},t.id),ym=({className:t})=>u.jsxs("button",{className:t,"aria-label":"探索数学课程",children:[u.jsx("span",{className:"explore-icon",children:"🌍"}),u.jsx("span",{className:"explore-text",children:"探索"})]}),bm=({className:t="",style:e,logoHref:n="/",logoText:r="MathWiz",onLogoClick:s,exploreItems:o=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:l,renderExploreItem:c=pm,userData:d,userMenuItems:f,onUserMenuItemClick:g,onLogout:h,isLoading:m=!1,error:p=null,headerClassName:y="",logoClassName:b="",exploreClassName:w="",userProfileClassName:v="",variant:S="gradient",color:_,background:A,height:C,gradientFrom:R,gradientTo:k,gradientVia:M,logoColor:F,logoSize:D="md",exploreButtonVariant:P="flat",exploreButtonColor:j="primary","aria-label":O,"aria-labelledby":T,...B})=>{const $=o.map(L=>({id:L.id,label:c(L),onClick:()=>l?.(L)})),Q=["mathwiz-header",`mathwiz-header--${S}`,_&&`mathwiz-header--color-${_}`,y,t].filter(Boolean).join(" "),oe=["logo",`logo--${D}`,b].filter(Boolean).join(" "),se=["explore-button",`explore-button--${P}`,`explore-button--color-${j}`,w].filter(Boolean).join(" "),ee={...e,...C&&{height:typeof C=="number"?`${C}px`:C},...A&&{"--custom-bg":A},...F&&{"--logo-color":F},...R&&k&&{"--header-bg":M?`linear-gradient(to right, ${R}, ${M}, ${k})`:`linear-gradient(to right, ${R}, ${k})`}};return u.jsx("header",{className:Q,style:ee,"aria-label":O,"aria-labelledby":T,role:"banner",...B,children:u.jsxs("div",{className:"header-content",children:[u.jsx("div",{className:"header-section left",children:u.jsx(wi,{trigger:u.jsx(ym,{className:se}),items:$,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),u.jsx("div",{className:"header-section center",children:u.jsx("a",{href:n,className:oe,onClick:s,"aria-label":"MathWiz 首页",children:r})}),u.jsx("div",{className:"header-section right",children:u.jsx(ad,{userName:d?.name,userAvatar:d?.avatar,menuItems:f,onMenuItemClick:g,onLogout:h,containerClassName:v,isLoading:m,error:p})})]})})},ld=x.memo(bm,(t,e)=>t.logoText===e.logoText&&t.logoHref===e.logoHref&&t.className===e.className&&t.headerClassName===e.headerClassName&&t.logoClassName===e.logoClassName&&t.exploreClassName===e.exploreClassName&&t.userProfileClassName===e.userProfileClassName&&t["aria-label"]===e["aria-label"]&&t["aria-labelledby"]===e["aria-labelledby"]&&t.isLoading===e.isLoading&&t.error===e.error&&t.variant===e.variant&&t.color===e.color&&t.background===e.background&&t.height===e.height&&t.gradientFrom===e.gradientFrom&&t.gradientTo===e.gradientTo&&t.gradientVia===e.gradientVia&&t.logoColor===e.logoColor&&t.logoSize===e.logoSize&&t.exploreButtonVariant===e.exploreButtonVariant&&t.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(t.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(t.userData)===JSON.stringify(e.userData)&&JSON.stringify(t.userMenuItems)===JSON.stringify(e.userMenuItems)),rr={LEFT:"left",RIGHT:"right",TOP:"top",BOTTOM:"bottom"},fo={NUMBER:"number",TIME:"time",CUSTOM:"custom"},Pa={iconPosition:rr.LEFT,interactive:!1},cd=t=>{const{label:e,value:n,unit:r,color:s,icon:o,iconPosition:i=Pa.iconPosition,render:a,onClick:l,className:c="",style:d,interactive:f=Pa.interactive,"aria-label":g,"aria-role":h,"data-testid":m,subtitle:p,showHelpIcon:y,helpIconTitle:b="What is this?",contentType:w=fo.NUMBER,timeValue:v,themeColorVar:S}=t,_=x.useMemo(()=>h||(l?"button":"group"),[h,l]),A=x.useMemo(()=>{const k=["mathwiz-statblock"];return c&&k.push(c),f&&k.push("mathwiz-statblock-interactive"),s&&!s.startsWith("#")&&k.push(`mathwiz-statblock-color-${s}`),k.join(" ")},[c,f,s]),C=x.useMemo(()=>{const k={...d};return s&&s.startsWith("#")&&(k.backgroundColor=s),S&&(k["--statblock-current-theme-color"]=`var(${S})`),k},[d,s,S]),R={label:e,value:n,unit:r,icon:o,iconPosition:i,color:s,interactive:f,className:A,style:C,subtitle:p,showHelpIcon:y,contentType:w,timeValue:v};return a?a(R):u.jsxs("div",{className:A,style:C,onClick:l,role:_,"aria-label":g,"data-testid":m,tabIndex:f?0:void 0,children:[u.jsxs("div",{className:"mathwiz-statblock-header",children:[u.jsx("div",{className:"mathwiz-statblock-title",children:e}),(p||y)&&u.jsxs("div",{className:"mathwiz-statblock-subtitle",children:[p,y&&u.jsx("span",{className:"mathwiz-statblock-help-icon",title:b,children:"?"})]})]}),u.jsx("div",{className:"mathwiz-statblock-body",children:w===fo.TIME&&v?u.jsxs("div",{className:"mathwiz-statblock-time-display",children:[u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.hours).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"HR"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.minutes).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"MIN"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.seconds).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"SEC"})]})]}):w===fo.CUSTOM?u.jsxs(u.Fragment,{children:[i===rr.TOP&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-top",children:o}),u.jsxs("div",{className:"mathwiz-statblock-content",children:[i===rr.LEFT&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-left",children:o}),u.jsxs("div",{className:"mathwiz-statblock-text",children:[u.jsx("div",{className:"mathwiz-statblock-label",children:e}),u.jsxs("div",{className:"mathwiz-statblock-value-container",children:[u.jsx("span",{className:"mathwiz-statblock-value",children:n}),r&&u.jsx("span",{className:"mathwiz-statblock-unit",children:r})]})]}),i===rr.RIGHT&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-right",children:o})]}),i===rr.BOTTOM&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-bottom",children:o})]}):u.jsx("div",{className:"mathwiz-statblock-value-large",children:n})})]})};x.memo(cd);var xm=/\s+/g,vm=t=>typeof t!="string"||!t?t:t.replace(xm," ").trim(),As=(...t)=>{const e=[],n=r=>{if(!r&&r!==0&&r!==0n)return;if(Array.isArray(r)){for(let o=0,i=r.length;o<i;o++)n(r[o]);return}const s=typeof r;if(s==="string"||s==="number"||s==="bigint"){if(s==="number"&&r!==r)return;e.push(String(r))}else if(s==="object"){const o=Object.keys(r);for(let i=0,a=o.length;i<a;i++){const l=o[i];r[l]&&e.push(l)}}};for(let r=0,s=t.length;r<s;r++){const o=t[r];o!=null&&n(o)}return e.length>0?vm(e.join(" ")):void 0},Fa=t=>t===!1?"false":t===!0?"true":t===0?"0":t,We=t=>{if(!t||typeof t!="object")return!0;for(const e in t)return!1;return!0},wm=(t,e)=>{if(t===e)return!0;if(!t||!e)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++){const o=n[s];if(!r.includes(o)||t[o]!==e[o])return!1}return!0},_m=(t,e)=>{for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const r=e[n];n in t?t[n]=As(t[n],r):t[n]=r}return t},dd=(t,e)=>{for(let n=0;n<t.length;n++){const r=t[n];Array.isArray(r)?dd(r,e):r&&e.push(r)}},ud=(...t)=>{const e=[];dd(t,e);const n=[];for(let r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},Wo=(t,e)=>{const n={};for(const r in t){const s=t[r];if(r in e){const o=e[r];Array.isArray(s)||Array.isArray(o)?n[r]=ud(o,s):typeof s=="object"&&typeof o=="object"&&s&&o?n[r]=Wo(s,o):n[r]=o+" "+s}else n[r]=s}for(const r in e)r in t||(n[r]=e[r]);return n},Sm={twMerge:!0,twMergeConfig:{}};function Cm(){let t=null,e={},n=!1;return{get cachedTwMerge(){return t},set cachedTwMerge(r){t=r},get cachedTwMergeConfig(){return e},set cachedTwMergeConfig(r){e=r},get didTwMergeConfigChange(){return n},set didTwMergeConfigChange(r){n=r},reset(){t=null,e={},n=!1}}}var $t=Cm(),Rm=t=>{const e=(r,s)=>{const{extend:o=null,slots:i={},variants:a={},compoundVariants:l=[],compoundSlots:c=[],defaultVariants:d={}}=r,f={...Sm,...s},g=o?.base?As(o.base,r?.base):r?.base,h=o?.variants&&!We(o.variants)?Wo(a,o.variants):a,m=o?.defaultVariants&&!We(o.defaultVariants)?{...o.defaultVariants,...d}:d;!We(f.twMergeConfig)&&!wm(f.twMergeConfig,$t.cachedTwMergeConfig)&&($t.didTwMergeConfigChange=!0,$t.cachedTwMergeConfig=f.twMergeConfig);const p=We(o?.slots),y=We(i)?{}:{base:As(r?.base,p&&o?.base),...i},b=p?y:_m({...o?.slots},We(y)?{base:r?.base}:y),w=We(o?.compoundVariants)?l:ud(o?.compoundVariants,l),v=_=>{if(We(h)&&We(i)&&p)return t(g,_?.class,_?.className)(f);if(w&&!Array.isArray(w))throw new TypeError(`The "compoundVariants" prop must be an array. Received: ${typeof w}`);if(c&&!Array.isArray(c))throw new TypeError(`The "compoundSlots" prop must be an array. Received: ${typeof c}`);const A=(j,O=h,T=null,B=null)=>{const $=O[j];if(!$||We($))return null;const Q=B?.[j]??_?.[j];if(Q===null)return null;const oe=Fa(Q);if(typeof oe=="object")return null;const se=m?.[j],ee=oe??Fa(se);return $[ee||"false"]},C=()=>{if(!h)return null;const j=Object.keys(h),O=[];for(let T=0;T<j.length;T++){const B=A(j[T],h);B&&O.push(B)}return O},R=(j,O)=>{if(!h||typeof h!="object")return null;const T=[];for(const B in h){const $=A(B,h,j,O),Q=j==="base"&&typeof $=="string"?$:$&&$[j];Q&&T.push(Q)}return T},k={};for(const j in _){const O=_[j];O!==void 0&&(k[j]=O)}const M=(j,O)=>{const T=typeof _?.[j]=="object"?{[j]:_[j]?.initial}:{};return{...m,...k,...T,...O}},F=(j=[],O)=>{const T=[],B=j.length;for(let $=0;$<B;$++){const{class:Q,className:oe,...se}=j[$];let ee=!0;const L=M(null,O);for(const X in se){const ae=se[X],ve=L[X];if(Array.isArray(ae)){if(!ae.includes(ve)){ee=!1;break}}else{if((ae==null||ae===!1)&&(ve==null||ve===!1))continue;if(ve!==ae){ee=!1;break}}}ee&&(Q&&T.push(Q),oe&&T.push(oe))}return T},D=j=>{const O=F(w,j);if(!Array.isArray(O))return O;const T={},B=t;for(let $=0;$<O.length;$++){const Q=O[$];if(typeof Q=="string")T.base=B(T.base,Q)(f);else if(typeof Q=="object")for(const oe in Q)T[oe]=B(T[oe],Q[oe])(f)}return T},P=j=>{if(c.length<1)return null;const O={},T=M(null,j);for(let B=0;B<c.length;B++){const{slots:$=[],class:Q,className:oe,...se}=c[B];if(!We(se)){let ee=!0;for(const L in se){const X=T[L],ae=se[L];if(X===void 0||(Array.isArray(ae)?!ae.includes(X):ae!==X)){ee=!1;break}}if(!ee)continue}for(let ee=0;ee<$.length;ee++){const L=$[ee];O[L]||(O[L]=[]),O[L].push([Q,oe])}}return O};if(!We(i)||!p){const j={};if(typeof b=="object"&&!We(b)){const O=t;for(const T in b)j[T]=B=>{const $=D(B),Q=P(B);return O(b[T],R(T,B),$?$[T]:void 0,Q?Q[T]:void 0,B?.class,B?.className)(f)}}return j}return t(g,C(),F(w),_?.class,_?.className)(f)},S=()=>{if(!(!h||typeof h!="object"))return Object.keys(h)};return v.variantKeys=S(),v.extend=o,v.base=g,v.slots=b,v.variants=h,v.defaultVariants=m,v.compoundSlots=c,v.compoundVariants=w,v};return{tv:e,createTV:r=>(s,o)=>e(s,o?Wo(r,o):r)}};const Am=(t,e)=>{const n=new Array(t.length+e.length);for(let r=0;r<t.length;r++)n[r]=t[r];for(let r=0;r<e.length;r++)n[t.length+r]=e[r];return n},km=(t,e)=>({classGroupId:t,validator:e}),fd=(t=new Map,e=null,n)=>({nextPart:t,validators:e,classGroupId:n}),ks="-",Da=[],Em="arbitrary..",Nm=t=>{const e=Mm(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Tm(i);const a=i.split(ks),l=a[0]===""&&a.length>1?1:0;return hd(a,l,e)},getConflictingClassGroupIds:(i,a)=>{if(a){const l=r[i],c=n[i];return l?c?Am(c,l):l:c||Da}return n[i]||Da}}},hd=(t,e,n)=>{if(t.length-e===0)return n.classGroupId;const s=t[e],o=n.nextPart.get(s);if(o){const c=hd(t,e+1,o);if(c)return c}const i=n.validators;if(i===null)return;const a=e===0?t.join(ks):t.slice(e).join(ks),l=i.length;for(let c=0;c<l;c++){const d=i[c];if(d.validator(a))return d.classGroupId}},Tm=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),n=e.indexOf(":"),r=e.slice(0,n);return r?Em+r:void 0})(),Mm=t=>{const{theme:e,classGroups:n}=t;return $m(n,e)},$m=(t,e)=>{const n=fd();for(const r in t){const s=t[r];ki(s,n,r,e)}return n},ki=(t,e,n,r)=>{const s=t.length;for(let o=0;o<s;o++){const i=t[o];jm(i,e,n,r)}},jm=(t,e,n,r)=>{if(typeof t=="string"){Om(t,e,n);return}if(typeof t=="function"){Im(t,e,n,r);return}Pm(t,e,n,r)},Om=(t,e,n)=>{const r=t===""?e:gd(e,t);r.classGroupId=n},Im=(t,e,n,r)=>{if(Fm(t)){ki(t(r),e,n,r);return}e.validators===null&&(e.validators=[]),e.validators.push(km(n,t))},Pm=(t,e,n,r)=>{const s=Object.entries(t),o=s.length;for(let i=0;i<o;i++){const[a,l]=s[i];ki(l,gd(e,a),n,r)}},gd=(t,e)=>{let n=t;const r=e.split(ks),s=r.length;for(let o=0;o<s;o++){const i=r[o];let a=n.nextPart.get(i);a||(a=fd(),n.nextPart.set(i,a)),n=a}return n},Fm=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,Dm=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=Object.create(null),r=Object.create(null);const s=(o,i)=>{n[o]=i,e++,e>t&&(e=0,r=n,n=Object.create(null))};return{get(o){let i=n[o];if(i!==void 0)return i;if((i=r[o])!==void 0)return s(o,i),i},set(o,i){o in n?n[o]=i:s(o,i)}}},qo="!",La=":",Lm=[],za=(t,e,n,r,s)=>({modifiers:t,hasImportantModifier:e,baseClassName:n,maybePostfixModifierPosition:r,isExternal:s}),zm=t=>{const{prefix:e,experimentalParseClassName:n}=t;let r=s=>{const o=[];let i=0,a=0,l=0,c;const d=s.length;for(let p=0;p<d;p++){const y=s[p];if(i===0&&a===0){if(y===La){o.push(s.slice(l,p)),l=p+1;continue}if(y==="/"){c=p;continue}}y==="["?i++:y==="]"?i--:y==="("?a++:y===")"&&a--}const f=o.length===0?s:s.slice(l);let g=f,h=!1;f.endsWith(qo)?(g=f.slice(0,-1),h=!0):f.startsWith(qo)&&(g=f.slice(1),h=!0);const m=c&&c>l?c-l:void 0;return za(o,h,g,m)};if(e){const s=e+La,o=r;r=i=>i.startsWith(s)?o(i.slice(s.length)):za(Lm,!1,i,void 0,!0)}if(n){const s=r;r=o=>n({className:o,parseClassName:s})}return r},Vm=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((n,r)=>{e.set(n,1e6+r)}),n=>{const r=[];let s=[];for(let o=0;o<n.length;o++){const i=n[o],a=i[0]==="[",l=e.has(i);a||l?(s.length>0&&(s.sort(),r.push(...s),s=[]),r.push(i)):s.push(i)}return s.length>0&&(s.sort(),r.push(...s)),r}},Gm=t=>({cache:Dm(t.cacheSize),parseClassName:zm(t),sortModifiers:Vm(t),...Nm(t)}),Um=/\s+/,Bm=(t,e)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s,sortModifiers:o}=e,i=[],a=t.trim().split(Um);let l="";for(let c=a.length-1;c>=0;c-=1){const d=a[c],{isExternal:f,modifiers:g,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);if(f){l=d+(l.length>0?" "+l:l);continue}let y=!!p,b=r(y?m.substring(0,p):m);if(!b){if(!y){l=d+(l.length>0?" "+l:l);continue}if(b=r(m),!b){l=d+(l.length>0?" "+l:l);continue}y=!1}const w=g.length===0?"":g.length===1?g[0]:o(g).join(":"),v=h?w+qo:w,S=v+b;if(i.indexOf(S)>-1)continue;i.push(S);const _=s(b,y);for(let A=0;A<_.length;++A){const C=_[A];i.push(v+C)}l=d+(l.length>0?" "+l:l)}return l},Hm=(...t)=>{let e=0,n,r,s="";for(;e<t.length;)(n=t[e++])&&(r=md(n))&&(s&&(s+=" "),s+=r);return s},md=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=md(t[r]))&&(n&&(n+=" "),n+=e);return n},Yo=(t,...e)=>{let n,r,s,o;const i=l=>{const c=e.reduce((d,f)=>f(d),t());return n=Gm(c),r=n.cache.get,s=n.cache.set,o=a,a(l)},a=l=>{const c=r(l);if(c)return c;const d=Bm(l,n);return s(l,d),d};return o=i,(...l)=>o(Hm(...l))},Wm=[],Me=t=>{const e=n=>n[t]||Wm;return e.isThemeGetter=!0,e},pd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,yd=/^\((?:(\w[\w-]*):)?(.+)\)$/i,qm=/^\d+\/\d+$/,Ym=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Km=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Xm=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Jm=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Zm=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sn=t=>qm.test(t),ne=t=>!!t&&!Number.isNaN(Number(t)),Dt=t=>!!t&&Number.isInteger(Number(t)),ho=t=>t.endsWith("%")&&ne(t.slice(0,-1)),kt=t=>Ym.test(t),Qm=()=>!0,ep=t=>Km.test(t)&&!Xm.test(t),bd=()=>!1,tp=t=>Jm.test(t),np=t=>Zm.test(t),rp=t=>!G(t)&&!U(t),sp=t=>zn(t,wd,bd),G=t=>pd.test(t),Zt=t=>zn(t,_d,ep),go=t=>zn(t,cp,ne),Va=t=>zn(t,xd,bd),op=t=>zn(t,vd,np),Dr=t=>zn(t,Sd,tp),U=t=>yd.test(t),Kn=t=>Vn(t,_d),ip=t=>Vn(t,dp),Ga=t=>Vn(t,xd),ap=t=>Vn(t,wd),lp=t=>Vn(t,vd),Lr=t=>Vn(t,Sd,!0),zn=(t,e,n)=>{const r=pd.exec(t);return r?r[1]?e(r[1]):n(r[2]):!1},Vn=(t,e,n=!1)=>{const r=yd.exec(t);return r?r[1]?e(r[1]):n:!1},xd=t=>t==="position"||t==="percentage",vd=t=>t==="image"||t==="url",wd=t=>t==="length"||t==="size"||t==="bg-size",_d=t=>t==="length",cp=t=>t==="number",dp=t=>t==="family-name",Sd=t=>t==="shadow",Ko=()=>{const t=Me("color"),e=Me("font"),n=Me("text"),r=Me("font-weight"),s=Me("tracking"),o=Me("leading"),i=Me("breakpoint"),a=Me("container"),l=Me("spacing"),c=Me("radius"),d=Me("shadow"),f=Me("inset-shadow"),g=Me("text-shadow"),h=Me("drop-shadow"),m=Me("blur"),p=Me("perspective"),y=Me("aspect"),b=Me("ease"),w=Me("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],_=()=>[...S(),U,G],A=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],R=()=>[U,G,l],k=()=>[Sn,"full","auto",...R()],M=()=>[Dt,"none","subgrid",U,G],F=()=>["auto",{span:["full",Dt,U,G]},Dt,U,G],D=()=>[Dt,"auto",U,G],P=()=>["auto","min","max","fr",U,G],j=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],O=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...R()],B=()=>[Sn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],$=()=>[t,U,G],Q=()=>[...S(),Ga,Va,{position:[U,G]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],se=()=>["auto","cover","contain",ap,sp,{size:[U,G]}],ee=()=>[ho,Kn,Zt],L=()=>["","none","full",c,U,G],X=()=>["",ne,Kn,Zt],ae=()=>["solid","dashed","dotted","double"],ve=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],me=()=>[ne,ho,Ga,Va],Ft=()=>["","none",m,U,G],At=()=>["none",ne,U,G],z=()=>["none",ne,U,G],I=()=>[ne,U,G],N=()=>[Sn,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[kt],breakpoint:[kt],color:[Qm],container:[kt],"drop-shadow":[kt],ease:["in","out","in-out"],font:[rp],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[kt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[kt],shadow:[kt],spacing:["px",ne],text:[kt],"text-shadow":[kt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Sn,G,U,y]}],container:["container"],columns:[{columns:[ne,G,U,a]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:_()}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:k()}],"inset-x":[{"inset-x":k()}],"inset-y":[{"inset-y":k()}],start:[{start:k()}],end:[{end:k()}],top:[{top:k()}],right:[{right:k()}],bottom:[{bottom:k()}],left:[{left:k()}],visibility:["visible","invisible","collapse"],z:[{z:[Dt,"auto",U,G]}],basis:[{basis:[Sn,"full","auto",a,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Sn,"auto","initial","none",G]}],grow:[{grow:["",ne,U,G]}],shrink:[{shrink:["",ne,U,G]}],order:[{order:[Dt,"first","last","none",U,G]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:F()}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:F()}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":P()}],"auto-rows":[{"auto-rows":P()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...j(),"normal"]}],"justify-items":[{"justify-items":[...O(),"normal"]}],"justify-self":[{"justify-self":["auto",...O()]}],"align-content":[{content:["normal",...j()]}],"align-items":[{items:[...O(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...O(),{baseline:["","last"]}]}],"place-content":[{"place-content":j()}],"place-items":[{"place-items":[...O(),"baseline"]}],"place-self":[{"place-self":["auto",...O()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:B()}],w:[{w:[a,"screen",...B()]}],"min-w":[{"min-w":[a,"screen","none",...B()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...B()]}],h:[{h:["screen","lh",...B()]}],"min-h":[{"min-h":["screen","lh","none",...B()]}],"max-h":[{"max-h":["screen","lh",...B()]}],"font-size":[{text:["base",n,Kn,Zt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,U,go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ho,G]}],"font-family":[{font:[ip,G,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,U,G]}],"line-clamp":[{"line-clamp":[ne,"none",U,go]}],leading:[{leading:[o,...R()]}],"list-image":[{"list-image":["none",U,G]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",U,G]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ae(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",U,Zt]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[ne,"auto",U,G]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",U,G]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",U,G]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Q()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:se()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Dt,U,G],radial:["",U,G],conic:[Dt,U,G]},lp,op]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:ee()}],"gradient-via-pos":[{via:ee()}],"gradient-to-pos":[{to:ee()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:L()}],"rounded-s":[{"rounded-s":L()}],"rounded-e":[{"rounded-e":L()}],"rounded-t":[{"rounded-t":L()}],"rounded-r":[{"rounded-r":L()}],"rounded-b":[{"rounded-b":L()}],"rounded-l":[{"rounded-l":L()}],"rounded-ss":[{"rounded-ss":L()}],"rounded-se":[{"rounded-se":L()}],"rounded-ee":[{"rounded-ee":L()}],"rounded-es":[{"rounded-es":L()}],"rounded-tl":[{"rounded-tl":L()}],"rounded-tr":[{"rounded-tr":L()}],"rounded-br":[{"rounded-br":L()}],"rounded-bl":[{"rounded-bl":L()}],"border-w":[{border:X()}],"border-w-x":[{"border-x":X()}],"border-w-y":[{"border-y":X()}],"border-w-s":[{"border-s":X()}],"border-w-e":[{"border-e":X()}],"border-w-t":[{"border-t":X()}],"border-w-r":[{"border-r":X()}],"border-w-b":[{"border-b":X()}],"border-w-l":[{"border-l":X()}],"divide-x":[{"divide-x":X()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":X()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ae(),"hidden","none"]}],"divide-style":[{divide:[...ae(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...ae(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,U,G]}],"outline-w":[{outline:["",ne,Kn,Zt]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","none",d,Lr,Dr]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",f,Lr,Dr]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:X()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[ne,Zt]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":X()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",g,Lr,Dr]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[ne,U,G]}],"mix-blend":[{"mix-blend":[...ve(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ve()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":me()}],"mask-image-linear-to-pos":[{"mask-linear-to":me()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":me()}],"mask-image-t-to-pos":[{"mask-t-to":me()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":me()}],"mask-image-r-to-pos":[{"mask-r-to":me()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":me()}],"mask-image-b-to-pos":[{"mask-b-to":me()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":me()}],"mask-image-l-to-pos":[{"mask-l-to":me()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":me()}],"mask-image-x-to-pos":[{"mask-x-to":me()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":me()}],"mask-image-y-to-pos":[{"mask-y-to":me()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[U,G]}],"mask-image-radial-from-pos":[{"mask-radial-from":me()}],"mask-image-radial-to-pos":[{"mask-radial-to":me()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":me()}],"mask-image-conic-to-pos":[{"mask-conic-to":me()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Q()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:se()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",U,G]}],filter:[{filter:["","none",U,G]}],blur:[{blur:Ft()}],brightness:[{brightness:[ne,U,G]}],contrast:[{contrast:[ne,U,G]}],"drop-shadow":[{"drop-shadow":["","none",h,Lr,Dr]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",ne,U,G]}],"hue-rotate":[{"hue-rotate":[ne,U,G]}],invert:[{invert:["",ne,U,G]}],saturate:[{saturate:[ne,U,G]}],sepia:[{sepia:["",ne,U,G]}],"backdrop-filter":[{"backdrop-filter":["","none",U,G]}],"backdrop-blur":[{"backdrop-blur":Ft()}],"backdrop-brightness":[{"backdrop-brightness":[ne,U,G]}],"backdrop-contrast":[{"backdrop-contrast":[ne,U,G]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,U,G]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,U,G]}],"backdrop-invert":[{"backdrop-invert":["",ne,U,G]}],"backdrop-opacity":[{"backdrop-opacity":[ne,U,G]}],"backdrop-saturate":[{"backdrop-saturate":[ne,U,G]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,U,G]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",U,G]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",U,G]}],ease:[{ease:["linear","initial",b,U,G]}],delay:[{delay:[ne,U,G]}],animate:[{animate:["none",w,U,G]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,U,G]}],"perspective-origin":[{"perspective-origin":_()}],rotate:[{rotate:At()}],"rotate-x":[{"rotate-x":At()}],"rotate-y":[{"rotate-y":At()}],"rotate-z":[{"rotate-z":At()}],scale:[{scale:z()}],"scale-x":[{"scale-x":z()}],"scale-y":[{"scale-y":z()}],"scale-z":[{"scale-z":z()}],"scale-3d":["scale-3d"],skew:[{skew:I()}],"skew-x":[{"skew-x":I()}],"skew-y":[{"skew-y":I()}],transform:[{transform:[U,G,"","none","gpu","cpu"]}],"transform-origin":[{origin:_()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:N()}],"translate-x":[{"translate-x":N()}],"translate-y":[{"translate-y":N()}],"translate-z":[{"translate-z":N()}],"translate-none":["translate-none"],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",U,G]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",U,G]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[ne,Kn,Zt,go]}],stroke:[{stroke:["none",...$()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},up=(t,{cacheSize:e,prefix:n,experimentalParseClassName:r,extend:s={},override:o={}})=>(sr(t,"cacheSize",e),sr(t,"prefix",n),sr(t,"experimentalParseClassName",r),zr(t.theme,o.theme),zr(t.classGroups,o.classGroups),zr(t.conflictingClassGroups,o.conflictingClassGroups),zr(t.conflictingClassGroupModifiers,o.conflictingClassGroupModifiers),sr(t,"orderSensitiveModifiers",o.orderSensitiveModifiers),Vr(t.theme,s.theme),Vr(t.classGroups,s.classGroups),Vr(t.conflictingClassGroups,s.conflictingClassGroups),Vr(t.conflictingClassGroupModifiers,s.conflictingClassGroupModifiers),Cd(t,s,"orderSensitiveModifiers"),t),sr=(t,e,n)=>{n!==void 0&&(t[e]=n)},zr=(t,e)=>{if(e)for(const n in e)sr(t,n,e[n])},Vr=(t,e)=>{if(e)for(const n in e)Cd(t,e,n)},Cd=(t,e,n)=>{const r=e[n];r!==void 0&&(t[n]=t[n]?t[n].concat(r):r)},fp=(t,...e)=>typeof t=="function"?Yo(Ko,t,...e):Yo(()=>up(Ko(),t),...e),hp=Yo(Ko);var gp=t=>We(t)?hp:fp({...t,extend:{theme:t.theme,classGroups:t.classGroups,conflictingClassGroupModifiers:t.conflictingClassGroupModifiers,conflictingClassGroups:t.conflictingClassGroups,...t.extend}}),mp=(t,e)=>{const n=As(t);return!n||!(e?.twMerge??!0)?n:((!$t.cachedTwMerge||$t.didTwMergeConfigChange)&&($t.didTwMergeConfigChange=!1,$t.cachedTwMerge=gp($t.cachedTwMergeConfig)),$t.cachedTwMerge(n)||void 0)},pp=(...t)=>e=>mp(t,e),{tv:Us}=Rm(pp);const yp=Us({base:["rounded-lg border p-4 transition-all duration-200","flex items-center justify-between gap-4","cursor-pointer select-none","focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2","w-full max-w-md"],variants:{selected:{true:"!bg-blue-100 !border-blue-500 shadow-sm",false:""},disabled:{true:"opacity-50 cursor-not-allowed",false:""},correct:{true:"!border-green-500 !bg-green-50",false:""},wrong:{true:"!border-red-500 !bg-red-50",false:""},variant:{default:"border-gray-200 bg-white hover:bg-blue-50 hover:border-blue-300",ixl:"border-transparent bg-transparent hover:bg-gray-50"}},compoundVariants:[{selected:!0,disabled:!0,class:"opacity-70"},{selected:!0,variant:"ixl",class:"bg-blue-50 border-l-4 border-l-blue-500 border-t-transparent border-r-transparent border-b-transparent"},{correct:!0,variant:"ixl",class:"!border-l-4 !border-l-green-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-green-50/50"},{wrong:!0,variant:"ixl",class:"!border-l-4 !border-l-red-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-red-50/50"}],defaultVariants:{selected:!1,disabled:!1,correct:!1,wrong:!1,variant:"default"}}),bp=Us({base:"flex gap-3",variants:{layout:{vertical:"flex-col",horizontal:"flex-row flex-wrap"}},defaultVariants:{layout:"vertical"}}),Ei=x.memo(({id:t,children:e,selected:n,disabled:r=!1,correct:s=!1,wrong:o=!1,variant:i="default",onClick:a,className:l,style:c})=>{const d=x.useCallback(h=>{r||(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),a())},[r,a]),f=x.useCallback(()=>{r||a()},[r,a]),g=yp({selected:n,disabled:r,correct:s,wrong:o,variant:i,className:l});return u.jsx("div",{id:t,role:"radio","aria-checked":n,"aria-disabled":r,tabIndex:r?-1:0,className:g,style:c,onClick:f,onKeyDown:d,children:e})});Ei.displayName="OptionCard";const Ni=x.memo(({type:t,options:e,value:n,onChange:r,disabled:s=!1,showResult:o=!1,correctAnswers:i=[],layout:a="vertical",variant:l="default",className:c,style:d})=>{const f=x.useMemo(()=>new Set(n.map(p=>p.id)),[n]),g=x.useMemo(()=>new Set(i),[i]),h=x.useCallback((p,y,b)=>{if(!s)if(t==="single")r([{id:p,content:y,contentType:b}]);else{const w=f.has(p);let v;w?v=n.filter(S=>S.id!==p):v=[...n,{id:p,content:y,contentType:b}],r(v)}},[t,s,f,n,r]),m=bp({layout:a,className:c});return u.jsx("div",{role:"radiogroup",className:m,style:d,children:e.map(p=>{const y=f.has(p.id),b=o&&g.has(p.id),w=o&&y&&!g.has(p.id);return u.jsx(Ei,{id:p.id,selected:y,disabled:s,correct:b,wrong:w,variant:l,onClick:()=>h(p.id,p.rawContent,p.contentType),children:p.label},p.id)})})});Ni.displayName="OptionGroup";function Rd(t){const[e,n]=x.useState(()=>new Set(t.map(p=>p.id))),[r,s]=x.useState(()=>{const p=new Set;return t.forEach(y=>{y.categories.forEach(b=>p.add(b.id))}),p}),o=x.useCallback(p=>{n(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),i=x.useCallback(p=>{s(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),a=x.useCallback(p=>{n(y=>new Set([...y,p]))},[]),l=x.useCallback(p=>{n(y=>{const b=new Set(y);return b.delete(p),b})},[]),c=x.useCallback(p=>{s(y=>new Set([...y,p]))},[]),d=x.useCallback(p=>{s(y=>{const b=new Set(y);return b.delete(p),b})},[]),f=x.useCallback(()=>{const p=new Set(t.map(b=>b.id)),y=new Set;t.forEach(b=>{b.categories.forEach(w=>y.add(w.id))}),n(p),s(y)},[t]),g=x.useCallback(()=>{n(new Set),s(new Set)},[]),h=x.useMemo(()=>({expandedGroups:e,expandedCategories:r}),[e,r]),m=x.useMemo(()=>({toggleGroup:o,toggleCategory:i,expandGroup:a,collapseGroup:l,expandCategory:c,collapseCategory:d,expandAll:f,collapseAll:g}),[o,i,a,l,c,d,f,g]);return{state:h,actions:m}}function Ad({data:t,renderGroupHeader:e,renderCategoryHeader:n,renderRow:r,renderCell:s,onCellClick:o,onRowClick:i,columns:a,enableTanStack:l=!1,className:c,getRowKey:d,"aria-label":f,"aria-labelledby":g}){const{state:h,actions:m}=Rd(t),p=x.useCallback(v=>t.find(S=>S.categories.some(_=>_.id===v)),[t]),y=x.useCallback((v,S,_)=>{const A=p(_.id);if(!A)return null;const C={index:S,category:_,group:A,isFirst:S===0,isLast:S===_.items.length-1},R=d?d(v,S):`row-${_.id}-${S}`,k=()=>{i?.(v)},M=()=>a&&a.length>0?a.map((F,D)=>{const P=F.accessorKey,j=P?v[P]:null;return u.jsx("td",{onClick:()=>o?.(v,String(P)),children:s?s(j,v,F):String(j??"")},D)}):u.jsx("td",{});return u.jsx("tr",{onClick:k,role:"row",className:i?"cursor-pointer":void 0,children:r?r(v,C):M()},R)},[r,s,i,o,a,d,p]),b=x.useCallback(v=>{const S=h.expandedCategories.has(v.id),_=()=>u.jsxs("div",{className:"table-category-header",onClick:()=>m.toggleCategory(v.id),role:"button","aria-expanded":S,children:[u.jsx("span",{children:S?"▼":"▶"}),u.jsx("span",{children:v.title})]});return u.jsxs("div",{className:"table-category","data-category-id":v.id,children:[n?n(v,{isExpanded:S,onToggle:()=>m.toggleCategory(v.id)}):_(),S&&u.jsx("table",{className:"w-full border-collapse",role:"table",children:u.jsx("tbody",{children:v.items.map((A,C)=>y(A,C,v))})})]},v.id)},[h.expandedCategories,m.toggleCategory,n,y]),w=x.useCallback(v=>{const S=h.expandedGroups.has(v.id),_=()=>u.jsxs("div",{className:"table-group-header",onClick:()=>m.toggleGroup(v.id),role:"button","aria-expanded":S,children:[u.jsx("span",{children:S?"▼":"▶"}),u.jsx("span",{children:v.title})]});return u.jsxs("div",{className:"table-group","data-group-id":v.id,children:[e?e(v,{isExpanded:S,onToggle:()=>m.toggleGroup(v.id)}):_(),S&&v.categories.map(b)]},v.id)},[h.expandedGroups,m.toggleGroup,e,b]);return u.jsx("div",{className:c,role:"region","aria-label":f,"aria-labelledby":g,children:t.map(w)})}x.memo(Ad);function Vt(t,e){return typeof t=="function"?t(e):t}function rt(t,e){return n=>{e.setState(r=>({...r,[t]:Vt(n,r[t])}))}}function Bs(t){return t instanceof Function}function xp(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function vp(t,e){const n=[],r=s=>{s.forEach(o=>{n.push(o);const i=e(o);i!=null&&i.length&&r(i)})};return r(t),n}function q(t,e,n){let r=[],s;return o=>{let i;n.key&&n.debug&&(i=Date.now());const a=t(o);if(!(a.length!==r.length||a.some((d,f)=>r[f]!==d)))return s;r=a;let c;if(n.key&&n.debug&&(c=Date.now()),s=e(...a),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-i)*100)/100,f=Math.round((Date.now()-c)*100)/100,g=f/16,h=(m,p)=>{for(m=String(m);m.length<p;)m=" "+m;return m};console.info(`%c⏱ ${h(f,5)} /${h(d,5)} ms`,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),x=require("react"),Ph=require("@heroui/progress"),ao=require("@heroui/card"),Z=require("lucide-react"),H=require("@heroui/react"),Fh=require("katex"),Ic=require("jsxgraph"),Dn=require("zustand"),Pc=require("zustand/shallow"),bn=require("zustand/react/shallow"),Dh=require("zustand/middleware");function Lh(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const et=Lh(x),Pt=({progress:t,variant:e="solid",size:n="md",radius:r="md",children:s,className:o="",loading:i,intent:a,useNewClassName:l=!1,...c})=>{const f=t!==void 0?(p=>{const y=l?"mathwiz-btn--":"button--";return p===0?`${y}primary`:p===100?`${y}success`:`${y}secondary`})(t):l?"mathwiz-btn--primary":"button--primary",g=l?"mathwiz-btn":"button",h=l?"mathwiz-btn--":"button--",m=[g,`${h}${n}`,`${h}${e}`,`${h}radius-${r}`,f,i&&`${h}loading`,a&&l?`mathwiz-btn--${a}`:null,o].filter(Boolean).join(" ");return u.jsx("button",{type:"button",className:m,"data-progress":t,disabled:i||c.disabled,...c,children:i?"加载中...":s})},xa=t=>t===0?"开始学习":t===100?"复习":"继续学习",zh=t=>{if(t.length===0)return 0;const e=t.reduce((n,r)=>n+r.progress,0);return Math.round(e/t.length)},Vh=({knowledgeItem:t,onLearnAction:e})=>{const n=()=>{e(t)};return console.log("KnowledgeCard render:",{progress:t.progress,text:xa(t.progress)}),u.jsxs(ao.Card,{className:"content-accordion__knowledge-card",children:[u.jsxs(ao.CardBody,{children:[u.jsx("h3",{className:"content-accordion__knowledge-title",children:t.title}),u.jsx("p",{className:"content-accordion__knowledge-description",children:t.description})]}),u.jsxs(ao.CardFooter,{className:"content-accordion__knowledge-actions",children:[u.jsxs("div",{className:"content-accordion__progress-container",children:[u.jsx(Ph.Progress,{value:t.progress,size:"sm",color:"primary","aria-label":`${t.title} 进度`,className:"content-accordion__progress-bar"}),u.jsxs("span",{className:"content-accordion__progress-text",children:[t.progress,"%"]})]}),u.jsx(Pt,{size:"sm",radius:"md",onClick:n,progress:t.progress,variant:t.progress===100?"light":t.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:xa(t.progress)})]})]})},Gh=({lesson:t,isExpanded:e,onToggle:n,onLearnAction:r})=>{const s=()=>{n(t.id)},o=zh(t.knowledgeItems);return u.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header",onClick:s,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${t.title},点击${e?"收起":"展开"}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header-content",children:[u.jsx("h2",{className:"content-accordion__lesson-title",children:t.title}),u.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",t.duration," 分钟"]})]}),u.jsxs("div",{className:"content-accordion__lesson-actions",children:[u.jsxs("span",{className:"content-accordion__lesson-progress",children:[o,"%"]}),e?u.jsx(Z.ChevronDown,{className:"content-accordion__lesson-icon"}):u.jsx(Z.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&u.jsx("div",{className:"content-accordion__knowledge-list",children:t.knowledgeItems.map(i=>u.jsx(Vh,{knowledgeItem:i,onLearnAction:r},i.id))})]})},Fc=({unit:t,activeLessonIds:e,onToggleLesson:n,onLearnAction:r,loading:s=!1,className:o="",emptyState:i})=>s?u.jsx("div",{className:"content-accordion content-accordion--loading",children:u.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):t?u.jsxs("div",{className:`content-accordion ${o}`,children:[u.jsxs("header",{className:"content-accordion__header",children:[u.jsx("h1",{className:"content-accordion__unit-title",children:t.title}),u.jsx("p",{className:"content-accordion__unit-description",children:t.description}),u.jsxs("div",{className:"content-accordion__unit-meta",children:[u.jsxs("span",{children:["总共 ",t.totalLessons," 节课"]}),u.jsx("span",{children:"•"}),u.jsxs("span",{children:["预计学习 ",t.estimatedDuration]})]})]}),u.jsx("div",{className:"content-accordion__lessons",children:t.lessons.map(a=>u.jsx(Gh,{lesson:a,isExpanded:e.includes(a.id),onToggle:n,onLearnAction:r},a.id))})]}):u.jsx("div",{className:"content-accordion content-accordion--empty",children:i||u.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),Uh=t=>{switch(t){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},Dc=({data:t,loading:e=!1,error:n=null,collapsed:r=!1,onToggleCollapse:s,activeUnitId:o=null,onUnitSelect:i,renderUnitItem:a,className:l="",unitItemClassName:c="",style:d={},unitItemStyle:f={}})=>{const g=(y,b)=>{b.preventDefault(),i?.(y)},h=()=>{s?.()},m=y=>u.jsxs("div",{className:`sidebar__unit-item ${c} ${o===y.unitId?"sidebar__unit-item--active":""} ${y.status?`sidebar__unit-item--${y.status}`:""}`,style:f,onClick:b=>g(y.unitId,b),role:"button",tabIndex:0,"aria-label":`${y.title},进度 ${y.progressPercentage}%`,children:[u.jsxs("div",{className:"sidebar__unit-item__content",children:[y.icon&&u.jsx("span",{className:"sidebar__unit-item__icon",children:y.icon}),!r&&u.jsx("span",{className:"sidebar__unit-item__title",children:y.title})]}),!r&&y.progressPercentage!==void 0&&u.jsxs("div",{className:"sidebar__unit-item__progress",children:[u.jsx(H.Progress,{value:y.progressPercentage,size:"sm",color:Uh(y.status),"aria-label":`${y.title} 进度`}),u.jsxs("span",{className:"progress-percentage",children:[y.progressPercentage,"%"]})]})]},y.unitId),p=()=>e?u.jsx("div",{className:"sidebar__loading",children:"加载中..."}):n?u.jsxs("div",{className:"sidebar__error",children:["加载失败: ",n.message]}):t?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar__header",children:[u.jsx("button",{className:"sidebar__toggle-btn",onClick:h,"aria-label":"切换侧边栏折叠状态",children:r?"→":"←"}),!r&&u.jsxs("div",{className:"sidebar__course-info",children:[u.jsx("h3",{className:"sidebar__course-title",children:t.courseTitle}),u.jsxs("span",{className:"sidebar__course-level",children:[t.courseLevel,"年级"]})]})]}),u.jsx("nav",{className:"sidebar__content",children:u.jsx("ul",{className:"sidebar__unit-list",children:t.units&&t.units.length>0?t.units.map(y=>u.jsx("li",{children:a?a(y,y):m(y)},y.unitId)):u.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):u.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return u.jsx("aside",{className:`sidebar ${l} ${r?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${n?"sidebar--error":""}`,style:d,"aria-label":"课程导航侧边栏",role:"complementary",children:p()})},wi=({trigger:t,items:e,position:n="bottom",alignment:r="start",openDelay:s=300,closeDelay:o=100,onOpen:i,onClose:a,renderItem:l,itemConfig:c={},className:d,menuClassName:f,itemClassName:g})=>{const[h,m]=x.useState(!1),p=x.useRef(null),y=x.useRef(null),b=()=>{p.current&&clearTimeout(p.current),y.current&&clearTimeout(y.current)},w=()=>{b(),p.current=setTimeout(()=>{m(!0),i?.()},s)},v=()=>{b(),y.current=setTimeout(()=>{m(!1),a?.()},o)},S=C=>{!C.disabled&&C.onClick&&C.onClick(C)};x.useEffect(()=>()=>b(),[]);const _=C=>u.jsxs("div",{className:`submenu-item ${C.disabled?"is-disabled":""} ${g||""}`,onClick:()=>S(C),children:[C.icon&&u.jsx("span",{className:"submenu-item-icon",children:C.icon}),u.jsx("span",{children:C.label})]},C.id),A=()=>{const C=["submenu-panel"];return f&&C.push(f),C.push(`position-${n}`),r!=="start"&&C.push(`alignment-${r}`),h&&C.push("is-open"),C.join(" ")};return u.jsxs("div",{className:`submenu-container ${d||""}`,onMouseEnter:w,onMouseLeave:v,children:[u.jsx("div",{className:"submenu-trigger",children:t}),u.jsx("div",{className:A(),children:e.map(C=>l?l(C,c):_(C))})]})};function Lc(t,e){return function(){return t.apply(e,arguments)}}const{toString:Bh}=Object.prototype,{getPrototypeOf:_i}=Object,{iterator:Ds,toStringTag:zc}=Symbol,Ls=(t=>e=>{const n=Bh.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),dt=t=>(t=t.toLowerCase(),e=>Ls(e)===t),zs=t=>e=>typeof e===t,{isArray:Ln}=Array,Mn=zs("undefined");function Cr(t){return t!==null&&!Mn(t)&&t.constructor!==null&&!Mn(t.constructor)&&Ke(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Vc=dt("ArrayBuffer");function Hh(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Vc(t.buffer),e}const Wh=zs("string"),Ke=zs("function"),Gc=zs("number"),Rr=t=>t!==null&&typeof t=="object",qh=t=>t===!0||t===!1,fs=t=>{if(Ls(t)!=="object")return!1;const e=_i(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(zc in t)&&!(Ds in t)},Yh=t=>{if(!Rr(t)||Cr(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Kh=dt("Date"),Xh=dt("File"),Jh=dt("Blob"),Zh=dt("FileList"),Qh=t=>Rr(t)&&Ke(t.pipe),eg=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Ke(t.append)&&((e=Ls(t))==="formdata"||e==="object"&&Ke(t.toString)&&t.toString()==="[object FormData]"))},tg=dt("URLSearchParams"),[ng,rg,sg,og]=["ReadableStream","Request","Response","Headers"].map(dt),ig=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ar(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),Ln(t))for(r=0,s=t.length;r<s;r++)e.call(null,t[r],r,t);else{if(Cr(t))return;const o=n?Object.getOwnPropertyNames(t):Object.keys(t),i=o.length;let a;for(r=0;r<i;r++)a=o[r],e.call(null,t[a],a,t)}}function Uc(t,e){if(Cr(t))return null;e=e.toLowerCase();const n=Object.keys(t);let r=n.length,s;for(;r-- >0;)if(s=n[r],e===s.toLowerCase())return s;return null}const dn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Bc=t=>!Mn(t)&&t!==dn;function Go(){const{caseless:t,skipUndefined:e}=Bc(this)&&this||{},n={},r=(s,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const i=t&&Uc(n,o)||o;fs(n[i])&&fs(s)?n[i]=Go(n[i],s):fs(s)?n[i]=Go({},s):Ln(s)?n[i]=s.slice():(!e||!Mn(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&Ar(arguments[s],r);return n}const ag=(t,e,n,{allOwnKeys:r}={})=>(Ar(e,(s,o)=>{n&&Ke(s)?Object.defineProperty(t,o,{value:Lc(s,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),t),lg=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),cg=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},dg=(t,e,n,r)=>{let s,o,i;const a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=n!==!1&&_i(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},ug=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},fg=t=>{if(!t)return null;if(Ln(t))return t;let e=t.length;if(!Gc(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},hg=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&_i(Uint8Array)),gg=(t,e)=>{const r=(t&&t[Ds]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},mg=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},pg=dt("HTMLFormElement"),yg=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),va=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),bg=dt("RegExp"),Hc=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};Ar(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},xg=t=>{Hc(t,(e,n)=>{if(Ke(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(Ke(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},vg=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Ln(t)?r(t):r(String(t).split(e)),n},wg=()=>{},_g=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Sg(t){return!!(t&&Ke(t.append)&&t[zc]==="FormData"&&t[Ds])}const Cg=t=>{const e=new Array(10),n=(r,s)=>{if(Rr(r)){if(e.indexOf(r)>=0)return;if(Cr(r))return r;if(!("toJSON"in r)){e[s]=r;const o=Ln(r)?[]:{};return Ar(r,(i,a)=>{const l=n(i,s+1);!Mn(l)&&(o[a]=l)}),e[s]=void 0,o}}return r};return n(t,0)},Rg=dt("AsyncFunction"),Ag=t=>t&&(Rr(t)||Ke(t))&&Ke(t.then)&&Ke(t.catch),Wc=((t,e)=>t?setImmediate:e?((n,r)=>(dn.addEventListener("message",({source:s,data:o})=>{s===dn&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),dn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ke(dn.postMessage)),Ng=typeof queueMicrotask<"u"?queueMicrotask.bind(dn):typeof process<"u"&&process.nextTick||Wc,Eg=t=>t!=null&&Ke(t[Ds]),E={isArray:Ln,isArrayBuffer:Vc,isBuffer:Cr,isFormData:eg,isArrayBufferView:Hh,isString:Wh,isNumber:Gc,isBoolean:qh,isObject:Rr,isPlainObject:fs,isEmptyObject:Yh,isReadableStream:ng,isRequest:rg,isResponse:sg,isHeaders:og,isUndefined:Mn,isDate:Kh,isFile:Xh,isBlob:Jh,isRegExp:bg,isFunction:Ke,isStream:Qh,isURLSearchParams:tg,isTypedArray:hg,isFileList:Zh,forEach:Ar,merge:Go,extend:ag,trim:ig,stripBOM:lg,inherits:cg,toFlatObject:dg,kindOf:Ls,kindOfTest:dt,endsWith:ug,toArray:fg,forEachEntry:gg,matchAll:mg,isHTMLForm:pg,hasOwnProperty:va,hasOwnProp:va,reduceDescriptors:Hc,freezeMethods:xg,toObjectSet:vg,toCamelCase:yg,noop:wg,toFiniteNumber:_g,findKey:Uc,global:dn,isContextDefined:Bc,isSpecCompliantForm:Sg,toJSONObject:Cg,isAsyncFn:Rg,isThenable:Ag,setImmediate:Wc,asap:Ng,isIterable:Eg};let K=class qc extends Error{static from(e,n,r,s,o,i){const a=new qc(e.message,n||e.code,r,s,o);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,n,r,s,o){super(e),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),s&&(this.request=s),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:E.toJSONObject(this.config),code:this.code,status:this.status}}};K.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";K.ERR_BAD_OPTION="ERR_BAD_OPTION";K.ECONNABORTED="ECONNABORTED";K.ETIMEDOUT="ETIMEDOUT";K.ERR_NETWORK="ERR_NETWORK";K.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";K.ERR_DEPRECATED="ERR_DEPRECATED";K.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";K.ERR_BAD_REQUEST="ERR_BAD_REQUEST";K.ERR_CANCELED="ERR_CANCELED";K.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";K.ERR_INVALID_URL="ERR_INVALID_URL";const kg=null;function Uo(t){return E.isPlainObject(t)||E.isArray(t)}function Yc(t){return E.endsWith(t,"[]")?t.slice(0,-2):t}function wa(t,e,n){return t?t.concat(e).map(function(s,o){return s=Yc(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function Tg(t){return E.isArray(t)&&!t.some(Uo)}const Mg=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function Vs(t,e,n){if(!E.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=E.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,y){return!E.isUndefined(y[p])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,i=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&E.isSpecCompliantForm(e);if(!E.isFunction(s))throw new TypeError("visitor must be a function");function c(m){if(m===null)return"";if(E.isDate(m))return m.toISOString();if(E.isBoolean(m))return m.toString();if(!l&&E.isBlob(m))throw new K("Blob is not supported. Use a Buffer instead.");return E.isArrayBuffer(m)||E.isTypedArray(m)?l&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function d(m,p,y){let b=m;if(m&&!y&&typeof m=="object"){if(E.endsWith(p,"{}"))p=r?p:p.slice(0,-2),m=JSON.stringify(m);else if(E.isArray(m)&&Tg(m)||(E.isFileList(m)||E.endsWith(p,"[]"))&&(b=E.toArray(m)))return p=Yc(p),b.forEach(function(v,S){!(E.isUndefined(v)||v===null)&&e.append(i===!0?wa([p],S,o):i===null?p:p+"[]",c(v))}),!1}return Uo(m)?!0:(e.append(wa(y,p,o),c(m)),!1)}const f=[],g=Object.assign(Mg,{defaultVisitor:d,convertValue:c,isVisitable:Uo});function h(m,p){if(!E.isUndefined(m)){if(f.indexOf(m)!==-1)throw Error("Circular reference detected in "+p.join("."));f.push(m),E.forEach(m,function(b,w){(!(E.isUndefined(b)||b===null)&&s.call(e,b,E.isString(w)?w.trim():w,p,g))===!0&&h(b,p?p.concat(w):[w])}),f.pop()}}if(!E.isObject(t))throw new TypeError("data must be an object");return h(t),e}function _a(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function Si(t,e){this._pairs=[],t&&Vs(t,this,e)}const Kc=Si.prototype;Kc.append=function(e,n){this._pairs.push([e,n])};Kc.toString=function(e){const n=e?function(r){return e.call(this,r,_a)}:_a;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function jg(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Xc(t,e,n){if(!e)return t;const r=n&&n.encode||jg,s=E.isFunction(n)?{serialize:n}:n,o=s&&s.serialize;let i;if(o?i=o(e,s):i=E.isURLSearchParams(e)?e.toString():new Si(e,s).toString(r),i){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+i}return t}class Sa{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){E.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ci={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},$g=typeof URLSearchParams<"u"?URLSearchParams:Si,Og=typeof FormData<"u"?FormData:null,Ig=typeof Blob<"u"?Blob:null,Pg={isBrowser:!0,classes:{URLSearchParams:$g,FormData:Og,Blob:Ig},protocols:["http","https","file","blob","url","data"]},Ri=typeof window<"u"&&typeof document<"u",Bo=typeof navigator=="object"&&navigator||void 0,Fg=Ri&&(!Bo||["ReactNative","NativeScript","NS"].indexOf(Bo.product)<0),Dg=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Lg=Ri&&window.location.href||"http://localhost",zg=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ri,hasStandardBrowserEnv:Fg,hasStandardBrowserWebWorkerEnv:Dg,navigator:Bo,origin:Lg},Symbol.toStringTag,{value:"Module"})),Ve={...zg,...Pg};function Vg(t,e){return Vs(t,new Ve.classes.URLSearchParams,{visitor:function(n,r,s,o){return Ve.isNode&&E.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Gg(t){return E.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Ug(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],e[o]=t[o];return e}function Jc(t){function e(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),l=o>=n.length;return i=!i&&E.isArray(s)?s.length:i,l?(E.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!a):((!s[i]||!E.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&E.isArray(s[i])&&(s[i]=Ug(s[i])),!a)}if(E.isFormData(t)&&E.isFunction(t.entries)){const n={};return E.forEachEntry(t,(r,s)=>{e(Gg(r),s,n,0)}),n}return null}function Bg(t,e,n){if(E.isString(t))try{return(e||JSON.parse)(t),E.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const Nr={transitional:Ci,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=E.isObject(e);if(o&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return s?JSON.stringify(Jc(e)):e;if(E.isArrayBuffer(e)||E.isBuffer(e)||E.isStream(e)||E.isFile(e)||E.isBlob(e)||E.isReadableStream(e))return e;if(E.isArrayBufferView(e))return e.buffer;if(E.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Vg(e,this.formSerializer).toString();if((a=E.isFileList(e))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return Vs(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Bg(e)):e}],transformResponse:[function(e){const n=this.transitional||Nr.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(E.isResponse(e)||E.isReadableStream(e))return e;if(e&&E.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?K.from(a,K.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ve.classes.FormData,Blob:Ve.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};E.forEach(["delete","get","head","post","put","patch"],t=>{Nr.headers[t]={}});const Hg=E.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Wg=t=>{const e={};let n,r,s;return t&&t.split(`
2
+ `).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&Hg[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Ca=Symbol("internals");function Yn(t){return t&&String(t).trim().toLowerCase()}function hs(t){return t===!1||t==null?t:E.isArray(t)?t.map(hs):String(t)}function qg(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const Yg=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function lo(t,e,n,r,s){if(E.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!E.isString(e)){if(E.isString(r))return e.indexOf(r)!==-1;if(E.isRegExp(r))return r.test(e)}}function Kg(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function Xg(t,e){const n=E.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let Xe=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(a,l,c){const d=Yn(l);if(!d)throw new Error("header name must be a non-empty string");const f=E.findKey(s,d);(!f||s[f]===void 0||c===!0||c===void 0&&s[f]!==!1)&&(s[f||l]=hs(a))}const i=(a,l)=>E.forEach(a,(c,d)=>o(c,d,l));if(E.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(E.isString(e)&&(e=e.trim())&&!Yg(e))i(Wg(e),n);else if(E.isObject(e)&&E.isIterable(e)){let a={},l,c;for(const d of e){if(!E.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?E.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}i(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=Yn(e),e){const r=E.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return qg(s);if(E.isFunction(n))return n.call(this,s,r);if(E.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=Yn(e),e){const r=E.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||lo(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=Yn(i),i){const a=E.findKey(r,i);a&&(!n||lo(r,r[a],a,n))&&(delete r[a],s=!0)}}return E.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||lo(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return E.forEach(this,(s,o)=>{const i=E.findKey(r,o);if(i){n[i]=hs(s),delete n[o];return}const a=e?Kg(o):String(o).trim();a!==o&&delete n[o],n[a]=hs(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return E.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&E.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(`
3
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[Ca]=this[Ca]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=Yn(i);r[a]||(Xg(s,i),r[a]=!0)}return E.isArray(e)?e.forEach(o):o(e),this}};Xe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);E.reduceDescriptors(Xe.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});E.freezeMethods(Xe);function co(t,e){const n=this||Nr,r=e||n,s=Xe.from(r.headers);let o=r.data;return E.forEach(t,function(a){o=a.call(n,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Zc(t){return!!(t&&t.__CANCEL__)}let Er=class extends K{constructor(e,n,r){super(e??"canceled",K.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function Qc(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new K("Request failed with status code "+n.status,[K.ERR_BAD_REQUEST,K.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Jg(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Zg(t,e){t=t||10;const n=new Array(t),r=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(l){const c=Date.now(),d=r[o];i||(i=c),n[s]=l,r[s]=c;let f=o,g=0;for(;f!==s;)g+=n[f++],f=f%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),c-i<e)return;const h=d&&c-d;return h?Math.round(g*1e3/h):void 0}}function Qg(t,e){let n=0,r=1e3/e,s,o;const i=(c,d=Date.now())=>{n=d,s=null,o&&(clearTimeout(o),o=null),t(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(s=c,o||(o=setTimeout(()=>{o=null,i(s)},r-f)))},()=>s&&i(s)]}const Rs=(t,e,n=3)=>{let r=0;const s=Zg(50,250);return Qg(o=>{const i=o.loaded,a=o.lengthComputable?o.total:void 0,l=i-r,c=s(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(f)},n)},Ra=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},Aa=t=>(...e)=>E.asap(()=>t(...e)),em=Ve.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,Ve.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(Ve.origin),Ve.navigator&&/(msie|trident)/i.test(Ve.navigator.userAgent)):()=>!0,tm=Ve.hasStandardBrowserEnv?{write(t,e,n,r,s,o,i){if(typeof document>"u")return;const a=[`${t}=${encodeURIComponent(e)}`];E.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),E.isString(r)&&a.push(`path=${r}`),E.isString(s)&&a.push(`domain=${s}`),o===!0&&a.push("secure"),E.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function nm(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function rm(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function ed(t,e,n){let r=!nm(e);return t&&(r||n==!1)?rm(t,e):e}const Na=t=>t instanceof Xe?{...t}:t;function mn(t,e){e=e||{};const n={};function r(c,d,f,g){return E.isPlainObject(c)&&E.isPlainObject(d)?E.merge.call({caseless:g},c,d):E.isPlainObject(d)?E.merge({},d):E.isArray(d)?d.slice():d}function s(c,d,f,g){if(E.isUndefined(d)){if(!E.isUndefined(c))return r(void 0,c,f,g)}else return r(c,d,f,g)}function o(c,d){if(!E.isUndefined(d))return r(void 0,d)}function i(c,d){if(E.isUndefined(d)){if(!E.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in e)return r(c,d);if(f in t)return r(void 0,c)}const l={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>s(Na(c),Na(d),f,!0)};return E.forEach(Object.keys({...t,...e}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const f=E.hasOwnProp(l,d)?l[d]:s,g=f(t[d],e[d],d);E.isUndefined(g)&&f!==a||(n[d]=g)}),n}const td=t=>{const e=mn({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;if(e.headers=i=Xe.from(i),e.url=Xc(ed(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),E.isFormData(n)){if(Ve.hasStandardBrowserEnv||Ve.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(E.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Ve.hasStandardBrowserEnv&&(r&&E.isFunction(r)&&(r=r(e)),r||r!==!1&&em(e.url))){const l=s&&o&&tm.read(o);l&&i.set(s,l)}return e},sm=typeof XMLHttpRequest<"u",om=sm&&function(t){return new Promise(function(n,r){const s=td(t);let o=s.data;const i=Xe.from(s.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=s,d,f,g,h,m;function p(){h&&h(),m&&m(),s.cancelToken&&s.cancelToken.unsubscribe(d),s.signal&&s.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(s.method.toUpperCase(),s.url,!0),y.timeout=s.timeout;function b(){if(!y)return;const v=Xe.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),_={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:v,config:t,request:y};Qc(function(C){n(C),p()},function(C){r(C),p()},_),y=null}"onloadend"in y?y.onloadend=b:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(b)},y.onabort=function(){y&&(r(new K("Request aborted",K.ECONNABORTED,t,y)),y=null)},y.onerror=function(S){const _=S&&S.message?S.message:"Network Error",A=new K(_,K.ERR_NETWORK,t,y);A.event=S||null,r(A),y=null},y.ontimeout=function(){let S=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const _=s.transitional||Ci;s.timeoutErrorMessage&&(S=s.timeoutErrorMessage),r(new K(S,_.clarifyTimeoutError?K.ETIMEDOUT:K.ECONNABORTED,t,y)),y=null},o===void 0&&i.setContentType(null),"setRequestHeader"in y&&E.forEach(i.toJSON(),function(S,_){y.setRequestHeader(_,S)}),E.isUndefined(s.withCredentials)||(y.withCredentials=!!s.withCredentials),a&&a!=="json"&&(y.responseType=s.responseType),c&&([g,m]=Rs(c,!0),y.addEventListener("progress",g)),l&&y.upload&&([f,h]=Rs(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",h)),(s.cancelToken||s.signal)&&(d=v=>{y&&(r(!v||v.type?new Er(null,t,y):v),y.abort(),y=null)},s.cancelToken&&s.cancelToken.subscribe(d),s.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d)));const w=Jg(s.url);if(w&&Ve.protocols.indexOf(w)===-1){r(new K("Unsupported protocol "+w+":",K.ERR_BAD_REQUEST,t));return}y.send(o||null)})},im=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,s;const o=function(c){if(!s){s=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof K?d:new Er(d instanceof Error?d.message:d))}};let i=e&&setTimeout(()=>{i=null,o(new K(`timeout of ${e}ms exceeded`,K.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),t=null)};t.forEach(c=>c.addEventListener("abort",o));const{signal:l}=r;return l.unsubscribe=()=>E.asap(a),l}},am=function*(t,e){let n=t.byteLength;if(n<e){yield t;return}let r=0,s;for(;r<n;)s=r+e,yield t.slice(r,s),r=s},lm=async function*(t,e){for await(const n of cm(t))yield*am(n,e)},cm=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{await e.cancel()}},Ea=(t,e,n,r)=>{const s=lm(t,e);let o=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await s.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let g=o+=f;n(g)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),s.return()}},{highWaterMark:2})},ka=64*1024,{isFunction:Fr}=E,dm=(({Request:t,Response:e})=>({Request:t,Response:e}))(E.global),{ReadableStream:Ta,TextEncoder:Ma}=E.global,ja=(t,...e)=>{try{return!!t(...e)}catch{return!1}},um=t=>{t=E.merge.call({skipUndefined:!0},dm,t);const{fetch:e,Request:n,Response:r}=t,s=e?Fr(e):typeof fetch=="function",o=Fr(n),i=Fr(r);if(!s)return!1;const a=s&&Fr(Ta),l=s&&(typeof Ma=="function"?(m=>p=>m.encode(p))(new Ma):async m=>new Uint8Array(await new n(m).arrayBuffer())),c=o&&a&&ja(()=>{let m=!1;const p=new n(Ve.origin,{body:new Ta,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!p}),d=i&&a&&ja(()=>E.isReadableStream(new r("").body)),f={stream:d&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(p,y)=>{let b=p&&p[m];if(b)return b.call(p);throw new K(`Response type '${m}' is not supported`,K.ERR_NOT_SUPPORT,y)})});const g=async m=>{if(m==null)return 0;if(E.isBlob(m))return m.size;if(E.isSpecCompliantForm(m))return(await new n(Ve.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(E.isArrayBufferView(m)||E.isArrayBuffer(m))return m.byteLength;if(E.isURLSearchParams(m)&&(m=m+""),E.isString(m))return(await l(m)).byteLength},h=async(m,p)=>{const y=E.toFiniteNumber(m.getContentLength());return y??g(p)};return async m=>{let{url:p,method:y,data:b,signal:w,cancelToken:v,timeout:S,onDownloadProgress:_,onUploadProgress:A,responseType:C,headers:R,withCredentials:N="same-origin",fetchOptions:M}=td(m),F=e||fetch;C=C?(C+"").toLowerCase():"text";let D=im([w,v&&v.toAbortSignal()],S),P=null;const $=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let O;try{if(A&&c&&y!=="get"&&y!=="head"&&(O=await h(R,b))!==0){let se=new n(p,{method:"POST",body:b,duplex:"half"}),ee;if(E.isFormData(b)&&(ee=se.headers.get("content-type"))&&R.setContentType(ee),se.body){const[L,X]=Ra(O,Rs(Aa(A)));b=Ea(se.body,ka,L,X)}}E.isString(N)||(N=N?"include":"omit");const T=o&&"credentials"in n.prototype,B={...M,signal:D,method:y.toUpperCase(),headers:R.normalize().toJSON(),body:b,duplex:"half",credentials:T?N:void 0};P=o&&new n(p,B);let j=await(o?F(P,M):F(p,B));const Q=d&&(C==="stream"||C==="response");if(d&&(_||Q&&$)){const se={};["status","statusText","headers"].forEach(ae=>{se[ae]=j[ae]});const ee=E.toFiniteNumber(j.headers.get("content-length")),[L,X]=_&&Ra(ee,Rs(Aa(_),!0))||[];j=new r(Ea(j.body,ka,L,()=>{X&&X(),$&&$()}),se)}C=C||"text";let oe=await f[E.findKey(f,C)||"text"](j,m);return!Q&&$&&$(),await new Promise((se,ee)=>{Qc(se,ee,{data:oe,headers:Xe.from(j.headers),status:j.status,statusText:j.statusText,config:m,request:P})})}catch(T){throw $&&$(),T&&T.name==="TypeError"&&/Load failed|fetch/i.test(T.message)?Object.assign(new K("Network Error",K.ERR_NETWORK,m,P,T&&T.response),{cause:T.cause||T}):K.from(T,T&&T.code,m,P,T&&T.response)}}},fm=new Map,nd=t=>{let e=t&&t.env||{};const{fetch:n,Request:r,Response:s}=e,o=[r,s,n];let i=o.length,a=i,l,c,d=fm;for(;a--;)l=o[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:um(e)),d=c;return c};nd();const Ai={http:kg,xhr:om,fetch:{get:nd}};E.forEach(Ai,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const $a=t=>`- ${t}`,hm=t=>E.isFunction(t)||t===null||t===!1;function gm(t,e){t=E.isArray(t)?t:[t];const{length:n}=t;let r,s;const o={};for(let i=0;i<n;i++){r=t[i];let a;if(s=r,!hm(r)&&(s=Ai[(a=String(r)).toLowerCase()],s===void 0))throw new K(`Unknown adapter '${a}'`);if(s&&(E.isFunction(s)||(s=s.get(e))))break;o[a||"#"+i]=s}if(!s){const i=Object.entries(o).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
4
+ `+i.map($a).join(`
5
+ `):" "+$a(i[0]):"as no adapter specified";throw new K("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const rd={getAdapter:gm,adapters:Ai};function uo(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Er(null,t)}function Oa(t){return uo(t),t.headers=Xe.from(t.headers),t.data=co.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),rd.getAdapter(t.adapter||Nr.adapter,t)(t).then(function(r){return uo(t),r.data=co.call(t,t.transformResponse,r),r.headers=Xe.from(r.headers),r},function(r){return Zc(r)||(uo(t),r&&r.response&&(r.response.data=co.call(t,t.transformResponse,r.response),r.response.headers=Xe.from(r.response.headers))),Promise.reject(r)})}const sd="1.13.5",Gs={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Gs[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Ia={};Gs.transitional=function(e,n,r){function s(o,i){return"[Axios v"+sd+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,a)=>{if(e===!1)throw new K(s(i," has been removed"+(n?" in "+n:"")),K.ERR_DEPRECATED);return n&&!Ia[i]&&(Ia[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,i,a):!0}};Gs.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function mm(t,e,n){if(typeof t!="object")throw new K("options must be an object",K.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let s=r.length;for(;s-- >0;){const o=r[s],i=e[o];if(i){const a=t[o],l=a===void 0||i(a,o,t);if(l!==!0)throw new K("option "+o+" must be "+l,K.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new K("Unknown option "+o,K.ERR_BAD_OPTION)}}const gs={assertOptions:mm,validators:Gs},st=gs.validators;let hn=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Sa,response:new Sa}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
+ `+o):r.stack=o}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=mn(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&gs.assertOptions(r,{silentJSONParsing:st.transitional(st.boolean),forcedJSONParsing:st.transitional(st.boolean),clarifyTimeoutError:st.transitional(st.boolean),legacyInterceptorReqResOrdering:st.transitional(st.boolean)},!1),s!=null&&(E.isFunction(s)?n.paramsSerializer={serialize:s}:gs.assertOptions(s,{encode:st.function,serialize:st.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),gs.assertOptions(n,{baseUrl:st.spelling("baseURL"),withXsrfToken:st.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&E.merge(o.common,o[n.method]);o&&E.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),n.headers=Xe.concat(i,o);const a=[];let l=!0;this.interceptors.request.forEach(function(p){if(typeof p.runWhen=="function"&&p.runWhen(n)===!1)return;l=l&&p.synchronous;const y=n.transitional||Ci;y&&y.legacyInterceptorReqResOrdering?a.unshift(p.fulfilled,p.rejected):a.push(p.fulfilled,p.rejected)});const c=[];this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let d,f=0,g;if(!l){const m=[Oa.bind(this),void 0];for(m.unshift(...a),m.push(...c),g=m.length,d=Promise.resolve(n);f<g;)d=d.then(m[f++],m[f++]);return d}g=a.length;let h=n;for(;f<g;){const m=a[f++],p=a[f++];try{h=m(h)}catch(y){p.call(this,y);break}}try{d=Oa.call(this,h)}catch(m){return Promise.reject(m)}for(f=0,g=c.length;f<g;)d=d.then(c[f++],c[f++]);return d}getUri(e){e=mn(this.defaults,e);const n=ed(e.baseURL,e.url,e.allowAbsoluteUrls);return Xc(n,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],function(e){hn.prototype[e]=function(n,r){return this.request(mn(r||{},{method:e,url:n,data:(r||{}).data}))}});E.forEach(["post","put","patch"],function(e){function n(r){return function(o,i,a){return this.request(mn(a||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}hn.prototype[e]=n(),hn.prototype[e+"Form"]=n(!0)});let pm=class od{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{r.subscribe(a),o=a}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},e(function(o,i,a){r.reason||(r.reason=new Er(o,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new od(function(s){e=s}),cancel:e}}};function ym(t){return function(n){return t.apply(null,n)}}function bm(t){return E.isObject(t)&&t.isAxiosError===!0}const Ho={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Ho).forEach(([t,e])=>{Ho[e]=t});function id(t){const e=new hn(t),n=Lc(hn.prototype.request,e);return E.extend(n,hn.prototype,e,{allOwnKeys:!0}),E.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return id(mn(t,s))},n}const Se=id(Nr);Se.Axios=hn;Se.CanceledError=Er;Se.CancelToken=pm;Se.isCancel=Zc;Se.VERSION=sd;Se.toFormData=Vs;Se.AxiosError=K;Se.Cancel=Se.CanceledError;Se.all=function(e){return Promise.all(e)};Se.spread=ym;Se.isAxiosError=bm;Se.mergeConfig=mn;Se.AxiosHeaders=Xe;Se.formToJSON=t=>Jc(E.isHTMLForm(t)?new FormData(t):t);Se.getAdapter=rd.getAdapter;Se.HttpStatusCode=Ho;Se.default=Se;const{Axios:d1,AxiosError:u1,CanceledError:f1,isCancel:h1,CancelToken:g1,VERSION:m1,all:p1,Cancel:y1,isAxiosError:b1,spread:x1,toFormData:v1,AxiosHeaders:w1,HttpStatusCode:_1,formToJSON:S1,getAdapter:C1,mergeConfig:R1}=Se,xm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),vm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),wm=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),_m=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),Sm=[{id:"profile",label:"个人主页",icon:u.jsx(xm,{})},{id:"settings",label:"设置",icon:u.jsx(vm,{})},{id:"help",label:"帮助",icon:u.jsx(wm,{})},{id:"logout",label:"退出",icon:u.jsx(_m,{})}],ad=({userId:t,userName:e,userAvatar:n,apiConfig:r,menuItems:s=Sm,avatarSize:o="md",isLoading:i=!1,error:a=null,avatarClassName:l,userNameClassName:c,containerClassName:d,onMenuOpen:f,onMenuClose:g,onMenuItemClick:h,onLogout:m,renderMenuItem:p,renderUserInfo:y})=>{const[b,w]=x.useState({id:t||"",name:e||"",avatar:n||"",level:0,badges:[]}),[v,S]=x.useState(i),[_,A]=x.useState(a);x.useEffect(()=>{t&&r&&!e&&!n&&C()},[t,r,e,n]);const C=async()=>{S(!0),A(null);try{const P=r.endpoints.userProfile.replace(":userId",t),$=await Se.get(`${r.baseURL}${P}`,{headers:r.headers});w($.data)}catch(P){A(P)}finally{S(!1)}},R=P=>{h?.(P.id),P.id==="logout"&&m?.()},N=()=>{f?.()},M=()=>{g?.()},F=()=>u.jsxs("div",{className:"user-profile-trigger",children:[u.jsx(H.Avatar,{src:b.avatar,size:o,className:l,alt:"用户头像"}),u.jsx("span",{className:`user-name ${c||""}`,children:b.name})]}),D=P=>u.jsxs("div",{className:"submenu-item",onClick:()=>R(P),children:[P.icon&&u.jsx("span",{className:"submenu-item-icon",children:P.icon}),u.jsx("span",{children:P.label})]},P.id);return v?u.jsx("div",{className:`user-profile-container ${d||""} is-loading`,children:u.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):_?u.jsx("div",{className:`user-profile-container ${d||""} has-error`,children:u.jsxs("div",{className:"user-profile-error",children:["错误: ",_.message]})}):b.name?u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx(wi,{trigger:y?y(b):F(),items:s.map(P=>({...P,onClick:()=>R(P)})),position:"bottom",alignment:"end",onOpen:N,onClose:M,renderItem:p?P=>p(P,b):D})}):u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx("div",{className:"user-profile-loading",children:"未登录"})})},Cm=t=>u.jsxs("div",{className:"explore-menu-item",onClick:()=>t.onClick?.(t),children:[u.jsx("span",{className:"explore-item-label",children:t.label}),t.status&&u.jsx("span",{className:`explore-item-status status-${t.status.toLowerCase().replace("%","").replace(" ","-")}`,children:t.status})]},t.id),Rm=({className:t})=>u.jsxs("button",{className:t,"aria-label":"探索数学课程",children:[u.jsx("span",{className:"explore-icon",children:"🌍"}),u.jsx("span",{className:"explore-text",children:"探索"})]}),Am=({className:t="",style:e,logoHref:n="/",logoText:r="MathWiz",onLogoClick:s,exploreItems:o=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:l,renderExploreItem:c=Cm,userData:d,userMenuItems:f,onUserMenuItemClick:g,onLogout:h,isLoading:m=!1,error:p=null,headerClassName:y="",logoClassName:b="",exploreClassName:w="",userProfileClassName:v="",variant:S="gradient",color:_,background:A,height:C,gradientFrom:R,gradientTo:N,gradientVia:M,logoColor:F,logoSize:D="md",exploreButtonVariant:P="flat",exploreButtonColor:$="primary","aria-label":O,"aria-labelledby":T,...B})=>{const j=o.map(L=>({id:L.id,label:c(L),onClick:()=>l?.(L)})),Q=["mathwiz-header",`mathwiz-header--${S}`,_&&`mathwiz-header--color-${_}`,y,t].filter(Boolean).join(" "),oe=["logo",`logo--${D}`,b].filter(Boolean).join(" "),se=["explore-button",`explore-button--${P}`,`explore-button--color-${$}`,w].filter(Boolean).join(" "),ee={...e,...C&&{height:typeof C=="number"?`${C}px`:C},...A&&{"--custom-bg":A},...F&&{"--logo-color":F},...R&&N&&{"--header-bg":M?`linear-gradient(to right, ${R}, ${M}, ${N})`:`linear-gradient(to right, ${R}, ${N})`}};return u.jsx("header",{className:Q,style:ee,"aria-label":O,"aria-labelledby":T,role:"banner",...B,children:u.jsxs("div",{className:"header-content",children:[u.jsx("div",{className:"header-section left",children:u.jsx(wi,{trigger:u.jsx(Rm,{className:se}),items:j,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),u.jsx("div",{className:"header-section center",children:u.jsx("a",{href:n,className:oe,onClick:s,"aria-label":"MathWiz 首页",children:r})}),u.jsx("div",{className:"header-section right",children:u.jsx(ad,{userName:d?.name,userAvatar:d?.avatar,menuItems:f,onMenuItemClick:g,onLogout:h,containerClassName:v,isLoading:m,error:p})})]})})},ld=x.memo(Am,(t,e)=>t.logoText===e.logoText&&t.logoHref===e.logoHref&&t.className===e.className&&t.headerClassName===e.headerClassName&&t.logoClassName===e.logoClassName&&t.exploreClassName===e.exploreClassName&&t.userProfileClassName===e.userProfileClassName&&t["aria-label"]===e["aria-label"]&&t["aria-labelledby"]===e["aria-labelledby"]&&t.isLoading===e.isLoading&&t.error===e.error&&t.variant===e.variant&&t.color===e.color&&t.background===e.background&&t.height===e.height&&t.gradientFrom===e.gradientFrom&&t.gradientTo===e.gradientTo&&t.gradientVia===e.gradientVia&&t.logoColor===e.logoColor&&t.logoSize===e.logoSize&&t.exploreButtonVariant===e.exploreButtonVariant&&t.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(t.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(t.userData)===JSON.stringify(e.userData)&&JSON.stringify(t.userMenuItems)===JSON.stringify(e.userMenuItems)),rr={LEFT:"left",RIGHT:"right",TOP:"top",BOTTOM:"bottom"},fo={NUMBER:"number",TIME:"time",CUSTOM:"custom"},Pa={iconPosition:rr.LEFT,interactive:!1},cd=t=>{const{label:e,value:n,unit:r,color:s,icon:o,iconPosition:i=Pa.iconPosition,render:a,onClick:l,className:c="",style:d,interactive:f=Pa.interactive,"aria-label":g,"aria-role":h,"data-testid":m,subtitle:p,showHelpIcon:y,helpIconTitle:b="What is this?",contentType:w=fo.NUMBER,timeValue:v,themeColorVar:S}=t,_=x.useMemo(()=>h||(l?"button":"group"),[h,l]),A=x.useMemo(()=>{const N=["mathwiz-statblock"];return c&&N.push(c),f&&N.push("mathwiz-statblock-interactive"),s&&!s.startsWith("#")&&N.push(`mathwiz-statblock-color-${s}`),N.join(" ")},[c,f,s]),C=x.useMemo(()=>{const N={...d};return s&&s.startsWith("#")&&(N.backgroundColor=s),S&&(N["--statblock-current-theme-color"]=`var(${S})`),N},[d,s,S]),R={label:e,value:n,unit:r,icon:o,iconPosition:i,color:s,interactive:f,className:A,style:C,subtitle:p,showHelpIcon:y,contentType:w,timeValue:v};return a?a(R):u.jsxs("div",{className:A,style:C,onClick:l,role:_,"aria-label":g,"data-testid":m,tabIndex:f?0:void 0,children:[u.jsxs("div",{className:"mathwiz-statblock-header",children:[u.jsx("div",{className:"mathwiz-statblock-title",children:e}),(p||y)&&u.jsxs("div",{className:"mathwiz-statblock-subtitle",children:[p,y&&u.jsx("span",{className:"mathwiz-statblock-help-icon",title:b,children:"?"})]})]}),u.jsx("div",{className:"mathwiz-statblock-body",children:w===fo.TIME&&v?u.jsxs("div",{className:"mathwiz-statblock-time-display",children:[u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.hours).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"HR"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.minutes).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"MIN"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(v.seconds).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"SEC"})]})]}):w===fo.CUSTOM?u.jsxs(u.Fragment,{children:[i===rr.TOP&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-top",children:o}),u.jsxs("div",{className:"mathwiz-statblock-content",children:[i===rr.LEFT&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-left",children:o}),u.jsxs("div",{className:"mathwiz-statblock-text",children:[u.jsx("div",{className:"mathwiz-statblock-label",children:e}),u.jsxs("div",{className:"mathwiz-statblock-value-container",children:[u.jsx("span",{className:"mathwiz-statblock-value",children:n}),r&&u.jsx("span",{className:"mathwiz-statblock-unit",children:r})]})]}),i===rr.RIGHT&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-right",children:o})]}),i===rr.BOTTOM&&o&&u.jsx("div",{className:"mathwiz-statblock-icon-bottom",children:o})]}):u.jsx("div",{className:"mathwiz-statblock-value-large",children:n})})]})};x.memo(cd);var Nm=/\s+/g,Em=t=>typeof t!="string"||!t?t:t.replace(Nm," ").trim(),As=(...t)=>{const e=[],n=r=>{if(!r&&r!==0&&r!==0n)return;if(Array.isArray(r)){for(let o=0,i=r.length;o<i;o++)n(r[o]);return}const s=typeof r;if(s==="string"||s==="number"||s==="bigint"){if(s==="number"&&r!==r)return;e.push(String(r))}else if(s==="object"){const o=Object.keys(r);for(let i=0,a=o.length;i<a;i++){const l=o[i];r[l]&&e.push(l)}}};for(let r=0,s=t.length;r<s;r++){const o=t[r];o!=null&&n(o)}return e.length>0?Em(e.join(" ")):void 0},Fa=t=>t===!1?"false":t===!0?"true":t===0?"0":t,We=t=>{if(!t||typeof t!="object")return!0;for(const e in t)return!1;return!0},km=(t,e)=>{if(t===e)return!0;if(!t||!e)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++){const o=n[s];if(!r.includes(o)||t[o]!==e[o])return!1}return!0},Tm=(t,e)=>{for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const r=e[n];n in t?t[n]=As(t[n],r):t[n]=r}return t},dd=(t,e)=>{for(let n=0;n<t.length;n++){const r=t[n];Array.isArray(r)?dd(r,e):r&&e.push(r)}},ud=(...t)=>{const e=[];dd(t,e);const n=[];for(let r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},Wo=(t,e)=>{const n={};for(const r in t){const s=t[r];if(r in e){const o=e[r];Array.isArray(s)||Array.isArray(o)?n[r]=ud(o,s):typeof s=="object"&&typeof o=="object"&&s&&o?n[r]=Wo(s,o):n[r]=o+" "+s}else n[r]=s}for(const r in e)r in t||(n[r]=e[r]);return n},Mm={twMerge:!0,twMergeConfig:{}};function jm(){let t=null,e={},n=!1;return{get cachedTwMerge(){return t},set cachedTwMerge(r){t=r},get cachedTwMergeConfig(){return e},set cachedTwMergeConfig(r){e=r},get didTwMergeConfigChange(){return n},set didTwMergeConfigChange(r){n=r},reset(){t=null,e={},n=!1}}}var jt=jm(),$m=t=>{const e=(r,s)=>{const{extend:o=null,slots:i={},variants:a={},compoundVariants:l=[],compoundSlots:c=[],defaultVariants:d={}}=r,f={...Mm,...s},g=o?.base?As(o.base,r?.base):r?.base,h=o?.variants&&!We(o.variants)?Wo(a,o.variants):a,m=o?.defaultVariants&&!We(o.defaultVariants)?{...o.defaultVariants,...d}:d;!We(f.twMergeConfig)&&!km(f.twMergeConfig,jt.cachedTwMergeConfig)&&(jt.didTwMergeConfigChange=!0,jt.cachedTwMergeConfig=f.twMergeConfig);const p=We(o?.slots),y=We(i)?{}:{base:As(r?.base,p&&o?.base),...i},b=p?y:Tm({...o?.slots},We(y)?{base:r?.base}:y),w=We(o?.compoundVariants)?l:ud(o?.compoundVariants,l),v=_=>{if(We(h)&&We(i)&&p)return t(g,_?.class,_?.className)(f);if(w&&!Array.isArray(w))throw new TypeError(`The "compoundVariants" prop must be an array. Received: ${typeof w}`);if(c&&!Array.isArray(c))throw new TypeError(`The "compoundSlots" prop must be an array. Received: ${typeof c}`);const A=($,O=h,T=null,B=null)=>{const j=O[$];if(!j||We(j))return null;const Q=B?.[$]??_?.[$];if(Q===null)return null;const oe=Fa(Q);if(typeof oe=="object")return null;const se=m?.[$],ee=oe??Fa(se);return j[ee||"false"]},C=()=>{if(!h)return null;const $=Object.keys(h),O=[];for(let T=0;T<$.length;T++){const B=A($[T],h);B&&O.push(B)}return O},R=($,O)=>{if(!h||typeof h!="object")return null;const T=[];for(const B in h){const j=A(B,h,$,O),Q=$==="base"&&typeof j=="string"?j:j&&j[$];Q&&T.push(Q)}return T},N={};for(const $ in _){const O=_[$];O!==void 0&&(N[$]=O)}const M=($,O)=>{const T=typeof _?.[$]=="object"?{[$]:_[$]?.initial}:{};return{...m,...N,...T,...O}},F=($=[],O)=>{const T=[],B=$.length;for(let j=0;j<B;j++){const{class:Q,className:oe,...se}=$[j];let ee=!0;const L=M(null,O);for(const X in se){const ae=se[X],ve=L[X];if(Array.isArray(ae)){if(!ae.includes(ve)){ee=!1;break}}else{if((ae==null||ae===!1)&&(ve==null||ve===!1))continue;if(ve!==ae){ee=!1;break}}}ee&&(Q&&T.push(Q),oe&&T.push(oe))}return T},D=$=>{const O=F(w,$);if(!Array.isArray(O))return O;const T={},B=t;for(let j=0;j<O.length;j++){const Q=O[j];if(typeof Q=="string")T.base=B(T.base,Q)(f);else if(typeof Q=="object")for(const oe in Q)T[oe]=B(T[oe],Q[oe])(f)}return T},P=$=>{if(c.length<1)return null;const O={},T=M(null,$);for(let B=0;B<c.length;B++){const{slots:j=[],class:Q,className:oe,...se}=c[B];if(!We(se)){let ee=!0;for(const L in se){const X=T[L],ae=se[L];if(X===void 0||(Array.isArray(ae)?!ae.includes(X):ae!==X)){ee=!1;break}}if(!ee)continue}for(let ee=0;ee<j.length;ee++){const L=j[ee];O[L]||(O[L]=[]),O[L].push([Q,oe])}}return O};if(!We(i)||!p){const $={};if(typeof b=="object"&&!We(b)){const O=t;for(const T in b)$[T]=B=>{const j=D(B),Q=P(B);return O(b[T],R(T,B),j?j[T]:void 0,Q?Q[T]:void 0,B?.class,B?.className)(f)}}return $}return t(g,C(),F(w),_?.class,_?.className)(f)},S=()=>{if(!(!h||typeof h!="object"))return Object.keys(h)};return v.variantKeys=S(),v.extend=o,v.base=g,v.slots=b,v.variants=h,v.defaultVariants=m,v.compoundSlots=c,v.compoundVariants=w,v};return{tv:e,createTV:r=>(s,o)=>e(s,o?Wo(r,o):r)}};const Om=(t,e)=>{const n=new Array(t.length+e.length);for(let r=0;r<t.length;r++)n[r]=t[r];for(let r=0;r<e.length;r++)n[t.length+r]=e[r];return n},Im=(t,e)=>({classGroupId:t,validator:e}),fd=(t=new Map,e=null,n)=>({nextPart:t,validators:e,classGroupId:n}),Ns="-",Da=[],Pm="arbitrary..",Fm=t=>{const e=Lm(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Dm(i);const a=i.split(Ns),l=a[0]===""&&a.length>1?1:0;return hd(a,l,e)},getConflictingClassGroupIds:(i,a)=>{if(a){const l=r[i],c=n[i];return l?c?Om(c,l):l:c||Da}return n[i]||Da}}},hd=(t,e,n)=>{if(t.length-e===0)return n.classGroupId;const s=t[e],o=n.nextPart.get(s);if(o){const c=hd(t,e+1,o);if(c)return c}const i=n.validators;if(i===null)return;const a=e===0?t.join(Ns):t.slice(e).join(Ns),l=i.length;for(let c=0;c<l;c++){const d=i[c];if(d.validator(a))return d.classGroupId}},Dm=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),n=e.indexOf(":"),r=e.slice(0,n);return r?Pm+r:void 0})(),Lm=t=>{const{theme:e,classGroups:n}=t;return zm(n,e)},zm=(t,e)=>{const n=fd();for(const r in t){const s=t[r];Ni(s,n,r,e)}return n},Ni=(t,e,n,r)=>{const s=t.length;for(let o=0;o<s;o++){const i=t[o];Vm(i,e,n,r)}},Vm=(t,e,n,r)=>{if(typeof t=="string"){Gm(t,e,n);return}if(typeof t=="function"){Um(t,e,n,r);return}Bm(t,e,n,r)},Gm=(t,e,n)=>{const r=t===""?e:gd(e,t);r.classGroupId=n},Um=(t,e,n,r)=>{if(Hm(t)){Ni(t(r),e,n,r);return}e.validators===null&&(e.validators=[]),e.validators.push(Im(n,t))},Bm=(t,e,n,r)=>{const s=Object.entries(t),o=s.length;for(let i=0;i<o;i++){const[a,l]=s[i];Ni(l,gd(e,a),n,r)}},gd=(t,e)=>{let n=t;const r=e.split(Ns),s=r.length;for(let o=0;o<s;o++){const i=r[o];let a=n.nextPart.get(i);a||(a=fd(),n.nextPart.set(i,a)),n=a}return n},Hm=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,Wm=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=Object.create(null),r=Object.create(null);const s=(o,i)=>{n[o]=i,e++,e>t&&(e=0,r=n,n=Object.create(null))};return{get(o){let i=n[o];if(i!==void 0)return i;if((i=r[o])!==void 0)return s(o,i),i},set(o,i){o in n?n[o]=i:s(o,i)}}},qo="!",La=":",qm=[],za=(t,e,n,r,s)=>({modifiers:t,hasImportantModifier:e,baseClassName:n,maybePostfixModifierPosition:r,isExternal:s}),Ym=t=>{const{prefix:e,experimentalParseClassName:n}=t;let r=s=>{const o=[];let i=0,a=0,l=0,c;const d=s.length;for(let p=0;p<d;p++){const y=s[p];if(i===0&&a===0){if(y===La){o.push(s.slice(l,p)),l=p+1;continue}if(y==="/"){c=p;continue}}y==="["?i++:y==="]"?i--:y==="("?a++:y===")"&&a--}const f=o.length===0?s:s.slice(l);let g=f,h=!1;f.endsWith(qo)?(g=f.slice(0,-1),h=!0):f.startsWith(qo)&&(g=f.slice(1),h=!0);const m=c&&c>l?c-l:void 0;return za(o,h,g,m)};if(e){const s=e+La,o=r;r=i=>i.startsWith(s)?o(i.slice(s.length)):za(qm,!1,i,void 0,!0)}if(n){const s=r;r=o=>n({className:o,parseClassName:s})}return r},Km=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((n,r)=>{e.set(n,1e6+r)}),n=>{const r=[];let s=[];for(let o=0;o<n.length;o++){const i=n[o],a=i[0]==="[",l=e.has(i);a||l?(s.length>0&&(s.sort(),r.push(...s),s=[]),r.push(i)):s.push(i)}return s.length>0&&(s.sort(),r.push(...s)),r}},Xm=t=>({cache:Wm(t.cacheSize),parseClassName:Ym(t),sortModifiers:Km(t),...Fm(t)}),Jm=/\s+/,Zm=(t,e)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s,sortModifiers:o}=e,i=[],a=t.trim().split(Jm);let l="";for(let c=a.length-1;c>=0;c-=1){const d=a[c],{isExternal:f,modifiers:g,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);if(f){l=d+(l.length>0?" "+l:l);continue}let y=!!p,b=r(y?m.substring(0,p):m);if(!b){if(!y){l=d+(l.length>0?" "+l:l);continue}if(b=r(m),!b){l=d+(l.length>0?" "+l:l);continue}y=!1}const w=g.length===0?"":g.length===1?g[0]:o(g).join(":"),v=h?w+qo:w,S=v+b;if(i.indexOf(S)>-1)continue;i.push(S);const _=s(b,y);for(let A=0;A<_.length;++A){const C=_[A];i.push(v+C)}l=d+(l.length>0?" "+l:l)}return l},Qm=(...t)=>{let e=0,n,r,s="";for(;e<t.length;)(n=t[e++])&&(r=md(n))&&(s&&(s+=" "),s+=r);return s},md=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=md(t[r]))&&(n&&(n+=" "),n+=e);return n},Yo=(t,...e)=>{let n,r,s,o;const i=l=>{const c=e.reduce((d,f)=>f(d),t());return n=Xm(c),r=n.cache.get,s=n.cache.set,o=a,a(l)},a=l=>{const c=r(l);if(c)return c;const d=Zm(l,n);return s(l,d),d};return o=i,(...l)=>o(Qm(...l))},ep=[],Me=t=>{const e=n=>n[t]||ep;return e.isThemeGetter=!0,e},pd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,yd=/^\((?:(\w[\w-]*):)?(.+)\)$/i,tp=/^\d+\/\d+$/,np=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,rp=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,sp=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,op=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ip=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sn=t=>tp.test(t),ne=t=>!!t&&!Number.isNaN(Number(t)),Dt=t=>!!t&&Number.isInteger(Number(t)),ho=t=>t.endsWith("%")&&ne(t.slice(0,-1)),Nt=t=>np.test(t),ap=()=>!0,lp=t=>rp.test(t)&&!sp.test(t),bd=()=>!1,cp=t=>op.test(t),dp=t=>ip.test(t),up=t=>!G(t)&&!U(t),fp=t=>zn(t,wd,bd),G=t=>pd.test(t),Zt=t=>zn(t,_d,lp),go=t=>zn(t,yp,ne),Va=t=>zn(t,xd,bd),hp=t=>zn(t,vd,dp),Dr=t=>zn(t,Sd,cp),U=t=>yd.test(t),Kn=t=>Vn(t,_d),gp=t=>Vn(t,bp),Ga=t=>Vn(t,xd),mp=t=>Vn(t,wd),pp=t=>Vn(t,vd),Lr=t=>Vn(t,Sd,!0),zn=(t,e,n)=>{const r=pd.exec(t);return r?r[1]?e(r[1]):n(r[2]):!1},Vn=(t,e,n=!1)=>{const r=yd.exec(t);return r?r[1]?e(r[1]):n:!1},xd=t=>t==="position"||t==="percentage",vd=t=>t==="image"||t==="url",wd=t=>t==="length"||t==="size"||t==="bg-size",_d=t=>t==="length",yp=t=>t==="number",bp=t=>t==="family-name",Sd=t=>t==="shadow",Ko=()=>{const t=Me("color"),e=Me("font"),n=Me("text"),r=Me("font-weight"),s=Me("tracking"),o=Me("leading"),i=Me("breakpoint"),a=Me("container"),l=Me("spacing"),c=Me("radius"),d=Me("shadow"),f=Me("inset-shadow"),g=Me("text-shadow"),h=Me("drop-shadow"),m=Me("blur"),p=Me("perspective"),y=Me("aspect"),b=Me("ease"),w=Me("animate"),v=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],_=()=>[...S(),U,G],A=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],R=()=>[U,G,l],N=()=>[Sn,"full","auto",...R()],M=()=>[Dt,"none","subgrid",U,G],F=()=>["auto",{span:["full",Dt,U,G]},Dt,U,G],D=()=>[Dt,"auto",U,G],P=()=>["auto","min","max","fr",U,G],$=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],O=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...R()],B=()=>[Sn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],j=()=>[t,U,G],Q=()=>[...S(),Ga,Va,{position:[U,G]}],oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],se=()=>["auto","cover","contain",mp,fp,{size:[U,G]}],ee=()=>[ho,Kn,Zt],L=()=>["","none","full",c,U,G],X=()=>["",ne,Kn,Zt],ae=()=>["solid","dashed","dotted","double"],ve=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],me=()=>[ne,ho,Ga,Va],Ft=()=>["","none",m,U,G],At=()=>["none",ne,U,G],z=()=>["none",ne,U,G],I=()=>[ne,U,G],k=()=>[Sn,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Nt],breakpoint:[Nt],color:[ap],container:[Nt],"drop-shadow":[Nt],ease:["in","out","in-out"],font:[up],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Nt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Nt],shadow:[Nt],spacing:["px",ne],text:[Nt],"text-shadow":[Nt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Sn,G,U,y]}],container:["container"],columns:[{columns:[ne,G,U,a]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:_()}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{start:N()}],end:[{end:N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Dt,"auto",U,G]}],basis:[{basis:[Sn,"full","auto",a,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Sn,"auto","initial","none",G]}],grow:[{grow:["",ne,U,G]}],shrink:[{shrink:["",ne,U,G]}],order:[{order:[Dt,"first","last","none",U,G]}],"grid-cols":[{"grid-cols":M()}],"col-start-end":[{col:F()}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":M()}],"row-start-end":[{row:F()}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":P()}],"auto-rows":[{"auto-rows":P()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...$(),"normal"]}],"justify-items":[{"justify-items":[...O(),"normal"]}],"justify-self":[{"justify-self":["auto",...O()]}],"align-content":[{content:["normal",...$()]}],"align-items":[{items:[...O(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...O(),{baseline:["","last"]}]}],"place-content":[{"place-content":$()}],"place-items":[{"place-items":[...O(),"baseline"]}],"place-self":[{"place-self":["auto",...O()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:B()}],w:[{w:[a,"screen",...B()]}],"min-w":[{"min-w":[a,"screen","none",...B()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...B()]}],h:[{h:["screen","lh",...B()]}],"min-h":[{"min-h":["screen","lh","none",...B()]}],"max-h":[{"max-h":["screen","lh",...B()]}],"font-size":[{text:["base",n,Kn,Zt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,U,go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ho,G]}],"font-family":[{font:[gp,G,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,U,G]}],"line-clamp":[{"line-clamp":[ne,"none",U,go]}],leading:[{leading:[o,...R()]}],"list-image":[{"list-image":["none",U,G]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",U,G]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:j()}],"text-color":[{text:j()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ae(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",U,Zt]}],"text-decoration-color":[{decoration:j()}],"underline-offset":[{"underline-offset":[ne,"auto",U,G]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",U,G]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",U,G]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Q()}],"bg-repeat":[{bg:oe()}],"bg-size":[{bg:se()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Dt,U,G],radial:["",U,G],conic:[Dt,U,G]},pp,hp]}],"bg-color":[{bg:j()}],"gradient-from-pos":[{from:ee()}],"gradient-via-pos":[{via:ee()}],"gradient-to-pos":[{to:ee()}],"gradient-from":[{from:j()}],"gradient-via":[{via:j()}],"gradient-to":[{to:j()}],rounded:[{rounded:L()}],"rounded-s":[{"rounded-s":L()}],"rounded-e":[{"rounded-e":L()}],"rounded-t":[{"rounded-t":L()}],"rounded-r":[{"rounded-r":L()}],"rounded-b":[{"rounded-b":L()}],"rounded-l":[{"rounded-l":L()}],"rounded-ss":[{"rounded-ss":L()}],"rounded-se":[{"rounded-se":L()}],"rounded-ee":[{"rounded-ee":L()}],"rounded-es":[{"rounded-es":L()}],"rounded-tl":[{"rounded-tl":L()}],"rounded-tr":[{"rounded-tr":L()}],"rounded-br":[{"rounded-br":L()}],"rounded-bl":[{"rounded-bl":L()}],"border-w":[{border:X()}],"border-w-x":[{"border-x":X()}],"border-w-y":[{"border-y":X()}],"border-w-s":[{"border-s":X()}],"border-w-e":[{"border-e":X()}],"border-w-t":[{"border-t":X()}],"border-w-r":[{"border-r":X()}],"border-w-b":[{"border-b":X()}],"border-w-l":[{"border-l":X()}],"divide-x":[{"divide-x":X()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":X()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ae(),"hidden","none"]}],"divide-style":[{divide:[...ae(),"hidden","none"]}],"border-color":[{border:j()}],"border-color-x":[{"border-x":j()}],"border-color-y":[{"border-y":j()}],"border-color-s":[{"border-s":j()}],"border-color-e":[{"border-e":j()}],"border-color-t":[{"border-t":j()}],"border-color-r":[{"border-r":j()}],"border-color-b":[{"border-b":j()}],"border-color-l":[{"border-l":j()}],"divide-color":[{divide:j()}],"outline-style":[{outline:[...ae(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,U,G]}],"outline-w":[{outline:["",ne,Kn,Zt]}],"outline-color":[{outline:j()}],shadow:[{shadow:["","none",d,Lr,Dr]}],"shadow-color":[{shadow:j()}],"inset-shadow":[{"inset-shadow":["none",f,Lr,Dr]}],"inset-shadow-color":[{"inset-shadow":j()}],"ring-w":[{ring:X()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:j()}],"ring-offset-w":[{"ring-offset":[ne,Zt]}],"ring-offset-color":[{"ring-offset":j()}],"inset-ring-w":[{"inset-ring":X()}],"inset-ring-color":[{"inset-ring":j()}],"text-shadow":[{"text-shadow":["none",g,Lr,Dr]}],"text-shadow-color":[{"text-shadow":j()}],opacity:[{opacity:[ne,U,G]}],"mix-blend":[{"mix-blend":[...ve(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ve()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":me()}],"mask-image-linear-to-pos":[{"mask-linear-to":me()}],"mask-image-linear-from-color":[{"mask-linear-from":j()}],"mask-image-linear-to-color":[{"mask-linear-to":j()}],"mask-image-t-from-pos":[{"mask-t-from":me()}],"mask-image-t-to-pos":[{"mask-t-to":me()}],"mask-image-t-from-color":[{"mask-t-from":j()}],"mask-image-t-to-color":[{"mask-t-to":j()}],"mask-image-r-from-pos":[{"mask-r-from":me()}],"mask-image-r-to-pos":[{"mask-r-to":me()}],"mask-image-r-from-color":[{"mask-r-from":j()}],"mask-image-r-to-color":[{"mask-r-to":j()}],"mask-image-b-from-pos":[{"mask-b-from":me()}],"mask-image-b-to-pos":[{"mask-b-to":me()}],"mask-image-b-from-color":[{"mask-b-from":j()}],"mask-image-b-to-color":[{"mask-b-to":j()}],"mask-image-l-from-pos":[{"mask-l-from":me()}],"mask-image-l-to-pos":[{"mask-l-to":me()}],"mask-image-l-from-color":[{"mask-l-from":j()}],"mask-image-l-to-color":[{"mask-l-to":j()}],"mask-image-x-from-pos":[{"mask-x-from":me()}],"mask-image-x-to-pos":[{"mask-x-to":me()}],"mask-image-x-from-color":[{"mask-x-from":j()}],"mask-image-x-to-color":[{"mask-x-to":j()}],"mask-image-y-from-pos":[{"mask-y-from":me()}],"mask-image-y-to-pos":[{"mask-y-to":me()}],"mask-image-y-from-color":[{"mask-y-from":j()}],"mask-image-y-to-color":[{"mask-y-to":j()}],"mask-image-radial":[{"mask-radial":[U,G]}],"mask-image-radial-from-pos":[{"mask-radial-from":me()}],"mask-image-radial-to-pos":[{"mask-radial-to":me()}],"mask-image-radial-from-color":[{"mask-radial-from":j()}],"mask-image-radial-to-color":[{"mask-radial-to":j()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":me()}],"mask-image-conic-to-pos":[{"mask-conic-to":me()}],"mask-image-conic-from-color":[{"mask-conic-from":j()}],"mask-image-conic-to-color":[{"mask-conic-to":j()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Q()}],"mask-repeat":[{mask:oe()}],"mask-size":[{mask:se()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",U,G]}],filter:[{filter:["","none",U,G]}],blur:[{blur:Ft()}],brightness:[{brightness:[ne,U,G]}],contrast:[{contrast:[ne,U,G]}],"drop-shadow":[{"drop-shadow":["","none",h,Lr,Dr]}],"drop-shadow-color":[{"drop-shadow":j()}],grayscale:[{grayscale:["",ne,U,G]}],"hue-rotate":[{"hue-rotate":[ne,U,G]}],invert:[{invert:["",ne,U,G]}],saturate:[{saturate:[ne,U,G]}],sepia:[{sepia:["",ne,U,G]}],"backdrop-filter":[{"backdrop-filter":["","none",U,G]}],"backdrop-blur":[{"backdrop-blur":Ft()}],"backdrop-brightness":[{"backdrop-brightness":[ne,U,G]}],"backdrop-contrast":[{"backdrop-contrast":[ne,U,G]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,U,G]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,U,G]}],"backdrop-invert":[{"backdrop-invert":["",ne,U,G]}],"backdrop-opacity":[{"backdrop-opacity":[ne,U,G]}],"backdrop-saturate":[{"backdrop-saturate":[ne,U,G]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,U,G]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",U,G]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",U,G]}],ease:[{ease:["linear","initial",b,U,G]}],delay:[{delay:[ne,U,G]}],animate:[{animate:["none",w,U,G]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,U,G]}],"perspective-origin":[{"perspective-origin":_()}],rotate:[{rotate:At()}],"rotate-x":[{"rotate-x":At()}],"rotate-y":[{"rotate-y":At()}],"rotate-z":[{"rotate-z":At()}],scale:[{scale:z()}],"scale-x":[{"scale-x":z()}],"scale-y":[{"scale-y":z()}],"scale-z":[{"scale-z":z()}],"scale-3d":["scale-3d"],skew:[{skew:I()}],"skew-x":[{"skew-x":I()}],"skew-y":[{"skew-y":I()}],transform:[{transform:[U,G,"","none","gpu","cpu"]}],"transform-origin":[{origin:_()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:k()}],"translate-x":[{"translate-x":k()}],"translate-y":[{"translate-y":k()}],"translate-z":[{"translate-z":k()}],"translate-none":["translate-none"],accent:[{accent:j()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:j()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",U,G]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",U,G]}],fill:[{fill:["none",...j()]}],"stroke-w":[{stroke:[ne,Kn,Zt,go]}],stroke:[{stroke:["none",...j()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},xp=(t,{cacheSize:e,prefix:n,experimentalParseClassName:r,extend:s={},override:o={}})=>(sr(t,"cacheSize",e),sr(t,"prefix",n),sr(t,"experimentalParseClassName",r),zr(t.theme,o.theme),zr(t.classGroups,o.classGroups),zr(t.conflictingClassGroups,o.conflictingClassGroups),zr(t.conflictingClassGroupModifiers,o.conflictingClassGroupModifiers),sr(t,"orderSensitiveModifiers",o.orderSensitiveModifiers),Vr(t.theme,s.theme),Vr(t.classGroups,s.classGroups),Vr(t.conflictingClassGroups,s.conflictingClassGroups),Vr(t.conflictingClassGroupModifiers,s.conflictingClassGroupModifiers),Cd(t,s,"orderSensitiveModifiers"),t),sr=(t,e,n)=>{n!==void 0&&(t[e]=n)},zr=(t,e)=>{if(e)for(const n in e)sr(t,n,e[n])},Vr=(t,e)=>{if(e)for(const n in e)Cd(t,e,n)},Cd=(t,e,n)=>{const r=e[n];r!==void 0&&(t[n]=t[n]?t[n].concat(r):r)},vp=(t,...e)=>typeof t=="function"?Yo(Ko,t,...e):Yo(()=>xp(Ko(),t),...e),wp=Yo(Ko);var _p=t=>We(t)?wp:vp({...t,extend:{theme:t.theme,classGroups:t.classGroups,conflictingClassGroupModifiers:t.conflictingClassGroupModifiers,conflictingClassGroups:t.conflictingClassGroups,...t.extend}}),Sp=(t,e)=>{const n=As(t);return!n||!(e?.twMerge??!0)?n:((!jt.cachedTwMerge||jt.didTwMergeConfigChange)&&(jt.didTwMergeConfigChange=!1,jt.cachedTwMerge=_p(jt.cachedTwMergeConfig)),jt.cachedTwMerge(n)||void 0)},Cp=(...t)=>e=>Sp(t,e),{tv:Us}=$m(Cp);const Rp=Us({base:["rounded-lg border p-4 transition-all duration-200","flex items-center justify-between gap-4","cursor-pointer select-none","focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2","w-full max-w-md"],variants:{selected:{true:"!bg-blue-100 !border-blue-500 shadow-sm",false:""},disabled:{true:"opacity-50 cursor-not-allowed",false:""},correct:{true:"!border-green-500 !bg-green-50",false:""},wrong:{true:"!border-red-500 !bg-red-50",false:""},variant:{default:"border-gray-200 bg-white hover:bg-blue-50 hover:border-blue-300",ixl:"border-transparent bg-transparent hover:bg-gray-50"}},compoundVariants:[{selected:!0,disabled:!0,class:"opacity-70"},{selected:!0,variant:"ixl",class:"bg-blue-50 border-l-4 border-l-blue-500 border-t-transparent border-r-transparent border-b-transparent"},{correct:!0,variant:"ixl",class:"!border-l-4 !border-l-green-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-green-50/50"},{wrong:!0,variant:"ixl",class:"!border-l-4 !border-l-red-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-red-50/50"}],defaultVariants:{selected:!1,disabled:!1,correct:!1,wrong:!1,variant:"default"}}),Ap=Us({base:"flex gap-3",variants:{layout:{vertical:"flex-col",horizontal:"flex-row flex-wrap"}},defaultVariants:{layout:"vertical"}}),Ei=x.memo(({id:t,children:e,selected:n,disabled:r=!1,correct:s=!1,wrong:o=!1,variant:i="default",onClick:a,className:l,style:c})=>{const d=x.useCallback(h=>{r||(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),a())},[r,a]),f=x.useCallback(()=>{r||a()},[r,a]),g=Rp({selected:n,disabled:r,correct:s,wrong:o,variant:i,className:l});return u.jsx("div",{id:t,role:"radio","aria-checked":n,"aria-disabled":r,tabIndex:r?-1:0,className:g,style:c,onClick:f,onKeyDown:d,children:e})});Ei.displayName="OptionCard";const ki=x.memo(({type:t,options:e,value:n,onChange:r,disabled:s=!1,showResult:o=!1,correctAnswers:i=[],layout:a="vertical",variant:l="default",className:c,style:d})=>{const f=x.useMemo(()=>new Set(n.map(p=>p.id)),[n]),g=x.useMemo(()=>new Set(i),[i]),h=x.useCallback((p,y,b)=>{if(!s)if(t==="single")r([{id:p,content:y,contentType:b}]);else{const w=f.has(p);let v;w?v=n.filter(S=>S.id!==p):v=[...n,{id:p,content:y,contentType:b}],r(v)}},[t,s,f,n,r]),m=Ap({layout:a,className:c});return u.jsx("div",{role:"radiogroup",className:m,style:d,children:e.map(p=>{const y=f.has(p.id),b=o&&g.has(p.id),w=o&&y&&!g.has(p.id);return u.jsx(Ei,{id:p.id,selected:y,disabled:s,correct:b,wrong:w,variant:l,onClick:()=>h(p.id,p.rawContent,p.contentType),children:p.label},p.id)})})});ki.displayName="OptionGroup";function Rd(t){const[e,n]=x.useState(()=>new Set(t.map(p=>p.id))),[r,s]=x.useState(()=>{const p=new Set;return t.forEach(y=>{y.categories.forEach(b=>p.add(b.id))}),p}),o=x.useCallback(p=>{n(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),i=x.useCallback(p=>{s(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),a=x.useCallback(p=>{n(y=>new Set([...y,p]))},[]),l=x.useCallback(p=>{n(y=>{const b=new Set(y);return b.delete(p),b})},[]),c=x.useCallback(p=>{s(y=>new Set([...y,p]))},[]),d=x.useCallback(p=>{s(y=>{const b=new Set(y);return b.delete(p),b})},[]),f=x.useCallback(()=>{const p=new Set(t.map(b=>b.id)),y=new Set;t.forEach(b=>{b.categories.forEach(w=>y.add(w.id))}),n(p),s(y)},[t]),g=x.useCallback(()=>{n(new Set),s(new Set)},[]),h=x.useMemo(()=>({expandedGroups:e,expandedCategories:r}),[e,r]),m=x.useMemo(()=>({toggleGroup:o,toggleCategory:i,expandGroup:a,collapseGroup:l,expandCategory:c,collapseCategory:d,expandAll:f,collapseAll:g}),[o,i,a,l,c,d,f,g]);return{state:h,actions:m}}function Ad({data:t,renderGroupHeader:e,renderCategoryHeader:n,renderRow:r,renderCell:s,onCellClick:o,onRowClick:i,columns:a,enableTanStack:l=!1,className:c,getRowKey:d,"aria-label":f,"aria-labelledby":g}){const{state:h,actions:m}=Rd(t),p=x.useCallback(v=>t.find(S=>S.categories.some(_=>_.id===v)),[t]),y=x.useCallback((v,S,_)=>{const A=p(_.id);if(!A)return null;const C={index:S,category:_,group:A,isFirst:S===0,isLast:S===_.items.length-1},R=d?d(v,S):`row-${_.id}-${S}`,N=()=>{i?.(v)},M=()=>a&&a.length>0?a.map((F,D)=>{const P=F.accessorKey,$=P?v[P]:null;return u.jsx("td",{onClick:()=>o?.(v,String(P)),children:s?s($,v,F):String($??"")},D)}):u.jsx("td",{});return u.jsx("tr",{onClick:N,role:"row",className:i?"cursor-pointer":void 0,children:r?r(v,C):M()},R)},[r,s,i,o,a,d,p]),b=x.useCallback(v=>{const S=h.expandedCategories.has(v.id),_=()=>u.jsxs("div",{className:"table-category-header",onClick:()=>m.toggleCategory(v.id),role:"button","aria-expanded":S,children:[u.jsx("span",{children:S?"▼":"▶"}),u.jsx("span",{children:v.title})]});return u.jsxs("div",{className:"table-category","data-category-id":v.id,children:[n?n(v,{isExpanded:S,onToggle:()=>m.toggleCategory(v.id)}):_(),S&&u.jsx("table",{className:"w-full border-collapse",role:"table",children:u.jsx("tbody",{children:v.items.map((A,C)=>y(A,C,v))})})]},v.id)},[h.expandedCategories,m.toggleCategory,n,y]),w=x.useCallback(v=>{const S=h.expandedGroups.has(v.id),_=()=>u.jsxs("div",{className:"table-group-header",onClick:()=>m.toggleGroup(v.id),role:"button","aria-expanded":S,children:[u.jsx("span",{children:S?"▼":"▶"}),u.jsx("span",{children:v.title})]});return u.jsxs("div",{className:"table-group","data-group-id":v.id,children:[e?e(v,{isExpanded:S,onToggle:()=>m.toggleGroup(v.id)}):_(),S&&v.categories.map(b)]},v.id)},[h.expandedGroups,m.toggleGroup,e,b]);return u.jsx("div",{className:c,role:"region","aria-label":f,"aria-labelledby":g,children:t.map(w)})}x.memo(Ad);function Vt(t,e){return typeof t=="function"?t(e):t}function rt(t,e){return n=>{e.setState(r=>({...r,[t]:Vt(n,r[t])}))}}function Bs(t){return t instanceof Function}function Np(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Ep(t,e){const n=[],r=s=>{s.forEach(o=>{n.push(o);const i=e(o);i!=null&&i.length&&r(i)})};return r(t),n}function q(t,e,n){let r=[],s;return o=>{let i;n.key&&n.debug&&(i=Date.now());const a=t(o);if(!(a.length!==r.length||a.some((d,f)=>r[f]!==d)))return s;r=a;let c;if(n.key&&n.debug&&(c=Date.now()),s=e(...a),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-i)*100)/100,f=Math.round((Date.now()-c)*100)/100,g=f/16,h=(m,p)=>{for(m=String(m);m.length<p;)m=" "+m;return m};console.info(`%c⏱ ${h(f,5)} /${h(d,5)} ms`,`
7
7
  font-size: .6rem;
8
8
  font-weight: bold;
9
- color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return s}}function Y(t,e,n,r){return{debug:()=>{var s;return(s=t?.debugAll)!=null?s:t[e]},key:process.env.NODE_ENV==="development"&&n,onChange:r}}function wp(t,e,n,r){const s=()=>{var i;return(i=o.getValue())!=null?i:t.options.renderFallbackValue},o={id:`${e.id}_${n.id}`,row:e,column:n,getValue:()=>e.getValue(r),renderValue:s,getContext:q(()=>[t,n,e,o],(i,a,l,c)=>({table:i,column:a,row:l,cell:c,getValue:c.getValue,renderValue:c.renderValue}),Y(t.options,"debugCells","cell.getContext"))};return t._features.forEach(i=>{i.createCell==null||i.createCell(o,n,e,t)},{}),o}function _p(t,e,n,r){var s,o;const a={...t._getDefaultColumnDef(),...e},l=a.accessorKey;let c=(s=(o=a.id)!=null?o:l?typeof String.prototype.replaceAll=="function"?l.replaceAll(".","_"):l.replace(/\./g,"_"):void 0)!=null?s:typeof a.header=="string"?a.header:void 0,d;if(a.accessorFn?d=a.accessorFn:l&&(l.includes(".")?d=g=>{let h=g;for(const p of l.split(".")){var m;h=(m=h)==null?void 0:m[p],process.env.NODE_ENV!=="production"&&h===void 0&&console.warn(`"${p}" in deeply nested key "${l}" returned undefined.`)}return h}:d=g=>g[a.accessorKey]),!c)throw process.env.NODE_ENV!=="production"?new Error(a.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let f={id:`${String(c)}`,accessorFn:d,parent:r,depth:n,columnDef:a,columns:[],getFlatColumns:q(()=>[!0],()=>{var g;return[f,...(g=f.columns)==null?void 0:g.flatMap(h=>h.getFlatColumns())]},Y(t.options,"debugColumns","column.getFlatColumns")),getLeafColumns:q(()=>[t._getOrderColumnsFn()],g=>{var h;if((h=f.columns)!=null&&h.length){let m=f.columns.flatMap(p=>p.getLeafColumns());return g(m)}return[f]},Y(t.options,"debugColumns","column.getLeafColumns"))};for(const g of t._features)g.createColumn==null||g.createColumn(f,t);return f}const Fe="debugHeaders";function Ua(t,e,n){var r;let o={id:(r=n.id)!=null?r:e.id,column:e,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],a=l=>{l.subHeaders&&l.subHeaders.length&&l.subHeaders.map(a),i.push(l)};return a(o),i},getContext:()=>({table:t,header:o,column:e})};return t._features.forEach(i=>{i.createHeader==null||i.createHeader(o,t)}),o}const Sp={createTable:t=>{t.getHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r,s)=>{var o,i;const a=(o=r?.map(f=>n.find(g=>g.id===f)).filter(Boolean))!=null?o:[],l=(i=s?.map(f=>n.find(g=>g.id===f)).filter(Boolean))!=null?i:[],c=n.filter(f=>!(r!=null&&r.includes(f.id))&&!(s!=null&&s.includes(f.id)));return Gr(e,[...a,...c,...l],t)},Y(t.options,Fe,"getHeaderGroups")),t.getCenterHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Gr(e,n,t,"center")),Y(t.options,Fe,"getCenterHeaderGroups")),t.getLeftHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left],(e,n,r)=>{var s;const o=(s=r?.map(i=>n.find(a=>a.id===i)).filter(Boolean))!=null?s:[];return Gr(e,o,t,"left")},Y(t.options,Fe,"getLeftHeaderGroups")),t.getRightHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.right],(e,n,r)=>{var s;const o=(s=r?.map(i=>n.find(a=>a.id===i)).filter(Boolean))!=null?s:[];return Gr(e,o,t,"right")},Y(t.options,Fe,"getRightHeaderGroups")),t.getFooterGroups=q(()=>[t.getHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getFooterGroups")),t.getLeftFooterGroups=q(()=>[t.getLeftHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getLeftFooterGroups")),t.getCenterFooterGroups=q(()=>[t.getCenterHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getCenterFooterGroups")),t.getRightFooterGroups=q(()=>[t.getRightHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getRightFooterGroups")),t.getFlatHeaders=q(()=>[t.getHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getFlatHeaders")),t.getLeftFlatHeaders=q(()=>[t.getLeftHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getLeftFlatHeaders")),t.getCenterFlatHeaders=q(()=>[t.getCenterHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getCenterFlatHeaders")),t.getRightFlatHeaders=q(()=>[t.getRightHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getRightFlatHeaders")),t.getCenterLeafHeaders=q(()=>[t.getCenterFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getCenterLeafHeaders")),t.getLeftLeafHeaders=q(()=>[t.getLeftFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getLeftLeafHeaders")),t.getRightLeafHeaders=q(()=>[t.getRightFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getRightLeafHeaders")),t.getLeafHeaders=q(()=>[t.getLeftHeaderGroups(),t.getCenterHeaderGroups(),t.getRightHeaderGroups()],(e,n,r)=>{var s,o,i,a,l,c;return[...(s=(o=e[0])==null?void 0:o.headers)!=null?s:[],...(i=(a=n[0])==null?void 0:a.headers)!=null?i:[],...(l=(c=r[0])==null?void 0:c.headers)!=null?l:[]].map(d=>d.getLeafHeaders()).flat()},Y(t.options,Fe,"getLeafHeaders"))}};function Gr(t,e,n,r){var s,o;let i=0;const a=function(g,h){h===void 0&&(h=1),i=Math.max(i,h),g.filter(m=>m.getIsVisible()).forEach(m=>{var p;(p=m.columns)!=null&&p.length&&a(m.columns,h+1)},0)};a(t);let l=[];const c=(g,h)=>{const m={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},p=[];g.forEach(y=>{const b=[...p].reverse()[0],w=y.column.depth===m.depth;let v,S=!1;if(w&&y.column.parent?v=y.column.parent:(v=y.column,S=!0),b&&b?.column===v)b.subHeaders.push(y);else{const _=Ua(n,v,{id:[r,h,v.id,y?.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${p.filter(A=>A.column===v).length}`:void 0,depth:h,index:p.length});_.subHeaders.push(y),p.push(_)}m.headers.push(y),y.headerGroup=m}),l.push(m),h>0&&c(p,h-1)},d=e.map((g,h)=>Ua(n,g,{depth:i,index:h}));c(d,i-1),l.reverse();const f=g=>g.filter(m=>m.column.getIsVisible()).map(m=>{let p=0,y=0,b=[0];m.subHeaders&&m.subHeaders.length?(b=[],f(m.subHeaders).forEach(v=>{let{colSpan:S,rowSpan:_}=v;p+=S,b.push(_)})):p=1;const w=Math.min(...b);return y=y+w,m.colSpan=p,m.rowSpan=y,{colSpan:p,rowSpan:y}});return f((s=(o=l[0])==null?void 0:o.headers)!=null?s:[]),l}const Ti=(t,e,n,r,s,o,i)=>{let a={id:e,index:r,original:n,depth:s,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:l=>{if(a._valuesCache.hasOwnProperty(l))return a._valuesCache[l];const c=t.getColumn(l);if(c!=null&&c.accessorFn)return a._valuesCache[l]=c.accessorFn(a.original,r),a._valuesCache[l]},getUniqueValues:l=>{if(a._uniqueValuesCache.hasOwnProperty(l))return a._uniqueValuesCache[l];const c=t.getColumn(l);if(c!=null&&c.accessorFn)return c.columnDef.getUniqueValues?(a._uniqueValuesCache[l]=c.columnDef.getUniqueValues(a.original,r),a._uniqueValuesCache[l]):(a._uniqueValuesCache[l]=[a.getValue(l)],a._uniqueValuesCache[l])},renderValue:l=>{var c;return(c=a.getValue(l))!=null?c:t.options.renderFallbackValue},subRows:[],getLeafRows:()=>vp(a.subRows,l=>l.subRows),getParentRow:()=>a.parentId?t.getRow(a.parentId,!0):void 0,getParentRows:()=>{let l=[],c=a;for(;;){const d=c.getParentRow();if(!d)break;l.push(d),c=d}return l.reverse()},getAllCells:q(()=>[t.getAllLeafColumns()],l=>l.map(c=>wp(t,a,c,c.id)),Y(t.options,"debugRows","getAllCells")),_getAllCellsByColumnId:q(()=>[a.getAllCells()],l=>l.reduce((c,d)=>(c[d.column.id]=d,c),{}),Y(t.options,"debugRows","getAllCellsByColumnId"))};for(let l=0;l<t._features.length;l++){const c=t._features[l];c==null||c.createRow==null||c.createRow(a,t)}return a},Cp={createColumn:(t,e)=>{t._getFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,t.id),t.getFacetedRowModel=()=>t._getFacetedRowModel?t._getFacetedRowModel():e.getPreFilteredRowModel(),t._getFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,t.id),t.getFacetedUniqueValues=()=>t._getFacetedUniqueValues?t._getFacetedUniqueValues():new Map,t._getFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,t.id),t.getFacetedMinMaxValues=()=>{if(t._getFacetedMinMaxValues)return t._getFacetedMinMaxValues()}}},kd=(t,e,n)=>{var r,s;const o=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((s=t.getValue(e))==null||(s=s.toString())==null||(s=s.toLowerCase())==null)&&s.includes(o))};kd.autoRemove=t=>ct(t);const Ed=(t,e,n)=>{var r;return!!(!((r=t.getValue(e))==null||(r=r.toString())==null)&&r.includes(n))};Ed.autoRemove=t=>ct(t);const Nd=(t,e,n)=>{var r;return((r=t.getValue(e))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};Nd.autoRemove=t=>ct(t);const Td=(t,e,n)=>{var r;return(r=t.getValue(e))==null?void 0:r.includes(n)};Td.autoRemove=t=>ct(t);const Md=(t,e,n)=>!n.some(r=>{var s;return!((s=t.getValue(e))!=null&&s.includes(r))});Md.autoRemove=t=>ct(t)||!(t!=null&&t.length);const $d=(t,e,n)=>n.some(r=>{var s;return(s=t.getValue(e))==null?void 0:s.includes(r)});$d.autoRemove=t=>ct(t)||!(t!=null&&t.length);const jd=(t,e,n)=>t.getValue(e)===n;jd.autoRemove=t=>ct(t);const Od=(t,e,n)=>t.getValue(e)==n;Od.autoRemove=t=>ct(t);const Mi=(t,e,n)=>{let[r,s]=n;const o=t.getValue(e);return o>=r&&o<=s};Mi.resolveFilterValue=t=>{let[e,n]=t,r=typeof e!="number"?parseFloat(e):e,s=typeof n!="number"?parseFloat(n):n,o=e===null||Number.isNaN(r)?-1/0:r,i=n===null||Number.isNaN(s)?1/0:s;if(o>i){const a=o;o=i,i=a}return[o,i]};Mi.autoRemove=t=>ct(t)||ct(t[0])&&ct(t[1]);const Mt={includesString:kd,includesStringSensitive:Ed,equalsString:Nd,arrIncludes:Td,arrIncludesAll:Md,arrIncludesSome:$d,equals:jd,weakEquals:Od,inNumberRange:Mi};function ct(t){return t==null||t===""}const Rp={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:t=>({columnFilters:[],...t}),getDefaultOptions:t=>({onColumnFiltersChange:rt("columnFilters",t),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(t,e)=>{t.getAutoFilterFn=()=>{const n=e.getCoreRowModel().flatRows[0],r=n?.getValue(t.id);return typeof r=="string"?Mt.includesString:typeof r=="number"?Mt.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Mt.equals:Array.isArray(r)?Mt.arrIncludes:Mt.weakEquals},t.getFilterFn=()=>{var n,r;return Bs(t.columnDef.filterFn)?t.columnDef.filterFn:t.columnDef.filterFn==="auto"?t.getAutoFilterFn():(n=(r=e.options.filterFns)==null?void 0:r[t.columnDef.filterFn])!=null?n:Mt[t.columnDef.filterFn]},t.getCanFilter=()=>{var n,r,s;return((n=t.columnDef.enableColumnFilter)!=null?n:!0)&&((r=e.options.enableColumnFilters)!=null?r:!0)&&((s=e.options.enableFilters)!=null?s:!0)&&!!t.accessorFn},t.getIsFiltered=()=>t.getFilterIndex()>-1,t.getFilterValue=()=>{var n;return(n=e.getState().columnFilters)==null||(n=n.find(r=>r.id===t.id))==null?void 0:n.value},t.getFilterIndex=()=>{var n,r;return(n=(r=e.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===t.id))!=null?n:-1},t.setFilterValue=n=>{e.setColumnFilters(r=>{const s=t.getFilterFn(),o=r?.find(d=>d.id===t.id),i=Vt(n,o?o.value:void 0);if(Ba(s,i,t)){var a;return(a=r?.filter(d=>d.id!==t.id))!=null?a:[]}const l={id:t.id,value:i};if(o){var c;return(c=r?.map(d=>d.id===t.id?l:d))!=null?c:[]}return r!=null&&r.length?[...r,l]:[l]})}},createRow:(t,e)=>{t.columnFilters={},t.columnFiltersMeta={}},createTable:t=>{t.setColumnFilters=e=>{const n=t.getAllLeafColumns(),r=s=>{var o;return(o=Vt(e,s))==null?void 0:o.filter(i=>{const a=n.find(l=>l.id===i.id);if(a){const l=a.getFilterFn();if(Ba(l,i.value,a))return!1}return!0})};t.options.onColumnFiltersChange==null||t.options.onColumnFiltersChange(r)},t.resetColumnFilters=e=>{var n,r;t.setColumnFilters(e?[]:(n=(r=t.initialState)==null?void 0:r.columnFilters)!=null?n:[])},t.getPreFilteredRowModel=()=>t.getCoreRowModel(),t.getFilteredRowModel=()=>(!t._getFilteredRowModel&&t.options.getFilteredRowModel&&(t._getFilteredRowModel=t.options.getFilteredRowModel(t)),t.options.manualFiltering||!t._getFilteredRowModel?t.getPreFilteredRowModel():t._getFilteredRowModel())}};function Ba(t,e,n){return(t&&t.autoRemove?t.autoRemove(e,n):!1)||typeof e>"u"||typeof e=="string"&&!e}const Ap=(t,e,n)=>n.reduce((r,s)=>{const o=s.getValue(t);return r+(typeof o=="number"?o:0)},0),kp=(t,e,n)=>{let r;return n.forEach(s=>{const o=s.getValue(t);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},Ep=(t,e,n)=>{let r;return n.forEach(s=>{const o=s.getValue(t);o!=null&&(r<o||r===void 0&&o>=o)&&(r=o)}),r},Np=(t,e,n)=>{let r,s;return n.forEach(o=>{const i=o.getValue(t);i!=null&&(r===void 0?i>=i&&(r=s=i):(r>i&&(r=i),s<i&&(s=i)))}),[r,s]},Tp=(t,e)=>{let n=0,r=0;if(e.forEach(s=>{let o=s.getValue(t);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},Mp=(t,e)=>{if(!e.length)return;const n=e.map(o=>o.getValue(t));if(!xp(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,i)=>o-i);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},$p=(t,e)=>Array.from(new Set(e.map(n=>n.getValue(t))).values()),jp=(t,e)=>new Set(e.map(n=>n.getValue(t))).size,Op=(t,e)=>e.length,mo={sum:Ap,min:kp,max:Ep,extent:Np,mean:Tp,median:Mp,unique:$p,uniqueCount:jp,count:Op},Ip={getDefaultColumnDef:()=>({aggregatedCell:t=>{var e,n;return(e=(n=t.getValue())==null||n.toString==null?void 0:n.toString())!=null?e:null},aggregationFn:"auto"}),getInitialState:t=>({grouping:[],...t}),getDefaultOptions:t=>({onGroupingChange:rt("grouping",t),groupedColumnMode:"reorder"}),createColumn:(t,e)=>{t.toggleGrouping=()=>{e.setGrouping(n=>n!=null&&n.includes(t.id)?n.filter(r=>r!==t.id):[...n??[],t.id])},t.getCanGroup=()=>{var n,r;return((n=t.columnDef.enableGrouping)!=null?n:!0)&&((r=e.options.enableGrouping)!=null?r:!0)&&(!!t.accessorFn||!!t.columnDef.getGroupingValue)},t.getIsGrouped=()=>{var n;return(n=e.getState().grouping)==null?void 0:n.includes(t.id)},t.getGroupedIndex=()=>{var n;return(n=e.getState().grouping)==null?void 0:n.indexOf(t.id)},t.getToggleGroupingHandler=()=>{const n=t.getCanGroup();return()=>{n&&t.toggleGrouping()}},t.getAutoAggregationFn=()=>{const n=e.getCoreRowModel().flatRows[0],r=n?.getValue(t.id);if(typeof r=="number")return mo.sum;if(Object.prototype.toString.call(r)==="[object Date]")return mo.extent},t.getAggregationFn=()=>{var n,r;if(!t)throw new Error;return Bs(t.columnDef.aggregationFn)?t.columnDef.aggregationFn:t.columnDef.aggregationFn==="auto"?t.getAutoAggregationFn():(n=(r=e.options.aggregationFns)==null?void 0:r[t.columnDef.aggregationFn])!=null?n:mo[t.columnDef.aggregationFn]}},createTable:t=>{t.setGrouping=e=>t.options.onGroupingChange==null?void 0:t.options.onGroupingChange(e),t.resetGrouping=e=>{var n,r;t.setGrouping(e?[]:(n=(r=t.initialState)==null?void 0:r.grouping)!=null?n:[])},t.getPreGroupedRowModel=()=>t.getFilteredRowModel(),t.getGroupedRowModel=()=>(!t._getGroupedRowModel&&t.options.getGroupedRowModel&&(t._getGroupedRowModel=t.options.getGroupedRowModel(t)),t.options.manualGrouping||!t._getGroupedRowModel?t.getPreGroupedRowModel():t._getGroupedRowModel())},createRow:(t,e)=>{t.getIsGrouped=()=>!!t.groupingColumnId,t.getGroupingValue=n=>{if(t._groupingValuesCache.hasOwnProperty(n))return t._groupingValuesCache[n];const r=e.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(t._groupingValuesCache[n]=r.columnDef.getGroupingValue(t.original),t._groupingValuesCache[n]):t.getValue(n)},t._groupingValuesCache={}},createCell:(t,e,n,r)=>{t.getIsGrouped=()=>e.getIsGrouped()&&e.id===n.groupingColumnId,t.getIsPlaceholder=()=>!t.getIsGrouped()&&e.getIsGrouped(),t.getIsAggregated=()=>{var s;return!t.getIsGrouped()&&!t.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function Pp(t,e,n){if(!(e!=null&&e.length)||!n)return t;const r=t.filter(o=>!e.includes(o.id));return n==="remove"?r:[...e.map(o=>t.find(i=>i.id===o)).filter(Boolean),...r]}const Fp={getInitialState:t=>({columnOrder:[],...t}),getDefaultOptions:t=>({onColumnOrderChange:rt("columnOrder",t)}),createColumn:(t,e)=>{t.getIndex=q(n=>[dr(e,n)],n=>n.findIndex(r=>r.id===t.id),Y(e.options,"debugColumns","getIndex")),t.getIsFirstColumn=n=>{var r;return((r=dr(e,n)[0])==null?void 0:r.id)===t.id},t.getIsLastColumn=n=>{var r;const s=dr(e,n);return((r=s[s.length-1])==null?void 0:r.id)===t.id}},createTable:t=>{t.setColumnOrder=e=>t.options.onColumnOrderChange==null?void 0:t.options.onColumnOrderChange(e),t.resetColumnOrder=e=>{var n;t.setColumnOrder(e?[]:(n=t.initialState.columnOrder)!=null?n:[])},t._getOrderColumnsFn=q(()=>[t.getState().columnOrder,t.getState().grouping,t.options.groupedColumnMode],(e,n,r)=>s=>{let o=[];if(!(e!=null&&e.length))o=s;else{const i=[...e],a=[...s];for(;a.length&&i.length;){const l=i.shift(),c=a.findIndex(d=>d.id===l);c>-1&&o.push(a.splice(c,1)[0])}o=[...o,...a]}return Pp(o,n,r)},Y(t.options,"debugTable","_getOrderColumnsFn"))}},po=()=>({left:[],right:[]}),Dp={getInitialState:t=>({columnPinning:po(),...t}),getDefaultOptions:t=>({onColumnPinningChange:rt("columnPinning",t)}),createColumn:(t,e)=>{t.pin=n=>{const r=t.getLeafColumns().map(s=>s.id).filter(Boolean);e.setColumnPinning(s=>{var o,i;if(n==="right"){var a,l;return{left:((a=s?.left)!=null?a:[]).filter(f=>!(r!=null&&r.includes(f))),right:[...((l=s?.right)!=null?l:[]).filter(f=>!(r!=null&&r.includes(f))),...r]}}if(n==="left"){var c,d;return{left:[...((c=s?.left)!=null?c:[]).filter(f=>!(r!=null&&r.includes(f))),...r],right:((d=s?.right)!=null?d:[]).filter(f=>!(r!=null&&r.includes(f)))}}return{left:((o=s?.left)!=null?o:[]).filter(f=>!(r!=null&&r.includes(f))),right:((i=s?.right)!=null?i:[]).filter(f=>!(r!=null&&r.includes(f)))}})},t.getCanPin=()=>t.getLeafColumns().some(r=>{var s,o,i;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(i=e.options.enableColumnPinning)!=null?i:e.options.enablePinning)!=null?o:!0)}),t.getIsPinned=()=>{const n=t.getLeafColumns().map(a=>a.id),{left:r,right:s}=e.getState().columnPinning,o=n.some(a=>r?.includes(a)),i=n.some(a=>s?.includes(a));return o?"left":i?"right":!1},t.getPinnedIndex=()=>{var n,r;const s=t.getIsPinned();return s?(n=(r=e.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(t.id))!=null?n:-1:0}},createRow:(t,e)=>{t.getCenterVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(i=>!o.includes(i.column.id))},Y(e.options,"debugRows","getCenterVisibleCells")),t.getLeftVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(i=>i.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Y(e.options,"debugRows","getLeftVisibleCells")),t.getRightVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(i=>i.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Y(e.options,"debugRows","getRightVisibleCells"))},createTable:t=>{t.setColumnPinning=e=>t.options.onColumnPinningChange==null?void 0:t.options.onColumnPinningChange(e),t.resetColumnPinning=e=>{var n,r;return t.setColumnPinning(e?po():(n=(r=t.initialState)==null?void 0:r.columnPinning)!=null?n:po())},t.getIsSomeColumnsPinned=e=>{var n;const r=t.getState().columnPinning;if(!e){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[e])!=null&&n.length)},t.getLeftLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left],(e,n)=>(n??[]).map(r=>e.find(s=>s.id===r)).filter(Boolean),Y(t.options,"debugColumns","getLeftLeafColumns")),t.getRightLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.right],(e,n)=>(n??[]).map(r=>e.find(s=>s.id===r)).filter(Boolean),Y(t.options,"debugColumns","getRightLeafColumns")),t.getCenterLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r)=>{const s=[...n??[],...r??[]];return e.filter(o=>!s.includes(o.id))},Y(t.options,"debugColumns","getCenterLeafColumns"))}};function Lp(t){return t||(typeof document<"u"?document:null)}const Ur={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},yo=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),zp={getDefaultColumnDef:()=>Ur,getInitialState:t=>({columnSizing:{},columnSizingInfo:yo(),...t}),getDefaultOptions:t=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:rt("columnSizing",t),onColumnSizingInfoChange:rt("columnSizingInfo",t)}),createColumn:(t,e)=>{t.getSize=()=>{var n,r,s;const o=e.getState().columnSizing[t.id];return Math.min(Math.max((n=t.columnDef.minSize)!=null?n:Ur.minSize,(r=o??t.columnDef.size)!=null?r:Ur.size),(s=t.columnDef.maxSize)!=null?s:Ur.maxSize)},t.getStart=q(n=>[n,dr(e,n),e.getState().columnSizing],(n,r)=>r.slice(0,t.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Y(e.options,"debugColumns","getStart")),t.getAfter=q(n=>[n,dr(e,n),e.getState().columnSizing],(n,r)=>r.slice(t.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Y(e.options,"debugColumns","getAfter")),t.resetSize=()=>{e.setColumnSizing(n=>{let{[t.id]:r,...s}=n;return s})},t.getCanResize=()=>{var n,r;return((n=t.columnDef.enableResizing)!=null?n:!0)&&((r=e.options.enableColumnResizing)!=null?r:!0)},t.getIsResizing=()=>e.getState().columnSizingInfo.isResizingColumn===t.id},createHeader:(t,e)=>{t.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(t),n},t.getStart=()=>{if(t.index>0){const n=t.headerGroup.headers[t.index-1];return n.getStart()+n.getSize()}return 0},t.getResizeHandler=n=>{const r=e.getColumn(t.column.id),s=r?.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),bo(o)&&o.touches&&o.touches.length>1))return;const i=t.getSize(),a=t?t.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],l=bo(o)?Math.round(o.touches[0].clientX):o.clientX,c={},d=(b,w)=>{typeof w=="number"&&(e.setColumnSizingInfo(v=>{var S,_;const A=e.options.columnResizeDirection==="rtl"?-1:1,C=(w-((S=v?.startOffset)!=null?S:0))*A,R=Math.max(C/((_=v?.startSize)!=null?_:0),-.999999);return v.columnSizingStart.forEach(k=>{let[M,F]=k;c[M]=Math.round(Math.max(F+F*R,0)*100)/100}),{...v,deltaOffset:C,deltaPercentage:R}}),(e.options.columnResizeMode==="onChange"||b==="end")&&e.setColumnSizing(v=>({...v,...c})))},f=b=>d("move",b),g=b=>{d("end",b),e.setColumnSizingInfo(w=>({...w,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=Lp(n),m={moveHandler:b=>f(b.clientX),upHandler:b=>{h?.removeEventListener("mousemove",m.moveHandler),h?.removeEventListener("mouseup",m.upHandler),g(b.clientX)}},p={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),f(b.touches[0].clientX),!1),upHandler:b=>{var w;h?.removeEventListener("touchmove",p.moveHandler),h?.removeEventListener("touchend",p.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),g((w=b.touches[0])==null?void 0:w.clientX)}},y=Vp()?{passive:!1}:!1;bo(o)?(h?.addEventListener("touchmove",p.moveHandler,y),h?.addEventListener("touchend",p.upHandler,y)):(h?.addEventListener("mousemove",m.moveHandler,y),h?.addEventListener("mouseup",m.upHandler,y)),e.setColumnSizingInfo(b=>({...b,startOffset:l,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:r.id}))}}},createTable:t=>{t.setColumnSizing=e=>t.options.onColumnSizingChange==null?void 0:t.options.onColumnSizingChange(e),t.setColumnSizingInfo=e=>t.options.onColumnSizingInfoChange==null?void 0:t.options.onColumnSizingInfoChange(e),t.resetColumnSizing=e=>{var n;t.setColumnSizing(e?{}:(n=t.initialState.columnSizing)!=null?n:{})},t.resetHeaderSizeInfo=e=>{var n;t.setColumnSizingInfo(e?yo():(n=t.initialState.columnSizingInfo)!=null?n:yo())},t.getTotalSize=()=>{var e,n;return(e=(n=t.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getLeftTotalSize=()=>{var e,n;return(e=(n=t.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getCenterTotalSize=()=>{var e,n;return(e=(n=t.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getRightTotalSize=()=>{var e,n;return(e=(n=t.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0}}};let Br=null;function Vp(){if(typeof Br=="boolean")return Br;let t=!1;try{const e={get passive(){return t=!0,!1}},n=()=>{};window.addEventListener("test",n,e),window.removeEventListener("test",n)}catch{t=!1}return Br=t,Br}function bo(t){return t.type==="touchstart"}const Gp={getInitialState:t=>({columnVisibility:{},...t}),getDefaultOptions:t=>({onColumnVisibilityChange:rt("columnVisibility",t)}),createColumn:(t,e)=>{t.toggleVisibility=n=>{t.getCanHide()&&e.setColumnVisibility(r=>({...r,[t.id]:n??!t.getIsVisible()}))},t.getIsVisible=()=>{var n,r;const s=t.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=e.getState().columnVisibility)==null?void 0:r[t.id])!=null?n:!0},t.getCanHide=()=>{var n,r;return((n=t.columnDef.enableHiding)!=null?n:!0)&&((r=e.options.enableHiding)!=null?r:!0)},t.getToggleVisibilityHandler=()=>n=>{t.toggleVisibility==null||t.toggleVisibility(n.target.checked)}},createRow:(t,e)=>{t._getAllVisibleCells=q(()=>[t.getAllCells(),e.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Y(e.options,"debugRows","_getAllVisibleCells")),t.getVisibleCells=q(()=>[t.getLeftVisibleCells(),t.getCenterVisibleCells(),t.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Y(e.options,"debugRows","getVisibleCells"))},createTable:t=>{const e=(n,r)=>q(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Y(t.options,"debugColumns",n));t.getVisibleFlatColumns=e("getVisibleFlatColumns",()=>t.getAllFlatColumns()),t.getVisibleLeafColumns=e("getVisibleLeafColumns",()=>t.getAllLeafColumns()),t.getLeftVisibleLeafColumns=e("getLeftVisibleLeafColumns",()=>t.getLeftLeafColumns()),t.getRightVisibleLeafColumns=e("getRightVisibleLeafColumns",()=>t.getRightLeafColumns()),t.getCenterVisibleLeafColumns=e("getCenterVisibleLeafColumns",()=>t.getCenterLeafColumns()),t.setColumnVisibility=n=>t.options.onColumnVisibilityChange==null?void 0:t.options.onColumnVisibilityChange(n),t.resetColumnVisibility=n=>{var r;t.setColumnVisibility(n?{}:(r=t.initialState.columnVisibility)!=null?r:{})},t.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!t.getIsAllColumnsVisible(),t.setColumnVisibility(t.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},t.getIsAllColumnsVisible=()=>!t.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),t.getIsSomeColumnsVisible=()=>t.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),t.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;t.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function dr(t,e){return e?e==="center"?t.getCenterVisibleLeafColumns():e==="left"?t.getLeftVisibleLeafColumns():t.getRightVisibleLeafColumns():t.getVisibleLeafColumns()}const Up={createTable:t=>{t._getGlobalFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,"__global__"),t.getGlobalFacetedRowModel=()=>t.options.manualFiltering||!t._getGlobalFacetedRowModel?t.getPreFilteredRowModel():t._getGlobalFacetedRowModel(),t._getGlobalFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,"__global__"),t.getGlobalFacetedUniqueValues=()=>t._getGlobalFacetedUniqueValues?t._getGlobalFacetedUniqueValues():new Map,t._getGlobalFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,"__global__"),t.getGlobalFacetedMinMaxValues=()=>{if(t._getGlobalFacetedMinMaxValues)return t._getGlobalFacetedMinMaxValues()}}},Bp={getInitialState:t=>({globalFilter:void 0,...t}),getDefaultOptions:t=>({onGlobalFilterChange:rt("globalFilter",t),globalFilterFn:"auto",getColumnCanGlobalFilter:e=>{var n;const r=(n=t.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[e.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(t,e)=>{t.getCanGlobalFilter=()=>{var n,r,s,o;return((n=t.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=e.options.enableGlobalFilter)!=null?r:!0)&&((s=e.options.enableFilters)!=null?s:!0)&&((o=e.options.getColumnCanGlobalFilter==null?void 0:e.options.getColumnCanGlobalFilter(t))!=null?o:!0)&&!!t.accessorFn}},createTable:t=>{t.getGlobalAutoFilterFn=()=>Mt.includesString,t.getGlobalFilterFn=()=>{var e,n;const{globalFilterFn:r}=t.options;return Bs(r)?r:r==="auto"?t.getGlobalAutoFilterFn():(e=(n=t.options.filterFns)==null?void 0:n[r])!=null?e:Mt[r]},t.setGlobalFilter=e=>{t.options.onGlobalFilterChange==null||t.options.onGlobalFilterChange(e)},t.resetGlobalFilter=e=>{t.setGlobalFilter(e?void 0:t.initialState.globalFilter)}}},Hp={getInitialState:t=>({expanded:{},...t}),getDefaultOptions:t=>({onExpandedChange:rt("expanded",t),paginateExpandedRows:!0}),createTable:t=>{let e=!1,n=!1;t._autoResetExpanded=()=>{var r,s;if(!e){t._queue(()=>{e=!0});return}if((r=(s=t.options.autoResetAll)!=null?s:t.options.autoResetExpanded)!=null?r:!t.options.manualExpanding){if(n)return;n=!0,t._queue(()=>{t.resetExpanded(),n=!1})}},t.setExpanded=r=>t.options.onExpandedChange==null?void 0:t.options.onExpandedChange(r),t.toggleAllRowsExpanded=r=>{r??!t.getIsAllRowsExpanded()?t.setExpanded(!0):t.setExpanded({})},t.resetExpanded=r=>{var s,o;t.setExpanded(r?{}:(s=(o=t.initialState)==null?void 0:o.expanded)!=null?s:{})},t.getCanSomeRowsExpand=()=>t.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),t.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),t.toggleAllRowsExpanded()},t.getIsSomeRowsExpanded=()=>{const r=t.getState().expanded;return r===!0||Object.values(r).some(Boolean)},t.getIsAllRowsExpanded=()=>{const r=t.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||t.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},t.getExpandedDepth=()=>{let r=0;return(t.getState().expanded===!0?Object.keys(t.getRowModel().rowsById):Object.keys(t.getState().expanded)).forEach(o=>{const i=o.split(".");r=Math.max(r,i.length)}),r},t.getPreExpandedRowModel=()=>t.getSortedRowModel(),t.getExpandedRowModel=()=>(!t._getExpandedRowModel&&t.options.getExpandedRowModel&&(t._getExpandedRowModel=t.options.getExpandedRowModel(t)),t.options.manualExpanding||!t._getExpandedRowModel?t.getPreExpandedRowModel():t._getExpandedRowModel())},createRow:(t,e)=>{t.toggleExpanded=n=>{e.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[t.id]);let i={};if(r===!0?Object.keys(e.getRowModel().rowsById).forEach(a=>{i[a]=!0}):i=r,n=(s=n)!=null?s:!o,!o&&n)return{...i,[t.id]:!0};if(o&&!n){const{[t.id]:a,...l}=i;return l}return r})},t.getIsExpanded=()=>{var n;const r=e.getState().expanded;return!!((n=e.options.getIsRowExpanded==null?void 0:e.options.getIsRowExpanded(t))!=null?n:r===!0||r?.[t.id])},t.getCanExpand=()=>{var n,r,s;return(n=e.options.getRowCanExpand==null?void 0:e.options.getRowCanExpand(t))!=null?n:((r=e.options.enableExpanding)!=null?r:!0)&&!!((s=t.subRows)!=null&&s.length)},t.getIsAllParentsExpanded=()=>{let n=!0,r=t;for(;n&&r.parentId;)r=e.getRow(r.parentId,!0),n=r.getIsExpanded();return n},t.getToggleExpandedHandler=()=>{const n=t.getCanExpand();return()=>{n&&t.toggleExpanded()}}}},Xo=0,Jo=10,xo=()=>({pageIndex:Xo,pageSize:Jo}),Wp={getInitialState:t=>({...t,pagination:{...xo(),...t?.pagination}}),getDefaultOptions:t=>({onPaginationChange:rt("pagination",t)}),createTable:t=>{let e=!1,n=!1;t._autoResetPageIndex=()=>{var r,s;if(!e){t._queue(()=>{e=!0});return}if((r=(s=t.options.autoResetAll)!=null?s:t.options.autoResetPageIndex)!=null?r:!t.options.manualPagination){if(n)return;n=!0,t._queue(()=>{t.resetPageIndex(),n=!1})}},t.setPagination=r=>{const s=o=>Vt(r,o);return t.options.onPaginationChange==null?void 0:t.options.onPaginationChange(s)},t.resetPagination=r=>{var s;t.setPagination(r?xo():(s=t.initialState.pagination)!=null?s:xo())},t.setPageIndex=r=>{t.setPagination(s=>{let o=Vt(r,s.pageIndex);const i=typeof t.options.pageCount>"u"||t.options.pageCount===-1?Number.MAX_SAFE_INTEGER:t.options.pageCount-1;return o=Math.max(0,Math.min(o,i)),{...s,pageIndex:o}})},t.resetPageIndex=r=>{var s,o;t.setPageIndex(r?Xo:(s=(o=t.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Xo)},t.resetPageSize=r=>{var s,o;t.setPageSize(r?Jo:(s=(o=t.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Jo)},t.setPageSize=r=>{t.setPagination(s=>{const o=Math.max(1,Vt(r,s.pageSize)),i=s.pageSize*s.pageIndex,a=Math.floor(i/o);return{...s,pageIndex:a,pageSize:o}})},t.setPageCount=r=>t.setPagination(s=>{var o;let i=Vt(r,(o=t.options.pageCount)!=null?o:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...s,pageCount:i}}),t.getPageOptions=q(()=>[t.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,i)=>i)),s},Y(t.options,"debugTable","getPageOptions")),t.getCanPreviousPage=()=>t.getState().pagination.pageIndex>0,t.getCanNextPage=()=>{const{pageIndex:r}=t.getState().pagination,s=t.getPageCount();return s===-1?!0:s===0?!1:r<s-1},t.previousPage=()=>t.setPageIndex(r=>r-1),t.nextPage=()=>t.setPageIndex(r=>r+1),t.firstPage=()=>t.setPageIndex(0),t.lastPage=()=>t.setPageIndex(t.getPageCount()-1),t.getPrePaginationRowModel=()=>t.getExpandedRowModel(),t.getPaginationRowModel=()=>(!t._getPaginationRowModel&&t.options.getPaginationRowModel&&(t._getPaginationRowModel=t.options.getPaginationRowModel(t)),t.options.manualPagination||!t._getPaginationRowModel?t.getPrePaginationRowModel():t._getPaginationRowModel()),t.getPageCount=()=>{var r;return(r=t.options.pageCount)!=null?r:Math.ceil(t.getRowCount()/t.getState().pagination.pageSize)},t.getRowCount=()=>{var r;return(r=t.options.rowCount)!=null?r:t.getPrePaginationRowModel().rows.length}}},vo=()=>({top:[],bottom:[]}),qp={getInitialState:t=>({rowPinning:vo(),...t}),getDefaultOptions:t=>({onRowPinningChange:rt("rowPinning",t)}),createRow:(t,e)=>{t.pin=(n,r,s)=>{const o=r?t.getLeafRows().map(l=>{let{id:c}=l;return c}):[],i=s?t.getParentRows().map(l=>{let{id:c}=l;return c}):[],a=new Set([...i,t.id,...o]);e.setRowPinning(l=>{var c,d;if(n==="bottom"){var f,g;return{top:((f=l?.top)!=null?f:[]).filter(p=>!(a!=null&&a.has(p))),bottom:[...((g=l?.bottom)!=null?g:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)]}}if(n==="top"){var h,m;return{top:[...((h=l?.top)!=null?h:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)],bottom:((m=l?.bottom)!=null?m:[]).filter(p=>!(a!=null&&a.has(p)))}}return{top:((c=l?.top)!=null?c:[]).filter(p=>!(a!=null&&a.has(p))),bottom:((d=l?.bottom)!=null?d:[]).filter(p=>!(a!=null&&a.has(p)))}})},t.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=e.options;return typeof r=="function"?r(t):(n=r??s)!=null?n:!0},t.getIsPinned=()=>{const n=[t.id],{top:r,bottom:s}=e.getState().rowPinning,o=n.some(a=>r?.includes(a)),i=n.some(a=>s?.includes(a));return o?"top":i?"bottom":!1},t.getPinnedIndex=()=>{var n,r;const s=t.getIsPinned();if(!s)return-1;const o=(n=s==="top"?e.getTopRows():e.getBottomRows())==null?void 0:n.map(i=>{let{id:a}=i;return a});return(r=o?.indexOf(t.id))!=null?r:-1}},createTable:t=>{t.setRowPinning=e=>t.options.onRowPinningChange==null?void 0:t.options.onRowPinningChange(e),t.resetRowPinning=e=>{var n,r;return t.setRowPinning(e?vo():(n=(r=t.initialState)==null?void 0:r.rowPinning)!=null?n:vo())},t.getIsSomeRowsPinned=e=>{var n;const r=t.getState().rowPinning;if(!e){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[e])!=null&&n.length)},t._getPinnedRows=(e,n,r)=>{var s;return((s=t.options.keepPinnedRows)==null||s?(n??[]).map(i=>{const a=t.getRow(i,!0);return a.getIsAllParentsExpanded()?a:null}):(n??[]).map(i=>e.find(a=>a.id===i))).filter(Boolean).map(i=>({...i,position:r}))},t.getTopRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top],(e,n)=>t._getPinnedRows(e,n,"top"),Y(t.options,"debugRows","getTopRows")),t.getBottomRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.bottom],(e,n)=>t._getPinnedRows(e,n,"bottom"),Y(t.options,"debugRows","getBottomRows")),t.getCenterRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top,t.getState().rowPinning.bottom],(e,n,r)=>{const s=new Set([...n??[],...r??[]]);return e.filter(o=>!s.has(o.id))},Y(t.options,"debugRows","getCenterRows"))}},Yp={getInitialState:t=>({rowSelection:{},...t}),getDefaultOptions:t=>({onRowSelectionChange:rt("rowSelection",t),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:t=>{t.setRowSelection=e=>t.options.onRowSelectionChange==null?void 0:t.options.onRowSelectionChange(e),t.resetRowSelection=e=>{var n;return t.setRowSelection(e?{}:(n=t.initialState.rowSelection)!=null?n:{})},t.toggleAllRowsSelected=e=>{t.setRowSelection(n=>{e=typeof e<"u"?e:!t.getIsAllRowsSelected();const r={...n},s=t.getPreGroupedRowModel().flatRows;return e?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},t.toggleAllPageRowsSelected=e=>t.setRowSelection(n=>{const r=typeof e<"u"?e:!t.getIsAllPageRowsSelected(),s={...n};return t.getRowModel().rows.forEach(o=>{Zo(s,o.id,r,!0,t)}),s}),t.getPreSelectedRowModel=()=>t.getCoreRowModel(),t.getSelectedRowModel=q(()=>[t.getState().rowSelection,t.getCoreRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getSelectedRowModel")),t.getFilteredSelectedRowModel=q(()=>[t.getState().rowSelection,t.getFilteredRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getFilteredSelectedRowModel")),t.getGroupedSelectedRowModel=q(()=>[t.getState().rowSelection,t.getSortedRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getGroupedSelectedRowModel")),t.getIsAllRowsSelected=()=>{const e=t.getFilteredRowModel().flatRows,{rowSelection:n}=t.getState();let r=!!(e.length&&Object.keys(n).length);return r&&e.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},t.getIsAllPageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=t.getState();let r=!!e.length;return r&&e.some(s=>!n[s.id])&&(r=!1),r},t.getIsSomeRowsSelected=()=>{var e;const n=Object.keys((e=t.getState().rowSelection)!=null?e:{}).length;return n>0&&n<t.getFilteredRowModel().flatRows.length},t.getIsSomePageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows;return t.getIsAllPageRowsSelected()?!1:e.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},t.getToggleAllRowsSelectedHandler=()=>e=>{t.toggleAllRowsSelected(e.target.checked)},t.getToggleAllPageRowsSelectedHandler=()=>e=>{t.toggleAllPageRowsSelected(e.target.checked)}},createRow:(t,e)=>{t.toggleSelected=(n,r)=>{const s=t.getIsSelected();e.setRowSelection(o=>{var i;if(n=typeof n<"u"?n:!s,t.getCanSelect()&&s===n)return o;const a={...o};return Zo(a,t.id,n,(i=r?.selectChildren)!=null?i:!0,e),a})},t.getIsSelected=()=>{const{rowSelection:n}=e.getState();return $i(t,n)},t.getIsSomeSelected=()=>{const{rowSelection:n}=e.getState();return Qo(t,n)==="some"},t.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=e.getState();return Qo(t,n)==="all"},t.getCanSelect=()=>{var n;return typeof e.options.enableRowSelection=="function"?e.options.enableRowSelection(t):(n=e.options.enableRowSelection)!=null?n:!0},t.getCanSelectSubRows=()=>{var n;return typeof e.options.enableSubRowSelection=="function"?e.options.enableSubRowSelection(t):(n=e.options.enableSubRowSelection)!=null?n:!0},t.getCanMultiSelect=()=>{var n;return typeof e.options.enableMultiRowSelection=="function"?e.options.enableMultiRowSelection(t):(n=e.options.enableMultiRowSelection)!=null?n:!0},t.getToggleSelectedHandler=()=>{const n=t.getCanSelect();return r=>{var s;n&&t.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Zo=(t,e,n,r,s)=>{var o;const i=s.getRow(e,!0);n?(i.getCanMultiSelect()||Object.keys(t).forEach(a=>delete t[a]),i.getCanSelect()&&(t[e]=!0)):delete t[e],r&&(o=i.subRows)!=null&&o.length&&i.getCanSelectSubRows()&&i.subRows.forEach(a=>Zo(t,a.id,n,r,s))};function wo(t,e){const n=t.getState().rowSelection,r=[],s={},o=function(i,a){return i.map(l=>{var c;const d=$i(l,n);if(d&&(r.push(l),s[l.id]=l),(c=l.subRows)!=null&&c.length&&(l={...l,subRows:o(l.subRows)}),d)return l}).filter(Boolean)};return{rows:o(e.rows),flatRows:r,rowsById:s}}function $i(t,e){var n;return(n=e[t.id])!=null?n:!1}function Qo(t,e,n){var r;if(!((r=t.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return t.subRows.forEach(i=>{if(!(o&&!s)&&(i.getCanSelect()&&($i(i,e)?o=!0:s=!1),i.subRows&&i.subRows.length)){const a=Qo(i,e);a==="all"?o=!0:(a==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const ei=/([0-9]+)/gm,Kp=(t,e,n)=>Id(Wt(t.getValue(n)).toLowerCase(),Wt(e.getValue(n)).toLowerCase()),Xp=(t,e,n)=>Id(Wt(t.getValue(n)),Wt(e.getValue(n))),Jp=(t,e,n)=>ji(Wt(t.getValue(n)).toLowerCase(),Wt(e.getValue(n)).toLowerCase()),Zp=(t,e,n)=>ji(Wt(t.getValue(n)),Wt(e.getValue(n))),Qp=(t,e,n)=>{const r=t.getValue(n),s=e.getValue(n);return r>s?1:r<s?-1:0},ey=(t,e,n)=>ji(t.getValue(n),e.getValue(n));function ji(t,e){return t===e?0:t>e?1:-1}function Wt(t){return typeof t=="number"?isNaN(t)||t===1/0||t===-1/0?"":String(t):typeof t=="string"?t:""}function Id(t,e){const n=t.split(ei).filter(Boolean),r=e.split(ei).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),i=parseInt(s,10),a=parseInt(o,10),l=[i,a].sort();if(isNaN(l[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(l[1]))return isNaN(i)?-1:1;if(i>a)return 1;if(a>i)return-1}return n.length-r.length}const Xn={alphanumeric:Kp,alphanumericCaseSensitive:Xp,text:Jp,textCaseSensitive:Zp,datetime:Qp,basic:ey},ty={getInitialState:t=>({sorting:[],...t}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:t=>({onSortingChange:rt("sorting",t),isMultiSortEvent:e=>e.shiftKey}),createColumn:(t,e)=>{t.getAutoSortingFn=()=>{const n=e.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s?.getValue(t.id);if(Object.prototype.toString.call(o)==="[object Date]")return Xn.datetime;if(typeof o=="string"&&(r=!0,o.split(ei).length>1))return Xn.alphanumeric}return r?Xn.text:Xn.basic},t.getAutoSortDir=()=>{const n=e.getFilteredRowModel().flatRows[0];return typeof n?.getValue(t.id)=="string"?"asc":"desc"},t.getSortingFn=()=>{var n,r;if(!t)throw new Error;return Bs(t.columnDef.sortingFn)?t.columnDef.sortingFn:t.columnDef.sortingFn==="auto"?t.getAutoSortingFn():(n=(r=e.options.sortingFns)==null?void 0:r[t.columnDef.sortingFn])!=null?n:Xn[t.columnDef.sortingFn]},t.toggleSorting=(n,r)=>{const s=t.getNextSortingOrder(),o=typeof n<"u"&&n!==null;e.setSorting(i=>{const a=i?.find(h=>h.id===t.id),l=i?.findIndex(h=>h.id===t.id);let c=[],d,f=o?n:s==="desc";if(i!=null&&i.length&&t.getCanMultiSort()&&r?a?d="toggle":d="add":i!=null&&i.length&&l!==i.length-1?d="replace":a?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var g;c=[...i,{id:t.id,desc:f}],c.splice(0,c.length-((g=e.options.maxMultiSortColCount)!=null?g:Number.MAX_SAFE_INTEGER))}else d==="toggle"?c=i.map(h=>h.id===t.id?{...h,desc:f}:h):d==="remove"?c=i.filter(h=>h.id!==t.id):c=[{id:t.id,desc:f}];return c})},t.getFirstSortDir=()=>{var n,r;return((n=(r=t.columnDef.sortDescFirst)!=null?r:e.options.sortDescFirst)!=null?n:t.getAutoSortDir()==="desc")?"desc":"asc"},t.getNextSortingOrder=n=>{var r,s;const o=t.getFirstSortDir(),i=t.getIsSorted();return i?i!==o&&((r=e.options.enableSortingRemoval)==null||r)&&(!(n&&(s=e.options.enableMultiRemove)!=null)||s)?!1:i==="desc"?"asc":"desc":o},t.getCanSort=()=>{var n,r;return((n=t.columnDef.enableSorting)!=null?n:!0)&&((r=e.options.enableSorting)!=null?r:!0)&&!!t.accessorFn},t.getCanMultiSort=()=>{var n,r;return(n=(r=t.columnDef.enableMultiSort)!=null?r:e.options.enableMultiSort)!=null?n:!!t.accessorFn},t.getIsSorted=()=>{var n;const r=(n=e.getState().sorting)==null?void 0:n.find(s=>s.id===t.id);return r?r.desc?"desc":"asc":!1},t.getSortIndex=()=>{var n,r;return(n=(r=e.getState().sorting)==null?void 0:r.findIndex(s=>s.id===t.id))!=null?n:-1},t.clearSorting=()=>{e.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==t.id):[])},t.getToggleSortingHandler=()=>{const n=t.getCanSort();return r=>{n&&(r.persist==null||r.persist(),t.toggleSorting==null||t.toggleSorting(void 0,t.getCanMultiSort()?e.options.isMultiSortEvent==null?void 0:e.options.isMultiSortEvent(r):!1))}}},createTable:t=>{t.setSorting=e=>t.options.onSortingChange==null?void 0:t.options.onSortingChange(e),t.resetSorting=e=>{var n,r;t.setSorting(e?[]:(n=(r=t.initialState)==null?void 0:r.sorting)!=null?n:[])},t.getPreSortedRowModel=()=>t.getGroupedRowModel(),t.getSortedRowModel=()=>(!t._getSortedRowModel&&t.options.getSortedRowModel&&(t._getSortedRowModel=t.options.getSortedRowModel(t)),t.options.manualSorting||!t._getSortedRowModel?t.getPreSortedRowModel():t._getSortedRowModel())}},ny=[Sp,Gp,Fp,Dp,Cp,Rp,Up,Bp,ty,Ip,Hp,Wp,qp,Yp,zp];function ry(t){var e,n;process.env.NODE_ENV!=="production"&&(t.debugAll||t.debugTable)&&console.info("Creating Table Instance...");const r=[...ny,...(e=t._features)!=null?e:[]];let s={_features:r};const o=s._features.reduce((g,h)=>Object.assign(g,h.getDefaultOptions==null?void 0:h.getDefaultOptions(s)),{}),i=g=>s.options.mergeOptions?s.options.mergeOptions(o,g):{...o,...g};let l={...{},...(n=t.initialState)!=null?n:{}};s._features.forEach(g=>{var h;l=(h=g.getInitialState==null?void 0:g.getInitialState(l))!=null?h:l});const c=[];let d=!1;const f={_features:r,options:{...o,...t},initialState:l,_queue:g=>{c.push(g),d||(d=!0,Promise.resolve().then(()=>{for(;c.length;)c.shift()();d=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{s.setState(s.initialState)},setOptions:g=>{const h=Vt(g,s.options);s.options=i(h)},getState:()=>s.options.state,setState:g=>{s.options.onStateChange==null||s.options.onStateChange(g)},_getRowId:(g,h,m)=>{var p;return(p=s.options.getRowId==null?void 0:s.options.getRowId(g,h,m))!=null?p:`${m?[m.id,h].join("."):h}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(g,h)=>{let m=(h?s.getPrePaginationRowModel():s.getRowModel()).rowsById[g];if(!m&&(m=s.getCoreRowModel().rowsById[g],!m))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${g}`):new Error;return m},_getDefaultColumnDef:q(()=>[s.options.defaultColumn],g=>{var h;return g=(h=g)!=null?h:{},{header:m=>{const p=m.header.column.columnDef;return p.accessorKey?p.accessorKey:p.accessorFn?p.id:null},cell:m=>{var p,y;return(p=(y=m.renderValue())==null||y.toString==null?void 0:y.toString())!=null?p:null},...s._features.reduce((m,p)=>Object.assign(m,p.getDefaultColumnDef==null?void 0:p.getDefaultColumnDef()),{}),...g}},Y(t,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>s.options.columns,getAllColumns:q(()=>[s._getColumnDefs()],g=>{const h=function(m,p,y){return y===void 0&&(y=0),m.map(b=>{const w=_p(s,b,y,p),v=b;return w.columns=v.columns?h(v.columns,w,y+1):[],w})};return h(g)},Y(t,"debugColumns","getAllColumns")),getAllFlatColumns:q(()=>[s.getAllColumns()],g=>g.flatMap(h=>h.getFlatColumns()),Y(t,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:q(()=>[s.getAllFlatColumns()],g=>g.reduce((h,m)=>(h[m.id]=m,h),{}),Y(t,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:q(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(g,h)=>{let m=g.flatMap(p=>p.getLeafColumns());return h(m)},Y(t,"debugColumns","getAllLeafColumns")),getColumn:g=>{const h=s._getAllFlatColumnsById()[g];return process.env.NODE_ENV!=="production"&&!h&&console.error(`[Table] Column with id '${g}' does not exist.`),h}};Object.assign(s,f);for(let g=0;g<s._features.length;g++){const h=s._features[g];h==null||h.createTable==null||h.createTable(s)}return s}function sy(){return t=>q(()=>[t.options.data],e=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,i){o===void 0&&(o=0);const a=[];for(let c=0;c<s.length;c++){const d=Ti(t,t._getRowId(s[c],c,i),s[c],c,o,void 0,i?.id);if(n.flatRows.push(d),n.rowsById[d.id]=d,a.push(d),t.options.getSubRows){var l;d.originalSubRows=t.options.getSubRows(s[c],c),(l=d.originalSubRows)!=null&&l.length&&(d.subRows=r(d.originalSubRows,o+1,d))}}return a};return n.rows=r(e),n},Y(t.options,"debugTable","getRowModel",()=>t._autoResetPageIndex()))}function oy(t){const e=[],n=r=>{var s;e.push(r),(s=r.subRows)!=null&&s.length&&r.getIsExpanded()&&r.subRows.forEach(n)};return t.rows.forEach(n),{rows:e,flatRows:t.flatRows,rowsById:t.rowsById}}function iy(t,e,n){return n.options.filterFromLeafRows?ay(t,e,n):ly(t,e,n)}function ay(t,e,n){var r;const s=[],o={},i=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,a=function(l,c){c===void 0&&(c=0);const d=[];for(let g=0;g<l.length;g++){var f;let h=l[g];const m=Ti(n,h.id,h.original,h.index,h.depth,void 0,h.parentId);if(m.columnFilters=h.columnFilters,(f=h.subRows)!=null&&f.length&&c<i){if(m.subRows=a(h.subRows,c+1),h=m,e(h)&&!m.subRows.length){d.push(h),o[h.id]=h,s.push(h);continue}if(e(h)||m.subRows.length){d.push(h),o[h.id]=h,s.push(h);continue}}else h=m,e(h)&&(d.push(h),o[h.id]=h,s.push(h))}return d};return{rows:a(t),flatRows:s,rowsById:o}}function ly(t,e,n){var r;const s=[],o={},i=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,a=function(l,c){c===void 0&&(c=0);const d=[];for(let g=0;g<l.length;g++){let h=l[g];if(e(h)){var f;if((f=h.subRows)!=null&&f.length&&c<i){const p=Ti(n,h.id,h.original,h.index,h.depth,void 0,h.parentId);p.subRows=a(h.subRows,c+1),h=p}d.push(h),s.push(h),o[h.id]=h}}return d};return{rows:a(t),flatRows:s,rowsById:o}}function cy(){return t=>q(()=>[t.getPreFilteredRowModel(),t.getState().columnFilters,t.getState().globalFilter],(e,n,r)=>{if(!e.rows.length||!(n!=null&&n.length)&&!r){for(let g=0;g<e.flatRows.length;g++)e.flatRows[g].columnFilters={},e.flatRows[g].columnFiltersMeta={};return e}const s=[],o=[];(n??[]).forEach(g=>{var h;const m=t.getColumn(g.id);if(!m)return;const p=m.getFilterFn();if(!p){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${m.id}.`);return}s.push({id:g.id,filterFn:p,resolvedValue:(h=p.resolveFilterValue==null?void 0:p.resolveFilterValue(g.value))!=null?h:g.value})});const i=(n??[]).map(g=>g.id),a=t.getGlobalFilterFn(),l=t.getAllLeafColumns().filter(g=>g.getCanGlobalFilter());r&&a&&l.length&&(i.push("__global__"),l.forEach(g=>{var h;o.push({id:g.id,filterFn:a,resolvedValue:(h=a.resolveFilterValue==null?void 0:a.resolveFilterValue(r))!=null?h:r})}));let c,d;for(let g=0;g<e.flatRows.length;g++){const h=e.flatRows[g];if(h.columnFilters={},s.length)for(let m=0;m<s.length;m++){c=s[m];const p=c.id;h.columnFilters[p]=c.filterFn(h,p,c.resolvedValue,y=>{h.columnFiltersMeta[p]=y})}if(o.length){for(let m=0;m<o.length;m++){d=o[m];const p=d.id;if(d.filterFn(h,p,d.resolvedValue,y=>{h.columnFiltersMeta[p]=y})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const f=g=>{for(let h=0;h<i.length;h++)if(g.columnFilters[i[h]]===!1)return!1;return!0};return iy(e.rows,f,t)},Y(t.options,"debugTable","getFilteredRowModel",()=>t._autoResetPageIndex()))}function dy(t){return e=>q(()=>[e.getState().pagination,e.getPrePaginationRowModel(),e.options.paginateExpandedRows?void 0:e.getState().expanded],(n,r)=>{if(!r.rows.length)return r;const{pageSize:s,pageIndex:o}=n;let{rows:i,flatRows:a,rowsById:l}=r;const c=s*o,d=c+s;i=i.slice(c,d);let f;e.options.paginateExpandedRows?f={rows:i,flatRows:a,rowsById:l}:f=oy({rows:i,flatRows:a,rowsById:l}),f.flatRows=[];const g=h=>{f.flatRows.push(h),h.subRows.length&&h.subRows.forEach(g)};return f.rows.forEach(g),f},Y(e.options,"debugTable","getPaginationRowModel"))}function uy(){return t=>q(()=>[t.getState().sorting,t.getPreSortedRowModel()],(e,n)=>{if(!n.rows.length||!(e!=null&&e.length))return n;const r=t.getState().sorting,s=[],o=r.filter(l=>{var c;return(c=t.getColumn(l.id))==null?void 0:c.getCanSort()}),i={};o.forEach(l=>{const c=t.getColumn(l.id);c&&(i[l.id]={sortUndefined:c.columnDef.sortUndefined,invertSorting:c.columnDef.invertSorting,sortingFn:c.getSortingFn()})});const a=l=>{const c=l.map(d=>({...d}));return c.sort((d,f)=>{for(let h=0;h<o.length;h+=1){var g;const m=o[h],p=i[m.id],y=p.sortUndefined,b=(g=m?.desc)!=null?g:!1;let w=0;if(y){const v=d.getValue(m.id),S=f.getValue(m.id),_=v===void 0,A=S===void 0;if(_||A){if(y==="first")return _?-1:1;if(y==="last")return _?1:-1;w=_&&A?0:_?y:-y}}if(w===0&&(w=p.sortingFn(d,f,m.id)),w!==0)return b&&(w*=-1),p.invertSorting&&(w*=-1),w}return d.index-f.index}),c.forEach(d=>{var f;s.push(d),(f=d.subRows)!=null&&f.length&&(d.subRows=a(d.subRows))}),c};return{rows:a(n.rows),flatRows:s,rowsById:n.rowsById}},Y(t.options,"debugTable","getSortedRowModel",()=>t._autoResetPageIndex()))}function fy(t){const e={state:{},onStateChange:()=>{},renderFallbackValue:null,...t},[n]=et.useState(()=>({current:ry(e)})),[r,s]=et.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...t,state:{...r,...t.state},onStateChange:i=>{s(i),t.onStateChange==null||t.onStateChange(i)}})),n.current}function hy({data:t,columns:e,enabled:n=!1}){const r=x.useMemo(()=>t,[t]),s=fy({data:r,columns:e||[],getCoreRowModel:sy(),getSortedRowModel:uy(),getFilteredRowModel:cy(),getPaginationRowModel:dy(),enableSorting:n,enableFilters:n});return n?s:null}const Gn=x.memo(({parts:t=[],children:e=null,fontSize:n="1rem",color:r="#333333",displayMode:s=!1,className:o=""})=>{x.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(f=>{try{return f.href&&f.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
9
+ color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return s}}function Y(t,e,n,r){return{debug:()=>{var s;return(s=t?.debugAll)!=null?s:t[e]},key:process.env.NODE_ENV==="development"&&n,onChange:r}}function kp(t,e,n,r){const s=()=>{var i;return(i=o.getValue())!=null?i:t.options.renderFallbackValue},o={id:`${e.id}_${n.id}`,row:e,column:n,getValue:()=>e.getValue(r),renderValue:s,getContext:q(()=>[t,n,e,o],(i,a,l,c)=>({table:i,column:a,row:l,cell:c,getValue:c.getValue,renderValue:c.renderValue}),Y(t.options,"debugCells","cell.getContext"))};return t._features.forEach(i=>{i.createCell==null||i.createCell(o,n,e,t)},{}),o}function Tp(t,e,n,r){var s,o;const a={...t._getDefaultColumnDef(),...e},l=a.accessorKey;let c=(s=(o=a.id)!=null?o:l?typeof String.prototype.replaceAll=="function"?l.replaceAll(".","_"):l.replace(/\./g,"_"):void 0)!=null?s:typeof a.header=="string"?a.header:void 0,d;if(a.accessorFn?d=a.accessorFn:l&&(l.includes(".")?d=g=>{let h=g;for(const p of l.split(".")){var m;h=(m=h)==null?void 0:m[p],process.env.NODE_ENV!=="production"&&h===void 0&&console.warn(`"${p}" in deeply nested key "${l}" returned undefined.`)}return h}:d=g=>g[a.accessorKey]),!c)throw process.env.NODE_ENV!=="production"?new Error(a.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let f={id:`${String(c)}`,accessorFn:d,parent:r,depth:n,columnDef:a,columns:[],getFlatColumns:q(()=>[!0],()=>{var g;return[f,...(g=f.columns)==null?void 0:g.flatMap(h=>h.getFlatColumns())]},Y(t.options,"debugColumns","column.getFlatColumns")),getLeafColumns:q(()=>[t._getOrderColumnsFn()],g=>{var h;if((h=f.columns)!=null&&h.length){let m=f.columns.flatMap(p=>p.getLeafColumns());return g(m)}return[f]},Y(t.options,"debugColumns","column.getLeafColumns"))};for(const g of t._features)g.createColumn==null||g.createColumn(f,t);return f}const Fe="debugHeaders";function Ua(t,e,n){var r;let o={id:(r=n.id)!=null?r:e.id,column:e,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],a=l=>{l.subHeaders&&l.subHeaders.length&&l.subHeaders.map(a),i.push(l)};return a(o),i},getContext:()=>({table:t,header:o,column:e})};return t._features.forEach(i=>{i.createHeader==null||i.createHeader(o,t)}),o}const Mp={createTable:t=>{t.getHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r,s)=>{var o,i;const a=(o=r?.map(f=>n.find(g=>g.id===f)).filter(Boolean))!=null?o:[],l=(i=s?.map(f=>n.find(g=>g.id===f)).filter(Boolean))!=null?i:[],c=n.filter(f=>!(r!=null&&r.includes(f.id))&&!(s!=null&&s.includes(f.id)));return Gr(e,[...a,...c,...l],t)},Y(t.options,Fe,"getHeaderGroups")),t.getCenterHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Gr(e,n,t,"center")),Y(t.options,Fe,"getCenterHeaderGroups")),t.getLeftHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left],(e,n,r)=>{var s;const o=(s=r?.map(i=>n.find(a=>a.id===i)).filter(Boolean))!=null?s:[];return Gr(e,o,t,"left")},Y(t.options,Fe,"getLeftHeaderGroups")),t.getRightHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.right],(e,n,r)=>{var s;const o=(s=r?.map(i=>n.find(a=>a.id===i)).filter(Boolean))!=null?s:[];return Gr(e,o,t,"right")},Y(t.options,Fe,"getRightHeaderGroups")),t.getFooterGroups=q(()=>[t.getHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getFooterGroups")),t.getLeftFooterGroups=q(()=>[t.getLeftHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getLeftFooterGroups")),t.getCenterFooterGroups=q(()=>[t.getCenterHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getCenterFooterGroups")),t.getRightFooterGroups=q(()=>[t.getRightHeaderGroups()],e=>[...e].reverse(),Y(t.options,Fe,"getRightFooterGroups")),t.getFlatHeaders=q(()=>[t.getHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getFlatHeaders")),t.getLeftFlatHeaders=q(()=>[t.getLeftHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getLeftFlatHeaders")),t.getCenterFlatHeaders=q(()=>[t.getCenterHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getCenterFlatHeaders")),t.getRightFlatHeaders=q(()=>[t.getRightHeaderGroups()],e=>e.map(n=>n.headers).flat(),Y(t.options,Fe,"getRightFlatHeaders")),t.getCenterLeafHeaders=q(()=>[t.getCenterFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getCenterLeafHeaders")),t.getLeftLeafHeaders=q(()=>[t.getLeftFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getLeftLeafHeaders")),t.getRightLeafHeaders=q(()=>[t.getRightFlatHeaders()],e=>e.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Y(t.options,Fe,"getRightLeafHeaders")),t.getLeafHeaders=q(()=>[t.getLeftHeaderGroups(),t.getCenterHeaderGroups(),t.getRightHeaderGroups()],(e,n,r)=>{var s,o,i,a,l,c;return[...(s=(o=e[0])==null?void 0:o.headers)!=null?s:[],...(i=(a=n[0])==null?void 0:a.headers)!=null?i:[],...(l=(c=r[0])==null?void 0:c.headers)!=null?l:[]].map(d=>d.getLeafHeaders()).flat()},Y(t.options,Fe,"getLeafHeaders"))}};function Gr(t,e,n,r){var s,o;let i=0;const a=function(g,h){h===void 0&&(h=1),i=Math.max(i,h),g.filter(m=>m.getIsVisible()).forEach(m=>{var p;(p=m.columns)!=null&&p.length&&a(m.columns,h+1)},0)};a(t);let l=[];const c=(g,h)=>{const m={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},p=[];g.forEach(y=>{const b=[...p].reverse()[0],w=y.column.depth===m.depth;let v,S=!1;if(w&&y.column.parent?v=y.column.parent:(v=y.column,S=!0),b&&b?.column===v)b.subHeaders.push(y);else{const _=Ua(n,v,{id:[r,h,v.id,y?.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${p.filter(A=>A.column===v).length}`:void 0,depth:h,index:p.length});_.subHeaders.push(y),p.push(_)}m.headers.push(y),y.headerGroup=m}),l.push(m),h>0&&c(p,h-1)},d=e.map((g,h)=>Ua(n,g,{depth:i,index:h}));c(d,i-1),l.reverse();const f=g=>g.filter(m=>m.column.getIsVisible()).map(m=>{let p=0,y=0,b=[0];m.subHeaders&&m.subHeaders.length?(b=[],f(m.subHeaders).forEach(v=>{let{colSpan:S,rowSpan:_}=v;p+=S,b.push(_)})):p=1;const w=Math.min(...b);return y=y+w,m.colSpan=p,m.rowSpan=y,{colSpan:p,rowSpan:y}});return f((s=(o=l[0])==null?void 0:o.headers)!=null?s:[]),l}const Ti=(t,e,n,r,s,o,i)=>{let a={id:e,index:r,original:n,depth:s,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:l=>{if(a._valuesCache.hasOwnProperty(l))return a._valuesCache[l];const c=t.getColumn(l);if(c!=null&&c.accessorFn)return a._valuesCache[l]=c.accessorFn(a.original,r),a._valuesCache[l]},getUniqueValues:l=>{if(a._uniqueValuesCache.hasOwnProperty(l))return a._uniqueValuesCache[l];const c=t.getColumn(l);if(c!=null&&c.accessorFn)return c.columnDef.getUniqueValues?(a._uniqueValuesCache[l]=c.columnDef.getUniqueValues(a.original,r),a._uniqueValuesCache[l]):(a._uniqueValuesCache[l]=[a.getValue(l)],a._uniqueValuesCache[l])},renderValue:l=>{var c;return(c=a.getValue(l))!=null?c:t.options.renderFallbackValue},subRows:[],getLeafRows:()=>Ep(a.subRows,l=>l.subRows),getParentRow:()=>a.parentId?t.getRow(a.parentId,!0):void 0,getParentRows:()=>{let l=[],c=a;for(;;){const d=c.getParentRow();if(!d)break;l.push(d),c=d}return l.reverse()},getAllCells:q(()=>[t.getAllLeafColumns()],l=>l.map(c=>kp(t,a,c,c.id)),Y(t.options,"debugRows","getAllCells")),_getAllCellsByColumnId:q(()=>[a.getAllCells()],l=>l.reduce((c,d)=>(c[d.column.id]=d,c),{}),Y(t.options,"debugRows","getAllCellsByColumnId"))};for(let l=0;l<t._features.length;l++){const c=t._features[l];c==null||c.createRow==null||c.createRow(a,t)}return a},jp={createColumn:(t,e)=>{t._getFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,t.id),t.getFacetedRowModel=()=>t._getFacetedRowModel?t._getFacetedRowModel():e.getPreFilteredRowModel(),t._getFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,t.id),t.getFacetedUniqueValues=()=>t._getFacetedUniqueValues?t._getFacetedUniqueValues():new Map,t._getFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,t.id),t.getFacetedMinMaxValues=()=>{if(t._getFacetedMinMaxValues)return t._getFacetedMinMaxValues()}}},Nd=(t,e,n)=>{var r,s;const o=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((s=t.getValue(e))==null||(s=s.toString())==null||(s=s.toLowerCase())==null)&&s.includes(o))};Nd.autoRemove=t=>ct(t);const Ed=(t,e,n)=>{var r;return!!(!((r=t.getValue(e))==null||(r=r.toString())==null)&&r.includes(n))};Ed.autoRemove=t=>ct(t);const kd=(t,e,n)=>{var r;return((r=t.getValue(e))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};kd.autoRemove=t=>ct(t);const Td=(t,e,n)=>{var r;return(r=t.getValue(e))==null?void 0:r.includes(n)};Td.autoRemove=t=>ct(t);const Md=(t,e,n)=>!n.some(r=>{var s;return!((s=t.getValue(e))!=null&&s.includes(r))});Md.autoRemove=t=>ct(t)||!(t!=null&&t.length);const jd=(t,e,n)=>n.some(r=>{var s;return(s=t.getValue(e))==null?void 0:s.includes(r)});jd.autoRemove=t=>ct(t)||!(t!=null&&t.length);const $d=(t,e,n)=>t.getValue(e)===n;$d.autoRemove=t=>ct(t);const Od=(t,e,n)=>t.getValue(e)==n;Od.autoRemove=t=>ct(t);const Mi=(t,e,n)=>{let[r,s]=n;const o=t.getValue(e);return o>=r&&o<=s};Mi.resolveFilterValue=t=>{let[e,n]=t,r=typeof e!="number"?parseFloat(e):e,s=typeof n!="number"?parseFloat(n):n,o=e===null||Number.isNaN(r)?-1/0:r,i=n===null||Number.isNaN(s)?1/0:s;if(o>i){const a=o;o=i,i=a}return[o,i]};Mi.autoRemove=t=>ct(t)||ct(t[0])&&ct(t[1]);const Mt={includesString:Nd,includesStringSensitive:Ed,equalsString:kd,arrIncludes:Td,arrIncludesAll:Md,arrIncludesSome:jd,equals:$d,weakEquals:Od,inNumberRange:Mi};function ct(t){return t==null||t===""}const $p={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:t=>({columnFilters:[],...t}),getDefaultOptions:t=>({onColumnFiltersChange:rt("columnFilters",t),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(t,e)=>{t.getAutoFilterFn=()=>{const n=e.getCoreRowModel().flatRows[0],r=n?.getValue(t.id);return typeof r=="string"?Mt.includesString:typeof r=="number"?Mt.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Mt.equals:Array.isArray(r)?Mt.arrIncludes:Mt.weakEquals},t.getFilterFn=()=>{var n,r;return Bs(t.columnDef.filterFn)?t.columnDef.filterFn:t.columnDef.filterFn==="auto"?t.getAutoFilterFn():(n=(r=e.options.filterFns)==null?void 0:r[t.columnDef.filterFn])!=null?n:Mt[t.columnDef.filterFn]},t.getCanFilter=()=>{var n,r,s;return((n=t.columnDef.enableColumnFilter)!=null?n:!0)&&((r=e.options.enableColumnFilters)!=null?r:!0)&&((s=e.options.enableFilters)!=null?s:!0)&&!!t.accessorFn},t.getIsFiltered=()=>t.getFilterIndex()>-1,t.getFilterValue=()=>{var n;return(n=e.getState().columnFilters)==null||(n=n.find(r=>r.id===t.id))==null?void 0:n.value},t.getFilterIndex=()=>{var n,r;return(n=(r=e.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===t.id))!=null?n:-1},t.setFilterValue=n=>{e.setColumnFilters(r=>{const s=t.getFilterFn(),o=r?.find(d=>d.id===t.id),i=Vt(n,o?o.value:void 0);if(Ba(s,i,t)){var a;return(a=r?.filter(d=>d.id!==t.id))!=null?a:[]}const l={id:t.id,value:i};if(o){var c;return(c=r?.map(d=>d.id===t.id?l:d))!=null?c:[]}return r!=null&&r.length?[...r,l]:[l]})}},createRow:(t,e)=>{t.columnFilters={},t.columnFiltersMeta={}},createTable:t=>{t.setColumnFilters=e=>{const n=t.getAllLeafColumns(),r=s=>{var o;return(o=Vt(e,s))==null?void 0:o.filter(i=>{const a=n.find(l=>l.id===i.id);if(a){const l=a.getFilterFn();if(Ba(l,i.value,a))return!1}return!0})};t.options.onColumnFiltersChange==null||t.options.onColumnFiltersChange(r)},t.resetColumnFilters=e=>{var n,r;t.setColumnFilters(e?[]:(n=(r=t.initialState)==null?void 0:r.columnFilters)!=null?n:[])},t.getPreFilteredRowModel=()=>t.getCoreRowModel(),t.getFilteredRowModel=()=>(!t._getFilteredRowModel&&t.options.getFilteredRowModel&&(t._getFilteredRowModel=t.options.getFilteredRowModel(t)),t.options.manualFiltering||!t._getFilteredRowModel?t.getPreFilteredRowModel():t._getFilteredRowModel())}};function Ba(t,e,n){return(t&&t.autoRemove?t.autoRemove(e,n):!1)||typeof e>"u"||typeof e=="string"&&!e}const Op=(t,e,n)=>n.reduce((r,s)=>{const o=s.getValue(t);return r+(typeof o=="number"?o:0)},0),Ip=(t,e,n)=>{let r;return n.forEach(s=>{const o=s.getValue(t);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},Pp=(t,e,n)=>{let r;return n.forEach(s=>{const o=s.getValue(t);o!=null&&(r<o||r===void 0&&o>=o)&&(r=o)}),r},Fp=(t,e,n)=>{let r,s;return n.forEach(o=>{const i=o.getValue(t);i!=null&&(r===void 0?i>=i&&(r=s=i):(r>i&&(r=i),s<i&&(s=i)))}),[r,s]},Dp=(t,e)=>{let n=0,r=0;if(e.forEach(s=>{let o=s.getValue(t);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},Lp=(t,e)=>{if(!e.length)return;const n=e.map(o=>o.getValue(t));if(!Np(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,i)=>o-i);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},zp=(t,e)=>Array.from(new Set(e.map(n=>n.getValue(t))).values()),Vp=(t,e)=>new Set(e.map(n=>n.getValue(t))).size,Gp=(t,e)=>e.length,mo={sum:Op,min:Ip,max:Pp,extent:Fp,mean:Dp,median:Lp,unique:zp,uniqueCount:Vp,count:Gp},Up={getDefaultColumnDef:()=>({aggregatedCell:t=>{var e,n;return(e=(n=t.getValue())==null||n.toString==null?void 0:n.toString())!=null?e:null},aggregationFn:"auto"}),getInitialState:t=>({grouping:[],...t}),getDefaultOptions:t=>({onGroupingChange:rt("grouping",t),groupedColumnMode:"reorder"}),createColumn:(t,e)=>{t.toggleGrouping=()=>{e.setGrouping(n=>n!=null&&n.includes(t.id)?n.filter(r=>r!==t.id):[...n??[],t.id])},t.getCanGroup=()=>{var n,r;return((n=t.columnDef.enableGrouping)!=null?n:!0)&&((r=e.options.enableGrouping)!=null?r:!0)&&(!!t.accessorFn||!!t.columnDef.getGroupingValue)},t.getIsGrouped=()=>{var n;return(n=e.getState().grouping)==null?void 0:n.includes(t.id)},t.getGroupedIndex=()=>{var n;return(n=e.getState().grouping)==null?void 0:n.indexOf(t.id)},t.getToggleGroupingHandler=()=>{const n=t.getCanGroup();return()=>{n&&t.toggleGrouping()}},t.getAutoAggregationFn=()=>{const n=e.getCoreRowModel().flatRows[0],r=n?.getValue(t.id);if(typeof r=="number")return mo.sum;if(Object.prototype.toString.call(r)==="[object Date]")return mo.extent},t.getAggregationFn=()=>{var n,r;if(!t)throw new Error;return Bs(t.columnDef.aggregationFn)?t.columnDef.aggregationFn:t.columnDef.aggregationFn==="auto"?t.getAutoAggregationFn():(n=(r=e.options.aggregationFns)==null?void 0:r[t.columnDef.aggregationFn])!=null?n:mo[t.columnDef.aggregationFn]}},createTable:t=>{t.setGrouping=e=>t.options.onGroupingChange==null?void 0:t.options.onGroupingChange(e),t.resetGrouping=e=>{var n,r;t.setGrouping(e?[]:(n=(r=t.initialState)==null?void 0:r.grouping)!=null?n:[])},t.getPreGroupedRowModel=()=>t.getFilteredRowModel(),t.getGroupedRowModel=()=>(!t._getGroupedRowModel&&t.options.getGroupedRowModel&&(t._getGroupedRowModel=t.options.getGroupedRowModel(t)),t.options.manualGrouping||!t._getGroupedRowModel?t.getPreGroupedRowModel():t._getGroupedRowModel())},createRow:(t,e)=>{t.getIsGrouped=()=>!!t.groupingColumnId,t.getGroupingValue=n=>{if(t._groupingValuesCache.hasOwnProperty(n))return t._groupingValuesCache[n];const r=e.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(t._groupingValuesCache[n]=r.columnDef.getGroupingValue(t.original),t._groupingValuesCache[n]):t.getValue(n)},t._groupingValuesCache={}},createCell:(t,e,n,r)=>{t.getIsGrouped=()=>e.getIsGrouped()&&e.id===n.groupingColumnId,t.getIsPlaceholder=()=>!t.getIsGrouped()&&e.getIsGrouped(),t.getIsAggregated=()=>{var s;return!t.getIsGrouped()&&!t.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function Bp(t,e,n){if(!(e!=null&&e.length)||!n)return t;const r=t.filter(o=>!e.includes(o.id));return n==="remove"?r:[...e.map(o=>t.find(i=>i.id===o)).filter(Boolean),...r]}const Hp={getInitialState:t=>({columnOrder:[],...t}),getDefaultOptions:t=>({onColumnOrderChange:rt("columnOrder",t)}),createColumn:(t,e)=>{t.getIndex=q(n=>[dr(e,n)],n=>n.findIndex(r=>r.id===t.id),Y(e.options,"debugColumns","getIndex")),t.getIsFirstColumn=n=>{var r;return((r=dr(e,n)[0])==null?void 0:r.id)===t.id},t.getIsLastColumn=n=>{var r;const s=dr(e,n);return((r=s[s.length-1])==null?void 0:r.id)===t.id}},createTable:t=>{t.setColumnOrder=e=>t.options.onColumnOrderChange==null?void 0:t.options.onColumnOrderChange(e),t.resetColumnOrder=e=>{var n;t.setColumnOrder(e?[]:(n=t.initialState.columnOrder)!=null?n:[])},t._getOrderColumnsFn=q(()=>[t.getState().columnOrder,t.getState().grouping,t.options.groupedColumnMode],(e,n,r)=>s=>{let o=[];if(!(e!=null&&e.length))o=s;else{const i=[...e],a=[...s];for(;a.length&&i.length;){const l=i.shift(),c=a.findIndex(d=>d.id===l);c>-1&&o.push(a.splice(c,1)[0])}o=[...o,...a]}return Bp(o,n,r)},Y(t.options,"debugTable","_getOrderColumnsFn"))}},po=()=>({left:[],right:[]}),Wp={getInitialState:t=>({columnPinning:po(),...t}),getDefaultOptions:t=>({onColumnPinningChange:rt("columnPinning",t)}),createColumn:(t,e)=>{t.pin=n=>{const r=t.getLeafColumns().map(s=>s.id).filter(Boolean);e.setColumnPinning(s=>{var o,i;if(n==="right"){var a,l;return{left:((a=s?.left)!=null?a:[]).filter(f=>!(r!=null&&r.includes(f))),right:[...((l=s?.right)!=null?l:[]).filter(f=>!(r!=null&&r.includes(f))),...r]}}if(n==="left"){var c,d;return{left:[...((c=s?.left)!=null?c:[]).filter(f=>!(r!=null&&r.includes(f))),...r],right:((d=s?.right)!=null?d:[]).filter(f=>!(r!=null&&r.includes(f)))}}return{left:((o=s?.left)!=null?o:[]).filter(f=>!(r!=null&&r.includes(f))),right:((i=s?.right)!=null?i:[]).filter(f=>!(r!=null&&r.includes(f)))}})},t.getCanPin=()=>t.getLeafColumns().some(r=>{var s,o,i;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(i=e.options.enableColumnPinning)!=null?i:e.options.enablePinning)!=null?o:!0)}),t.getIsPinned=()=>{const n=t.getLeafColumns().map(a=>a.id),{left:r,right:s}=e.getState().columnPinning,o=n.some(a=>r?.includes(a)),i=n.some(a=>s?.includes(a));return o?"left":i?"right":!1},t.getPinnedIndex=()=>{var n,r;const s=t.getIsPinned();return s?(n=(r=e.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(t.id))!=null?n:-1:0}},createRow:(t,e)=>{t.getCenterVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(i=>!o.includes(i.column.id))},Y(e.options,"debugRows","getCenterVisibleCells")),t.getLeftVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(i=>i.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Y(e.options,"debugRows","getLeftVisibleCells")),t.getRightVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(i=>i.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Y(e.options,"debugRows","getRightVisibleCells"))},createTable:t=>{t.setColumnPinning=e=>t.options.onColumnPinningChange==null?void 0:t.options.onColumnPinningChange(e),t.resetColumnPinning=e=>{var n,r;return t.setColumnPinning(e?po():(n=(r=t.initialState)==null?void 0:r.columnPinning)!=null?n:po())},t.getIsSomeColumnsPinned=e=>{var n;const r=t.getState().columnPinning;if(!e){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[e])!=null&&n.length)},t.getLeftLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left],(e,n)=>(n??[]).map(r=>e.find(s=>s.id===r)).filter(Boolean),Y(t.options,"debugColumns","getLeftLeafColumns")),t.getRightLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.right],(e,n)=>(n??[]).map(r=>e.find(s=>s.id===r)).filter(Boolean),Y(t.options,"debugColumns","getRightLeafColumns")),t.getCenterLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,n,r)=>{const s=[...n??[],...r??[]];return e.filter(o=>!s.includes(o.id))},Y(t.options,"debugColumns","getCenterLeafColumns"))}};function qp(t){return t||(typeof document<"u"?document:null)}const Ur={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},yo=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),Yp={getDefaultColumnDef:()=>Ur,getInitialState:t=>({columnSizing:{},columnSizingInfo:yo(),...t}),getDefaultOptions:t=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:rt("columnSizing",t),onColumnSizingInfoChange:rt("columnSizingInfo",t)}),createColumn:(t,e)=>{t.getSize=()=>{var n,r,s;const o=e.getState().columnSizing[t.id];return Math.min(Math.max((n=t.columnDef.minSize)!=null?n:Ur.minSize,(r=o??t.columnDef.size)!=null?r:Ur.size),(s=t.columnDef.maxSize)!=null?s:Ur.maxSize)},t.getStart=q(n=>[n,dr(e,n),e.getState().columnSizing],(n,r)=>r.slice(0,t.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Y(e.options,"debugColumns","getStart")),t.getAfter=q(n=>[n,dr(e,n),e.getState().columnSizing],(n,r)=>r.slice(t.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Y(e.options,"debugColumns","getAfter")),t.resetSize=()=>{e.setColumnSizing(n=>{let{[t.id]:r,...s}=n;return s})},t.getCanResize=()=>{var n,r;return((n=t.columnDef.enableResizing)!=null?n:!0)&&((r=e.options.enableColumnResizing)!=null?r:!0)},t.getIsResizing=()=>e.getState().columnSizingInfo.isResizingColumn===t.id},createHeader:(t,e)=>{t.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(t),n},t.getStart=()=>{if(t.index>0){const n=t.headerGroup.headers[t.index-1];return n.getStart()+n.getSize()}return 0},t.getResizeHandler=n=>{const r=e.getColumn(t.column.id),s=r?.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),bo(o)&&o.touches&&o.touches.length>1))return;const i=t.getSize(),a=t?t.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],l=bo(o)?Math.round(o.touches[0].clientX):o.clientX,c={},d=(b,w)=>{typeof w=="number"&&(e.setColumnSizingInfo(v=>{var S,_;const A=e.options.columnResizeDirection==="rtl"?-1:1,C=(w-((S=v?.startOffset)!=null?S:0))*A,R=Math.max(C/((_=v?.startSize)!=null?_:0),-.999999);return v.columnSizingStart.forEach(N=>{let[M,F]=N;c[M]=Math.round(Math.max(F+F*R,0)*100)/100}),{...v,deltaOffset:C,deltaPercentage:R}}),(e.options.columnResizeMode==="onChange"||b==="end")&&e.setColumnSizing(v=>({...v,...c})))},f=b=>d("move",b),g=b=>{d("end",b),e.setColumnSizingInfo(w=>({...w,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=qp(n),m={moveHandler:b=>f(b.clientX),upHandler:b=>{h?.removeEventListener("mousemove",m.moveHandler),h?.removeEventListener("mouseup",m.upHandler),g(b.clientX)}},p={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),f(b.touches[0].clientX),!1),upHandler:b=>{var w;h?.removeEventListener("touchmove",p.moveHandler),h?.removeEventListener("touchend",p.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),g((w=b.touches[0])==null?void 0:w.clientX)}},y=Kp()?{passive:!1}:!1;bo(o)?(h?.addEventListener("touchmove",p.moveHandler,y),h?.addEventListener("touchend",p.upHandler,y)):(h?.addEventListener("mousemove",m.moveHandler,y),h?.addEventListener("mouseup",m.upHandler,y)),e.setColumnSizingInfo(b=>({...b,startOffset:l,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:r.id}))}}},createTable:t=>{t.setColumnSizing=e=>t.options.onColumnSizingChange==null?void 0:t.options.onColumnSizingChange(e),t.setColumnSizingInfo=e=>t.options.onColumnSizingInfoChange==null?void 0:t.options.onColumnSizingInfoChange(e),t.resetColumnSizing=e=>{var n;t.setColumnSizing(e?{}:(n=t.initialState.columnSizing)!=null?n:{})},t.resetHeaderSizeInfo=e=>{var n;t.setColumnSizingInfo(e?yo():(n=t.initialState.columnSizingInfo)!=null?n:yo())},t.getTotalSize=()=>{var e,n;return(e=(n=t.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getLeftTotalSize=()=>{var e,n;return(e=(n=t.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getCenterTotalSize=()=>{var e,n;return(e=(n=t.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0},t.getRightTotalSize=()=>{var e,n;return(e=(n=t.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?e:0}}};let Br=null;function Kp(){if(typeof Br=="boolean")return Br;let t=!1;try{const e={get passive(){return t=!0,!1}},n=()=>{};window.addEventListener("test",n,e),window.removeEventListener("test",n)}catch{t=!1}return Br=t,Br}function bo(t){return t.type==="touchstart"}const Xp={getInitialState:t=>({columnVisibility:{},...t}),getDefaultOptions:t=>({onColumnVisibilityChange:rt("columnVisibility",t)}),createColumn:(t,e)=>{t.toggleVisibility=n=>{t.getCanHide()&&e.setColumnVisibility(r=>({...r,[t.id]:n??!t.getIsVisible()}))},t.getIsVisible=()=>{var n,r;const s=t.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=e.getState().columnVisibility)==null?void 0:r[t.id])!=null?n:!0},t.getCanHide=()=>{var n,r;return((n=t.columnDef.enableHiding)!=null?n:!0)&&((r=e.options.enableHiding)!=null?r:!0)},t.getToggleVisibilityHandler=()=>n=>{t.toggleVisibility==null||t.toggleVisibility(n.target.checked)}},createRow:(t,e)=>{t._getAllVisibleCells=q(()=>[t.getAllCells(),e.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Y(e.options,"debugRows","_getAllVisibleCells")),t.getVisibleCells=q(()=>[t.getLeftVisibleCells(),t.getCenterVisibleCells(),t.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Y(e.options,"debugRows","getVisibleCells"))},createTable:t=>{const e=(n,r)=>q(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Y(t.options,"debugColumns",n));t.getVisibleFlatColumns=e("getVisibleFlatColumns",()=>t.getAllFlatColumns()),t.getVisibleLeafColumns=e("getVisibleLeafColumns",()=>t.getAllLeafColumns()),t.getLeftVisibleLeafColumns=e("getLeftVisibleLeafColumns",()=>t.getLeftLeafColumns()),t.getRightVisibleLeafColumns=e("getRightVisibleLeafColumns",()=>t.getRightLeafColumns()),t.getCenterVisibleLeafColumns=e("getCenterVisibleLeafColumns",()=>t.getCenterLeafColumns()),t.setColumnVisibility=n=>t.options.onColumnVisibilityChange==null?void 0:t.options.onColumnVisibilityChange(n),t.resetColumnVisibility=n=>{var r;t.setColumnVisibility(n?{}:(r=t.initialState.columnVisibility)!=null?r:{})},t.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!t.getIsAllColumnsVisible(),t.setColumnVisibility(t.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},t.getIsAllColumnsVisible=()=>!t.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),t.getIsSomeColumnsVisible=()=>t.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),t.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;t.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function dr(t,e){return e?e==="center"?t.getCenterVisibleLeafColumns():e==="left"?t.getLeftVisibleLeafColumns():t.getRightVisibleLeafColumns():t.getVisibleLeafColumns()}const Jp={createTable:t=>{t._getGlobalFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,"__global__"),t.getGlobalFacetedRowModel=()=>t.options.manualFiltering||!t._getGlobalFacetedRowModel?t.getPreFilteredRowModel():t._getGlobalFacetedRowModel(),t._getGlobalFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,"__global__"),t.getGlobalFacetedUniqueValues=()=>t._getGlobalFacetedUniqueValues?t._getGlobalFacetedUniqueValues():new Map,t._getGlobalFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,"__global__"),t.getGlobalFacetedMinMaxValues=()=>{if(t._getGlobalFacetedMinMaxValues)return t._getGlobalFacetedMinMaxValues()}}},Zp={getInitialState:t=>({globalFilter:void 0,...t}),getDefaultOptions:t=>({onGlobalFilterChange:rt("globalFilter",t),globalFilterFn:"auto",getColumnCanGlobalFilter:e=>{var n;const r=(n=t.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[e.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(t,e)=>{t.getCanGlobalFilter=()=>{var n,r,s,o;return((n=t.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=e.options.enableGlobalFilter)!=null?r:!0)&&((s=e.options.enableFilters)!=null?s:!0)&&((o=e.options.getColumnCanGlobalFilter==null?void 0:e.options.getColumnCanGlobalFilter(t))!=null?o:!0)&&!!t.accessorFn}},createTable:t=>{t.getGlobalAutoFilterFn=()=>Mt.includesString,t.getGlobalFilterFn=()=>{var e,n;const{globalFilterFn:r}=t.options;return Bs(r)?r:r==="auto"?t.getGlobalAutoFilterFn():(e=(n=t.options.filterFns)==null?void 0:n[r])!=null?e:Mt[r]},t.setGlobalFilter=e=>{t.options.onGlobalFilterChange==null||t.options.onGlobalFilterChange(e)},t.resetGlobalFilter=e=>{t.setGlobalFilter(e?void 0:t.initialState.globalFilter)}}},Qp={getInitialState:t=>({expanded:{},...t}),getDefaultOptions:t=>({onExpandedChange:rt("expanded",t),paginateExpandedRows:!0}),createTable:t=>{let e=!1,n=!1;t._autoResetExpanded=()=>{var r,s;if(!e){t._queue(()=>{e=!0});return}if((r=(s=t.options.autoResetAll)!=null?s:t.options.autoResetExpanded)!=null?r:!t.options.manualExpanding){if(n)return;n=!0,t._queue(()=>{t.resetExpanded(),n=!1})}},t.setExpanded=r=>t.options.onExpandedChange==null?void 0:t.options.onExpandedChange(r),t.toggleAllRowsExpanded=r=>{r??!t.getIsAllRowsExpanded()?t.setExpanded(!0):t.setExpanded({})},t.resetExpanded=r=>{var s,o;t.setExpanded(r?{}:(s=(o=t.initialState)==null?void 0:o.expanded)!=null?s:{})},t.getCanSomeRowsExpand=()=>t.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),t.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),t.toggleAllRowsExpanded()},t.getIsSomeRowsExpanded=()=>{const r=t.getState().expanded;return r===!0||Object.values(r).some(Boolean)},t.getIsAllRowsExpanded=()=>{const r=t.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||t.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},t.getExpandedDepth=()=>{let r=0;return(t.getState().expanded===!0?Object.keys(t.getRowModel().rowsById):Object.keys(t.getState().expanded)).forEach(o=>{const i=o.split(".");r=Math.max(r,i.length)}),r},t.getPreExpandedRowModel=()=>t.getSortedRowModel(),t.getExpandedRowModel=()=>(!t._getExpandedRowModel&&t.options.getExpandedRowModel&&(t._getExpandedRowModel=t.options.getExpandedRowModel(t)),t.options.manualExpanding||!t._getExpandedRowModel?t.getPreExpandedRowModel():t._getExpandedRowModel())},createRow:(t,e)=>{t.toggleExpanded=n=>{e.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[t.id]);let i={};if(r===!0?Object.keys(e.getRowModel().rowsById).forEach(a=>{i[a]=!0}):i=r,n=(s=n)!=null?s:!o,!o&&n)return{...i,[t.id]:!0};if(o&&!n){const{[t.id]:a,...l}=i;return l}return r})},t.getIsExpanded=()=>{var n;const r=e.getState().expanded;return!!((n=e.options.getIsRowExpanded==null?void 0:e.options.getIsRowExpanded(t))!=null?n:r===!0||r?.[t.id])},t.getCanExpand=()=>{var n,r,s;return(n=e.options.getRowCanExpand==null?void 0:e.options.getRowCanExpand(t))!=null?n:((r=e.options.enableExpanding)!=null?r:!0)&&!!((s=t.subRows)!=null&&s.length)},t.getIsAllParentsExpanded=()=>{let n=!0,r=t;for(;n&&r.parentId;)r=e.getRow(r.parentId,!0),n=r.getIsExpanded();return n},t.getToggleExpandedHandler=()=>{const n=t.getCanExpand();return()=>{n&&t.toggleExpanded()}}}},Xo=0,Jo=10,xo=()=>({pageIndex:Xo,pageSize:Jo}),ey={getInitialState:t=>({...t,pagination:{...xo(),...t?.pagination}}),getDefaultOptions:t=>({onPaginationChange:rt("pagination",t)}),createTable:t=>{let e=!1,n=!1;t._autoResetPageIndex=()=>{var r,s;if(!e){t._queue(()=>{e=!0});return}if((r=(s=t.options.autoResetAll)!=null?s:t.options.autoResetPageIndex)!=null?r:!t.options.manualPagination){if(n)return;n=!0,t._queue(()=>{t.resetPageIndex(),n=!1})}},t.setPagination=r=>{const s=o=>Vt(r,o);return t.options.onPaginationChange==null?void 0:t.options.onPaginationChange(s)},t.resetPagination=r=>{var s;t.setPagination(r?xo():(s=t.initialState.pagination)!=null?s:xo())},t.setPageIndex=r=>{t.setPagination(s=>{let o=Vt(r,s.pageIndex);const i=typeof t.options.pageCount>"u"||t.options.pageCount===-1?Number.MAX_SAFE_INTEGER:t.options.pageCount-1;return o=Math.max(0,Math.min(o,i)),{...s,pageIndex:o}})},t.resetPageIndex=r=>{var s,o;t.setPageIndex(r?Xo:(s=(o=t.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Xo)},t.resetPageSize=r=>{var s,o;t.setPageSize(r?Jo:(s=(o=t.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Jo)},t.setPageSize=r=>{t.setPagination(s=>{const o=Math.max(1,Vt(r,s.pageSize)),i=s.pageSize*s.pageIndex,a=Math.floor(i/o);return{...s,pageIndex:a,pageSize:o}})},t.setPageCount=r=>t.setPagination(s=>{var o;let i=Vt(r,(o=t.options.pageCount)!=null?o:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...s,pageCount:i}}),t.getPageOptions=q(()=>[t.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,i)=>i)),s},Y(t.options,"debugTable","getPageOptions")),t.getCanPreviousPage=()=>t.getState().pagination.pageIndex>0,t.getCanNextPage=()=>{const{pageIndex:r}=t.getState().pagination,s=t.getPageCount();return s===-1?!0:s===0?!1:r<s-1},t.previousPage=()=>t.setPageIndex(r=>r-1),t.nextPage=()=>t.setPageIndex(r=>r+1),t.firstPage=()=>t.setPageIndex(0),t.lastPage=()=>t.setPageIndex(t.getPageCount()-1),t.getPrePaginationRowModel=()=>t.getExpandedRowModel(),t.getPaginationRowModel=()=>(!t._getPaginationRowModel&&t.options.getPaginationRowModel&&(t._getPaginationRowModel=t.options.getPaginationRowModel(t)),t.options.manualPagination||!t._getPaginationRowModel?t.getPrePaginationRowModel():t._getPaginationRowModel()),t.getPageCount=()=>{var r;return(r=t.options.pageCount)!=null?r:Math.ceil(t.getRowCount()/t.getState().pagination.pageSize)},t.getRowCount=()=>{var r;return(r=t.options.rowCount)!=null?r:t.getPrePaginationRowModel().rows.length}}},vo=()=>({top:[],bottom:[]}),ty={getInitialState:t=>({rowPinning:vo(),...t}),getDefaultOptions:t=>({onRowPinningChange:rt("rowPinning",t)}),createRow:(t,e)=>{t.pin=(n,r,s)=>{const o=r?t.getLeafRows().map(l=>{let{id:c}=l;return c}):[],i=s?t.getParentRows().map(l=>{let{id:c}=l;return c}):[],a=new Set([...i,t.id,...o]);e.setRowPinning(l=>{var c,d;if(n==="bottom"){var f,g;return{top:((f=l?.top)!=null?f:[]).filter(p=>!(a!=null&&a.has(p))),bottom:[...((g=l?.bottom)!=null?g:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)]}}if(n==="top"){var h,m;return{top:[...((h=l?.top)!=null?h:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)],bottom:((m=l?.bottom)!=null?m:[]).filter(p=>!(a!=null&&a.has(p)))}}return{top:((c=l?.top)!=null?c:[]).filter(p=>!(a!=null&&a.has(p))),bottom:((d=l?.bottom)!=null?d:[]).filter(p=>!(a!=null&&a.has(p)))}})},t.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=e.options;return typeof r=="function"?r(t):(n=r??s)!=null?n:!0},t.getIsPinned=()=>{const n=[t.id],{top:r,bottom:s}=e.getState().rowPinning,o=n.some(a=>r?.includes(a)),i=n.some(a=>s?.includes(a));return o?"top":i?"bottom":!1},t.getPinnedIndex=()=>{var n,r;const s=t.getIsPinned();if(!s)return-1;const o=(n=s==="top"?e.getTopRows():e.getBottomRows())==null?void 0:n.map(i=>{let{id:a}=i;return a});return(r=o?.indexOf(t.id))!=null?r:-1}},createTable:t=>{t.setRowPinning=e=>t.options.onRowPinningChange==null?void 0:t.options.onRowPinningChange(e),t.resetRowPinning=e=>{var n,r;return t.setRowPinning(e?vo():(n=(r=t.initialState)==null?void 0:r.rowPinning)!=null?n:vo())},t.getIsSomeRowsPinned=e=>{var n;const r=t.getState().rowPinning;if(!e){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[e])!=null&&n.length)},t._getPinnedRows=(e,n,r)=>{var s;return((s=t.options.keepPinnedRows)==null||s?(n??[]).map(i=>{const a=t.getRow(i,!0);return a.getIsAllParentsExpanded()?a:null}):(n??[]).map(i=>e.find(a=>a.id===i))).filter(Boolean).map(i=>({...i,position:r}))},t.getTopRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top],(e,n)=>t._getPinnedRows(e,n,"top"),Y(t.options,"debugRows","getTopRows")),t.getBottomRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.bottom],(e,n)=>t._getPinnedRows(e,n,"bottom"),Y(t.options,"debugRows","getBottomRows")),t.getCenterRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top,t.getState().rowPinning.bottom],(e,n,r)=>{const s=new Set([...n??[],...r??[]]);return e.filter(o=>!s.has(o.id))},Y(t.options,"debugRows","getCenterRows"))}},ny={getInitialState:t=>({rowSelection:{},...t}),getDefaultOptions:t=>({onRowSelectionChange:rt("rowSelection",t),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:t=>{t.setRowSelection=e=>t.options.onRowSelectionChange==null?void 0:t.options.onRowSelectionChange(e),t.resetRowSelection=e=>{var n;return t.setRowSelection(e?{}:(n=t.initialState.rowSelection)!=null?n:{})},t.toggleAllRowsSelected=e=>{t.setRowSelection(n=>{e=typeof e<"u"?e:!t.getIsAllRowsSelected();const r={...n},s=t.getPreGroupedRowModel().flatRows;return e?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},t.toggleAllPageRowsSelected=e=>t.setRowSelection(n=>{const r=typeof e<"u"?e:!t.getIsAllPageRowsSelected(),s={...n};return t.getRowModel().rows.forEach(o=>{Zo(s,o.id,r,!0,t)}),s}),t.getPreSelectedRowModel=()=>t.getCoreRowModel(),t.getSelectedRowModel=q(()=>[t.getState().rowSelection,t.getCoreRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getSelectedRowModel")),t.getFilteredSelectedRowModel=q(()=>[t.getState().rowSelection,t.getFilteredRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getFilteredSelectedRowModel")),t.getGroupedSelectedRowModel=q(()=>[t.getState().rowSelection,t.getSortedRowModel()],(e,n)=>Object.keys(e).length?wo(t,n):{rows:[],flatRows:[],rowsById:{}},Y(t.options,"debugTable","getGroupedSelectedRowModel")),t.getIsAllRowsSelected=()=>{const e=t.getFilteredRowModel().flatRows,{rowSelection:n}=t.getState();let r=!!(e.length&&Object.keys(n).length);return r&&e.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},t.getIsAllPageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=t.getState();let r=!!e.length;return r&&e.some(s=>!n[s.id])&&(r=!1),r},t.getIsSomeRowsSelected=()=>{var e;const n=Object.keys((e=t.getState().rowSelection)!=null?e:{}).length;return n>0&&n<t.getFilteredRowModel().flatRows.length},t.getIsSomePageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows;return t.getIsAllPageRowsSelected()?!1:e.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},t.getToggleAllRowsSelectedHandler=()=>e=>{t.toggleAllRowsSelected(e.target.checked)},t.getToggleAllPageRowsSelectedHandler=()=>e=>{t.toggleAllPageRowsSelected(e.target.checked)}},createRow:(t,e)=>{t.toggleSelected=(n,r)=>{const s=t.getIsSelected();e.setRowSelection(o=>{var i;if(n=typeof n<"u"?n:!s,t.getCanSelect()&&s===n)return o;const a={...o};return Zo(a,t.id,n,(i=r?.selectChildren)!=null?i:!0,e),a})},t.getIsSelected=()=>{const{rowSelection:n}=e.getState();return ji(t,n)},t.getIsSomeSelected=()=>{const{rowSelection:n}=e.getState();return Qo(t,n)==="some"},t.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=e.getState();return Qo(t,n)==="all"},t.getCanSelect=()=>{var n;return typeof e.options.enableRowSelection=="function"?e.options.enableRowSelection(t):(n=e.options.enableRowSelection)!=null?n:!0},t.getCanSelectSubRows=()=>{var n;return typeof e.options.enableSubRowSelection=="function"?e.options.enableSubRowSelection(t):(n=e.options.enableSubRowSelection)!=null?n:!0},t.getCanMultiSelect=()=>{var n;return typeof e.options.enableMultiRowSelection=="function"?e.options.enableMultiRowSelection(t):(n=e.options.enableMultiRowSelection)!=null?n:!0},t.getToggleSelectedHandler=()=>{const n=t.getCanSelect();return r=>{var s;n&&t.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Zo=(t,e,n,r,s)=>{var o;const i=s.getRow(e,!0);n?(i.getCanMultiSelect()||Object.keys(t).forEach(a=>delete t[a]),i.getCanSelect()&&(t[e]=!0)):delete t[e],r&&(o=i.subRows)!=null&&o.length&&i.getCanSelectSubRows()&&i.subRows.forEach(a=>Zo(t,a.id,n,r,s))};function wo(t,e){const n=t.getState().rowSelection,r=[],s={},o=function(i,a){return i.map(l=>{var c;const d=ji(l,n);if(d&&(r.push(l),s[l.id]=l),(c=l.subRows)!=null&&c.length&&(l={...l,subRows:o(l.subRows)}),d)return l}).filter(Boolean)};return{rows:o(e.rows),flatRows:r,rowsById:s}}function ji(t,e){var n;return(n=e[t.id])!=null?n:!1}function Qo(t,e,n){var r;if(!((r=t.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return t.subRows.forEach(i=>{if(!(o&&!s)&&(i.getCanSelect()&&(ji(i,e)?o=!0:s=!1),i.subRows&&i.subRows.length)){const a=Qo(i,e);a==="all"?o=!0:(a==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const ei=/([0-9]+)/gm,ry=(t,e,n)=>Id(Wt(t.getValue(n)).toLowerCase(),Wt(e.getValue(n)).toLowerCase()),sy=(t,e,n)=>Id(Wt(t.getValue(n)),Wt(e.getValue(n))),oy=(t,e,n)=>$i(Wt(t.getValue(n)).toLowerCase(),Wt(e.getValue(n)).toLowerCase()),iy=(t,e,n)=>$i(Wt(t.getValue(n)),Wt(e.getValue(n))),ay=(t,e,n)=>{const r=t.getValue(n),s=e.getValue(n);return r>s?1:r<s?-1:0},ly=(t,e,n)=>$i(t.getValue(n),e.getValue(n));function $i(t,e){return t===e?0:t>e?1:-1}function Wt(t){return typeof t=="number"?isNaN(t)||t===1/0||t===-1/0?"":String(t):typeof t=="string"?t:""}function Id(t,e){const n=t.split(ei).filter(Boolean),r=e.split(ei).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),i=parseInt(s,10),a=parseInt(o,10),l=[i,a].sort();if(isNaN(l[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(l[1]))return isNaN(i)?-1:1;if(i>a)return 1;if(a>i)return-1}return n.length-r.length}const Xn={alphanumeric:ry,alphanumericCaseSensitive:sy,text:oy,textCaseSensitive:iy,datetime:ay,basic:ly},cy={getInitialState:t=>({sorting:[],...t}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:t=>({onSortingChange:rt("sorting",t),isMultiSortEvent:e=>e.shiftKey}),createColumn:(t,e)=>{t.getAutoSortingFn=()=>{const n=e.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s?.getValue(t.id);if(Object.prototype.toString.call(o)==="[object Date]")return Xn.datetime;if(typeof o=="string"&&(r=!0,o.split(ei).length>1))return Xn.alphanumeric}return r?Xn.text:Xn.basic},t.getAutoSortDir=()=>{const n=e.getFilteredRowModel().flatRows[0];return typeof n?.getValue(t.id)=="string"?"asc":"desc"},t.getSortingFn=()=>{var n,r;if(!t)throw new Error;return Bs(t.columnDef.sortingFn)?t.columnDef.sortingFn:t.columnDef.sortingFn==="auto"?t.getAutoSortingFn():(n=(r=e.options.sortingFns)==null?void 0:r[t.columnDef.sortingFn])!=null?n:Xn[t.columnDef.sortingFn]},t.toggleSorting=(n,r)=>{const s=t.getNextSortingOrder(),o=typeof n<"u"&&n!==null;e.setSorting(i=>{const a=i?.find(h=>h.id===t.id),l=i?.findIndex(h=>h.id===t.id);let c=[],d,f=o?n:s==="desc";if(i!=null&&i.length&&t.getCanMultiSort()&&r?a?d="toggle":d="add":i!=null&&i.length&&l!==i.length-1?d="replace":a?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var g;c=[...i,{id:t.id,desc:f}],c.splice(0,c.length-((g=e.options.maxMultiSortColCount)!=null?g:Number.MAX_SAFE_INTEGER))}else d==="toggle"?c=i.map(h=>h.id===t.id?{...h,desc:f}:h):d==="remove"?c=i.filter(h=>h.id!==t.id):c=[{id:t.id,desc:f}];return c})},t.getFirstSortDir=()=>{var n,r;return((n=(r=t.columnDef.sortDescFirst)!=null?r:e.options.sortDescFirst)!=null?n:t.getAutoSortDir()==="desc")?"desc":"asc"},t.getNextSortingOrder=n=>{var r,s;const o=t.getFirstSortDir(),i=t.getIsSorted();return i?i!==o&&((r=e.options.enableSortingRemoval)==null||r)&&(!(n&&(s=e.options.enableMultiRemove)!=null)||s)?!1:i==="desc"?"asc":"desc":o},t.getCanSort=()=>{var n,r;return((n=t.columnDef.enableSorting)!=null?n:!0)&&((r=e.options.enableSorting)!=null?r:!0)&&!!t.accessorFn},t.getCanMultiSort=()=>{var n,r;return(n=(r=t.columnDef.enableMultiSort)!=null?r:e.options.enableMultiSort)!=null?n:!!t.accessorFn},t.getIsSorted=()=>{var n;const r=(n=e.getState().sorting)==null?void 0:n.find(s=>s.id===t.id);return r?r.desc?"desc":"asc":!1},t.getSortIndex=()=>{var n,r;return(n=(r=e.getState().sorting)==null?void 0:r.findIndex(s=>s.id===t.id))!=null?n:-1},t.clearSorting=()=>{e.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==t.id):[])},t.getToggleSortingHandler=()=>{const n=t.getCanSort();return r=>{n&&(r.persist==null||r.persist(),t.toggleSorting==null||t.toggleSorting(void 0,t.getCanMultiSort()?e.options.isMultiSortEvent==null?void 0:e.options.isMultiSortEvent(r):!1))}}},createTable:t=>{t.setSorting=e=>t.options.onSortingChange==null?void 0:t.options.onSortingChange(e),t.resetSorting=e=>{var n,r;t.setSorting(e?[]:(n=(r=t.initialState)==null?void 0:r.sorting)!=null?n:[])},t.getPreSortedRowModel=()=>t.getGroupedRowModel(),t.getSortedRowModel=()=>(!t._getSortedRowModel&&t.options.getSortedRowModel&&(t._getSortedRowModel=t.options.getSortedRowModel(t)),t.options.manualSorting||!t._getSortedRowModel?t.getPreSortedRowModel():t._getSortedRowModel())}},dy=[Mp,Xp,Hp,Wp,jp,$p,Jp,Zp,cy,Up,Qp,ey,ty,ny,Yp];function uy(t){var e,n;process.env.NODE_ENV!=="production"&&(t.debugAll||t.debugTable)&&console.info("Creating Table Instance...");const r=[...dy,...(e=t._features)!=null?e:[]];let s={_features:r};const o=s._features.reduce((g,h)=>Object.assign(g,h.getDefaultOptions==null?void 0:h.getDefaultOptions(s)),{}),i=g=>s.options.mergeOptions?s.options.mergeOptions(o,g):{...o,...g};let l={...{},...(n=t.initialState)!=null?n:{}};s._features.forEach(g=>{var h;l=(h=g.getInitialState==null?void 0:g.getInitialState(l))!=null?h:l});const c=[];let d=!1;const f={_features:r,options:{...o,...t},initialState:l,_queue:g=>{c.push(g),d||(d=!0,Promise.resolve().then(()=>{for(;c.length;)c.shift()();d=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{s.setState(s.initialState)},setOptions:g=>{const h=Vt(g,s.options);s.options=i(h)},getState:()=>s.options.state,setState:g=>{s.options.onStateChange==null||s.options.onStateChange(g)},_getRowId:(g,h,m)=>{var p;return(p=s.options.getRowId==null?void 0:s.options.getRowId(g,h,m))!=null?p:`${m?[m.id,h].join("."):h}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(g,h)=>{let m=(h?s.getPrePaginationRowModel():s.getRowModel()).rowsById[g];if(!m&&(m=s.getCoreRowModel().rowsById[g],!m))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${g}`):new Error;return m},_getDefaultColumnDef:q(()=>[s.options.defaultColumn],g=>{var h;return g=(h=g)!=null?h:{},{header:m=>{const p=m.header.column.columnDef;return p.accessorKey?p.accessorKey:p.accessorFn?p.id:null},cell:m=>{var p,y;return(p=(y=m.renderValue())==null||y.toString==null?void 0:y.toString())!=null?p:null},...s._features.reduce((m,p)=>Object.assign(m,p.getDefaultColumnDef==null?void 0:p.getDefaultColumnDef()),{}),...g}},Y(t,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>s.options.columns,getAllColumns:q(()=>[s._getColumnDefs()],g=>{const h=function(m,p,y){return y===void 0&&(y=0),m.map(b=>{const w=Tp(s,b,y,p),v=b;return w.columns=v.columns?h(v.columns,w,y+1):[],w})};return h(g)},Y(t,"debugColumns","getAllColumns")),getAllFlatColumns:q(()=>[s.getAllColumns()],g=>g.flatMap(h=>h.getFlatColumns()),Y(t,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:q(()=>[s.getAllFlatColumns()],g=>g.reduce((h,m)=>(h[m.id]=m,h),{}),Y(t,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:q(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(g,h)=>{let m=g.flatMap(p=>p.getLeafColumns());return h(m)},Y(t,"debugColumns","getAllLeafColumns")),getColumn:g=>{const h=s._getAllFlatColumnsById()[g];return process.env.NODE_ENV!=="production"&&!h&&console.error(`[Table] Column with id '${g}' does not exist.`),h}};Object.assign(s,f);for(let g=0;g<s._features.length;g++){const h=s._features[g];h==null||h.createTable==null||h.createTable(s)}return s}function fy(){return t=>q(()=>[t.options.data],e=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,i){o===void 0&&(o=0);const a=[];for(let c=0;c<s.length;c++){const d=Ti(t,t._getRowId(s[c],c,i),s[c],c,o,void 0,i?.id);if(n.flatRows.push(d),n.rowsById[d.id]=d,a.push(d),t.options.getSubRows){var l;d.originalSubRows=t.options.getSubRows(s[c],c),(l=d.originalSubRows)!=null&&l.length&&(d.subRows=r(d.originalSubRows,o+1,d))}}return a};return n.rows=r(e),n},Y(t.options,"debugTable","getRowModel",()=>t._autoResetPageIndex()))}function hy(t){const e=[],n=r=>{var s;e.push(r),(s=r.subRows)!=null&&s.length&&r.getIsExpanded()&&r.subRows.forEach(n)};return t.rows.forEach(n),{rows:e,flatRows:t.flatRows,rowsById:t.rowsById}}function gy(t,e,n){return n.options.filterFromLeafRows?my(t,e,n):py(t,e,n)}function my(t,e,n){var r;const s=[],o={},i=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,a=function(l,c){c===void 0&&(c=0);const d=[];for(let g=0;g<l.length;g++){var f;let h=l[g];const m=Ti(n,h.id,h.original,h.index,h.depth,void 0,h.parentId);if(m.columnFilters=h.columnFilters,(f=h.subRows)!=null&&f.length&&c<i){if(m.subRows=a(h.subRows,c+1),h=m,e(h)&&!m.subRows.length){d.push(h),o[h.id]=h,s.push(h);continue}if(e(h)||m.subRows.length){d.push(h),o[h.id]=h,s.push(h);continue}}else h=m,e(h)&&(d.push(h),o[h.id]=h,s.push(h))}return d};return{rows:a(t),flatRows:s,rowsById:o}}function py(t,e,n){var r;const s=[],o={},i=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,a=function(l,c){c===void 0&&(c=0);const d=[];for(let g=0;g<l.length;g++){let h=l[g];if(e(h)){var f;if((f=h.subRows)!=null&&f.length&&c<i){const p=Ti(n,h.id,h.original,h.index,h.depth,void 0,h.parentId);p.subRows=a(h.subRows,c+1),h=p}d.push(h),s.push(h),o[h.id]=h}}return d};return{rows:a(t),flatRows:s,rowsById:o}}function yy(){return t=>q(()=>[t.getPreFilteredRowModel(),t.getState().columnFilters,t.getState().globalFilter],(e,n,r)=>{if(!e.rows.length||!(n!=null&&n.length)&&!r){for(let g=0;g<e.flatRows.length;g++)e.flatRows[g].columnFilters={},e.flatRows[g].columnFiltersMeta={};return e}const s=[],o=[];(n??[]).forEach(g=>{var h;const m=t.getColumn(g.id);if(!m)return;const p=m.getFilterFn();if(!p){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${m.id}.`);return}s.push({id:g.id,filterFn:p,resolvedValue:(h=p.resolveFilterValue==null?void 0:p.resolveFilterValue(g.value))!=null?h:g.value})});const i=(n??[]).map(g=>g.id),a=t.getGlobalFilterFn(),l=t.getAllLeafColumns().filter(g=>g.getCanGlobalFilter());r&&a&&l.length&&(i.push("__global__"),l.forEach(g=>{var h;o.push({id:g.id,filterFn:a,resolvedValue:(h=a.resolveFilterValue==null?void 0:a.resolveFilterValue(r))!=null?h:r})}));let c,d;for(let g=0;g<e.flatRows.length;g++){const h=e.flatRows[g];if(h.columnFilters={},s.length)for(let m=0;m<s.length;m++){c=s[m];const p=c.id;h.columnFilters[p]=c.filterFn(h,p,c.resolvedValue,y=>{h.columnFiltersMeta[p]=y})}if(o.length){for(let m=0;m<o.length;m++){d=o[m];const p=d.id;if(d.filterFn(h,p,d.resolvedValue,y=>{h.columnFiltersMeta[p]=y})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const f=g=>{for(let h=0;h<i.length;h++)if(g.columnFilters[i[h]]===!1)return!1;return!0};return gy(e.rows,f,t)},Y(t.options,"debugTable","getFilteredRowModel",()=>t._autoResetPageIndex()))}function by(t){return e=>q(()=>[e.getState().pagination,e.getPrePaginationRowModel(),e.options.paginateExpandedRows?void 0:e.getState().expanded],(n,r)=>{if(!r.rows.length)return r;const{pageSize:s,pageIndex:o}=n;let{rows:i,flatRows:a,rowsById:l}=r;const c=s*o,d=c+s;i=i.slice(c,d);let f;e.options.paginateExpandedRows?f={rows:i,flatRows:a,rowsById:l}:f=hy({rows:i,flatRows:a,rowsById:l}),f.flatRows=[];const g=h=>{f.flatRows.push(h),h.subRows.length&&h.subRows.forEach(g)};return f.rows.forEach(g),f},Y(e.options,"debugTable","getPaginationRowModel"))}function xy(){return t=>q(()=>[t.getState().sorting,t.getPreSortedRowModel()],(e,n)=>{if(!n.rows.length||!(e!=null&&e.length))return n;const r=t.getState().sorting,s=[],o=r.filter(l=>{var c;return(c=t.getColumn(l.id))==null?void 0:c.getCanSort()}),i={};o.forEach(l=>{const c=t.getColumn(l.id);c&&(i[l.id]={sortUndefined:c.columnDef.sortUndefined,invertSorting:c.columnDef.invertSorting,sortingFn:c.getSortingFn()})});const a=l=>{const c=l.map(d=>({...d}));return c.sort((d,f)=>{for(let h=0;h<o.length;h+=1){var g;const m=o[h],p=i[m.id],y=p.sortUndefined,b=(g=m?.desc)!=null?g:!1;let w=0;if(y){const v=d.getValue(m.id),S=f.getValue(m.id),_=v===void 0,A=S===void 0;if(_||A){if(y==="first")return _?-1:1;if(y==="last")return _?1:-1;w=_&&A?0:_?y:-y}}if(w===0&&(w=p.sortingFn(d,f,m.id)),w!==0)return b&&(w*=-1),p.invertSorting&&(w*=-1),w}return d.index-f.index}),c.forEach(d=>{var f;s.push(d),(f=d.subRows)!=null&&f.length&&(d.subRows=a(d.subRows))}),c};return{rows:a(n.rows),flatRows:s,rowsById:n.rowsById}},Y(t.options,"debugTable","getSortedRowModel",()=>t._autoResetPageIndex()))}function vy(t){const e={state:{},onStateChange:()=>{},renderFallbackValue:null,...t},[n]=et.useState(()=>({current:uy(e)})),[r,s]=et.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...t,state:{...r,...t.state},onStateChange:i=>{s(i),t.onStateChange==null||t.onStateChange(i)}})),n.current}function wy({data:t,columns:e,enabled:n=!1}){const r=x.useMemo(()=>t,[t]),s=vy({data:r,columns:e||[],getCoreRowModel:fy(),getSortedRowModel:xy(),getFilteredRowModel:yy(),getPaginationRowModel:by(),enableSorting:n,enableFilters:n});return n?s:null}const Gn=x.memo(({parts:t=[],children:e=null,fontSize:n="1rem",color:r="#333333",displayMode:s=!1,className:o=""})=>{x.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(f=>{try{return f.href&&f.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
10
10
  import 'katex/dist/katex.min.css';
11
- 更多详情请参考组件库文档。`))},[]);const i=x.useMemo(()=>t.length===0?[]:t.map((d,f)=>{try{return Nh.renderToString(d,{displayMode:s,throwOnError:!1,errorColor:"#ff0000"})}catch(g){return console.error(`KaTeX rendering error in part ${f}:`,g),'<span style="color: red;">KaTeX Error</span>'}}),[t,s]);if(t.length===0)return null;const a=s?"div":"span",l=x.Children.toArray(e),c=[];return i.forEach((d,f)=>{c.push(u.jsx("span",{dangerouslySetInnerHTML:{__html:d},style:{display:"inline-block"}},`part-${f}`)),f<l.length&&f<t.length-1&&c.push(u.jsx("span",{style:{display:"inline-block"},children:l[f]},`slot-${f}`))}),u.jsx(a,{className:`equation-render ${o}`.trim(),style:{fontSize:n,color:r,display:"flex",alignItems:"center",gap:"0.3em",...s?{justifyContent:"center",margin:"1em 0"}:{}},children:c})});function or(t){return t.type!=="composite"}function ir(t){return t.type==="composite"}function gy(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function $n(t){if(!t)return gy();if(t.type==="composite"&&Array.isArray(t.transforms))return{type:"composite",transforms:t.transforms.map(o=>$n(o)),executionMode:t.executionMode||"sequential"};if(t.type&&t.config)return t;const e=t;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((o,i)=>$n(o)),executionMode:"sequential"};let n,r="translation";return e.rotation?(r="rotation",n=e.rotation):e.translation?(r="translation",n=e.translation):e.scale?(r="scale",n=e.scale):(r="translation",n={direction:"horizontal",distance:0}),{type:r,config:n,targetGroup:e.targetGroup}}const Hs=t=>{if(t.length===0)return[0,0];let e=0,n=0;for(const[r,s]of t)e+=r,n+=s;return[e/t.length,n/t.length]},ti=t=>{if(or(t)){const e=t;if(!e.config)return`${e.type}变换缺少配置`;switch(e.type){case"translation":if(e.config.distance<=0)return"平移距离必须大于0";break;case"rotation":if(e.config.startAngle===e.config.endAngle)return"旋转起始角度和结束角度不能相同";break;case"scale":const n=e.config;if(n.startScale<=0||n.endScale<=0)return"缩放比例必须大于0";break}return null}if(ir(t)){const e=t;if(!e.transforms)return"复合变换缺少transforms字段";for(const n of e.transforms){const r=ti(n);if(r)return`复合变换子配置错误: ${r}`}return null}return"未知的变换配置类型"},my=(t,e,n,r)=>{if(t<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(n.animated.length===0)return"至少需要一个动画图形";const s=ti(r);if(s)return`全局变换配置错误: ${s}`;for(const o of n.animated)if(o.transform){const i=$n(o.transform),a=ti(i);if(a)return`形状"${o.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const o of[...n.static,...n.animated]){if(!o.vertices||o.vertices.length<2)return`形状"${o.metadata?.id||"未知"}"缺少有效的顶点数据`;for(const i of o.vertices){if(!Array.isArray(i)||i.length!==2)return`形状"${o.metadata?.id||"未知"}"顶点格式错误`;const[a,l]=i;if(typeof a!="number"||typeof l!="number"||!isFinite(a)||!isFinite(l))return`形状"${o.metadata?.id||"未知"}"顶点坐标无效`}}return null},py=t=>{const{base:e,height:n,shapes:r,transform:s}=t,o=$n(s),i=my(e,n,r,o);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},yy=t=>{if(t.slider){const{slider:e}=t;if(e.length<=0)return"滑块长度必须大于0";if(e.min!==void 0&&e.max!==void 0&&e.min>=e.max)return"滑块最小值必须小于最大值";if(e.step!==void 0&&e.step<=0)return"滑块步长必须大于0"}return null},by=t=>{if(!t)return null;if(t.boundingBox){const[e,n,r,s]=t.boundingBox;if(e>=r||n<=s)return"画板边界框配置无效:left < right 且 top > bottom"}return t.gridSize!==void 0&&t.gridSize<=0?"网格大小必须大于0":null},xy=t=>{const e=py({base:t.base,height:t.height,shapes:t.shapes,transform:t.transform});if(e)return e;const n=yy(t.animation);if(n)return{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()};const r=by(t.boardConfig);return r?{code:"INVALID_CONFIG",message:r,timestamp:new Date().toISOString()}:t.autoCompleteThreshold!==void 0&&(t.autoCompleteThreshold<0||t.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class Ws{validateNumber(e,n,r,s){if(typeof e!="number"||isNaN(e))return`${n}必须是有效的数字`;if(r!==void 0&&e<r)return`${n}不能小于${r}`;if(s!==void 0&&e>s)return`${n}不能大于${s}`}validateArray(e,n,r){if(!Array.isArray(e))return`${n}必须是数组`;if(r!==void 0&&e.length!==r)return`${n}必须是长度为${r}的数组`}validateString(e,n,r){if(typeof e!="string")return`${n}必须是字符串`;if(r!==void 0&&!r.includes(e))return`${n}必须是以下值之一: ${r.join(", ")}`}createValidationResult(e,n,r){return{isValid:e,errors:n?.filter(Boolean),warnings:r?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let n=0;n<e.length;n++){const r=e[n],s=this.validateArray(r,`顶点[${n}]`,2);if(s)return s;const[o,i]=r,a=this.validateNumber(o,`顶点[${n}].x`),l=this.validateNumber(i,`顶点[${n}].y`);if(a||l)return`${a||l} (顶点[${n}])`}}}const vy=(t,e,n)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:t,progress:e,config:n,distance:n.distance,distanceType:typeof n.distance,direction:n.direction,directionType:typeof n.direction,configType:typeof n,configKeys:Object.keys(n)});let r;n.direction==="horizontal"?r=[n.distance,0]:n.direction==="vertical"?r=[0,n.distance]:r=[n.direction[0]*n.distance,n.direction[1]*n.distance];const s=r[0]*e,o=r[1]*e;return process.env.NODE_ENV==="development"&&console.log("📐 [calculateTranslation] 计算结果:",{directionVector:r,offsetX:s,offsetY:o,firstVertexOriginal:t[0],firstVertexTransformed:[t[0][0]+s,t[0][1]+o]}),t.map(([i,a])=>[i+s,a+o])},wy=(t,e,n)=>{const r=n.center==="auto"?Hs(t):n.center,[s,o]=r,i=n.endAngle-n.startAngle,a=n.direction==="clockwise"?-1:1,l=n.startAngle+i*e*a;return t.map(([c,d])=>{const f=c-s,g=d-o,h=Math.cos(l),m=Math.sin(l);return[s+f*h-g*m,o+f*m+g*h]})},_y=(t,e,n)=>{const r=n.center==="centroid"?Hs(t):n.center,[s,o]=r,i=n.endScale-n.startScale,a=n.startScale+i*e;return t.map(([l,c])=>{const d=l-s,f=c-o;return[s+d*a,o+f*a]})},Sy=(t,e=.95)=>t>=e;class Cy extends Ws{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,n,r){return vy(e,n,r)}validate(e){const n=[],r=[];if(typeof e.direction=="string"){const o=this.validateString(e.direction,"direction",["horizontal","vertical"]);o&&n.push(o)}else if(Array.isArray(e.direction)){const o=this.validateArray(e.direction,"direction",2);if(o)n.push(o);else{const[i,a]=e.direction,l=this.validateNumber(i,"direction[0]"),c=this.validateNumber(a,"direction[1]");l&&n.push(l),c&&n.push(c)}}else n.push("direction必须是字符串或数组");const s=this.validateNumber(e.distance,"distance",0);if(s&&n.push(s),e.startOffset!==void 0){const o=this.validateNumber(e.startOffset,"startOffset",0,1);o&&r.push(o)}if(Array.isArray(e.direction)){const[o,i]=e.direction;Math.sqrt(o*o+i*i)<.001&&r.push("方向向量长度过小,可能导致变换效果不明显")}return this.createValidationResult(n.length===0,n,r)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,n){const r=this.getDirectionVector(e),s=e.startOffset||0,o=Math.max(0,Math.min(1,n-s))/(1-s);return[r[0]*e.distance*o,r[1]*e.distance*o]}}class Ry extends Ws{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,n,r){return wy(e,n,r)}validate(e){const n=[],r=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)n.push(a);else{const[l,c]=e.center,d=this.validateNumber(l,"center[0]"),f=this.validateNumber(c,"center[1]");d&&n.push(d),f&&n.push(f)}}else n.push('center必须是"auto"或数组[x, y]');const s=this.validateNumber(e.startAngle,"startAngle");s&&n.push(s);const o=this.validateNumber(e.endAngle,"endAngle");if(o&&n.push(o),!s&&!o){const a=Math.abs(e.endAngle-e.startAngle);a<.001&&r.push("角度范围过小,可能导致变换效果不明显"),a>4*Math.PI&&r.push("角度范围过大,可能超过2圈")}const i=this.validateString(e.direction,"direction",["clockwise","counterclockwise","horizontal","vertical"]);return i&&n.push(i),this.createValidationResult(n.length===0,n,r)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=e[0][0],r=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];n=Math.min(n,a),r=Math.max(r,a),s=Math.min(s,l),o=Math.max(o,l)}return{minX:n,maxX:r,minY:s,maxY:o}}getActualCenter(e,n){return n.center==="auto"?Hs(e):n.center}calculateCurrentAngle(e,n){const r=e.endAngle-e.startAngle,s=e.direction==="clockwise"?-1:1;return e.startAngle+r*n*s}}class Ay extends Ws{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,n,r){return _y(e,n,r)}validate(e){const n=[],r=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)n.push(i);else{const[a,l]=e.center,c=this.validateNumber(a,"center[0]"),d=this.validateNumber(l,"center[1]");c&&n.push(c),d&&n.push(d)}}else n.push('center必须是"centroid"或数组[x, y]');const s=this.validateNumber(e.startScale,"startScale",.01);s&&n.push(s);const o=this.validateNumber(e.endScale,"endScale",.01);if(o&&n.push(o),!s&&!o){const i=e.endScale/e.startScale;Math.abs(e.endScale-e.startScale)<.01&&r.push("缩放比例变化过小,可能导致变换效果不明显"),i>10&&r.push("缩放比例过大,可能导致图形变形严重"),i<.1&&r.push("缩放比例过小,可能导致图形几乎不可见")}return typeof e.uniform!="boolean"?n.push("uniform必须是布尔值"):e.uniform||r.push("非均匀缩放可能导致图形变形"),this.createValidationResult(n.length===0,n,r)}getActualCenter(e,n){return n.center==="centroid"?Hs(e):n.center}calculateCurrentScale(e,n){const r=e.endScale-e.startScale;return e.startScale+r*n}calculateSizeChange(e,n,r){if(e.length<2)return{widthChange:0,heightChange:0,areaChange:0};const s=this.calculateBounds(e),o=s.maxX-s.minX,i=s.maxY-s.minY,a=o*i,l=this.calculateCurrentScale(n,r),c=(n.uniform,l),d=o*c,f=i*c,g=d*f;return{widthChange:(d-o)/o,heightChange:(f-i)/i,areaChange:(g-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=e[0][0],r=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];n=Math.min(n,a),r=Math.max(r,a),s=Math.min(s,l),o=Math.max(o,l)}return{minX:n,maxX:r,minY:s,maxY:o}}}function Ha(t){let e=t.trim().replace(/^#/,"");if((e.length===3||e.length===4)&&(e=e.split("").map(o=>o+o).join("")),e.length!==6&&e.length!==8)throw new Error(`无效的十六进制颜色格式: ${t}`);const n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);if(isNaN(n)||isNaN(r)||isNaN(s))throw new Error(`无效的十六进制颜色值: ${t}`);return[n,r,s]}function ky(t,e,n){const r=a=>Math.max(0,Math.min(255,Math.round(a))),s=r(t).toString(16).padStart(2,"0"),o=r(e).toString(16).padStart(2,"0"),i=r(n).toString(16).padStart(2,"0");return`#${s}${o}${i}`.toUpperCase()}function ni(t){const e=t.trim();if(e.startsWith("#"))return Ha(e);const n=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(n){const o=parseInt(n[1],10),i=parseInt(n[2],10),a=parseInt(n[3],10);if(o>=0&&o<=255&&i>=0&&i<=255&&a>=0&&a<=255)return[o,i,a]}const r={red:"#FF0000",green:"#00FF00",blue:"#0000FF",yellow:"#FFFF00",cyan:"#00FFFF",magenta:"#FF00FF",black:"#000000",white:"#FFFFFF",gray:"#808080",grey:"#808080",transparent:"transparent"},s=e.toLowerCase();if(r[s])return s==="transparent"?[0,0,0]:Ha(r[s]);throw new Error(`无法解析的颜色格式: ${t}`)}function Es(t){try{return ni(t),!0}catch{return!1}}function Ey(t,e,n){if(n<=0)return t;if(n>=1)return e;try{const r=ni(t),s=ni(e),o=r[0]+(s[0]-r[0])*n,i=r[1]+(s[1]-r[1])*n,a=r[2]+(s[2]-r[2])*n;return ky(o,i,a)}catch(r){return console.warn("颜色插值失败,返回起始颜色:",r),t}}function Pd(t,e,n,r="linear"){let s=n;switch(r){case"ease-in":s=n*n;break;case"ease-out":s=1-(1-n)*(1-n);break;case"ease-in-out":s=n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2;break;case"step":s=n>=1?1:0;break}return Ey(t,e,s)}class Ny extends Ws{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,n,r){return e}validate(e){const n=[],r=[];if(!e.targetColor||typeof e.targetColor!="string"?n.push("targetColor 是必需的且必须是字符串"):Es(e.targetColor)||n.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?n.push("fromColor 必须是字符串"):Es(e.fromColor)||n.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const s=this.validateNumber(e.startAt,"startAt",0,1);s&&n.push(s)}if(e.endAt!==void 0){const s=this.validateNumber(e.endAt,"endAt",0,1);s&&n.push(s)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&n.push("startAt 必须小于 endAt"),e.easing!==void 0){const s=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);s&&n.push(s)}return e.targetColor&&e.fromColor,this.createValidationResult(n.length===0,n,r)}calculateCurrentColor(e,n,r){const s=n.fromColor||r,o=n.targetColor,i=this.calculateEffectiveProgress(e,n);return Pd(s,o,i,n.easing)}calculateEffectiveProgress(e,n){const r=n.startAt??0,s=n.endAt??1;return e<=r?0:e>=s?1:(e-r)/(s-r)}isActive(e,n){const r=n.startAt??0,s=n.endAt??1;return e>=r&&e<=s}}class Ty{executors=new Map;register(e){this.executors.has(e.type)&&console.warn(`执行器类型 "${e.type}" 已存在,将被覆盖`),this.executors.set(e.type,e)}get(e){return this.executors.get(e)}has(e){return this.executors.has(e)}getSupportedTypes(){return Array.from(this.executors.keys())}getExecutorDisplayNames(){const e={};for(const[n,r]of this.executors)e[n]=r.getDisplayName();return e}validateConfig(e,n){const r=this.get(e);return r?r.validate(n):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,n,r,s){const o=this.get(e);if(!o)return console.error(`不支持变换类型: ${e}`),n;const i=o.validate(s);return i.isValid?o.execute(n,r,s):(console.error("配置验证失败:",i.errors),n)}executeTransforms(e,n,r){let s=n;for(const o of e){const i=this.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}s=i.execute(s,r,o.config)}return s}getDefaultConfig(e){return this.get(e)?.getDefaultConfig()}clear(){this.executors.clear()}size(){return this.executors.size}}let Qt=null;function Fd(){return Qt||(Qt=new Ty,Qt.register(new Cy),Qt.register(new Ry),Qt.register(new Ay),Qt.register(new Ny)),Qt}class ri{static matchesShape(e,n,r){if(!n)return!r||this.extractGroupId(e)===r;if("targetGroup"in n&&n.targetGroup)return this.matchesSimpleGroup(e,n.targetGroup,n.metadataField);if("pattern"in n){if(n.strategy==="any")return this.matchesWithConfig(e,n);if(n.pattern)return this.matchesWithConfig(e,n)}return!1}static matchesSimpleGroup(e,n,r){const s=this.extractGroupId(e,r);if(!s)return!1;if(n.includes("*")){const o=n.replace(/\*/g,".*");return new RegExp(`^${o}$`).test(s)}return s===n}static matchesWithConfig(e,n){const r=this.extractGroupId(e,n.metadataField);if(!r)return!1;const s=n.pattern,o=n.strategy||"exact",i=n.caseSensitive||!1;switch(o){case"exact":return i?r===s:r.toLowerCase()===s.toLowerCase();case"wildcard":const a=s.replace(/\*/g,".*");return new RegExp(`^${a}$`,i?"":"i").test(r);case"regex":return(s instanceof RegExp?s:new RegExp(s,i?"":"i")).test(r);case"multiple":return(Array.isArray(s)?s:s.split(",")).some(d=>this.matchesSimpleGroup(e,d,n.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,n="rotationGroup"){if(!e)return;const r=n.split(".");let s=e;for(const o of r){if(s==null)return;s=s[o]}return typeof s=="string"?s:void 0}static validateConfig(e){const n=[],r=[];if(!e||typeof e!="object")return n.push("配置必须是对象"),{isValid:!1,errors:n,warnings:r};switch(e.pattern||n.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&n.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&n.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&n.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:n.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&n.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&n.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&r.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:n.length===0,errors:n,warnings:r}}static convertToGroupMatchConfig(e,n){if(!e)return;const r=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:r,metadataField:n}}}function My(t,e,n){return!e&&!n?t.filter(r=>!r.targetGroup&&!r.groupMatch):t.filter(r=>{if(r.groupMatch&&n)return ri.matchesShape(n,r.groupMatch);if(r.targetGroup){if(!e)return!1;if(r.targetGroup.includes("*")){const s=r.targetGroup.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r.targetGroup===e}return!e})}class $y{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,n,r,s,o){const i=this.validate(r);if(!i.isValid)return console.error("复合变换配置验证失败:",i.errors),e;const a=this.filterTransformsByGroup(r.transforms,s,o);if(a.length===0)return e;switch(r.executionMode){case"sequential":return this.executeSequentially(e,n,a);case"parallel":return this.executeInParallel(e,n,a);default:return console.warn(`未知的执行模式: ${r.executionMode},使用顺序执行`),this.executeSequentially(e,n,a)}}validate(e){const n=[],r=[];if(!e||e.type!=="composite")return n.push("配置必须是复合变换类型"),this.createValidationResult(!1,n,r);if(!Array.isArray(e.transforms))return n.push("transforms必须是数组"),this.createValidationResult(!1,n,r);e.transforms.length===0&&r.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&n.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],l=this.validateSingleTransform(a,i);l&&n.push(l)}const s=e.transforms.map(i=>i.id).filter(Boolean),o=new Set(s);return s.length!==o.size&&r.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(n.length===0,n,r)}getTransformInfo(e){const n=e.transforms.map(s=>s.type),r=Array.from(new Set(e.transforms.map(s=>s.targetGroup).filter(s=>s!==void 0)));return{count:e.transforms.length,types:n,groups:r,executionMode:e.executionMode}}filterTransformsByGroup(e,n,r){return My(e,n,r)}getTransformsForGroup(e,n,r){return this.filterTransformsByGroup(e.transforms,n,r)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,n,r){let s=e;for(const o of r){const i=this.registry.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}const a=i.validate(o.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${o.type}`,a.errors);continue}s=i.execute(s,n,o.config)}return s}executeInParallel(e,n,r){if(r.length===0)return e;if(r.length===1)return this.executeSequentially(e,n,r);const s=[];for(const o of r){const i=this.registry.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}const a=i.validate(o.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${o.type}`,a.errors);continue}const l=i.execute(e,n,o.config);s.push(l)}return s.length===0?e:this.calculateAverageVertices(s)}calculateAverageVertices(e){if(e.length===0)return[];const n=e[0].length;for(const s of e)if(s.length!==n)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const r=[];for(let s=0;s<n;s++){let o=0,i=0;for(const a of e)o+=a[s][0],i+=a[s][1];r.push([o/e.length,i/e.length])}return r}validateSingleTransform(e,n){if(!e||typeof e!="object")return`变换[${n}]必须是对象`;if(!e.type)return`变换[${n}]缺少type字段`;if(!e.config)return`变换[${n}]缺少config字段`;const r=this.registry.get(e.type);if(!r)return`变换[${n}]不支持的变换类型: ${e.type}`;const s=r.validate(e.config);if(!s.isValid)return`变换[${n}]配置验证失败: ${s.errors?.join(", ")}`}createValidationResult(e,n,r){return{isValid:e,errors:n?.filter(Boolean),warnings:r?.filter(Boolean)}}getDefaultRegistry(){return Fd()}}class jy{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new $y(this.registry)}executeShapeTransform(e,n,r){const s=this.getEffectiveTransform(e,r);return s?this.executeTransform(e.vertices,n,s,e.metadata):e.vertices}executeTransform(e,n,r,s){if(!r)return e;const o=ri.extractGroupId(s,"rotationGroup");return or(r)?this.executeSingleTransform(e,n,r,s,o):ir(r)?this.compositor.execute(e,n,r,o,s):(console.error("未知的变换类型:",r),e)}getEffectiveTransform(e,n){return e.transform?e.transform:n}getTransformInfo(e){return e?or(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:ir(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?or(e)?this.validateSingleTransform(e):ir(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?or(e)?!1:ir(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,n,r){return e.map(s=>({...s,vertices:this.executeShapeTransform(s,n,r)}))}executeSingleTransform(e,n,r,s,o){if(!ri.matchesShape(s,r.groupMatch||(r.targetGroup?{targetGroup:r.targetGroup}:void 0),o))return e;const a=this.registry.get(r.type);if(!a)return console.error(`不支持变换类型: ${r.type}`),e;const l=a.validate(r.config);return l.isValid?a.execute(e,n,r.config):(console.error("变换配置验证失败:",l.errors),e)}validateSingleTransform(e){const n=this.registry.get(e.type);return n?n.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return Fd()}}const Oy=()=>{const t=x.useRef(null),e=x.useCallback((s,o,i=50)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{o&&o(s)},i)},[]),n=x.useCallback((s,o)=>{const i=Math.round(s*100);return o&&o>1?`阶段 ${s>=1?o:Math.min(Math.floor(s*o)+1,o)}/${o} (${i}%)`:`${i}%`},[]),r=x.useCallback(()=>(t.current&&(clearTimeout(t.current),t.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:Sy,getProgressLabel:n,resetProgress:r}},Iy=()=>{const t=x.useCallback((n,r,s=.05)=>{let o=r;switch(n.key){case"ArrowRight":case"ArrowUp":o=Math.min(r+s,1);break;case"ArrowLeft":case"ArrowDown":o=Math.max(r-s,0);break;case"Home":o=0;break;case"End":o=1;break;case"PageUp":o=Math.min(r+s*2,1);break;case"PageDown":o=Math.max(r-s*2,0);break;case" ":case"Enter":o=r>=.95?0:1;break;case"Escape":o=0;break;default:return null}return n.preventDefault(),o},[]),e=x.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
12
- `),[]);return{handleKeyDown:t,getNavigationInstructions:e}},Wa=Ic.JSXGraph,Py=t=>{const{base:e,height:n,unit:r,layoutDensity:s="default",boardHeight:o,shapes:i,transform:a,animation:l,boardConfig:c={},theme:d="light",className:f="",enableRigidityVerification:g=!1,enableKeyboardNavigation:h=!0,autoCompleteThreshold:m=.95,boardWidth:p,onTransformStart:y,onTransformChange:b,onTransformComplete:w,onError:v}=t,[S,_]=x.useState(0),[A,C]=x.useState(null),[R,k]=x.useState(0),[M,F]=x.useState(null),[D,P]=x.useState({width:800,height:560}),j=x.useMemo(()=>new jy,[]),O=x.useMemo(()=>$n(a),[a]),T=x.useRef(null),B=x.useRef({}),$=x.useRef(null),{handleProgressChange:Q,shouldAutoComplete:oe,resetProgress:se}=Oy(),{handleKeyDown:ee,getNavigationInstructions:L}=Iy();x.useEffect(()=>{const z=()=>{if($.current){const{clientWidth:N}=$.current;if(N>0){const de=c.boundingBox||[0,7,10,0],ye=de[2]-de[0],W=de[1]-de[3];let te;o?te=o:te=Math.round(N*(W/ye)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:de,ratio:`${W}:${ye}`,containerWidth:N,calculatedHeight:te,isCustomHeight:!!o}),P({width:N,height:te})}}};z(),window.addEventListener("resize",z);const I=new ResizeObserver(z);return $.current&&I.observe($.current),()=>{window.removeEventListener("resize",z),I.disconnect()}},[c.boundingBox,o]);const X={width:p??`${D.width}px`,height:`${D.height}px`},ae=x.useCallback((z,I)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:z.metadata?.id,shapeType:z.type,progress:I,hasMetadata:!!z.metadata,hasDynamicAppearance:!!z.metadata?.dynamicAppearance,dynamicAppearance:z.metadata?.dynamicAppearance});const N=z.metadata?.dynamicAppearance,de=z.style||{};let ye;if(z.transform?.type==="fillcolor_set"&&z.transform.fillColorSet){const be=z.transform.fillColorSet,{targetColor:Ae,startAt:$e=0,endAt:Pe=1,easing:Ze="linear",fromColor:ft}=be;if(Es(Ae)&&(!ft||Es(ft))){let Qe=I;I<$e?Qe=0:I>Pe?Qe=1:Qe=(I-$e)/(Pe-$e);const qn=ft||de.fillColor||"#FFFFFF";ye=Pd(qn,Ae,Qe,Ze),console.log("🎨 fillcolor_set applied:",{shapeId:z.metadata?.id,progress:I,effectiveProgress:Qe,startColor:qn,targetColor:Ae,resultColor:ye})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:Ae,fromColor:ft})}if(!N)return console.log("📝 No dynamicAppearance, returning base style"),ye?{...de,fillColor:ye}:de;const W=be=>{if(!be)return 1;const Ae=be.threshold??.5,$e=be.startValue??0,Pe=be.endValue??1,Ze=be.type??"step";if(Ze==="step")return I>=Ae?Pe:$e;if(Ze==="fade"){if(I<Ae)return $e;{const ft=Math.min((I-Ae)/(1-Ae),1);return $e+(Pe-$e)*ft}}return 1},te={...de};let Xt=!0;const ut=W(N.visibility),Jt=W(N.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:z.metadata?.id,progress:I,visibilityValue:ut,labelVisibilityValue:Jt,hasVisibility:!!N.visibility,hasLabelVisibility:!!N.labelVisibility}),N.visibility&&(te.fillOpacity===void 0&&(te.fillOpacity=1),te.fillOpacity*=ut,ut===0&&(te.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),te.strokeColor,Xt=ut>0,console.log("👁️ Shape visibility:",{shapeId:z.metadata?.id,visible:Xt,visibilityValue:ut})),N.labelVisibility){const be=Jt>0;te.labelVisible=be,console.log("🏷️ Label visibility:",{shapeId:z.metadata?.id,labelVisible:be,labelVisibilityValue:Jt,hasLabel:!!z.metadata?.label})}if(N.opacity){const be=N.opacity,Ae=be.startAt??0,$e=be.endAt??1,Pe=be.from??1,Ze=be.to??1,ft=be.type??"linear";let Qe=Pe;if(I<Ae)Qe=Pe;else if(I>$e)Qe=Ze;else{const qn=(I-Ae)/($e-Ae);Qe=Pe+(Ze-Pe)*qn}te.fillOpacity=Qe}if(ye)te.fillColor=ye,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:z.metadata?.id,transformColor:ye});else if(N.color){const be=N.color,Ae=be.startAt??0,$e=be.endAt??1,Pe=be.from??te.fillColor,Ze=be.to??te.fillColor,ft=be.type??"gradient";if(Pe&&Ze)if(I<Ae)te.fillColor=Pe;else if(I>$e)te.fillColor=Ze;else{const Qe=(I-Ae)/($e-Ae);ft==="gradient"?te.fillColor=Ze:te.fillColor=Qe>=.5?Ze:Pe}}return te.visible=Xt,te.labelVisible===void 0&&(te.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:z.metadata?.id,visible:te.visible,labelVisible:te.labelVisible,fillOpacity:te.fillOpacity,strokeWidth:te.strokeWidth}),te},[]),ve=x.useCallback((z,I,N=!1,de=0)=>{console.log("🎨 createShape called:",{shapeId:I.metadata?.id,shapeType:I.type,isStatic:N,progress:de,verticesLength:I.vertices?.length,hasMetadata:!!I.metadata,hasDynamicAppearance:!!I.metadata?.dynamicAppearance});const ye=I.type==="point"?1:2;if(!z||!I.vertices||I.vertices.length<ye)return console.warn(`⚠️ createShape: invalid board or vertices for ${I.type}`,{shapeId:I.metadata?.id,shapeType:I.type,verticesLength:I.vertices?.length,minVertices:ye}),null;const W=ae(I,de);let te;switch(I.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const Xt=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,ut=I.metadata?.label||I.metadata?.id||"";te=z.create("polygon",I.vertices,{name:ut,fillColor:W.fillColor!==void 0?W.fillColor:N?"#8ec5fc":"#6a5acd",fillOpacity:W.fillOpacity!==void 0?W.fillOpacity:N?.3:.7,strokeColor:W.strokeColor!==void 0?W.strokeColor:N?"#0074d9":"#4b0082",strokeWidth:W.strokeWidth!==void 0?W.strokeWidth:N?1:2,dash:W.dashStyle!==void 0?W.dashStyle:0,fixed:N,highlight:!N,withLabel:Xt,visible:W.visible!==void 0?W.visible:!0});break;case"circle":if(I.vertices.length>=2){const[Jt,be]=I.vertices,Ae=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,$e=I.metadata?.label||I.metadata?.id||"";te=z.create("circle",[Jt,be],{name:$e,fillColor:W.fillColor!==void 0?W.fillColor:N?"#8ec5fc":"#6a5acd",fillOpacity:W.fillOpacity!==void 0?W.fillOpacity:N?.3:.7,strokeColor:W.strokeColor!==void 0?W.strokeColor:N?"#0074d9":"#4b0082",strokeWidth:W.strokeWidth!==void 0?W.strokeWidth:N?1:2,dash:W.dashStyle!==void 0?W.dashStyle:0,fixed:N,highlight:!N,withLabel:Ae})}break;case"point":if(I.vertices.length>=1){const[Jt,be]=I.vertices[0],Ae=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,$e=I.metadata?.label||I.metadata?.id||"";te=z.create("point",[Jt,be],{name:$e,withLabel:Ae,fixed:N,size:4,strokeColor:W.strokeColor!==void 0?W.strokeColor:N?"#0074d9":"#4b0082",fillColor:W.fillColor!==void 0?W.fillColor:N?"#8ec5fc":"#6a5acd",visible:W.visible!==void 0?W.visible:!0,highlight:!N})}break;default:return console.warn(`Unsupported shape type: ${I.type}`),null}return console.log("✅ createShape finished:",{shapeId:I.metadata?.id,elementType:te?.type,elementName:te?.name,fillOpacity:te?.getAttribute?.("fillOpacity"),strokeWidth:te?.getAttribute?.("strokeWidth"),labelVisible:W.labelVisible,hasLabel:!!I.metadata?.label,withLabel:!!I.metadata?.label&&W.labelVisible}),te},[ae]);x.useEffect(()=>{if(!(e>0&&n>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:n,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:n>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig});const I=xy(t);console.log("🔍 GeometryTransform: 验证结果 =",I),C(I),I&&v&&v(I)},[e,n,i,a,l,c,v,t]),x.useEffect(()=>{if(T.current){try{const z=c.boundingBox||[0,7,10,0],I=d==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",c.boundingBox),console.warn(" - Container dimensions:",D.width,"x",D.height),console.warn(" - Container actual dimensions:",T.current.clientWidth,"x",T.current.clientHeight);const N=Wa.initBoard(T.current,{boundingbox:z,keepaspectratio:c.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:c.showAxis??!0,grid:c.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),de=c.axisColor||(I?"#ffffff":"#000000"),ye=c.gridColor||(I?"#444444":"#dddddd");N.defaultAxes?.x&&N.defaultAxes.x.setAttribute({strokeColor:de}),N.defaultAxes?.y&&N.defaultAxes.y.setAttribute({strokeColor:de}),N.defaultGrid&&N.defaultGrid.setAttribute({strokeColor:ye}),F(N)}catch(z){const I={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:z,timestamp:new Date().toISOString()};C(I),v?.(I)}return()=>{if(M)try{Wa.freeBoard(M)}catch(z){z instanceof Error&&z.name!=="AbortError"&&console.warn("Board cleanup warning:",z)}}}},[D]),x.useEffect(()=>{if(M)try{M.suspendUpdate(),Object.values(B.current).forEach(z=>{if(z&&M.removeObject)try{M.removeObject(z)}catch{}}),B.current={},i.static.forEach((z,I)=>{const N=z.metadata?.id||`static-${I}`,de=ve(M,z,!0,0);de&&(B.current[N]=de)}),i.animated.forEach((z,I)=>{const N=z.metadata?.id||`animated-${I}`,de=ve(M,z,!1,0);de&&(B.current[N]=de)}),M.unsuspendUpdate(),y&&y()}catch(z){const I={code:"RENDER_ERROR",message:"图形渲染失败",details:z,timestamp:new Date().toISOString()};C(I),v?.(I)}},[M,i,e,n]),x.useEffect(()=>{if(M){M.suspendUpdate();try{i.animated.forEach((N,de)=>{const ye=N.metadata?.id||`animated-${de}`,W=B.current[ye];if(W){try{M.removeObject(W)}catch{}delete B.current[ye]}}),i.animated.forEach((N,de)=>{const ye=N.metadata?.id||`animated-${de}`,W=N.transform?{...N,transform:$n(N.transform)}:N,te=j.executeShapeTransform(W,S,O),Xt={...N,vertices:te,metadata:{...N.metadata,id:ye,transformSource:N.transform?"shape":"global"}},ut=ve(M,Xt,!1,S);ut&&(B.current[ye]=ut)});const z=l.progressIndicator?.stages||1,I=Math.min(Math.floor(S*z),z-1);k(I)}catch(z){if(z instanceof Error&&z.name==="AbortError")return;console.warn("Transform update failed:",z)}finally{try{M.unsuspendUpdate()}catch{}}}},[M,S,i,a,l,ve,O,j]);const me=x.useCallback(z=>{const I=Array.isArray(z)?z[0]:z;_(I),Q(I,N=>{b?.(N)}),oe(I,m)&&(_(1),w?.())},[b,w,m,Q,oe]);x.useEffect(()=>{if(!h)return;const z=I=>{const N=ee(I,S);N!==null&&N!==S&&me(N)};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}},[h,S,me,ee]),x.useCallback(()=>{_(0),k(0),se()},[se]);const Ft=x.useCallback(()=>{C(null),_(0),k(0),se()},[se]);return e>0&&n>0&&i?.animated?.length>0?A?u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${f}`,children:u.jsx(H.CardBody,{"data-testid":"card-body",children:u.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[u.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:u.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),u.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),u.jsx("h3",{children:"几何变换演示加载失败"}),u.jsx("p",{children:A.message}),A.details&&u.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[u.jsx("summary",{children:"查看错误详情"}),u.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(A.details,null,2)})]}),u.jsx("div",{className:"geometry-transform__error-actions",children:u.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:Ft,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform ${s==="compact"?"geometry-transform--compact":""} ${d==="dark"?"geometry-transform--dark":""} ${f}`,children:u.jsxs(H.CardBody,{"data-testid":"card-body",children:[u.jsxs("div",{ref:$,className:"geometry-transform__board-container",children:[u.jsx("div",{ref:T,id:"geometry-board",className:"geometry-transform__board",style:X,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),u.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),u.jsxs("div",{className:"geometry-transform__controls",children:[u.jsx("div",{className:"geometry-transform__slider-group",children:u.jsx(H.Slider,{id:"transform-slider","data-testid":"slider",value:S,onChange:me,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),h&&u.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:u.jsxs("details",{children:[u.jsx("summary",{children:"键盘导航说明"}),u.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:L()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:n,shapesAnimatedLength:i?.animated?.length,error:A}),u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${f}`,children:u.jsx(H.CardBody,{"data-testid":"card-body",children:u.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},Dd=x.memo(Py,(t,e)=>{if(t.base!==e.base||t.height!==e.height||t.unit!==e.unit||t.theme!==e.theme||t.className!==e.className||t.enableRigidityVerification!==e.enableRigidityVerification||t.enableKeyboardNavigation!==e.enableKeyboardNavigation||t.autoCompleteThreshold!==e.autoCompleteThreshold||t.onTransformStart!==e.onTransformStart||t.onTransformChange!==e.onTransformChange||t.onTransformComplete!==e.onTransformComplete||t.onError!==e.onError)return!1;const n=JSON.stringify({shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig}),r=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return n===r}),Oi=Dn.create((t,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:n=>{t({internalValue:Math.max(0,Math.min(1,n))})},startDrag:n=>{t({isDragging:!0,dragState:{isDragging:!0,startIndex:n,currentIndex:n,direction:null}})},updateDrag:n=>{const{dragState:r}=e();let s=null;if(r.startIndex!==-1&&n!==-1){const o=Math.floor(r.startIndex/10),i=r.startIndex%10,a=Math.floor(n/10),l=n%10;a===o?s=l>i?"ltr":"rtl":l===i&&(s=a>o?"ttb":"btt")}t({dragState:{...r,currentIndex:n,direction:s}})},endDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Ld=()=>Oi(Pc.useShallow(t=>({internalValue:t.internalValue,setInternalValue:t.setInternalValue}))),zd=()=>Oi(Pc.useShallow(t=>({isDragging:t.isDragging,dragState:t.dragState,startDrag:t.startDrag,updateDrag:t.updateDrag,endDrag:t.endDrag,resetDrag:t.resetDrag}))),Vd=t=>{const{totalCells:e,fillRatio:n,direction:r,rows:s,cols:o}=t,i=Math.round(e*n),a=[];if(r==="ltr")for(let l=0;l<i;l++)a.push(l);else for(let l=0;l<s;l++)for(let c=0;c<o;c++){const d=l*o+c;a.length<i&&a.push(d)}return{filledCells:a,filledCount:i,actualRatio:i/e}},Gd=(t,e,n,r)=>{const s=[];for(let o=0;o<t;o++)for(let i=0;i<e;i++){const a=o*e+i;s.push({index:a,row:o,col:i,filled:r.includes(a),x:i*n,y:o*n})}return s},Ud=(t,e,n,r,s)=>{if(t===-1||e===-1||!n)return[];const o=Math.floor(t/s),i=t%s,a=Math.floor(e/s),l=e%s,c=[];switch(n){case"ltr":for(let d=i;d<=l;d++)c.push(o*s+d);break;case"rtl":for(let d=i;d>=l;d--)c.push(o*s+d);break;case"ttb":for(let d=o;d<=a;d++)c.push(d*s+i);break;case"btt":for(let d=o;d>=a;d--)c.push(d*s+i);break}return c},Bd=(t,e)=>Math.max(0,Math.min(1,t.length/e)),ms=t=>Math.max(0,Math.min(1,t)),Fy=t=>`${Math.round(t*100)}%`;function Dy(t,e,n,r,s){if(e&&e.length>0)for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.cells.includes(t))return i.color}return n?r:s}const Ii=({value:t,defaultValue:e=0,mode:n="readonly",onChange:r,rows:s=10,cols:o=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:l="#f3f4f6",strokeColor:c="#d1d5db",shadingDirection:d="ltr",hasShadow:f=!0,className:g="",showNumbers:h=!1,highlightGroups:m,numberFontSize:p=10,numberColor:y="#374151"})=>{const{internalValue:b,setInternalValue:w}=Ld(),{isDragging:v,dragState:S,startDrag:_,updateDrag:A,endDrag:C}=zd(),R=t!==void 0,k=R?ms(t):b,[M,F]=x.useState(!1);!M&&!R&&(w(ms(e)),F(!0));const D=x.useMemo(()=>{const X={totalCells:s*o,fillRatio:k,direction:d,rows:s,cols:o};return Vd(X).filledCells},[k,s,o,d]),P=x.useMemo(()=>Gd(s,o,i,D),[s,o,i,D]),j=x.useMemo(()=>!v||S.startIndex===-1||S.currentIndex===-1?[]:Ud(S.startIndex,S.currentIndex,S.direction,s,o),[v,S,s,o]),O=x.useCallback(L=>{if(n!=="edit")return;const X=ms((L+1)/(s*o));R||w(X),r?.(X)},[n,s,o,R,r,w]),T=x.useCallback(L=>{n==="edit"&&_(L)},[n,_]),B=x.useCallback(L=>{n!=="edit"||!v||A(L)},[n,v,A]),$=x.useCallback(()=>{if(!(n!=="edit"||!v)){if(j.length>0){const L=Bd(j,s*o);R||w(L),r?.(L)}C()}},[n,v,j,s,o,R,r,w,C]),Q=o*i,oe=s*i,se=["hundred-chart-container",`hundred-chart--${n}`,f&&"hundred-chart--has-shadow",g].filter(Boolean).join(" "),ee=Math.round(k*100);return u.jsx("div",{className:se,"data-testid":"hundred-chart-container",children:u.jsx("svg",{width:Q,height:oe,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${ee}% 已填充`,children:P.map(L=>{const X=D.includes(L.index),ae=j.includes(L.index),ve=X||ae,me=L.index+1,Ft=Dy(me,m,ve,a,l);return u.jsxs("g",{"data-testid":"hundred-chart-cell-group",className:"hundred-chart-cell-group",children:[u.jsx("rect",{x:L.x,y:L.y,width:i,height:i,fill:Ft,stroke:c,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":X,"data-drag":ae,"aria-label":`第${L.row+1}行第${L.col+1}列,数字${me},${ve?"已填充":"未填充"}`,tabIndex:n==="edit"?0:-1,onClick:()=>O(L.index),onMouseDown:()=>T(L.index),onMouseEnter:()=>B(L.index),onMouseUp:$,onKeyDown:At=>{n==="edit"&&At.key==="Enter"&&O(L.index)}}),h&&u.jsx("text",{x:L.x+i/2,y:L.y+i/2,textAnchor:"middle",dominantBaseline:"middle",fontSize:p,fill:y,className:"hundred-chart-cell-text",pointerEvents:"none","aria-hidden":"true",children:me})]},L.index)})})})},Ly=x.createContext(void 0),Hd=(t,e)=>x.useMemo(()=>{const n=t.scenes?.[e];return{...t,content:n?.content||t.content,layout:n?.layout||t.layout,renderer:n?.renderer||t.renderer}},[t,e]),Wd=({children:t,padding:e,shadow:n=!0,border:r=!0,theme:s="light",className:o=""})=>{const i=s==="dark"?"theme-dark":"",a=n?"with-shadow":"",l=r?"with-border":"",c=e?{"--mc-card-padding":e}:void 0;return u.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${l} ${o}`,style:c,"data-testid":"mathcard-v2-container",children:t})},qd=({children:t,columns:e,gap:n,responsive:r=!0,className:s=""})=>{const o={"--grid-columns":e,"--grid-gap":n},i=r?"mathcard-v2-grid-responsive":"";return u.jsx("div",{style:o,className:`mathcard-v2-grid ${i} ${s}`,"data-testid":"grid-layout",children:t})},Yd=({children:t,direction:e="vertical",gap:n,wrap:r=!1,className:s=""})=>{const o={"--flow-gap":n,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":r?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=r?"wrap":"";return u.jsx("div",{style:o,className:`mathcard-v2-flow ${i} ${a} ${s}`,"data-testid":"flow-layout",children:t})},Kd=({content:t,style:e={},onInteraction:n,className:r=""})=>u.jsx("div",{className:`mathcard-v2-text ${r}`,style:e,onClick:()=>n?.({type:"click",content:t}),"data-testid":"text-content",children:t}),Xd=({parts:t,children:e,displayMode:n=!1,style:r={},className:s=""})=>u.jsx("div",{className:`mathcard-v2-formula ${s}`,style:r,"data-testid":"equation-render",children:u.jsx(Gn,{parts:t,children:e,displayMode:n})});class zy extends x.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){console.error("MathGraph Error:",e,n.componentStack)}render(){return this.state.hasError?u.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[u.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),u.jsx("p",{className:"text-red-700",children:this.state.error?.message}),u.jsx("button",{className:"mt-2 px-3 py-1 bg-red-100 hover:bg-red-200 rounded",onClick:()=>this.setState({hasError:!1}),children:"重试"})]}):this.props.children}}function Vy(t){if(typeof t!="string")throw new Error(`parseFunctionString expects a string, got ${typeof t}`);const e=t.trim(),n=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(n){const r=(n[3]||n[4]||"").trim();if(!r)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return Gy(r)}catch(s){throw new Error(`Failed to create function from "${e}": ${s}`)}}throw new Error(`Invalid function string format: "${e}". Expected arrow function like "() => progress * Math.PI"`)}function Gy(t){const e=t.trim();if(e==="progress * Math.PI"||e==="progress*Math.PI")return l=>l*Math.PI;if(e==="progress * Math.PI * 2"||e==="progress*Math.PI*2")return l=>l*Math.PI*2;const n=/^progress\s*\*\s*([0-9.]+)$/,r=e.match(n);if(r){const l=parseFloat(r[1]);return c=>c*l}const s=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,o=e.match(s);if(o){const l=parseFloat(o[1]);return c=>c*Math.PI*l}if(e.includes("Math.sin")&&e.includes("progress"))return l=>Math.sin(l*Math.PI);if(e.includes("Math.cos")&&e.includes("progress"))return l=>Math.cos(l*Math.PI);const i=/^([0-9.]+)$/,a=e.match(i);if(a){const l=parseFloat(a[1]);return()=>l}return e==="progress"?l=>l:e.includes("control.value")?(console.warn(`Expression contains control.value: ${e}. Will be handled by parseParamsWithControl.`),l=>l*Math.PI):(console.warn(`Unsupported expression pattern: "${e}". Using generic evaluator.`),l=>{let c=e.replace(/\bprogress\b/g,l.toString());return c=c.replace(/Math\.PI/g,Math.PI.toString()),c=c.replace(/Math\.E/g,Math.E.toString()),Uy(c)})}function Uy(t){const e=t.replace(/\s/g,"");function n(r){for(;r.includes("(");){const a=r.match(/\(([^()]+)\)/);if(!a)break;const l=n(a[1]);r=r.replace(a[0],l.toString())}const s=r.match(/(-?\d+\.?\d*)([*/])(-?\d+\.?\d*)/);if(s){const a=parseFloat(s[1]),l=s[2],c=parseFloat(s[3]),d=l==="*"?a*c:a/c;return r=r.replace(s[0],d.toString()),n(r)}const o=r.match(/(-?\d+\.?\d*)([+\-])(-?\d+\.?\d*)/);if(o){const a=parseFloat(o[1]),l=o[2],c=parseFloat(o[3]),d=l==="+"?a+c:a-c;return r=r.replace(o[0],d.toString()),n(r)}const i=parseFloat(r);if(isNaN(i))throw new Error(`Invalid expression: ${r}`);return i}return n(e)}function By(t){return typeof t=="string"&&(t.includes("=>")||t.includes("progress"))}function De(t,e=0){return typeof t=="function"?t(e):t}function _o(t,e,n){switch(t.params.type){case"translate":{const r=t.params,s=typeof r.x=="function"&&n?function(){const i=n.Value();return r.x(i)}:De(r.x,e),o=typeof r.y=="function"&&n?function(){const i=n.Value();return r.y(i)}:De(r.y,e);return[s,o]}case"rotate":{const r=t.params,s=r.center||[0,0];return typeof r.angle=="function"&&n?[function(){const i=n.Value();return r.angle(i)},s[0],s[1]]:[De(r.angle,e),s[0],s[1]]}case"scale":{const r=t.params,s=typeof r.scaleX=="function"&&n?function(){const i=n.Value();return r.scaleX(i)}:De(r.scaleX,e),o=typeof r.scaleY=="function"&&n?function(){const i=n.Value();return r.scaleY(i)}:De(r.scaleY,e);return[s,o]}case"reflect":{const r=t.params;if(r.line)return[r.line];if(r.point1&&r.point2)return[r.point1,r.point2];if(r.p1&&r.p2)return[r.p1,r.p2];throw new Error(`Reflect transform requires one of:
11
+ 更多详情请参考组件库文档。`))},[]);const i=x.useMemo(()=>t.length===0?[]:t.map((d,f)=>{try{return Fh.renderToString(d,{displayMode:s,throwOnError:!1,errorColor:"#ff0000"})}catch(g){return console.error(`KaTeX rendering error in part ${f}:`,g),'<span style="color: red;">KaTeX Error</span>'}}),[t,s]);if(t.length===0)return null;const a=s?"div":"span",l=x.Children.toArray(e),c=[];return i.forEach((d,f)=>{c.push(u.jsx("span",{dangerouslySetInnerHTML:{__html:d},style:{display:"inline-block"}},`part-${f}`)),f<l.length&&f<t.length-1&&c.push(u.jsx("span",{style:{display:"inline-block"},children:l[f]},`slot-${f}`))}),u.jsx(a,{className:`equation-render ${o}`.trim(),style:{fontSize:n,color:r,display:"flex",alignItems:"center",gap:"0.3em",...s?{justifyContent:"center",margin:"1em 0"}:{}},children:c})});function or(t){return t.type!=="composite"}function ir(t){return t.type==="composite"}function _y(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function jn(t){if(!t)return _y();if(t.type==="composite"&&Array.isArray(t.transforms))return{type:"composite",transforms:t.transforms.map(o=>jn(o)),executionMode:t.executionMode||"sequential"};if(t.type&&t.config)return t;const e=t;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((o,i)=>jn(o)),executionMode:"sequential"};let n,r="translation";return e.rotation?(r="rotation",n=e.rotation):e.translation?(r="translation",n=e.translation):e.scale?(r="scale",n=e.scale):(r="translation",n={direction:"horizontal",distance:0}),{type:r,config:n,targetGroup:e.targetGroup}}const Hs=t=>{if(t.length===0)return[0,0];let e=0,n=0;for(const[r,s]of t)e+=r,n+=s;return[e/t.length,n/t.length]},ti=t=>{if(or(t)){const e=t;if(!e.config)return`${e.type}变换缺少配置`;switch(e.type){case"translation":if(e.config.distance<=0)return"平移距离必须大于0";break;case"rotation":if(e.config.startAngle===e.config.endAngle)return"旋转起始角度和结束角度不能相同";break;case"scale":const n=e.config;if(n.startScale<=0||n.endScale<=0)return"缩放比例必须大于0";break}return null}if(ir(t)){const e=t;if(!e.transforms)return"复合变换缺少transforms字段";for(const n of e.transforms){const r=ti(n);if(r)return`复合变换子配置错误: ${r}`}return null}return"未知的变换配置类型"},Sy=(t,e,n,r)=>{if(t<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(n.animated.length===0)return"至少需要一个动画图形";const s=ti(r);if(s)return`全局变换配置错误: ${s}`;for(const o of n.animated)if(o.transform){const i=jn(o.transform),a=ti(i);if(a)return`形状"${o.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const o of[...n.static,...n.animated]){if(!o.vertices||o.vertices.length<2)return`形状"${o.metadata?.id||"未知"}"缺少有效的顶点数据`;for(const i of o.vertices){if(!Array.isArray(i)||i.length!==2)return`形状"${o.metadata?.id||"未知"}"顶点格式错误`;const[a,l]=i;if(typeof a!="number"||typeof l!="number"||!isFinite(a)||!isFinite(l))return`形状"${o.metadata?.id||"未知"}"顶点坐标无效`}}return null},Cy=t=>{const{base:e,height:n,shapes:r,transform:s}=t,o=jn(s),i=Sy(e,n,r,o);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},Ry=t=>{if(t.slider){const{slider:e}=t;if(e.length<=0)return"滑块长度必须大于0";if(e.min!==void 0&&e.max!==void 0&&e.min>=e.max)return"滑块最小值必须小于最大值";if(e.step!==void 0&&e.step<=0)return"滑块步长必须大于0"}return null},Ay=t=>{if(!t)return null;if(t.boundingBox){const[e,n,r,s]=t.boundingBox;if(e>=r||n<=s)return"画板边界框配置无效:left < right 且 top > bottom"}return t.gridSize!==void 0&&t.gridSize<=0?"网格大小必须大于0":null},Ny=t=>{const e=Cy({base:t.base,height:t.height,shapes:t.shapes,transform:t.transform});if(e)return e;const n=Ry(t.animation);if(n)return{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()};const r=Ay(t.boardConfig);return r?{code:"INVALID_CONFIG",message:r,timestamp:new Date().toISOString()}:t.autoCompleteThreshold!==void 0&&(t.autoCompleteThreshold<0||t.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class Ws{validateNumber(e,n,r,s){if(typeof e!="number"||isNaN(e))return`${n}必须是有效的数字`;if(r!==void 0&&e<r)return`${n}不能小于${r}`;if(s!==void 0&&e>s)return`${n}不能大于${s}`}validateArray(e,n,r){if(!Array.isArray(e))return`${n}必须是数组`;if(r!==void 0&&e.length!==r)return`${n}必须是长度为${r}的数组`}validateString(e,n,r){if(typeof e!="string")return`${n}必须是字符串`;if(r!==void 0&&!r.includes(e))return`${n}必须是以下值之一: ${r.join(", ")}`}createValidationResult(e,n,r){return{isValid:e,errors:n?.filter(Boolean),warnings:r?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let n=0;n<e.length;n++){const r=e[n],s=this.validateArray(r,`顶点[${n}]`,2);if(s)return s;const[o,i]=r,a=this.validateNumber(o,`顶点[${n}].x`),l=this.validateNumber(i,`顶点[${n}].y`);if(a||l)return`${a||l} (顶点[${n}])`}}}const Ey=(t,e,n)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:t,progress:e,config:n,distance:n.distance,distanceType:typeof n.distance,direction:n.direction,directionType:typeof n.direction,configType:typeof n,configKeys:Object.keys(n)});let r;n.direction==="horizontal"?r=[n.distance,0]:n.direction==="vertical"?r=[0,n.distance]:r=[n.direction[0]*n.distance,n.direction[1]*n.distance];const s=r[0]*e,o=r[1]*e;return process.env.NODE_ENV==="development"&&console.log("📐 [calculateTranslation] 计算结果:",{directionVector:r,offsetX:s,offsetY:o,firstVertexOriginal:t[0],firstVertexTransformed:[t[0][0]+s,t[0][1]+o]}),t.map(([i,a])=>[i+s,a+o])},ky=(t,e,n)=>{const r=n.center==="auto"?Hs(t):n.center,[s,o]=r,i=n.endAngle-n.startAngle,a=n.direction==="clockwise"?-1:1,l=n.startAngle+i*e*a;return t.map(([c,d])=>{const f=c-s,g=d-o,h=Math.cos(l),m=Math.sin(l);return[s+f*h-g*m,o+f*m+g*h]})},Ty=(t,e,n)=>{const r=n.center==="centroid"?Hs(t):n.center,[s,o]=r,i=n.endScale-n.startScale,a=n.startScale+i*e;return t.map(([l,c])=>{const d=l-s,f=c-o;return[s+d*a,o+f*a]})},My=(t,e=.95)=>t>=e;class jy extends Ws{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,n,r){return Ey(e,n,r)}validate(e){const n=[],r=[];if(typeof e.direction=="string"){const o=this.validateString(e.direction,"direction",["horizontal","vertical"]);o&&n.push(o)}else if(Array.isArray(e.direction)){const o=this.validateArray(e.direction,"direction",2);if(o)n.push(o);else{const[i,a]=e.direction,l=this.validateNumber(i,"direction[0]"),c=this.validateNumber(a,"direction[1]");l&&n.push(l),c&&n.push(c)}}else n.push("direction必须是字符串或数组");const s=this.validateNumber(e.distance,"distance",0);if(s&&n.push(s),e.startOffset!==void 0){const o=this.validateNumber(e.startOffset,"startOffset",0,1);o&&r.push(o)}if(Array.isArray(e.direction)){const[o,i]=e.direction;Math.sqrt(o*o+i*i)<.001&&r.push("方向向量长度过小,可能导致变换效果不明显")}return this.createValidationResult(n.length===0,n,r)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,n){const r=this.getDirectionVector(e),s=e.startOffset||0,o=Math.max(0,Math.min(1,n-s))/(1-s);return[r[0]*e.distance*o,r[1]*e.distance*o]}}class $y extends Ws{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,n,r){return ky(e,n,r)}validate(e){const n=[],r=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)n.push(a);else{const[l,c]=e.center,d=this.validateNumber(l,"center[0]"),f=this.validateNumber(c,"center[1]");d&&n.push(d),f&&n.push(f)}}else n.push('center必须是"auto"或数组[x, y]');const s=this.validateNumber(e.startAngle,"startAngle");s&&n.push(s);const o=this.validateNumber(e.endAngle,"endAngle");if(o&&n.push(o),!s&&!o){const a=Math.abs(e.endAngle-e.startAngle);a<.001&&r.push("角度范围过小,可能导致变换效果不明显"),a>4*Math.PI&&r.push("角度范围过大,可能超过2圈")}const i=this.validateString(e.direction,"direction",["clockwise","counterclockwise","horizontal","vertical"]);return i&&n.push(i),this.createValidationResult(n.length===0,n,r)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=e[0][0],r=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];n=Math.min(n,a),r=Math.max(r,a),s=Math.min(s,l),o=Math.max(o,l)}return{minX:n,maxX:r,minY:s,maxY:o}}getActualCenter(e,n){return n.center==="auto"?Hs(e):n.center}calculateCurrentAngle(e,n){const r=e.endAngle-e.startAngle,s=e.direction==="clockwise"?-1:1;return e.startAngle+r*n*s}}class Oy extends Ws{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,n,r){return Ty(e,n,r)}validate(e){const n=[],r=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)n.push(i);else{const[a,l]=e.center,c=this.validateNumber(a,"center[0]"),d=this.validateNumber(l,"center[1]");c&&n.push(c),d&&n.push(d)}}else n.push('center必须是"centroid"或数组[x, y]');const s=this.validateNumber(e.startScale,"startScale",.01);s&&n.push(s);const o=this.validateNumber(e.endScale,"endScale",.01);if(o&&n.push(o),!s&&!o){const i=e.endScale/e.startScale;Math.abs(e.endScale-e.startScale)<.01&&r.push("缩放比例变化过小,可能导致变换效果不明显"),i>10&&r.push("缩放比例过大,可能导致图形变形严重"),i<.1&&r.push("缩放比例过小,可能导致图形几乎不可见")}return typeof e.uniform!="boolean"?n.push("uniform必须是布尔值"):e.uniform||r.push("非均匀缩放可能导致图形变形"),this.createValidationResult(n.length===0,n,r)}getActualCenter(e,n){return n.center==="centroid"?Hs(e):n.center}calculateCurrentScale(e,n){const r=e.endScale-e.startScale;return e.startScale+r*n}calculateSizeChange(e,n,r){if(e.length<2)return{widthChange:0,heightChange:0,areaChange:0};const s=this.calculateBounds(e),o=s.maxX-s.minX,i=s.maxY-s.minY,a=o*i,l=this.calculateCurrentScale(n,r),c=(n.uniform,l),d=o*c,f=i*c,g=d*f;return{widthChange:(d-o)/o,heightChange:(f-i)/i,areaChange:(g-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=e[0][0],r=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];n=Math.min(n,a),r=Math.max(r,a),s=Math.min(s,l),o=Math.max(o,l)}return{minX:n,maxX:r,minY:s,maxY:o}}}function Ha(t){let e=t.trim().replace(/^#/,"");if((e.length===3||e.length===4)&&(e=e.split("").map(o=>o+o).join("")),e.length!==6&&e.length!==8)throw new Error(`无效的十六进制颜色格式: ${t}`);const n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);if(isNaN(n)||isNaN(r)||isNaN(s))throw new Error(`无效的十六进制颜色值: ${t}`);return[n,r,s]}function Iy(t,e,n){const r=a=>Math.max(0,Math.min(255,Math.round(a))),s=r(t).toString(16).padStart(2,"0"),o=r(e).toString(16).padStart(2,"0"),i=r(n).toString(16).padStart(2,"0");return`#${s}${o}${i}`.toUpperCase()}function ni(t){const e=t.trim();if(e.startsWith("#"))return Ha(e);const n=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(n){const o=parseInt(n[1],10),i=parseInt(n[2],10),a=parseInt(n[3],10);if(o>=0&&o<=255&&i>=0&&i<=255&&a>=0&&a<=255)return[o,i,a]}const r={red:"#FF0000",green:"#00FF00",blue:"#0000FF",yellow:"#FFFF00",cyan:"#00FFFF",magenta:"#FF00FF",black:"#000000",white:"#FFFFFF",gray:"#808080",grey:"#808080",transparent:"transparent"},s=e.toLowerCase();if(r[s])return s==="transparent"?[0,0,0]:Ha(r[s]);throw new Error(`无法解析的颜色格式: ${t}`)}function Es(t){try{return ni(t),!0}catch{return!1}}function Py(t,e,n){if(n<=0)return t;if(n>=1)return e;try{const r=ni(t),s=ni(e),o=r[0]+(s[0]-r[0])*n,i=r[1]+(s[1]-r[1])*n,a=r[2]+(s[2]-r[2])*n;return Iy(o,i,a)}catch(r){return console.warn("颜色插值失败,返回起始颜色:",r),t}}function Pd(t,e,n,r="linear"){let s=n;switch(r){case"ease-in":s=n*n;break;case"ease-out":s=1-(1-n)*(1-n);break;case"ease-in-out":s=n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2;break;case"step":s=n>=1?1:0;break}return Py(t,e,s)}class Fy extends Ws{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,n,r){return e}validate(e){const n=[],r=[];if(!e.targetColor||typeof e.targetColor!="string"?n.push("targetColor 是必需的且必须是字符串"):Es(e.targetColor)||n.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?n.push("fromColor 必须是字符串"):Es(e.fromColor)||n.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const s=this.validateNumber(e.startAt,"startAt",0,1);s&&n.push(s)}if(e.endAt!==void 0){const s=this.validateNumber(e.endAt,"endAt",0,1);s&&n.push(s)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&n.push("startAt 必须小于 endAt"),e.easing!==void 0){const s=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);s&&n.push(s)}return e.targetColor&&e.fromColor,this.createValidationResult(n.length===0,n,r)}calculateCurrentColor(e,n,r){const s=n.fromColor||r,o=n.targetColor,i=this.calculateEffectiveProgress(e,n);return Pd(s,o,i,n.easing)}calculateEffectiveProgress(e,n){const r=n.startAt??0,s=n.endAt??1;return e<=r?0:e>=s?1:(e-r)/(s-r)}isActive(e,n){const r=n.startAt??0,s=n.endAt??1;return e>=r&&e<=s}}class Dy{executors=new Map;register(e){this.executors.has(e.type)&&console.warn(`执行器类型 "${e.type}" 已存在,将被覆盖`),this.executors.set(e.type,e)}get(e){return this.executors.get(e)}has(e){return this.executors.has(e)}getSupportedTypes(){return Array.from(this.executors.keys())}getExecutorDisplayNames(){const e={};for(const[n,r]of this.executors)e[n]=r.getDisplayName();return e}validateConfig(e,n){const r=this.get(e);return r?r.validate(n):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,n,r,s){const o=this.get(e);if(!o)return console.error(`不支持变换类型: ${e}`),n;const i=o.validate(s);return i.isValid?o.execute(n,r,s):(console.error("配置验证失败:",i.errors),n)}executeTransforms(e,n,r){let s=n;for(const o of e){const i=this.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}s=i.execute(s,r,o.config)}return s}getDefaultConfig(e){return this.get(e)?.getDefaultConfig()}clear(){this.executors.clear()}size(){return this.executors.size}}let Qt=null;function Fd(){return Qt||(Qt=new Dy,Qt.register(new jy),Qt.register(new $y),Qt.register(new Oy),Qt.register(new Fy)),Qt}class ri{static matchesShape(e,n,r){if(!n)return!r||this.extractGroupId(e)===r;if("targetGroup"in n&&n.targetGroup)return this.matchesSimpleGroup(e,n.targetGroup,n.metadataField);if("pattern"in n){if(n.strategy==="any")return this.matchesWithConfig(e,n);if(n.pattern)return this.matchesWithConfig(e,n)}return!1}static matchesSimpleGroup(e,n,r){const s=this.extractGroupId(e,r);if(!s)return!1;if(n.includes("*")){const o=n.replace(/\*/g,".*");return new RegExp(`^${o}$`).test(s)}return s===n}static matchesWithConfig(e,n){const r=this.extractGroupId(e,n.metadataField);if(!r)return!1;const s=n.pattern,o=n.strategy||"exact",i=n.caseSensitive||!1;switch(o){case"exact":return i?r===s:r.toLowerCase()===s.toLowerCase();case"wildcard":const a=s.replace(/\*/g,".*");return new RegExp(`^${a}$`,i?"":"i").test(r);case"regex":return(s instanceof RegExp?s:new RegExp(s,i?"":"i")).test(r);case"multiple":return(Array.isArray(s)?s:s.split(",")).some(d=>this.matchesSimpleGroup(e,d,n.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,n="rotationGroup"){if(!e)return;const r=n.split(".");let s=e;for(const o of r){if(s==null)return;s=s[o]}return typeof s=="string"?s:void 0}static validateConfig(e){const n=[],r=[];if(!e||typeof e!="object")return n.push("配置必须是对象"),{isValid:!1,errors:n,warnings:r};switch(e.pattern||n.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&n.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&n.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&n.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:n.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&n.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&n.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&r.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:n.length===0,errors:n,warnings:r}}static convertToGroupMatchConfig(e,n){if(!e)return;const r=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:r,metadataField:n}}}function Ly(t,e,n){return!e&&!n?t.filter(r=>!r.targetGroup&&!r.groupMatch):t.filter(r=>{if(r.groupMatch&&n)return ri.matchesShape(n,r.groupMatch);if(r.targetGroup){if(!e)return!1;if(r.targetGroup.includes("*")){const s=r.targetGroup.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r.targetGroup===e}return!e})}class zy{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,n,r,s,o){const i=this.validate(r);if(!i.isValid)return console.error("复合变换配置验证失败:",i.errors),e;const a=this.filterTransformsByGroup(r.transforms,s,o);if(a.length===0)return e;switch(r.executionMode){case"sequential":return this.executeSequentially(e,n,a);case"parallel":return this.executeInParallel(e,n,a);default:return console.warn(`未知的执行模式: ${r.executionMode},使用顺序执行`),this.executeSequentially(e,n,a)}}validate(e){const n=[],r=[];if(!e||e.type!=="composite")return n.push("配置必须是复合变换类型"),this.createValidationResult(!1,n,r);if(!Array.isArray(e.transforms))return n.push("transforms必须是数组"),this.createValidationResult(!1,n,r);e.transforms.length===0&&r.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&n.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],l=this.validateSingleTransform(a,i);l&&n.push(l)}const s=e.transforms.map(i=>i.id).filter(Boolean),o=new Set(s);return s.length!==o.size&&r.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(n.length===0,n,r)}getTransformInfo(e){const n=e.transforms.map(s=>s.type),r=Array.from(new Set(e.transforms.map(s=>s.targetGroup).filter(s=>s!==void 0)));return{count:e.transforms.length,types:n,groups:r,executionMode:e.executionMode}}filterTransformsByGroup(e,n,r){return Ly(e,n,r)}getTransformsForGroup(e,n,r){return this.filterTransformsByGroup(e.transforms,n,r)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,n,r){let s=e;for(const o of r){const i=this.registry.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}const a=i.validate(o.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${o.type}`,a.errors);continue}s=i.execute(s,n,o.config)}return s}executeInParallel(e,n,r){if(r.length===0)return e;if(r.length===1)return this.executeSequentially(e,n,r);const s=[];for(const o of r){const i=this.registry.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}const a=i.validate(o.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${o.type}`,a.errors);continue}const l=i.execute(e,n,o.config);s.push(l)}return s.length===0?e:this.calculateAverageVertices(s)}calculateAverageVertices(e){if(e.length===0)return[];const n=e[0].length;for(const s of e)if(s.length!==n)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const r=[];for(let s=0;s<n;s++){let o=0,i=0;for(const a of e)o+=a[s][0],i+=a[s][1];r.push([o/e.length,i/e.length])}return r}validateSingleTransform(e,n){if(!e||typeof e!="object")return`变换[${n}]必须是对象`;if(!e.type)return`变换[${n}]缺少type字段`;if(!e.config)return`变换[${n}]缺少config字段`;const r=this.registry.get(e.type);if(!r)return`变换[${n}]不支持的变换类型: ${e.type}`;const s=r.validate(e.config);if(!s.isValid)return`变换[${n}]配置验证失败: ${s.errors?.join(", ")}`}createValidationResult(e,n,r){return{isValid:e,errors:n?.filter(Boolean),warnings:r?.filter(Boolean)}}getDefaultRegistry(){return Fd()}}class Vy{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new zy(this.registry)}executeShapeTransform(e,n,r){const s=this.getEffectiveTransform(e,r);return s?this.executeTransform(e.vertices,n,s,e.metadata):e.vertices}executeTransform(e,n,r,s){if(!r)return e;const o=ri.extractGroupId(s,"rotationGroup");return or(r)?this.executeSingleTransform(e,n,r,s,o):ir(r)?this.compositor.execute(e,n,r,o,s):(console.error("未知的变换类型:",r),e)}getEffectiveTransform(e,n){return e.transform?e.transform:n}getTransformInfo(e){return e?or(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:ir(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?or(e)?this.validateSingleTransform(e):ir(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?or(e)?!1:ir(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,n,r){return e.map(s=>({...s,vertices:this.executeShapeTransform(s,n,r)}))}executeSingleTransform(e,n,r,s,o){if(!ri.matchesShape(s,r.groupMatch||(r.targetGroup?{targetGroup:r.targetGroup}:void 0),o))return e;const a=this.registry.get(r.type);if(!a)return console.error(`不支持变换类型: ${r.type}`),e;const l=a.validate(r.config);return l.isValid?a.execute(e,n,r.config):(console.error("变换配置验证失败:",l.errors),e)}validateSingleTransform(e){const n=this.registry.get(e.type);return n?n.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return Fd()}}const Gy=()=>{const t=x.useRef(null),e=x.useCallback((s,o,i=50)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{o&&o(s)},i)},[]),n=x.useCallback((s,o)=>{const i=Math.round(s*100);return o&&o>1?`阶段 ${s>=1?o:Math.min(Math.floor(s*o)+1,o)}/${o} (${i}%)`:`${i}%`},[]),r=x.useCallback(()=>(t.current&&(clearTimeout(t.current),t.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:My,getProgressLabel:n,resetProgress:r}},Uy=()=>{const t=x.useCallback((n,r,s=.05)=>{let o=r;switch(n.key){case"ArrowRight":case"ArrowUp":o=Math.min(r+s,1);break;case"ArrowLeft":case"ArrowDown":o=Math.max(r-s,0);break;case"Home":o=0;break;case"End":o=1;break;case"PageUp":o=Math.min(r+s*2,1);break;case"PageDown":o=Math.max(r-s*2,0);break;case" ":case"Enter":o=r>=.95?0:1;break;case"Escape":o=0;break;default:return null}return n.preventDefault(),o},[]),e=x.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
12
+ `),[]);return{handleKeyDown:t,getNavigationInstructions:e}},Wa=Ic.JSXGraph,By=t=>{const{base:e,height:n,unit:r,layoutDensity:s="default",boardHeight:o,shapes:i,transform:a,animation:l,boardConfig:c={},theme:d="light",className:f="",enableRigidityVerification:g=!1,enableKeyboardNavigation:h=!0,autoCompleteThreshold:m=.95,boardWidth:p,onTransformStart:y,onTransformChange:b,onTransformComplete:w,onError:v}=t,[S,_]=x.useState(0),[A,C]=x.useState(null),[R,N]=x.useState(0),[M,F]=x.useState(null),[D,P]=x.useState({width:800,height:560}),$=x.useMemo(()=>new Vy,[]),O=x.useMemo(()=>jn(a),[a]),T=x.useRef(null),B=x.useRef({}),j=x.useRef(null),{handleProgressChange:Q,shouldAutoComplete:oe,resetProgress:se}=Gy(),{handleKeyDown:ee,getNavigationInstructions:L}=Uy();x.useEffect(()=>{const z=()=>{if(j.current){const{clientWidth:k}=j.current;if(k>0){const de=c.boundingBox||[0,7,10,0],ye=de[2]-de[0],W=de[1]-de[3];let te;o?te=o:te=Math.round(k*(W/ye)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:de,ratio:`${W}:${ye}`,containerWidth:k,calculatedHeight:te,isCustomHeight:!!o}),P({width:k,height:te})}}};z(),window.addEventListener("resize",z);const I=new ResizeObserver(z);return j.current&&I.observe(j.current),()=>{window.removeEventListener("resize",z),I.disconnect()}},[c.boundingBox,o]);const X={width:p??`${D.width}px`,height:`${D.height}px`},ae=x.useCallback((z,I)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:z.metadata?.id,shapeType:z.type,progress:I,hasMetadata:!!z.metadata,hasDynamicAppearance:!!z.metadata?.dynamicAppearance,dynamicAppearance:z.metadata?.dynamicAppearance});const k=z.metadata?.dynamicAppearance,de=z.style||{};let ye;if(z.transform?.type==="fillcolor_set"&&z.transform.fillColorSet){const be=z.transform.fillColorSet,{targetColor:Ae,startAt:je=0,endAt:Pe=1,easing:Ze="linear",fromColor:ft}=be;if(Es(Ae)&&(!ft||Es(ft))){let Qe=I;I<je?Qe=0:I>Pe?Qe=1:Qe=(I-je)/(Pe-je);const qn=ft||de.fillColor||"#FFFFFF";ye=Pd(qn,Ae,Qe,Ze),console.log("🎨 fillcolor_set applied:",{shapeId:z.metadata?.id,progress:I,effectiveProgress:Qe,startColor:qn,targetColor:Ae,resultColor:ye})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:Ae,fromColor:ft})}if(!k)return console.log("📝 No dynamicAppearance, returning base style"),ye?{...de,fillColor:ye}:de;const W=be=>{if(!be)return 1;const Ae=be.threshold??.5,je=be.startValue??0,Pe=be.endValue??1,Ze=be.type??"step";if(Ze==="step")return I>=Ae?Pe:je;if(Ze==="fade"){if(I<Ae)return je;{const ft=Math.min((I-Ae)/(1-Ae),1);return je+(Pe-je)*ft}}return 1},te={...de};let Xt=!0;const ut=W(k.visibility),Jt=W(k.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:z.metadata?.id,progress:I,visibilityValue:ut,labelVisibilityValue:Jt,hasVisibility:!!k.visibility,hasLabelVisibility:!!k.labelVisibility}),k.visibility&&(te.fillOpacity===void 0&&(te.fillOpacity=1),te.fillOpacity*=ut,ut===0&&(te.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),te.strokeColor,Xt=ut>0,console.log("👁️ Shape visibility:",{shapeId:z.metadata?.id,visible:Xt,visibilityValue:ut})),k.labelVisibility){const be=Jt>0;te.labelVisible=be,console.log("🏷️ Label visibility:",{shapeId:z.metadata?.id,labelVisible:be,labelVisibilityValue:Jt,hasLabel:!!z.metadata?.label})}if(k.opacity){const be=k.opacity,Ae=be.startAt??0,je=be.endAt??1,Pe=be.from??1,Ze=be.to??1,ft=be.type??"linear";let Qe=Pe;if(I<Ae)Qe=Pe;else if(I>je)Qe=Ze;else{const qn=(I-Ae)/(je-Ae);Qe=Pe+(Ze-Pe)*qn}te.fillOpacity=Qe}if(ye)te.fillColor=ye,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:z.metadata?.id,transformColor:ye});else if(k.color){const be=k.color,Ae=be.startAt??0,je=be.endAt??1,Pe=be.from??te.fillColor,Ze=be.to??te.fillColor,ft=be.type??"gradient";if(Pe&&Ze)if(I<Ae)te.fillColor=Pe;else if(I>je)te.fillColor=Ze;else{const Qe=(I-Ae)/(je-Ae);ft==="gradient"?te.fillColor=Ze:te.fillColor=Qe>=.5?Ze:Pe}}return te.visible=Xt,te.labelVisible===void 0&&(te.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:z.metadata?.id,visible:te.visible,labelVisible:te.labelVisible,fillOpacity:te.fillOpacity,strokeWidth:te.strokeWidth}),te},[]),ve=x.useCallback((z,I,k=!1,de=0)=>{console.log("🎨 createShape called:",{shapeId:I.metadata?.id,shapeType:I.type,isStatic:k,progress:de,verticesLength:I.vertices?.length,hasMetadata:!!I.metadata,hasDynamicAppearance:!!I.metadata?.dynamicAppearance});const ye=I.type==="point"?1:2;if(!z||!I.vertices||I.vertices.length<ye)return console.warn(`⚠️ createShape: invalid board or vertices for ${I.type}`,{shapeId:I.metadata?.id,shapeType:I.type,verticesLength:I.vertices?.length,minVertices:ye}),null;const W=ae(I,de);let te;switch(I.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const Xt=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,ut=I.metadata?.label||I.metadata?.id||"";te=z.create("polygon",I.vertices,{name:ut,fillColor:W.fillColor!==void 0?W.fillColor:k?"#8ec5fc":"#6a5acd",fillOpacity:W.fillOpacity!==void 0?W.fillOpacity:k?.3:.7,strokeColor:W.strokeColor!==void 0?W.strokeColor:k?"#0074d9":"#4b0082",strokeWidth:W.strokeWidth!==void 0?W.strokeWidth:k?1:2,dash:W.dashStyle!==void 0?W.dashStyle:0,fixed:k,highlight:!k,withLabel:Xt,visible:W.visible!==void 0?W.visible:!0});break;case"circle":if(I.vertices.length>=2){const[Jt,be]=I.vertices,Ae=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,je=I.metadata?.label||I.metadata?.id||"";te=z.create("circle",[Jt,be],{name:je,fillColor:W.fillColor!==void 0?W.fillColor:k?"#8ec5fc":"#6a5acd",fillOpacity:W.fillOpacity!==void 0?W.fillOpacity:k?.3:.7,strokeColor:W.strokeColor!==void 0?W.strokeColor:k?"#0074d9":"#4b0082",strokeWidth:W.strokeWidth!==void 0?W.strokeWidth:k?1:2,dash:W.dashStyle!==void 0?W.dashStyle:0,fixed:k,highlight:!k,withLabel:Ae})}break;case"point":if(I.vertices.length>=1){const[Jt,be]=I.vertices[0],Ae=W.labelVisible!==void 0?W.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,je=I.metadata?.label||I.metadata?.id||"";te=z.create("point",[Jt,be],{name:je,withLabel:Ae,fixed:k,size:4,strokeColor:W.strokeColor!==void 0?W.strokeColor:k?"#0074d9":"#4b0082",fillColor:W.fillColor!==void 0?W.fillColor:k?"#8ec5fc":"#6a5acd",visible:W.visible!==void 0?W.visible:!0,highlight:!k})}break;default:return console.warn(`Unsupported shape type: ${I.type}`),null}return console.log("✅ createShape finished:",{shapeId:I.metadata?.id,elementType:te?.type,elementName:te?.name,fillOpacity:te?.getAttribute?.("fillOpacity"),strokeWidth:te?.getAttribute?.("strokeWidth"),labelVisible:W.labelVisible,hasLabel:!!I.metadata?.label,withLabel:!!I.metadata?.label&&W.labelVisible}),te},[ae]);x.useEffect(()=>{if(!(e>0&&n>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:n,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:n>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig});const I=Ny(t);console.log("🔍 GeometryTransform: 验证结果 =",I),C(I),I&&v&&v(I)},[e,n,i,a,l,c,v,t]),x.useEffect(()=>{if(T.current){try{const z=c.boundingBox||[0,7,10,0],I=d==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",c.boundingBox),console.warn(" - Container dimensions:",D.width,"x",D.height),console.warn(" - Container actual dimensions:",T.current.clientWidth,"x",T.current.clientHeight);const k=Wa.initBoard(T.current,{boundingbox:z,keepaspectratio:c.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:c.showAxis??!0,grid:c.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),de=c.axisColor||(I?"#ffffff":"#000000"),ye=c.gridColor||(I?"#444444":"#dddddd");k.defaultAxes?.x&&k.defaultAxes.x.setAttribute({strokeColor:de}),k.defaultAxes?.y&&k.defaultAxes.y.setAttribute({strokeColor:de}),k.defaultGrid&&k.defaultGrid.setAttribute({strokeColor:ye}),F(k)}catch(z){const I={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:z,timestamp:new Date().toISOString()};C(I),v?.(I)}return()=>{if(M)try{Wa.freeBoard(M)}catch(z){z instanceof Error&&z.name!=="AbortError"&&console.warn("Board cleanup warning:",z)}}}},[D]),x.useEffect(()=>{if(M)try{M.suspendUpdate(),Object.values(B.current).forEach(z=>{if(z&&M.removeObject)try{M.removeObject(z)}catch{}}),B.current={},i.static.forEach((z,I)=>{const k=z.metadata?.id||`static-${I}`,de=ve(M,z,!0,0);de&&(B.current[k]=de)}),i.animated.forEach((z,I)=>{const k=z.metadata?.id||`animated-${I}`,de=ve(M,z,!1,0);de&&(B.current[k]=de)}),M.unsuspendUpdate(),y&&y()}catch(z){const I={code:"RENDER_ERROR",message:"图形渲染失败",details:z,timestamp:new Date().toISOString()};C(I),v?.(I)}},[M,i,e,n]),x.useEffect(()=>{if(M){M.suspendUpdate();try{i.animated.forEach((k,de)=>{const ye=k.metadata?.id||`animated-${de}`,W=B.current[ye];if(W){try{M.removeObject(W)}catch{}delete B.current[ye]}}),i.animated.forEach((k,de)=>{const ye=k.metadata?.id||`animated-${de}`,W=k.transform?{...k,transform:jn(k.transform)}:k,te=$.executeShapeTransform(W,S,O),Xt={...k,vertices:te,metadata:{...k.metadata,id:ye,transformSource:k.transform?"shape":"global"}},ut=ve(M,Xt,!1,S);ut&&(B.current[ye]=ut)});const z=l.progressIndicator?.stages||1,I=Math.min(Math.floor(S*z),z-1);N(I)}catch(z){if(z instanceof Error&&z.name==="AbortError")return;console.warn("Transform update failed:",z)}finally{try{M.unsuspendUpdate()}catch{}}}},[M,S,i,a,l,ve,O,$]);const me=x.useCallback(z=>{const I=Array.isArray(z)?z[0]:z;_(I),Q(I,k=>{b?.(k)}),oe(I,m)&&(_(1),w?.())},[b,w,m,Q,oe]);x.useEffect(()=>{if(!h)return;const z=I=>{const k=ee(I,S);k!==null&&k!==S&&me(k)};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}},[h,S,me,ee]),x.useCallback(()=>{_(0),N(0),se()},[se]);const Ft=x.useCallback(()=>{C(null),_(0),N(0),se()},[se]);return e>0&&n>0&&i?.animated?.length>0?A?u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${f}`,children:u.jsx(H.CardBody,{"data-testid":"card-body",children:u.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[u.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:u.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),u.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),u.jsx("h3",{children:"几何变换演示加载失败"}),u.jsx("p",{children:A.message}),A.details&&u.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[u.jsx("summary",{children:"查看错误详情"}),u.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(A.details,null,2)})]}),u.jsx("div",{className:"geometry-transform__error-actions",children:u.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:Ft,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform ${s==="compact"?"geometry-transform--compact":""} ${d==="dark"?"geometry-transform--dark":""} ${f}`,children:u.jsxs(H.CardBody,{"data-testid":"card-body",children:[u.jsxs("div",{ref:j,className:"geometry-transform__board-container",children:[u.jsx("div",{ref:T,id:"geometry-board",className:"geometry-transform__board",style:X,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),u.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),u.jsxs("div",{className:"geometry-transform__controls",children:[u.jsx("div",{className:"geometry-transform__slider-group",children:u.jsx(H.Slider,{id:"transform-slider","data-testid":"slider",value:S,onChange:me,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),h&&u.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:u.jsxs("details",{children:[u.jsx("summary",{children:"键盘导航说明"}),u.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:L()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:n,shapesAnimatedLength:i?.animated?.length,error:A}),u.jsx(H.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${f}`,children:u.jsx(H.CardBody,{"data-testid":"card-body",children:u.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},Dd=x.memo(By,(t,e)=>{if(t.base!==e.base||t.height!==e.height||t.unit!==e.unit||t.theme!==e.theme||t.className!==e.className||t.enableRigidityVerification!==e.enableRigidityVerification||t.enableKeyboardNavigation!==e.enableKeyboardNavigation||t.autoCompleteThreshold!==e.autoCompleteThreshold||t.onTransformStart!==e.onTransformStart||t.onTransformChange!==e.onTransformChange||t.onTransformComplete!==e.onTransformComplete||t.onError!==e.onError)return!1;const n=JSON.stringify({shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig}),r=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return n===r}),Oi=Dn.create((t,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:n=>{t({internalValue:Math.max(0,Math.min(1,n))})},startDrag:n=>{t({isDragging:!0,dragState:{isDragging:!0,startIndex:n,currentIndex:n,direction:null}})},updateDrag:n=>{const{dragState:r}=e();let s=null;if(r.startIndex!==-1&&n!==-1){const o=Math.floor(r.startIndex/10),i=r.startIndex%10,a=Math.floor(n/10),l=n%10;a===o?s=l>i?"ltr":"rtl":l===i&&(s=a>o?"ttb":"btt")}t({dragState:{...r,currentIndex:n,direction:s}})},endDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Ld=()=>Oi(Pc.useShallow(t=>({internalValue:t.internalValue,setInternalValue:t.setInternalValue}))),zd=()=>Oi(Pc.useShallow(t=>({isDragging:t.isDragging,dragState:t.dragState,startDrag:t.startDrag,updateDrag:t.updateDrag,endDrag:t.endDrag,resetDrag:t.resetDrag}))),Vd=t=>{const{totalCells:e,fillRatio:n,direction:r,rows:s,cols:o}=t,i=Math.round(e*n),a=[];if(r==="ltr")for(let l=0;l<i;l++)a.push(l);else for(let l=0;l<s;l++)for(let c=0;c<o;c++){const d=l*o+c;a.length<i&&a.push(d)}return{filledCells:a,filledCount:i,actualRatio:i/e}},Gd=(t,e,n,r)=>{const s=[];for(let o=0;o<t;o++)for(let i=0;i<e;i++){const a=o*e+i;s.push({index:a,row:o,col:i,filled:r.includes(a),x:i*n,y:o*n})}return s},Ud=(t,e,n,r,s)=>{if(t===-1||e===-1||!n)return[];const o=Math.floor(t/s),i=t%s,a=Math.floor(e/s),l=e%s,c=[];switch(n){case"ltr":for(let d=i;d<=l;d++)c.push(o*s+d);break;case"rtl":for(let d=i;d>=l;d--)c.push(o*s+d);break;case"ttb":for(let d=o;d<=a;d++)c.push(d*s+i);break;case"btt":for(let d=o;d>=a;d--)c.push(d*s+i);break}return c},Bd=(t,e)=>Math.max(0,Math.min(1,t.length/e)),ms=t=>Math.max(0,Math.min(1,t)),Hy=t=>`${Math.round(t*100)}%`;function Wy(t,e,n,r,s){if(e&&e.length>0)for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.cells.includes(t))return i.color}return n?r:s}const Ii=({value:t,defaultValue:e=0,mode:n="readonly",onChange:r,rows:s=10,cols:o=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:l="#f3f4f6",strokeColor:c="#d1d5db",shadingDirection:d="ltr",hasShadow:f=!0,className:g="",showNumbers:h=!1,highlightGroups:m,numberFontSize:p=10,numberColor:y="#374151"})=>{const{internalValue:b,setInternalValue:w}=Ld(),{isDragging:v,dragState:S,startDrag:_,updateDrag:A,endDrag:C}=zd(),R=t!==void 0,N=R?ms(t):b,[M,F]=x.useState(!1);!M&&!R&&(w(ms(e)),F(!0));const D=x.useMemo(()=>{const X={totalCells:s*o,fillRatio:N,direction:d,rows:s,cols:o};return Vd(X).filledCells},[N,s,o,d]),P=x.useMemo(()=>Gd(s,o,i,D),[s,o,i,D]),$=x.useMemo(()=>!v||S.startIndex===-1||S.currentIndex===-1?[]:Ud(S.startIndex,S.currentIndex,S.direction,s,o),[v,S,s,o]),O=x.useCallback(L=>{if(n!=="edit")return;const X=ms((L+1)/(s*o));R||w(X),r?.(X)},[n,s,o,R,r,w]),T=x.useCallback(L=>{n==="edit"&&_(L)},[n,_]),B=x.useCallback(L=>{n!=="edit"||!v||A(L)},[n,v,A]),j=x.useCallback(()=>{if(!(n!=="edit"||!v)){if($.length>0){const L=Bd($,s*o);R||w(L),r?.(L)}C()}},[n,v,$,s,o,R,r,w,C]),Q=o*i,oe=s*i,se=["hundred-chart-container",`hundred-chart--${n}`,f&&"hundred-chart--has-shadow",g].filter(Boolean).join(" "),ee=Math.round(N*100);return u.jsx("div",{className:se,"data-testid":"hundred-chart-container",children:u.jsx("svg",{width:Q,height:oe,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${ee}% 已填充`,children:P.map(L=>{const X=D.includes(L.index),ae=$.includes(L.index),ve=X||ae,me=L.index+1,Ft=Wy(me,m,ve,a,l);return u.jsxs("g",{"data-testid":"hundred-chart-cell-group",className:"hundred-chart-cell-group",children:[u.jsx("rect",{x:L.x,y:L.y,width:i,height:i,fill:Ft,stroke:c,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":X,"data-drag":ae,"aria-label":`第${L.row+1}行第${L.col+1}列,数字${me},${ve?"已填充":"未填充"}`,tabIndex:n==="edit"?0:-1,onClick:()=>O(L.index),onMouseDown:()=>T(L.index),onMouseEnter:()=>B(L.index),onMouseUp:j,onKeyDown:At=>{n==="edit"&&At.key==="Enter"&&O(L.index)}}),h&&u.jsx("text",{x:L.x+i/2,y:L.y+i/2,textAnchor:"middle",dominantBaseline:"middle",fontSize:p,fill:y,className:"hundred-chart-cell-text",pointerEvents:"none","aria-hidden":"true",children:me})]},L.index)})})})},qy=x.createContext(void 0),Hd=(t,e)=>x.useMemo(()=>{const n=t.scenes?.[e];return{...t,content:n?.content||t.content,layout:n?.layout||t.layout,renderer:n?.renderer||t.renderer}},[t,e]),Wd=({children:t,padding:e,shadow:n=!0,border:r=!0,theme:s="light",className:o=""})=>{const i=s==="dark"?"theme-dark":"",a=n?"with-shadow":"",l=r?"with-border":"",c=e?{"--mc-card-padding":e}:void 0;return u.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${l} ${o}`,style:c,"data-testid":"mathcard-v2-container",children:t})},qd=({children:t,columns:e,gap:n,responsive:r=!0,className:s=""})=>{const o={"--grid-columns":e,"--grid-gap":n},i=r?"mathcard-v2-grid-responsive":"";return u.jsx("div",{style:o,className:`mathcard-v2-grid ${i} ${s}`,"data-testid":"grid-layout",children:t})},Yd=({children:t,direction:e="vertical",gap:n,wrap:r=!1,className:s=""})=>{const o={"--flow-gap":n,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":r?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=r?"wrap":"";return u.jsx("div",{style:o,className:`mathcard-v2-flow ${i} ${a} ${s}`,"data-testid":"flow-layout",children:t})},Kd=({content:t,style:e={},onInteraction:n,className:r=""})=>u.jsx("div",{className:`mathcard-v2-text ${r}`,style:e,onClick:()=>n?.({type:"click",content:t}),"data-testid":"text-content",children:t}),Xd=({parts:t,children:e,displayMode:n=!1,style:r={},className:s=""})=>u.jsx("div",{className:`mathcard-v2-formula ${s}`,style:r,"data-testid":"equation-render",children:u.jsx(Gn,{parts:t,children:e,displayMode:n})});class Yy extends x.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){console.error("MathGraph Error:",e,n.componentStack)}render(){return this.state.hasError?u.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[u.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),u.jsx("p",{className:"text-red-700",children:this.state.error?.message}),u.jsx("button",{className:"mt-2 px-3 py-1 bg-red-100 hover:bg-red-200 rounded",onClick:()=>this.setState({hasError:!1}),children:"重试"})]}):this.props.children}}function Ky(t){if(typeof t!="string")throw new Error(`parseFunctionString expects a string, got ${typeof t}`);const e=t.trim(),n=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(n){const r=(n[3]||n[4]||"").trim();if(!r)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return Xy(r)}catch(s){throw new Error(`Failed to create function from "${e}": ${s}`)}}throw new Error(`Invalid function string format: "${e}". Expected arrow function like "() => progress * Math.PI"`)}function Xy(t){const e=t.trim();if(e==="progress * Math.PI"||e==="progress*Math.PI")return l=>l*Math.PI;if(e==="progress * Math.PI * 2"||e==="progress*Math.PI*2")return l=>l*Math.PI*2;const n=/^progress\s*\*\s*([0-9.]+)$/,r=e.match(n);if(r){const l=parseFloat(r[1]);return c=>c*l}const s=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,o=e.match(s);if(o){const l=parseFloat(o[1]);return c=>c*Math.PI*l}if(e.includes("Math.sin")&&e.includes("progress"))return l=>Math.sin(l*Math.PI);if(e.includes("Math.cos")&&e.includes("progress"))return l=>Math.cos(l*Math.PI);const i=/^([0-9.]+)$/,a=e.match(i);if(a){const l=parseFloat(a[1]);return()=>l}return e==="progress"?l=>l:e.includes("control.value")?(console.warn(`Expression contains control.value: ${e}. Will be handled by parseParamsWithControl.`),l=>l*Math.PI):(console.warn(`Unsupported expression pattern: "${e}". Using generic evaluator.`),l=>{let c=e.replace(/\bprogress\b/g,l.toString());return c=c.replace(/Math\.PI/g,Math.PI.toString()),c=c.replace(/Math\.E/g,Math.E.toString()),Jy(c)})}function Jy(t){const e=t.replace(/\s/g,"");function n(r){for(;r.includes("(");){const a=r.match(/\(([^()]+)\)/);if(!a)break;const l=n(a[1]);r=r.replace(a[0],l.toString())}const s=r.match(/(-?\d+\.?\d*)([*/])(-?\d+\.?\d*)/);if(s){const a=parseFloat(s[1]),l=s[2],c=parseFloat(s[3]),d=l==="*"?a*c:a/c;return r=r.replace(s[0],d.toString()),n(r)}const o=r.match(/(-?\d+\.?\d*)([+\-])(-?\d+\.?\d*)/);if(o){const a=parseFloat(o[1]),l=o[2],c=parseFloat(o[3]),d=l==="+"?a+c:a-c;return r=r.replace(o[0],d.toString()),n(r)}const i=parseFloat(r);if(isNaN(i))throw new Error(`Invalid expression: ${r}`);return i}return n(e)}function Zy(t){return typeof t=="string"&&(t.includes("=>")||t.includes("progress"))}function De(t,e=0){return typeof t=="function"?t(e):t}function _o(t,e,n){switch(t.params.type){case"translate":{const r=t.params,s=typeof r.x=="function"&&n?function(){const i=n.Value();return r.x(i)}:De(r.x,e),o=typeof r.y=="function"&&n?function(){const i=n.Value();return r.y(i)}:De(r.y,e);return[s,o]}case"rotate":{const r=t.params,s=r.center||[0,0];return typeof r.angle=="function"&&n?[function(){const i=n.Value();return r.angle(i)},s[0],s[1]]:[De(r.angle,e),s[0],s[1]]}case"scale":{const r=t.params,s=typeof r.scaleX=="function"&&n?function(){const i=n.Value();return r.scaleX(i)}:De(r.scaleX,e),o=typeof r.scaleY=="function"&&n?function(){const i=n.Value();return r.scaleY(i)}:De(r.scaleY,e);return[s,o]}case"reflect":{const r=t.params;if(r.line)return[r.line];if(r.point1&&r.point2)return[r.point1,r.point2];if(r.p1&&r.p2)return[r.p1,r.p2];throw new Error(`Reflect transform requires one of:
13
13
  1. line ID (string)
14
14
  2. point1 + point2 IDs
15
15
  3. p1 + p2 coordinates
16
- Received: ${JSON.stringify(r)}`)}case"shear":{const r=t.params,s=De(r.shearX,e),o=De(r.shearY,e);return[s,o]}case"generic":{const r=t.params;return[De(r.a,e),De(r.b,e),De(r.c,e),De(r.d,e),De(r.e,e),De(r.f,e),De(r.g,e),De(r.h,e),De(r.i,e)]}case"matrix":{const r=t.params;if(!Array.isArray(r.matrix)||r.matrix.length!==3||!r.matrix.every(s=>Array.isArray(s)&&s.length===3))throw new Error("Matrix transform requires a 3x3 matrix array");return[r.matrix]}default:throw new Error(`Unsupported transform type: ${t.params.type}`)}}function Hy(t){const e={};return Object.entries(t).forEach(([n,r])=>{if(typeof r=="string"&&By(r))try{e[n]=Vy(r)}catch(s){console.warn(`Failed to parse function string for ${n}: ${r}`,s),e[n]=()=>0}else e[n]=r}),e}function Wy(t){if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!t.id||typeof t.id!="string"||t.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(t.transforms)?t.transforms.forEach((n,r)=>{(!n.id||typeof n.id!="string")&&e.push(`Transform at index ${r} must have a valid id`),(!n.type||typeof n.type!="string")&&e.push(`Transform at index ${r} must have a valid type`),(!n.params||typeof n.params!="object")&&e.push(`Transform at index ${r} must have valid params`),Array.isArray(n.targetShapes)?n.targetShapes.length===0&&e.push("targetShapes must not be empty"):e.push(`Transform at index ${r} must have targetShapes array`)}):e.push("Config must have a transforms array"),{valid:e.length===0,errors:e.length>0?e:void 0}}const qa=Ic.JSXGraph,Jd=t=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!t.animation,animationId:t.animation?.id,hasControl:!!t.animation?.control,controlConfig:t.animation?.control,animationProgress:t.animationProgress});const e=x.useRef(null),[n,r]=x.useState(null),[,s]=x.useState({}),[o,i]=x.useState(!1),a=x.useRef({}),l=x.useRef({}),c=x.useRef(null),d=x.useRef({}),f=x.useCallback((h,m)=>{t.onShapeChange},[t.onShapeChange]),g=x.useCallback(h=>{t.onSelectionChange&&t.onSelectionChange(h?[h]:[])},[t.onSelectionChange]);return x.useEffect(()=>{if(e.current){try{const h=t.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",h),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const m=qa.initBoard(e.current,{boundingbox:h,axis:t.showAxis??!0,grid:t.showGrid??!0,showNavigation:!1,pan:{enabled:t.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",m.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",h),console.warn(" * 实际边界框:",m.getBoundingBox()),console.warn(" * 实际显示范围:",{left:m.getBoundingBox()[0],top:m.getBoundingBox()[1],right:m.getBoundingBox()[2],bottom:m.getBoundingBox()[3]})},100),r(m)}catch(h){console.error("JSXGraph initialization failed:",h)}return()=>{n&&qa.freeBoard(n)}}},[]),x.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!n,hasAnimation:!!t.animation,hasControl:!!t.animation?.control,animationId:t.animation?.id,controlType:t.animation?.control?.type,controlPosition:t.animation?.control?.position,controlRange:t.animation?.control?.range}),!n||!t.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!n+", control="+!!t.animation?.control),c.current){try{c.current.remove&&c.current.remove()}catch(m){console.warn("Failed to remove control:",m)}c.current=null}return}const h=t.animation.control;console.warn("✨ Creating Control Component:",{type:h.type,config:h,position:h.position,range:h.range});try{if(h.type==="slider"){const m=h.position[0]+(h.length||5);console.warn("📐 Slider creation parameters:",{startPoint:h.position,endPoint:[m,h.position[1]],values:[h.range[0],h.initial||0,h.range[1]],label:h.label,snapWidth:h.snapWidth||.01});const p=n.create("slider",[h.position,[m,h.position[1]],[h.range[0],h.initial||0,h.range[1]]],{name:h.label||"control",snapWidth:h.snapWidth||.01,withLabel:h.showLabel!==void 0?h.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});c.current=p,console.warn("✅ Slider created:",{id:p.id,name:p.name,initialValue:p.Value(),startPoint:h.position,endPoint:[m,h.position[1]],boundingBox:n.getBoundingBox(),visProp:p.visProp});const y=n.objectsList.map(w=>({id:w.id,type:w.elType,name:w.name,visible:w.visProp?.visible})),b=y.find(w=>w.id===p.id);if(console.warn("📊 Slider in board.objectsList:",!!b,b),console.warn("📊 All board objects count:",y.length),t.onAnimationChange){let w=!1;p.on("drag",()=>{if(w)return;w=!0;const S=(p.Value()-h.range[0])/(h.range[1]-h.range[0]);t.onAnimationChange?.(S),w=!1})}}else if(h.type==="glider"){const m=n.select(h.line,!0);if(m){const p=n.create("glider",[h.initial||0,0,m],{name:h.label||"control",snapWidth:h.snapWidth||.01});if(c.current=p,console.warn("✅ Glider created:",{id:p.id,name:p.name}),t.onAnimationChange){let y=!1;p.on("drag",()=>{if(y)return;y=!0;const b=p.Value();t.onAnimationChange?.(b),y=!1})}}else console.warn(`Reference line not found for glider: ${h.line}`)}}catch(m){console.error("Failed to create control component:",m)}return()=>{if(c.current){try{c.current.remove()}catch(m){console.warn("Failed to remove control on cleanup:",m)}c.current=null}}},[n,t.animation?.control]),x.useEffect(()=>{if(!n||!t.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:t.animation.id,transformCount:t.animation.transforms.length}),Object.values(a.current).forEach(p=>{try{p&&p.remove&&p.remove()}catch(y){console.warn("Failed to remove transform:",y)}}),a.current={};const h={},m=t.animationProgress??0;t.animation.transforms.forEach(p=>{try{let y,b;const w=p.usesControl||!1;if(c.current&&w){y=_o(p,m,c.current),console.warn(`🔧 Creating transform ${p.id} (with dynamic params):`,{type:p.type,paramsTypes:y.map(S=>typeof S),targetShapes:p.targetShapes,controlValue:c.current.Value()}),b=n.create("transform",y,{type:p.type,id:`transform_${p.id}`});const v=()=>{if(!c.current)return;n.update();const S=c.current.Value();if(console.warn(`🎯 Slider drag - transform ${p.id} auto-updated (controlValue: ${S})`),t.onAnimationChange){const _=t.animation?.control?.range||[0,1],A=(S-_[0])/(_[1]-_[0]);t.onAnimationChange(A)}};c.current.on("drag",v),d.current[p.id]=v,console.warn(`🔗 Slider listener attached for transform ${p.id} (auto-update mode)`)}else y=_o(p,m),console.warn(`🔧 Creating transform ${p.id} (with progress ${m}):`,{type:p.type,params:y,targetShapes:p.targetShapes}),b=n.create("transform",y,{type:p.type,id:`transform_${p.id}`});h[p.id]=b,console.warn(`📝 Transform ${p.id} created:`,{type:p.type,paramsTypes:y.map(v=>typeof v),transformMethods:Object.keys(b).filter(v=>typeof b[v]=="function")})}catch(y){console.error(`Failed to create transform ${p.id}:`,y)}}),a.current=h}catch(h){console.error("Transform setup failed:",h)}},[n,t.animation]),x.useEffect(()=>{if(!o||!n||!t.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${o}, board=${!!n}, animation=${!!t.animation}`);return}if(console.warn("✅ Attempting to bind transforms to shapes..."),console.warn(` Available shapes: ${Object.keys(l.current).length}`),console.warn(` Available transforms: ${Object.keys(a.current).length}`),Object.keys(l.current).length===0){console.warn("❌ No shapes available, skipping transform binding");return}if(Object.keys(a.current).length===0){console.warn("❌ No transforms available, skipping binding");return}Object.entries(a.current).forEach(([h,m])=>{const p=t.animation?.transforms.find(b=>b.id===h);if(!p)return;console.warn(`🔍 Binding transform ${h} (type: ${p.type}) to shapes:`,p.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(l.current));const y=p.targetShapes.map(b=>{const w=l.current[b];return w?console.warn(`✅ Found shape ${b}:`,w):(console.warn(`❌ Shape not found for transform binding: ${b}`),console.warn(" Available IDs:",Object.keys(l.current))),w}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",y.length),y.length>0)try{console.warn(`🔗 Attempting to bind transform ${h} to ${y.length} shapes`),m.bindTo(y),console.warn(`✅ Successfully bound transform ${h} to ${y.length} shapes`),console.warn(" Transform object:",m),console.warn(" Target elements:",y.map(b=>({id:b.id,name:b.name,type:b.elementClass})))}catch(b){console.error(`❌ Failed to bind transform ${h}:`,b),console.error(" Transform:",m),console.error(" TargetElements:",y)}else console.warn(`⚠️ No valid target elements for transform ${h}`)}),n.update(),console.warn("✅ All transforms bound and board updated")},[o,n,t.animation]),x.useEffect(()=>{if(!n||Object.keys(a.current).length===0)return;const h=t.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${h}`);try{Object.entries(a.current).forEach(([m,p])=>{const y=t.animation?.transforms.find(w=>w.id===m);if(!y)return;const b=_o(y,h);console.warn(`🔄 Attempting to update transform ${m} with params:`,b),p.update?(console.warn(" Using transform.update(params)"),p.update(b)):p.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),p.setMatrix(n,y.type,b)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(p).filter(w=>typeof p[w]=="function")))}),n.update()}catch(m){console.error("Transform update failed:",m)}},[n,t.animationProgress]),x.useEffect(()=>{if(n)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:t.shapes.length,shapes:t.shapes.map(p=>({id:p.id,type:p.type,hasVertices:"vertices"in p,verticesCount:"vertices"in p&&p.vertices?p.vertices.length:"undefined",hasPosition:"position"in p,hasGeometryRef:"geometryRef"in p,geometryRef:"geometryRef"in p?p.geometryRef:void 0}))}),n.suspendUpdate(),[...n.objectsList].forEach(p=>{n.removeObject(p)});const m={};l.current={},t.shapes.forEach(p=>{if(p.type==="point")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create point shape ${p.id}:`,y)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",n.objectsList.map(p=>({id:p.id,name:p.name,type:p.elementClass}))),t.shapes.forEach(p=>{if(p.type==="line"||p.type==="circle"||p.type==="polygon")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create shape ${p.id}:`,y)}}),console.warn("📝 Starting phase 3: creating text labels"),t.shapes.forEach(p=>{if(p.type==="text")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create text ${p.id}:`,y)}}),s(m),l.current=m,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(m).length} shapes created`),n.unsuspendUpdate()}catch(h){console.error("Shape rendering failed:",h)}},[n,t.shapes,t.mode,f,g]),x.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),c.current&&Object.entries(d.current).forEach(([h,m])=>{try{c.current.off("drag",m),console.warn(` Removed drag listener for transform ${h}`)}catch(p){console.warn(`Failed to remove drag listener for ${h}:`,p)}}),d.current={},Object.values(a.current).forEach(h=>{try{h&&h.remove&&h.remove()}catch(m){console.warn("Failed to remove transform during cleanup:",m)}}),a.current={},l.current={},i(!1),console.warn("✅ Cleanup complete")},[]),u.jsx("div",{ref:e,className:"w-full h-full"})};function So(t,e,n,r,s){const o=n==="edit";switch(e.type){case"point":try{if(console.warn(`🔍 Creating point ${e.id}:`,{id:e.id,type:e.type,position:e.position,hasPosition:"position"in e,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),positionX:e.position?.x,positionY:e.position?.y,position0:Array.isArray(e.position)?e.position[0]:void 0,position1:Array.isArray(e.position)?e.position[1]:void 0}),!e.position)return console.error(`❌ Point ${e.id} has no position field`),null;let c,d;if(e.position.x!==void 0&&e.position.y!==void 0)c=e.position.x,d=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)c=e.position[0],d=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const f=t.create("point",[c,d],{id:e.id,name:e.name||"",withLabel:e.withLabel??!!e.name,fixed:!o,size:e.size??3,strokeColor:e.strokeColor||e.color||"black",visible:e.visible??!0,label:e.label?{offset:e.label.offset||[10,10],fontSize:e.label.fontSize||14,color:e.label.color,anchorX:e.label.anchorX||"middle",anchorY:e.label.anchorY||"bottom",cssClass:e.label.cssClass,position:e.label.position||"urt",autoPosition:e.label.autoPosition||!1,distance:e.label.distance||1.5}:void 0});return console.warn("🔵 Created point:",{shapeId:e.id,pointId:f.id,pointName:f.name,hasIdProperty:"id"in f}),o&&(t.on("drag",()=>{r(e.id,{x:f.X(),y:f.Y()})}),t.on("down",()=>{s(e.id)})),f}catch(c){return console.error(`Failed to create point ${e.id}:`,c),null}case"line":const i=Hr(e.start,t),a=Hr(e.end,t);if(i&&a)try{const c=t.create("line",[i,a],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",dash:e.dash??0,fixed:!o,visible:e.visible??!0,straightFirst:!1,straightLast:!1});return o&&t.on("down",()=>{s(e.id)}),c}catch(c){return console.error(`Failed to create line ${e.id}:`,c),null}else console.warn(`Cannot create line ${e.id}: missing start or end point`,{startPoint:!!i,endPoint:!!a,startRef:e.start,endRef:e.end});break;case"circle":const l=Hr(e.center,t);if(l){let c;if(e.through){const d=Hr(e.through,t);d&&(c=t.create("circle",[l,d],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}))}else e.radius!==void 0&&(c=t.create("circle",[l,e.radius],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}));return c&&o&&t.on("down",()=>{s(e.id)}),c}break;case"polygon":try{if(console.error(`🔍 Creating polygon ${e.id}:`,{id:e.id,type:e.type,hasVertices:"vertices"in e,vertices:e.vertices,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e),geometryRef:"geometryRef"in e?e.geometryRef:void 0,styleRef:"styleRef"in e?e.styleRef:void 0,fullShapeData:JSON.stringify(e,null,2)}),!e.vertices)return console.error(`❌ FATAL: Polygon ${e.id} has no vertices! Full shape data:`,JSON.stringify(e,null,2)),null;if(!Array.isArray(e.vertices))return console.error(`❌ FATAL: Polygon ${e.id} vertices is not an array:`,e.vertices),null;const c=e.vertices.map((d,f)=>{const g=e.verticesConfig?e.verticesConfig[f]:null;return qy(d,t,g)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,c),console.warn(`🔧 Polygon ${e.id} vertices types:`,c.map(d=>({type:typeof d,isArray:Array.isArray(d),value:d}))),c.every(d=>d!==null)){const d={strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"lightblue",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0};if(e.verticesConfig){console.warn(`🔧 GraphContainer processing verticesConfig for polygon ${e.id}:`,{verticesConfig:e.verticesConfig,verticesConfigKeys:Object.keys(e.verticesConfig),verticesConfigType:typeof e.verticesConfig});const g={};e.verticesConfig.withLabel!==void 0?g.withLabel=e.verticesConfig.withLabel:g.withLabel=!0;const h={};let m=!1;e.verticesConfig.offset&&(h.offset=e.verticesConfig.offset,m=!0),e.verticesConfig.fontSize&&(h.fontSize=e.verticesConfig.fontSize,m=!0),e.verticesConfig.color&&(h.color=e.verticesConfig.color,m=!0),e.verticesConfig.anchorX&&(h.anchorX=e.verticesConfig.anchorX,m=!0),e.verticesConfig.anchorY&&(h.anchorY=e.verticesConfig.anchorY,m=!0),m&&(g.label=h),d.vertices=g,console.warn("🔧 Using JSXGraph vertices config:",g)}else d.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",d);const f=t.create("polygon",c,d);return console.warn("🔧 Polygon created:",f),console.warn("🔧 Polygon vertices:",f.vertices),console.warn("🔧 Polygon vertices names:",f.vertices?f.vertices.map(g=>g.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",f.vertices?f.vertices.map(g=>g.hasLabel?g.label:"no label"):"no vertices"),o&&t.on("down",()=>{s(e.id)}),f}else console.warn(`Cannot create polygon ${e.id}: some vertices are missing`,{vertices:e.vertices,resolvedVertices:c})}catch(c){console.error(`Failed to create polygon ${e.id}:`,c)}break;case"text":try{return console.warn(`🔍 Creating text ${e.id}:`,{id:e.id,type:e.type,hasPosition:"position"in e,position:e.position,positionX:e.position?.x,positionY:e.position?.y,hasContent:"content"in e,content:e.content,shapeKeys:Object.keys(e)}),t.create("text",[e.position.x,e.position.y,e.content],{color:e.color||"black",fontSize:e.fontSize??14,fixed:!0,visible:e.visible??!0})}catch(c){console.error(`Failed to create text ${e.id}:`,c)}break}return null}function Hr(t,e){if(Array.isArray(t)&&t.length>=2)return t;if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return[t.x,t.y];if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const r=e.objects[t.$ref];if(r)return r}const n=e.objectsList.find(r=>r.id===t.$ref);if(n)return console.warn(`✅ Found referenced point ${t.$ref}:`,n),n;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${t.$ref}:`,n)}}return null}function qy(t,e,n){if(Array.isArray(t)&&t.length>=2){if(n&&n.name){const r=e.create("point",t,{name:n.name});return console.warn(`🔧 Created point with name ${n.name} at`,t),r}return t}if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t){const r=[t.x,t.y];if(n&&n.name){const s=e.create("point",r,{name:n.name});return console.warn(`🔧 Created point with name ${n.name} at`,r),s}return r}if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const s=e.objects[t.$ref];if(s)return n&&n.name&&s.setName&&(s.setName(n.name),console.warn(`🔧 Updated point ${t.$ref} name to ${n.name}`)),s}const r=e.objectsList.find(s=>s.id===t.$ref);if(r)return console.warn(`✅ Found referenced point ${t.$ref}:`,r),n&&n.name&&r.setName&&(r.setName(n.name),console.warn(`🔧 Updated point ${t.$ref} name to ${n.name}`)),r;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(r){console.warn(`Failed to resolve point reference ${t.$ref}:`,r)}}return null}function Pi(t,e={}){const{padding:n=.2,margin:r=1,minSize:s=4}=e,o=[];if(t.forEach(C=>{switch(C.type){case"point":o.push(C.position);break;case"line":const R=Rn(C.start,t),k=Rn(C.end,t);R&&o.push(R),k&&o.push(k);break;case"circle":const M=Rn(C.center,t);if(M&&(o.push(M),C.radius!==void 0&&o.push({x:M.x+C.radius,y:M.y},{x:M.x-C.radius,y:M.y},{x:M.x,y:M.y+C.radius},{x:M.x,y:M.y-C.radius})),C.through){const P=Rn(C.through,t);P&&o.push(P)}break;case"polygon":C.vertices.forEach(P=>{const j=Rn(P,t);j&&o.push(j)});break;case"text":o.push(C.position);const F=C.content.length*(C.fontSize||14)/20,D=(C.fontSize||14)/10;o.push({x:C.position.x+F,y:C.position.y},{x:C.position.x-F,y:C.position.y},{x:C.position.x,y:C.position.y+D},{x:C.position.x,y:C.position.y-D});break}}),o.length===0)return{boundingBox:[-s,s,s,-s],center:{x:0,y:0},width:s*2,height:s*2};const i=Math.min(...o.map(C=>C.x)),a=Math.max(...o.map(C=>C.x)),l=Math.min(...o.map(C=>C.y)),c=Math.max(...o.map(C=>C.y)),d=(i+a)/2,f=(l+c)/2;let g=Math.max(a-i,s),h=Math.max(c-l,s);const m=800/500,p=g/h;Math.abs(p-m)>.1&&(p>m?h=g/m:g=h*m);const y=g*(1+n)+r*2,b=h*(1+n)+r*2,w=d-y/2,v=f+b/2,S=d+y/2,_=f-b/2,A=[w,v,S,_];if(process.env.NODE_ENV==="development"){const R=o.map(k=>({x:k.x,y:k.y,insideX:k.x>=w&&k.x<=S,insideY:k.y<=v&&k.y>=_,inside:k.x>=w&&k.x<=S&&k.y<=v&&k.y>=_})).filter(k=>!k.inside);R.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:A,outsidePoints:R.slice(0,5),totalOutside:R.length})}return{boundingBox:A,center:{x:d,y:f},width:y,height:b}}function Rn(t,e=[]){if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return{x:t.x,y:t.y};if("$ref"in t){const n=e.find(r=>r.id===t.$ref&&r.type==="point");if(n)return n.position}}return null}function Yy(t,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const n=[];if(t.forEach(s=>{switch(s.type){case"point":n.push({x:s.position.x,y:s.position.y,source:`point:${s.id}`});break;case"text":n.push({x:s.position.x,y:s.position.y,source:`text:${s.id}`});const o=s.content.length*(s.fontSize||14)/20,i=(s.fontSize||14)/10;n.push({x:s.position.x+o,y:s.position.y,source:`text:${s.id}:right`},{x:s.position.x-o,y:s.position.y,source:`text:${s.id}:left`},{x:s.position.x,y:s.position.y+i,source:`text:${s.id}:top`},{x:s.position.x,y:s.position.y-i,source:`text:${s.id}:bottom`});break;case"polygon":s.vertices.forEach((a,l)=>{const c=Rn(a,t);c&&n.push({x:c.x,y:c.y,source:`polygon:${s.id}:vertex${l}`})});break}}),console.log("📊 收集到的坐标点:",n),n.length>0){const s=Math.min(...n.map(l=>l.x)),o=Math.max(...n.map(l=>l.x)),i=Math.min(...n.map(l=>l.y)),a=Math.max(...n.map(l=>l.y));console.log("📐 原始包围盒:",{minX:s,maxX:o,minY:i,maxY:a,width:o-s,height:a-i})}const r=Pi(t,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",r),console.groupEnd(),r}const Nr=t=>{const{shapes:e,mode:n,onShapeChange:r,onSelectionChange:s,width:o=600,height:i=400,showGrid:a=!0,showAxis:l=!0,className:c="",boundingBox:d,autoBoundingBox:f=!0,boundingBoxOptions:g,animation:h,animationProgress:m,onAnimationChange:p,showAnimationControls:y}=t,b=x.useMemo(()=>{if(d)return d;if(f&&e.length>0)try{process.env.NODE_ENV==="development"&&Yy(e,"MathGraph Auto BoundingBox");const v=Pi(e,g);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",v.boundingBox),console.log(" - Center:",v.center),console.log(" - Width:",v.width),console.log(" - Height:",v.height),console.log(" - Options used:",g),v.boundingBox}catch(v){return console.warn("Failed to calculate auto bounding box, using default:",v),[-10,10,10,-10]}return[-10,10,10,-10]},[d,f,e,g]),w=x.useMemo(()=>({width:typeof o=="number"?`${o}px`:o,height:typeof i=="number"?`${i}px`:i}),[o,i]);return u.jsx(zy,{children:u.jsx("div",{className:`bg-white overflow-hidden ${c}`,style:w,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:u.jsx(Jd,{shapes:e,mode:n,onShapeChange:r,onSelectionChange:s,boundingBox:b,showGrid:a,showAxis:l,animation:h,animationProgress:m,onAnimationChange:p})})})},Zd=({shapes:t,width:e,height:n,showGrid:r=!0,showAxis:s=!0,boundingBox:o,autoBoundingBox:i,onShapeChange:a,className:l="",animation:c,animationProgress:d,showAnimationControls:f,onAnimationChange:g})=>{const h=x.useRef(null),[m,p]=x.useState({width:600,height:400});x.useEffect(()=>{const b=()=>{if(h.current){const{clientWidth:v,clientHeight:S}=h.current;v>0&&S>0&&p({width:v,height:S})}};b(),window.addEventListener("resize",b);const w=new ResizeObserver(b);return h.current&&w.observe(h.current),()=>{window.removeEventListener("resize",b),w.disconnect()}},[]);const y={width:e?typeof e=="string"?e:`${e}px`:"100%",height:n?typeof n=="string"?n:`${n}px`:"100%"};return u.jsx("div",{ref:h,className:`mathcard-v2-graph ${l}`,style:y,children:u.jsx(Nr,{shapes:t,width:m.width,height:m.height,showGrid:r,showAxis:s,boundingBox:o,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:c,animationProgress:d,showAnimationControls:f,onAnimationChange:g})})},Fi=({config:t,onTransformChange:e,onTransformComplete:n,onError:r,layoutDensity:s,boardHeight:o,boardWidth:i,className:a=""})=>{const l=s??t.ui?.layoutDensity??"default",c=o??t.ui?.boardHeight??300,d=i??t.ui?.boardWidth??400,f=m=>{e?.(m)},g=()=>{n?.()},h=m=>{r?.(m)};return console.error("🔍 GeometryTransformContent: config =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,boardConfigKeys:t.boardConfig?Object.keys(t.boardConfig):[],boardConfigBoundingBox:t.boardConfig?.boundingBox,boardConfigOriginX:t.boardConfig?.originX,boardConfigOriginY:t.boardConfig?.originY,configKeys:Object.keys(t)}),u.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:u.jsx(Dd,{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,onTransformChange:f,onTransformComplete:g,onError:h,layoutDensity:l,boardHeight:c,boardWidth:d,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})};function Ky(t){switch(t.contentType){case"formula":return u.jsx(Gn,{parts:[t.content],children:null});case"graph":return u.jsx(Nr,{mode:"view",shapes:t.graphConfig?.shapes||[],boundingBox:t.graphConfig?.boundingBox,showGrid:t.graphConfig?.showGrid,showAxis:t.graphConfig?.showAxis});case"image":return u.jsx("img",{src:t.content,alt:"选项图片",className:"max-w-full"});default:return u.jsx("span",{children:t.content})}}const Xy=({options:t,correctAnswers:e,answerType:n,layout:r="vertical",variant:s="default",value:o=[],onChange:i,showResult:a=!1,disabled:l=!1,className:c})=>{const d=x.useMemo(()=>t.map(g=>({id:g.id,label:Ky(g),rawContent:g.content,contentType:g.contentType||"text"})),[t]),f=x.useCallback(g=>{i?.(g)},[i]);return u.jsx(Ni,{type:n,options:d,value:o,onChange:f,correctAnswers:e,showResult:a,disabled:l,layout:r,variant:s,className:c})},Jy={FACTOR_TABLE:"factorTable",SHORT_DIVISION:"shortDivision",VERTICAL_MULTIPLICATION:"verticalMultiplication",LONG_DIVISION:"longDivision"},Zy={EDIT:"edit",REVIEW:"review",SOLUTION:"solution"},Qy={CORRECT:"correct",INCORRECT:"incorrect",PENDING:"pending"};function Qd(t){const{config:e,initialAnswers:n={},onAnswerChange:r,onValidationChange:s}=t,{number:o,rows:i}=e,a=x.useRef(n),l=x.useRef({}),[c,d]=x.useState(n),[f,g]=x.useState({});x.useEffect(()=>{a.current=c},[c]),x.useEffect(()=>{l.current=f},[f]);const h=x.useCallback((w,v)=>w===null||v===null?"pending":w*v===o?"correct":"incorrect",[o]),m=x.useCallback((w,v)=>{const S=a.current,_=l.current,A={value:v,status:"pending"},C={...S,[w]:A};a.current=C,d(C),r?.(C);const R=w.split("_");if(R.length!==3)return;const k=parseInt(R[1],10),M=parseInt(R[2],10);if(isNaN(k)||isNaN(M))return;const D=`factor_${k}_${M===0?1:0}`,P=C[D];if(v!==null&&P?.value!=null){const j=M===0?v:P.value,O=M===0?P.value:v,T=h(j,O),B={..._,[w]:T,[D]:T};l.current=B,g(B),s?.(B)}},[h,r,s]),p=x.useCallback(w=>f[w]||c[w]?.status||"pending",[f,c]),y=x.useMemo(()=>{const w=i*2;return Object.values(c).filter(S=>S.value!==null).length===w},[c,i]),b=x.useCallback(()=>{d({}),g({}),a.current={},l.current={}},[]);return{answers:c,updateAnswer:m,getCellStatus:p,validation:f,isComplete:y,reset:b}}function eu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{dividend:s,divisor:o,steps:i}=e,a=x.useRef(n),[l,c]=x.useState(n),[d,f]=x.useState({});x.useEffect(()=>{a.current=l},[l]);const g=x.useCallback(w=>{const v=s.toString();if(w===0)return parseInt(v[0],10);const S=d[w-1]?.remainder??0,_=parseInt(v[w],10);return S*10+_},[s,d]),h=x.useCallback(w=>{const v=g(w);return{quotient:Math.floor(v/o),remainder:v%o}},[g,o]),m=x.useCallback((w,v)=>{const S=a.current,_={value:v,status:"pending"},A={...S,[w]:_};a.current=A,c(A),r?.(A);const C=w.split("_");if(C.length!==2)return;const R=C[0],k=parseInt(C[1],10);if(isNaN(k)||k<0||k>=i)return;const M=h(k);f(j=>({...j,[k]:M}));let F=!1;v!==null&&(R==="quotient"?F=v===M.quotient:R==="remainder"&&(F=v===M.remainder));const D={value:v,status:v===null?"pending":F?"correct":"incorrect"},P={...A,[w]:D};a.current=P,c(P)},[h,i,r]),p=x.useCallback(w=>l[w]?.status||"pending",[l]),y=x.useMemo(()=>{const w=i*2;return Object.values(l).filter(S=>S.value!==null).length===w},[l,i]),b=x.useCallback(()=>{c({}),f({}),a.current={}},[]);return{answers:l,updateAnswer:m,getCellStatus:p,stepResults:d,isComplete:y,reset:b}}function eb(t,e){return e.toString().split("").reverse().map(Number).map((r,s)=>({digit:r,partial:t*r*Math.pow(10,s),rowIndex:s}))}function tb(t,e){return t.reduce((r,s)=>r+s.partial.toString().length,0)+e.toString().length}function nb(t,e,n){const r=t.split("_"),s=r[0];if(s==="partial"&&r.length===3){const o=parseInt(r[1],10),i=parseInt(r[2],10);if(isNaN(o)||isNaN(i))return null;const a=e[o]?.partial;if(a===void 0)return null;const l=a.toString().split("").reverse();return l[i]!==void 0?parseInt(l[i],10):null}if(s==="product"&&r.length===2){const o=parseInt(r[1],10);if(isNaN(o))return null;const i=n.toString().split("").reverse();return i[o]!==void 0?parseInt(i[o],10):null}return null}function rb(t,e){return Object.values(t).filter(r=>r.value!==null).length===e&&e>0}function tu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{multiplicand:s,multiplier:o}=e,i=x.useRef(n),[a,l]=x.useState(n);x.useEffect(()=>{i.current=a},[a]);const c=x.useMemo(()=>s*o,[s,o]),d=x.useMemo(()=>eb(s,o),[s,o]),f=x.useMemo(()=>tb(d,c),[d,c]),g=x.useCallback((y,b)=>{const w=i.current,v=nb(y,d,c),_={value:b,status:b===null?"pending":b!==null&&b===v?"correct":"incorrect"},A={...w,[y]:_};i.current=A,l(A),r?.(A)},[d,c,r]),h=x.useCallback(y=>a[y]?.status||"pending",[a]),m=x.useMemo(()=>rb(a,f),[a,f]),p=x.useCallback(()=>{l({}),i.current={}},[]);return{answers:a,updateAnswer:g,getCellStatus:h,partialProducts:d,correctProduct:c,isComplete:m,reset:p}}function sb(t,e){if(t===0)return[{index:0,dividend:0,quotient:0,remainder:0,product:0}];const n=t.toString(),r=[];let s=0;for(let o=0;o<n.length;o++){s=s*10+parseInt(n[o],10);const i=Math.floor(s/e),a=s%e,l=i*e;r.push({index:o,dividend:s,quotient:i,remainder:a,product:l}),s=a}return r}function nu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{dividend:s,divisor:o}=e,i=x.useRef(n),[a,l]=x.useState(n),c=x.useMemo(()=>Math.floor(s/o),[s,o]),d=x.useMemo(()=>s%o,[s,o]),f=x.useMemo(()=>sb(s,o),[s,o]);x.useEffect(()=>{i.current=a},[a]);const g=(b,w)=>{if(b<0)return null;const v=b.toString();return w>=v.length?null:parseInt(v[v.length-1-w],10)},h=x.useCallback((b,w)=>{const v=i.current,S=b.split("_");if(S.length<2)return;let _=S[0],A;if(b.startsWith("div_q_"))_="quotient",A=parseInt(S[2],10);else if(b.startsWith("div_s")){_="product";const D=S[1].substring(1);A=parseInt(D,10)-1}else A=parseInt(S[1],10);if(isNaN(A)||A<0||A>=f.length)return;const C=f[A];let R=null,k=!1;if(_==="quotient")R=C.quotient,k=w!==null&&w===R;else if(_==="product")if(S.length===3){const D=parseInt(S[2],10);isNaN(D)||(R=g(C.product,D),k=w!==null&&w===R)}else R=C.product,k=w!==null&&w===R;else if(_==="remainder")if(S.length===3){const D=parseInt(S[2],10);isNaN(D)||(R=g(C.remainder,D),k=w!==null&&w===R)}else R=C.remainder,k=w!==null&&w===R;const M={value:w,status:w===null?"pending":k?"correct":"incorrect"},F={...v,[b]:M};i.current=F,l(F),r?.(F)},[f,r]),m=x.useCallback(b=>a[b]?.status||"pending",[a]),p=x.useMemo(()=>{const b=f.length*3;return Object.values(a).filter(v=>v.value!==null).length===b},[a,f]),y=x.useCallback(()=>{l({}),i.current={}},[]);return{answers:a,updateAnswer:h,getCellStatus:m,steps:f,quotient:c,remainder:d,isComplete:p,reset:y}}const ru=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,readonly:i=!1}=e,{number:a,rows:l}=n,c=x.useCallback((f,g)=>{const h=g.trim()===""?null:parseInt(g,10);g.trim()!==""&&isNaN(h)||s(f,h)},[s]),d=x.useCallback(f=>{const g=`factor_${f}_0`,h=`factor_${f}_1`,m=r[g],p=r[h],y=o(g),b=o(h),w=v=>{const S="w-16 h-10 text-center border-2 rounded focus:outline-none focus:ring-2";switch(v){case"correct":return`${S} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${S} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${S} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}};return u.jsxs("div",{className:"contents",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:m?.value??"",readOnly:i,onChange:v=>c(g,v.target.value),className:w(y),"aria-label":`第 ${f+1} 行左侧因数`,"data-cell-id":g}),u.jsx("span",{className:"text-gray-500 font-medium select-none",children:"×"})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:p?.value??"",readOnly:i,onChange:v=>c(h,v.target.value),className:w(b),"aria-label":`第 ${f+1} 行右侧因数`,"data-cell-id":h}),u.jsx("span",{className:"text-gray-500 font-medium select-none",children:"="}),u.jsx("span",{className:"text-gray-700 font-semibold min-w-[2rem] select-none",children:a})]})]},f)},[r,o,c,i,a]);return u.jsxs("div",{className:"inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`因数表:分解 ${a}`,children:[u.jsx("div",{className:"mb-4 text-center",children:u.jsxs("span",{className:"text-lg font-semibold text-gray-800",children:["找出 ",a," 的所有因数对"]})}),u.jsx("div",{className:"grid grid-cols-2 gap-x-8 gap-y-3",role:"grid","aria-label":`${a} 的因数表`,children:Array.from({length:l},(f,g)=>d(g))})]})});ru.displayName="FactorTableView";const Di=t=>{const{config:e,initialAnswers:n={},onAnswerChange:r,onValidationChange:s,readonly:o=!1}=t,{answers:i,updateAnswer:a,getCellStatus:l,validation:c,isComplete:d,reset:f}=Qd({config:e,initialAnswers:n,onAnswerChange:r,onValidationChange:s});x.useEffect(()=>{d&&r&&r(i)},[d,i,r]);const g=o||e.mode!=="edit";return u.jsx(ru,{config:e,answers:i,onCellChange:a,getCellStatus:l,readonly:g})};Di.displayName="FactorTable";const su=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,readonly:i=!1}=e,{dividend:a,divisor:l,steps:c}=n,d=x.useCallback((h,m)=>{const p=m.trim();if(p===""){s(h,null);return}const y=parseInt(p,10);isNaN(y)||s(h,y)},[s]),f=h=>{const m="w-12 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-medium";switch(h){case"correct":return`${m} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${m} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${m} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}},g=x.useCallback(h=>{const m=`quotient_${h}`,p=`remainder_${h}`,y=r[m],b=r[p],w=o(m),v=o(p);return u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:y?.value??"",readOnly:i,onChange:S=>d(m,S.target.value),className:f(w),"aria-label":`第 ${h+1} 步的商`,"data-cell-id":m}),u.jsx("span",{className:"text-gray-400 select-none",children:"..."}),u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:b?.value??"",readOnly:i,onChange:S=>d(p,S.target.value),className:f(v),"aria-label":`第 ${h+1} 步的余数`,"data-cell-id":p})]},h)},[r,o,d,i]);return u.jsx("div",{className:"mathwiz-short-division inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`短除法:${a} ÷ ${l}`,children:u.jsxs("div",{className:"flex items-start gap-4",children:[u.jsxs("div",{className:"flex flex-col items-center pt-2",children:[u.jsx("span",{className:"text-xl font-bold text-gray-800",children:l}),u.jsx("div",{className:"w-8 h-0.5 bg-gray-400 my-1"})]}),u.jsxs("div",{className:"flex flex-col gap-2",children:[u.jsx("div",{className:"text-xl font-bold text-gray-800 text-right border-b-2 border-gray-400 pb-1",children:a}),u.jsx("div",{className:"flex flex-col gap-2 pt-2",children:Array.from({length:c},(h,m)=>g(m))})]})]})})});su.displayName="ShortDivisionView";const Li=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,stepResults:l,isComplete:c}=eu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{c&&r&&r(o)},[c,o,r]),u.jsx(su,{config:e,answers:o,onCellChange:i,getCellStatus:a,stepResults:l,readonly:s})};Li.displayName="ShortDivision";function ob(t){const e=t.trim()===""?null:parseInt(t,10);return t.trim()!==""&&isNaN(e)?null:e}function ib(t){const e="w-8 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-semibold";switch(t){case"correct":return`${e} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${e} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${e} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}}function ab(t,e,n){return Math.max(t.toString().length,e.toString().length+1,n.toString().length)}const Ya=({digits:t,prefix:e,className:n=""})=>u.jsxs("div",{className:`flex justify-end items-center gap-1 ${n}`,children:[e,t.map((r,s)=>u.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-800",children:r},s))]}),Ka=({width:t})=>u.jsx("div",{className:"border-t-2 border-gray-400 my-2",style:{width:t},"aria-hidden":"true"}),ou=({cellId:t,value:e,status:n,readonly:r,ariaLabel:s,onChange:o})=>u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:e??"",readOnly:r,onChange:i=>o(t,i.target.value),className:ib(n),"aria-label":s,"data-cell-id":t}),lb=({rowIndex:t,partial:e,maxDigits:n,answers:r,getCellStatus:s,readonly:o,onChange:i})=>{const a=e.toString().split(""),l=n-a.length;return u.jsxs("div",{className:"flex justify-end items-center gap-1 mb-1",children:[Array.from({length:l}).map((c,d)=>u.jsx("span",{className:"w-8"},d)),[...a].reverse().map((c,d)=>{const f=`partial_${t}_${d}`;return u.jsx(ou,{cellId:f,value:r[f]?.value??null,status:s(f),readonly:o,ariaLabel:`第 ${t+1} 行中间积第 ${d+1} 位`,onChange:i},f)})]},`p-${t}`)},cb=({correctProduct:t,maxDigits:e,answers:n,getCellStatus:r,readonly:s,onChange:o})=>{const i=t.toString().split(""),a=e-i.length;return u.jsxs("div",{className:"flex justify-end items-center gap-1",children:[Array.from({length:a}).map((l,c)=>u.jsx("span",{className:"w-8"},c)),[...i].reverse().map((l,c)=>{const d=`product_${c}`;return u.jsx(ou,{cellId:d,value:n[d]?.value??null,status:r(d),readonly:s,ariaLabel:`乘积第 ${c+1} 位`,onChange:o},d)})]})},iu=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,partialProducts:i,correctProduct:a,readonly:l=!1}=e,{multiplicand:c,multiplier:d}=n,f=ab(c,d,a),g=x.useCallback((h,m)=>s(h,ob(m)),[s]);return u.jsx("div",{className:"inline-block p-6 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`乘法竖式:${c} × ${d}`,children:u.jsxs("div",{className:"flex flex-col items-end",children:[u.jsx(Ya,{digits:c.toString().split(""),className:"mb-1"}),u.jsx(Ya,{digits:d.toString().split(""),prefix:u.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-600 select-none",children:"×"}),className:"mb-2"}),u.jsx(Ka,{width:`${f*2.25}rem`}),i.map((h,m)=>u.jsx(lb,{rowIndex:m,partial:h.partial,maxDigits:f,answers:r,getCellStatus:o,readonly:l,onChange:g},m)),u.jsx(Ka,{width:`${f*2.25}rem`}),u.jsx(cb,{correctProduct:a,maxDigits:f,answers:r,getCellStatus:o,readonly:l,onChange:g})]})})});iu.displayName="VerticalMultiplicationView";const zi=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,partialProducts:l,correctProduct:c,isComplete:d}=tu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{d&&r&&r(o)},[d,o,r]),u.jsx(iu,{config:e,answers:o,onCellChange:i,getCellStatus:a,partialProducts:l,correctProduct:c,readonly:s})};zi.displayName="VerticalMultiplication";const db=Us({base:["border rounded text-center font-medium transition-colors duration-150","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent","text-lg"],variants:{size:{digit:"w-10 h-10",standard:"min-w-12 h-10 px-2"},status:{normal:"border-gray-300 bg-white text-gray-900",correct:"border-emerald-500 bg-emerald-50 text-emerald-700",incorrect:"border-red-500 bg-red-50 text-red-700 line-through",idle:"border-dashed border-gray-400 bg-gray-50 text-gray-500"},type:{input:"",label:"font-bold bg-gray-100 cursor-default",result:"font-semibold bg-blue-50",placeholder:"opacity-0 pointer-events-none"},disabled:{true:"cursor-not-allowed opacity-60",false:""},readonly:{true:"cursor-default",false:""}},defaultVariants:{size:"digit",status:"normal",type:"input",disabled:!1,readonly:!1}});Us({base:"inline-flex items-center gap-1"});const Vi=x.memo(function(e){const{type:n,value:r,readonly:s=!1,status:o,autoTab:i=!1,place:a,onChange:l,className:c,cellId:d,onAutoTab:f}=e,g=x.useRef(null),[h,m]=x.useState(r?.toString()||"");x.useEffect(()=>{m(r?.toString()||"")},[r]);const p=a===void 0||a!==null,y=x.useMemo(()=>db({size:p?"digit":"standard",status:o||"normal",type:n,readonly:s,disabled:s}),[p,o,n,s]),b=x.useCallback(v=>{if(s)return;let S=v.target.value;S=S.replace(/[^0-9]/g,""),p&&(S=S.slice(-1)),m(S);const _=S===""?null:Number(S);l?.(_),p&&i&&S&&d&&f&&f(d,"next")},[s,p,i,d,l,f]),w=x.useCallback(v=>{s||v.key==="Backspace"&&h===""&&d&&f&&f(d,"prev")},[s,h,d,f]);return n==="placeholder"?u.jsx("div",{className:`${y} ${c||""}`,"aria-hidden":"true","data-cell-id":d}):n==="label"||n==="result"||s?u.jsx("div",{className:`${y} ${c||""}`,role:"text","aria-label":d?`单元格 ${d}:${r||""}`:`值:${r||""}`,"aria-readonly":"true","data-cell-id":d,"data-place":a,"data-testid":d?`mathcell-${d}`:"mathcell",children:r||""}):u.jsx("input",{ref:g,type:"text",inputMode:"numeric",pattern:"[0-9]*",value:h,onChange:b,onKeyDown:w,className:`${y} ${c||""}`,disabled:s,"aria-label":d?`输入单元格 ${d}`:"数学输入","aria-invalid":o==="incorrect",maxLength:p?1:void 0,"data-cell-id":d,"data-place":a,"data-testid":d?`mathcell-input-${d}`:"mathcell-input"})});Vi.displayName="MathCell";function ub(t){return{display:"grid",gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${t.rows}, auto)`,gap:"0.1rem",justifyItems:"center",alignItems:"center"}}function fb(t,e){const{dividend:n,divisor:r}=t,o=n.toString().split("").map(Number);r.toString().split("").map(Number);const a=o.length+1;let l=2;for(let g=0;g<e.length;g++)l+=3;const c=[];for(let g=0;g<e.length;g++){const h=e[g];c.push({id:`div_q_${g}`,type:"quotient",value:h.quotient,place:g,readonly:!1,position:{row:0,col:g+1}})}c.push({id:"divisor",type:"divisor",value:r,readonly:!0,position:{row:1,col:0},className:"text-right pr-2 self-end pb-1"});for(let g=0;g<o.length;g++){const m=g===0?"div-bracket-left pt-2 mt-2":"div-bracket-top pt-2 mt-2";c.push({id:`dividend_${g}`,type:"dividend",value:o[g],readonly:!0,position:{row:1,col:g+1},className:m,dataAttrs:{"data-digit-index":g.toString()}})}let d=2;const f=o.length-e.length;for(let g=0;g<e.length;g++){const h=e[g],m=g+1;h.dividend.toString().split("").map(Number).length;const w=h.product.toString().split("").map(Number),v=w.length,_=h.remainder.toString().split("").map(Number),A=_.length,C=f+g+1,R=C-v+1;for(let k=0;k<v;k++)c.push({id:`div_s${m}_${k}`,type:"product",value:w[k],place:k,readonly:!1,position:{row:d,col:R+k}});if(d++,c.push({id:`hline_${g}`,type:"horizontalLine",value:null,readonly:!0,position:{row:d,col:R,colspan:v},className:"border-t-2 border-neutral-800 my-1"}),d++,g<e.length-1){const F=e[g+1].dividend.toString().split("").map(Number),D=C+1,P=D-A;for(let O=0;O<A;O++)c.push({id:`remainder_${g}_${O}`,type:"remainderWithBringDown",value:_[O],readonly:!0,position:{row:d,col:P+O}});const j=F[F.length-1];c.push({id:`bringdown_${g}`,type:"remainderWithBringDown",value:j,readonly:!0,position:{row:d,col:D}})}else{const k=C-A+1;for(let M=0;M<A;M++)c.push({id:`remainder_${g}_${M}`,type:"remainder",value:_[M],readonly:!0,position:{row:d,col:k+M}})}d+=1}return l=d,{columns:a,rows:l,cells:c,divisorPosition:[1,0],dividendStartPosition:[1,1],quotientStartPosition:[0,1]}}const au=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,steps:i,readonly:a=!1}=e;x.useEffect(()=>{if(document.getElementById("mathwiz-long-division-styles"))return;const g=document.createElement("style");return g.id="mathwiz-long-division-styles",g.textContent=`
16
+ Received: ${JSON.stringify(r)}`)}case"shear":{const r=t.params,s=De(r.shearX,e),o=De(r.shearY,e);return[s,o]}case"generic":{const r=t.params;return[De(r.a,e),De(r.b,e),De(r.c,e),De(r.d,e),De(r.e,e),De(r.f,e),De(r.g,e),De(r.h,e),De(r.i,e)]}case"matrix":{const r=t.params;if(!Array.isArray(r.matrix)||r.matrix.length!==3||!r.matrix.every(s=>Array.isArray(s)&&s.length===3))throw new Error("Matrix transform requires a 3x3 matrix array");return[r.matrix]}default:throw new Error(`Unsupported transform type: ${t.params.type}`)}}function Qy(t){const e={};return Object.entries(t).forEach(([n,r])=>{if(typeof r=="string"&&Zy(r))try{e[n]=Ky(r)}catch(s){console.warn(`Failed to parse function string for ${n}: ${r}`,s),e[n]=()=>0}else e[n]=r}),e}function eb(t){if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!t.id||typeof t.id!="string"||t.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(t.transforms)?t.transforms.forEach((n,r)=>{(!n.id||typeof n.id!="string")&&e.push(`Transform at index ${r} must have a valid id`),(!n.type||typeof n.type!="string")&&e.push(`Transform at index ${r} must have a valid type`),(!n.params||typeof n.params!="object")&&e.push(`Transform at index ${r} must have valid params`),Array.isArray(n.targetShapes)?n.targetShapes.length===0&&e.push("targetShapes must not be empty"):e.push(`Transform at index ${r} must have targetShapes array`)}):e.push("Config must have a transforms array"),{valid:e.length===0,errors:e.length>0?e:void 0}}const qa=Ic.JSXGraph,Jd=t=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!t.animation,animationId:t.animation?.id,hasControl:!!t.animation?.control,controlConfig:t.animation?.control,animationProgress:t.animationProgress});const e=x.useRef(null),[n,r]=x.useState(null),[,s]=x.useState({}),[o,i]=x.useState(!1),a=x.useRef({}),l=x.useRef({}),c=x.useRef(null),d=x.useRef({}),f=x.useCallback((h,m)=>{t.onShapeChange},[t.onShapeChange]),g=x.useCallback(h=>{t.onSelectionChange&&t.onSelectionChange(h?[h]:[])},[t.onSelectionChange]);return x.useEffect(()=>{if(e.current){try{const h=t.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",h),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const m=qa.initBoard(e.current,{boundingbox:h,axis:t.showAxis??!0,grid:t.showGrid??!0,showNavigation:!1,pan:{enabled:t.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",m.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",h),console.warn(" * 实际边界框:",m.getBoundingBox()),console.warn(" * 实际显示范围:",{left:m.getBoundingBox()[0],top:m.getBoundingBox()[1],right:m.getBoundingBox()[2],bottom:m.getBoundingBox()[3]})},100),r(m)}catch(h){console.error("JSXGraph initialization failed:",h)}return()=>{n&&qa.freeBoard(n)}}},[]),x.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!n,hasAnimation:!!t.animation,hasControl:!!t.animation?.control,animationId:t.animation?.id,controlType:t.animation?.control?.type,controlPosition:t.animation?.control?.position,controlRange:t.animation?.control?.range}),!n||!t.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!n+", control="+!!t.animation?.control),c.current){try{c.current.remove&&c.current.remove()}catch(m){console.warn("Failed to remove control:",m)}c.current=null}return}const h=t.animation.control;console.warn("✨ Creating Control Component:",{type:h.type,config:h,position:h.position,range:h.range});try{if(h.type==="slider"){const m=h.position[0]+(h.length||5);console.warn("📐 Slider creation parameters:",{startPoint:h.position,endPoint:[m,h.position[1]],values:[h.range[0],h.initial||0,h.range[1]],label:h.label,snapWidth:h.snapWidth||.01});const p=n.create("slider",[h.position,[m,h.position[1]],[h.range[0],h.initial||0,h.range[1]]],{name:h.label||"control",snapWidth:h.snapWidth||.01,withLabel:h.showLabel!==void 0?h.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});c.current=p,console.warn("✅ Slider created:",{id:p.id,name:p.name,initialValue:p.Value(),startPoint:h.position,endPoint:[m,h.position[1]],boundingBox:n.getBoundingBox(),visProp:p.visProp});const y=n.objectsList.map(w=>({id:w.id,type:w.elType,name:w.name,visible:w.visProp?.visible})),b=y.find(w=>w.id===p.id);if(console.warn("📊 Slider in board.objectsList:",!!b,b),console.warn("📊 All board objects count:",y.length),t.onAnimationChange){let w=!1;p.on("drag",()=>{if(w)return;w=!0;const S=(p.Value()-h.range[0])/(h.range[1]-h.range[0]);t.onAnimationChange?.(S),w=!1})}}else if(h.type==="glider"){const m=n.select(h.line,!0);if(m){const p=n.create("glider",[h.initial||0,0,m],{name:h.label||"control",snapWidth:h.snapWidth||.01});if(c.current=p,console.warn("✅ Glider created:",{id:p.id,name:p.name}),t.onAnimationChange){let y=!1;p.on("drag",()=>{if(y)return;y=!0;const b=p.Value();t.onAnimationChange?.(b),y=!1})}}else console.warn(`Reference line not found for glider: ${h.line}`)}}catch(m){console.error("Failed to create control component:",m)}return()=>{if(c.current){try{c.current.remove()}catch(m){console.warn("Failed to remove control on cleanup:",m)}c.current=null}}},[n,t.animation?.control]),x.useEffect(()=>{if(!n||!t.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:t.animation.id,transformCount:t.animation.transforms.length}),Object.values(a.current).forEach(p=>{try{p&&p.remove&&p.remove()}catch(y){console.warn("Failed to remove transform:",y)}}),a.current={};const h={},m=t.animationProgress??0;t.animation.transforms.forEach(p=>{try{let y,b;const w=p.usesControl||!1;if(c.current&&w){y=_o(p,m,c.current),console.warn(`🔧 Creating transform ${p.id} (with dynamic params):`,{type:p.type,paramsTypes:y.map(S=>typeof S),targetShapes:p.targetShapes,controlValue:c.current.Value()}),b=n.create("transform",y,{type:p.type,id:`transform_${p.id}`});const v=()=>{if(!c.current)return;n.update();const S=c.current.Value();if(console.warn(`🎯 Slider drag - transform ${p.id} auto-updated (controlValue: ${S})`),t.onAnimationChange){const _=t.animation?.control?.range||[0,1],A=(S-_[0])/(_[1]-_[0]);t.onAnimationChange(A)}};c.current.on("drag",v),d.current[p.id]=v,console.warn(`🔗 Slider listener attached for transform ${p.id} (auto-update mode)`)}else y=_o(p,m),console.warn(`🔧 Creating transform ${p.id} (with progress ${m}):`,{type:p.type,params:y,targetShapes:p.targetShapes}),b=n.create("transform",y,{type:p.type,id:`transform_${p.id}`});h[p.id]=b,console.warn(`📝 Transform ${p.id} created:`,{type:p.type,paramsTypes:y.map(v=>typeof v),transformMethods:Object.keys(b).filter(v=>typeof b[v]=="function")})}catch(y){console.error(`Failed to create transform ${p.id}:`,y)}}),a.current=h}catch(h){console.error("Transform setup failed:",h)}},[n,t.animation]),x.useEffect(()=>{if(!o||!n||!t.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${o}, board=${!!n}, animation=${!!t.animation}`);return}if(console.warn("✅ Attempting to bind transforms to shapes..."),console.warn(` Available shapes: ${Object.keys(l.current).length}`),console.warn(` Available transforms: ${Object.keys(a.current).length}`),Object.keys(l.current).length===0){console.warn("❌ No shapes available, skipping transform binding");return}if(Object.keys(a.current).length===0){console.warn("❌ No transforms available, skipping binding");return}Object.entries(a.current).forEach(([h,m])=>{const p=t.animation?.transforms.find(b=>b.id===h);if(!p)return;console.warn(`🔍 Binding transform ${h} (type: ${p.type}) to shapes:`,p.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(l.current));const y=p.targetShapes.map(b=>{const w=l.current[b];return w?console.warn(`✅ Found shape ${b}:`,w):(console.warn(`❌ Shape not found for transform binding: ${b}`),console.warn(" Available IDs:",Object.keys(l.current))),w}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",y.length),y.length>0)try{console.warn(`🔗 Attempting to bind transform ${h} to ${y.length} shapes`),m.bindTo(y),console.warn(`✅ Successfully bound transform ${h} to ${y.length} shapes`),console.warn(" Transform object:",m),console.warn(" Target elements:",y.map(b=>({id:b.id,name:b.name,type:b.elementClass})))}catch(b){console.error(`❌ Failed to bind transform ${h}:`,b),console.error(" Transform:",m),console.error(" TargetElements:",y)}else console.warn(`⚠️ No valid target elements for transform ${h}`)}),n.update(),console.warn("✅ All transforms bound and board updated")},[o,n,t.animation]),x.useEffect(()=>{if(!n||Object.keys(a.current).length===0)return;const h=t.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${h}`);try{Object.entries(a.current).forEach(([m,p])=>{const y=t.animation?.transforms.find(w=>w.id===m);if(!y)return;const b=_o(y,h);console.warn(`🔄 Attempting to update transform ${m} with params:`,b),p.update?(console.warn(" Using transform.update(params)"),p.update(b)):p.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),p.setMatrix(n,y.type,b)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(p).filter(w=>typeof p[w]=="function")))}),n.update()}catch(m){console.error("Transform update failed:",m)}},[n,t.animationProgress]),x.useEffect(()=>{if(n)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:t.shapes.length,shapes:t.shapes.map(p=>({id:p.id,type:p.type,hasVertices:"vertices"in p,verticesCount:"vertices"in p&&p.vertices?p.vertices.length:"undefined",hasPosition:"position"in p,hasGeometryRef:"geometryRef"in p,geometryRef:"geometryRef"in p?p.geometryRef:void 0}))}),n.suspendUpdate(),[...n.objectsList].forEach(p=>{n.removeObject(p)});const m={};l.current={},t.shapes.forEach(p=>{if(p.type==="point")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create point shape ${p.id}:`,y)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",n.objectsList.map(p=>({id:p.id,name:p.name,type:p.elementClass}))),t.shapes.forEach(p=>{if(p.type==="line"||p.type==="circle"||p.type==="polygon")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create shape ${p.id}:`,y)}}),console.warn("📝 Starting phase 3: creating text labels"),t.shapes.forEach(p=>{if(p.type==="text")try{const y=So(n,p,t.mode,f,g);y&&(m[p.id]=y)}catch(y){console.warn(`Failed to create text ${p.id}:`,y)}}),s(m),l.current=m,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(m).length} shapes created`),n.unsuspendUpdate()}catch(h){console.error("Shape rendering failed:",h)}},[n,t.shapes,t.mode,f,g]),x.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),c.current&&Object.entries(d.current).forEach(([h,m])=>{try{c.current.off("drag",m),console.warn(` Removed drag listener for transform ${h}`)}catch(p){console.warn(`Failed to remove drag listener for ${h}:`,p)}}),d.current={},Object.values(a.current).forEach(h=>{try{h&&h.remove&&h.remove()}catch(m){console.warn("Failed to remove transform during cleanup:",m)}}),a.current={},l.current={},i(!1),console.warn("✅ Cleanup complete")},[]),u.jsx("div",{ref:e,className:"w-full h-full"})};function So(t,e,n,r,s){const o=n==="edit";switch(e.type){case"point":try{if(console.warn(`🔍 Creating point ${e.id}:`,{id:e.id,type:e.type,position:e.position,hasPosition:"position"in e,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),positionX:e.position?.x,positionY:e.position?.y,position0:Array.isArray(e.position)?e.position[0]:void 0,position1:Array.isArray(e.position)?e.position[1]:void 0}),!e.position)return console.error(`❌ Point ${e.id} has no position field`),null;let c,d;if(e.position.x!==void 0&&e.position.y!==void 0)c=e.position.x,d=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)c=e.position[0],d=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const f=t.create("point",[c,d],{id:e.id,name:e.name||"",withLabel:e.withLabel??!!e.name,fixed:!o,size:e.size??3,strokeColor:e.strokeColor||e.color||"black",visible:e.visible??!0,label:e.label?{offset:e.label.offset||[10,10],fontSize:e.label.fontSize||14,color:e.label.color,anchorX:e.label.anchorX||"middle",anchorY:e.label.anchorY||"bottom",cssClass:e.label.cssClass,position:e.label.position||"urt",autoPosition:e.label.autoPosition||!1,distance:e.label.distance||1.5}:void 0});return console.warn("🔵 Created point:",{shapeId:e.id,pointId:f.id,pointName:f.name,hasIdProperty:"id"in f}),o&&(t.on("drag",()=>{r(e.id,{x:f.X(),y:f.Y()})}),t.on("down",()=>{s(e.id)})),f}catch(c){return console.error(`Failed to create point ${e.id}:`,c),null}case"line":const i=Hr(e.start,t),a=Hr(e.end,t);if(i&&a)try{const c=t.create("line",[i,a],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",dash:e.dash??0,fixed:!o,visible:e.visible??!0,straightFirst:!1,straightLast:!1});return o&&t.on("down",()=>{s(e.id)}),c}catch(c){return console.error(`Failed to create line ${e.id}:`,c),null}else console.warn(`Cannot create line ${e.id}: missing start or end point`,{startPoint:!!i,endPoint:!!a,startRef:e.start,endRef:e.end});break;case"circle":const l=Hr(e.center,t);if(l){let c;if(e.through){const d=Hr(e.through,t);d&&(c=t.create("circle",[l,d],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}))}else e.radius!==void 0&&(c=t.create("circle",[l,e.radius],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}));return c&&o&&t.on("down",()=>{s(e.id)}),c}break;case"polygon":try{if(console.error(`🔍 Creating polygon ${e.id}:`,{id:e.id,type:e.type,hasVertices:"vertices"in e,vertices:e.vertices,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e),geometryRef:"geometryRef"in e?e.geometryRef:void 0,styleRef:"styleRef"in e?e.styleRef:void 0,fullShapeData:JSON.stringify(e,null,2)}),!e.vertices)return console.error(`❌ FATAL: Polygon ${e.id} has no vertices! Full shape data:`,JSON.stringify(e,null,2)),null;if(!Array.isArray(e.vertices))return console.error(`❌ FATAL: Polygon ${e.id} vertices is not an array:`,e.vertices),null;const c=e.vertices.map((d,f)=>{const g=e.verticesConfig?e.verticesConfig[f]:null;return tb(d,t,g)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,c),console.warn(`🔧 Polygon ${e.id} vertices types:`,c.map(d=>({type:typeof d,isArray:Array.isArray(d),value:d}))),c.every(d=>d!==null)){const d={strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"lightblue",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0};if(e.verticesConfig){console.warn(`🔧 GraphContainer processing verticesConfig for polygon ${e.id}:`,{verticesConfig:e.verticesConfig,verticesConfigKeys:Object.keys(e.verticesConfig),verticesConfigType:typeof e.verticesConfig});const g={};e.verticesConfig.withLabel!==void 0?g.withLabel=e.verticesConfig.withLabel:g.withLabel=!0;const h={};let m=!1;e.verticesConfig.offset&&(h.offset=e.verticesConfig.offset,m=!0),e.verticesConfig.fontSize&&(h.fontSize=e.verticesConfig.fontSize,m=!0),e.verticesConfig.color&&(h.color=e.verticesConfig.color,m=!0),e.verticesConfig.anchorX&&(h.anchorX=e.verticesConfig.anchorX,m=!0),e.verticesConfig.anchorY&&(h.anchorY=e.verticesConfig.anchorY,m=!0),m&&(g.label=h),d.vertices=g,console.warn("🔧 Using JSXGraph vertices config:",g)}else d.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",d);const f=t.create("polygon",c,d);return console.warn("🔧 Polygon created:",f),console.warn("🔧 Polygon vertices:",f.vertices),console.warn("🔧 Polygon vertices names:",f.vertices?f.vertices.map(g=>g.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",f.vertices?f.vertices.map(g=>g.hasLabel?g.label:"no label"):"no vertices"),o&&t.on("down",()=>{s(e.id)}),f}else console.warn(`Cannot create polygon ${e.id}: some vertices are missing`,{vertices:e.vertices,resolvedVertices:c})}catch(c){console.error(`Failed to create polygon ${e.id}:`,c)}break;case"text":try{return console.warn(`🔍 Creating text ${e.id}:`,{id:e.id,type:e.type,hasPosition:"position"in e,position:e.position,positionX:e.position?.x,positionY:e.position?.y,hasContent:"content"in e,content:e.content,shapeKeys:Object.keys(e)}),t.create("text",[e.position.x,e.position.y,e.content],{color:e.color||"black",fontSize:e.fontSize??14,fixed:!0,visible:e.visible??!0})}catch(c){console.error(`Failed to create text ${e.id}:`,c)}break}return null}function Hr(t,e){if(Array.isArray(t)&&t.length>=2)return t;if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return[t.x,t.y];if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const r=e.objects[t.$ref];if(r)return r}const n=e.objectsList.find(r=>r.id===t.$ref);if(n)return console.warn(`✅ Found referenced point ${t.$ref}:`,n),n;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${t.$ref}:`,n)}}return null}function tb(t,e,n){if(Array.isArray(t)&&t.length>=2){if(n&&n.name){const r=e.create("point",t,{name:n.name});return console.warn(`🔧 Created point with name ${n.name} at`,t),r}return t}if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t){const r=[t.x,t.y];if(n&&n.name){const s=e.create("point",r,{name:n.name});return console.warn(`🔧 Created point with name ${n.name} at`,r),s}return r}if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const s=e.objects[t.$ref];if(s)return n&&n.name&&s.setName&&(s.setName(n.name),console.warn(`🔧 Updated point ${t.$ref} name to ${n.name}`)),s}const r=e.objectsList.find(s=>s.id===t.$ref);if(r)return console.warn(`✅ Found referenced point ${t.$ref}:`,r),n&&n.name&&r.setName&&(r.setName(n.name),console.warn(`🔧 Updated point ${t.$ref} name to ${n.name}`)),r;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(r){console.warn(`Failed to resolve point reference ${t.$ref}:`,r)}}return null}function Pi(t,e={}){const{padding:n=.2,margin:r=1,minSize:s=4}=e,o=[];if(t.forEach(C=>{switch(C.type){case"point":o.push(C.position);break;case"line":const R=Rn(C.start,t),N=Rn(C.end,t);R&&o.push(R),N&&o.push(N);break;case"circle":const M=Rn(C.center,t);if(M&&(o.push(M),C.radius!==void 0&&o.push({x:M.x+C.radius,y:M.y},{x:M.x-C.radius,y:M.y},{x:M.x,y:M.y+C.radius},{x:M.x,y:M.y-C.radius})),C.through){const P=Rn(C.through,t);P&&o.push(P)}break;case"polygon":C.vertices.forEach(P=>{const $=Rn(P,t);$&&o.push($)});break;case"text":o.push(C.position);const F=C.content.length*(C.fontSize||14)/20,D=(C.fontSize||14)/10;o.push({x:C.position.x+F,y:C.position.y},{x:C.position.x-F,y:C.position.y},{x:C.position.x,y:C.position.y+D},{x:C.position.x,y:C.position.y-D});break}}),o.length===0)return{boundingBox:[-s,s,s,-s],center:{x:0,y:0},width:s*2,height:s*2};const i=Math.min(...o.map(C=>C.x)),a=Math.max(...o.map(C=>C.x)),l=Math.min(...o.map(C=>C.y)),c=Math.max(...o.map(C=>C.y)),d=(i+a)/2,f=(l+c)/2;let g=Math.max(a-i,s),h=Math.max(c-l,s);const m=800/500,p=g/h;Math.abs(p-m)>.1&&(p>m?h=g/m:g=h*m);const y=g*(1+n)+r*2,b=h*(1+n)+r*2,w=d-y/2,v=f+b/2,S=d+y/2,_=f-b/2,A=[w,v,S,_];if(process.env.NODE_ENV==="development"){const R=o.map(N=>({x:N.x,y:N.y,insideX:N.x>=w&&N.x<=S,insideY:N.y<=v&&N.y>=_,inside:N.x>=w&&N.x<=S&&N.y<=v&&N.y>=_})).filter(N=>!N.inside);R.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:A,outsidePoints:R.slice(0,5),totalOutside:R.length})}return{boundingBox:A,center:{x:d,y:f},width:y,height:b}}function Rn(t,e=[]){if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return{x:t.x,y:t.y};if("$ref"in t){const n=e.find(r=>r.id===t.$ref&&r.type==="point");if(n)return n.position}}return null}function nb(t,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const n=[];if(t.forEach(s=>{switch(s.type){case"point":n.push({x:s.position.x,y:s.position.y,source:`point:${s.id}`});break;case"text":n.push({x:s.position.x,y:s.position.y,source:`text:${s.id}`});const o=s.content.length*(s.fontSize||14)/20,i=(s.fontSize||14)/10;n.push({x:s.position.x+o,y:s.position.y,source:`text:${s.id}:right`},{x:s.position.x-o,y:s.position.y,source:`text:${s.id}:left`},{x:s.position.x,y:s.position.y+i,source:`text:${s.id}:top`},{x:s.position.x,y:s.position.y-i,source:`text:${s.id}:bottom`});break;case"polygon":s.vertices.forEach((a,l)=>{const c=Rn(a,t);c&&n.push({x:c.x,y:c.y,source:`polygon:${s.id}:vertex${l}`})});break}}),console.log("📊 收集到的坐标点:",n),n.length>0){const s=Math.min(...n.map(l=>l.x)),o=Math.max(...n.map(l=>l.x)),i=Math.min(...n.map(l=>l.y)),a=Math.max(...n.map(l=>l.y));console.log("📐 原始包围盒:",{minX:s,maxX:o,minY:i,maxY:a,width:o-s,height:a-i})}const r=Pi(t,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",r),console.groupEnd(),r}const kr=t=>{const{shapes:e,mode:n,onShapeChange:r,onSelectionChange:s,width:o=600,height:i=400,showGrid:a=!0,showAxis:l=!0,className:c="",boundingBox:d,autoBoundingBox:f=!0,boundingBoxOptions:g,animation:h,animationProgress:m,onAnimationChange:p,showAnimationControls:y}=t,b=x.useMemo(()=>{if(d)return d;if(f&&e.length>0)try{process.env.NODE_ENV==="development"&&nb(e,"MathGraph Auto BoundingBox");const v=Pi(e,g);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",v.boundingBox),console.log(" - Center:",v.center),console.log(" - Width:",v.width),console.log(" - Height:",v.height),console.log(" - Options used:",g),v.boundingBox}catch(v){return console.warn("Failed to calculate auto bounding box, using default:",v),[-10,10,10,-10]}return[-10,10,10,-10]},[d,f,e,g]),w=x.useMemo(()=>({width:typeof o=="number"?`${o}px`:o,height:typeof i=="number"?`${i}px`:i}),[o,i]);return u.jsx(Yy,{children:u.jsx("div",{className:`bg-white overflow-hidden ${c}`,style:w,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:u.jsx(Jd,{shapes:e,mode:n,onShapeChange:r,onSelectionChange:s,boundingBox:b,showGrid:a,showAxis:l,animation:h,animationProgress:m,onAnimationChange:p})})})},Zd=({shapes:t,width:e,height:n,showGrid:r=!0,showAxis:s=!0,boundingBox:o,autoBoundingBox:i,onShapeChange:a,className:l="",animation:c,animationProgress:d,showAnimationControls:f,onAnimationChange:g})=>{const h=x.useRef(null),[m,p]=x.useState({width:600,height:400});x.useEffect(()=>{const b=()=>{if(h.current){const{clientWidth:v,clientHeight:S}=h.current;v>0&&S>0&&p({width:v,height:S})}};b(),window.addEventListener("resize",b);const w=new ResizeObserver(b);return h.current&&w.observe(h.current),()=>{window.removeEventListener("resize",b),w.disconnect()}},[]);const y={width:e?typeof e=="string"?e:`${e}px`:"100%",height:n?typeof n=="string"?n:`${n}px`:"100%"};return u.jsx("div",{ref:h,className:`mathcard-v2-graph ${l}`,style:y,children:u.jsx(kr,{shapes:t,width:m.width,height:m.height,showGrid:r,showAxis:s,boundingBox:o,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:c,animationProgress:d,showAnimationControls:f,onAnimationChange:g})})},Fi=({config:t,onTransformChange:e,onTransformComplete:n,onError:r,layoutDensity:s,boardHeight:o,boardWidth:i,className:a=""})=>{const l=s??t.ui?.layoutDensity??"default",c=o??t.ui?.boardHeight??300,d=i??t.ui?.boardWidth??400,f=m=>{e?.(m)},g=()=>{n?.()},h=m=>{r?.(m)};return console.error("🔍 GeometryTransformContent: config =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,boardConfigKeys:t.boardConfig?Object.keys(t.boardConfig):[],boardConfigBoundingBox:t.boardConfig?.boundingBox,boardConfigOriginX:t.boardConfig?.originX,boardConfigOriginY:t.boardConfig?.originY,configKeys:Object.keys(t)}),u.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:u.jsx(Dd,{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,onTransformChange:f,onTransformComplete:g,onError:h,layoutDensity:l,boardHeight:c,boardWidth:d,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})};function rb(t){switch(t.contentType){case"formula":return u.jsx(Gn,{parts:[t.content],children:null});case"graph":return u.jsx(kr,{mode:"view",shapes:t.graphConfig?.shapes||[],boundingBox:t.graphConfig?.boundingBox,showGrid:t.graphConfig?.showGrid,showAxis:t.graphConfig?.showAxis});case"image":return u.jsx("img",{src:t.content,alt:"选项图片",className:"max-w-full"});default:return u.jsx("span",{children:t.content})}}const sb=({options:t,correctAnswers:e,answerType:n,layout:r="vertical",variant:s="default",value:o=[],onChange:i,showResult:a=!1,disabled:l=!1,className:c})=>{const d=x.useMemo(()=>t.map(g=>({id:g.id,label:rb(g),rawContent:g.content,contentType:g.contentType||"text"})),[t]),f=x.useCallback(g=>{i?.(g)},[i]);return u.jsx(ki,{type:n,options:d,value:o,onChange:f,correctAnswers:e,showResult:a,disabled:l,layout:r,variant:s,className:c})},ob={FACTOR_TABLE:"factorTable",SHORT_DIVISION:"shortDivision",VERTICAL_MULTIPLICATION:"verticalMultiplication",LONG_DIVISION:"longDivision"},ib={EDIT:"edit",REVIEW:"review",SOLUTION:"solution"},ab={CORRECT:"correct",INCORRECT:"incorrect",PENDING:"pending"};function Qd(t){const{config:e,initialAnswers:n={},onAnswerChange:r,onValidationChange:s}=t,{number:o,rows:i}=e,a=x.useRef(n),l=x.useRef({}),[c,d]=x.useState(n),[f,g]=x.useState({});x.useEffect(()=>{a.current=c},[c]),x.useEffect(()=>{l.current=f},[f]);const h=x.useCallback((w,v)=>w===null||v===null?"pending":w*v===o?"correct":"incorrect",[o]),m=x.useCallback((w,v)=>{const S=a.current,_=l.current,A={value:v,status:"pending"},C={...S,[w]:A};a.current=C,d(C),r?.(C);const R=w.split("_");if(R.length!==3)return;const N=parseInt(R[1],10),M=parseInt(R[2],10);if(isNaN(N)||isNaN(M))return;const D=`factor_${N}_${M===0?1:0}`,P=C[D];if(v!==null&&P?.value!=null){const $=M===0?v:P.value,O=M===0?P.value:v,T=h($,O),B={..._,[w]:T,[D]:T};l.current=B,g(B),s?.(B)}},[h,r,s]),p=x.useCallback(w=>f[w]||c[w]?.status||"pending",[f,c]),y=x.useMemo(()=>{const w=i*2;return Object.values(c).filter(S=>S.value!==null).length===w},[c,i]),b=x.useCallback(()=>{d({}),g({}),a.current={},l.current={}},[]);return{answers:c,updateAnswer:m,getCellStatus:p,validation:f,isComplete:y,reset:b}}function eu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{dividend:s,divisor:o,steps:i}=e,a=x.useRef(n),[l,c]=x.useState(n),[d,f]=x.useState({});x.useEffect(()=>{a.current=l},[l]);const g=x.useCallback(w=>{const v=s.toString();if(w===0)return parseInt(v[0],10);const S=d[w-1]?.remainder??0,_=parseInt(v[w],10);return S*10+_},[s,d]),h=x.useCallback(w=>{const v=g(w);return{quotient:Math.floor(v/o),remainder:v%o}},[g,o]),m=x.useCallback((w,v)=>{const S=a.current,_={value:v,status:"pending"},A={...S,[w]:_};a.current=A,c(A),r?.(A);const C=w.split("_");if(C.length!==2)return;const R=C[0],N=parseInt(C[1],10);if(isNaN(N)||N<0||N>=i)return;const M=h(N);f($=>({...$,[N]:M}));let F=!1;v!==null&&(R==="quotient"?F=v===M.quotient:R==="remainder"&&(F=v===M.remainder));const D={value:v,status:v===null?"pending":F?"correct":"incorrect"},P={...A,[w]:D};a.current=P,c(P)},[h,i,r]),p=x.useCallback(w=>l[w]?.status||"pending",[l]),y=x.useMemo(()=>{const w=i*2;return Object.values(l).filter(S=>S.value!==null).length===w},[l,i]),b=x.useCallback(()=>{c({}),f({}),a.current={}},[]);return{answers:l,updateAnswer:m,getCellStatus:p,stepResults:d,isComplete:y,reset:b}}function lb(t,e){return e.toString().split("").reverse().map(Number).map((r,s)=>({digit:r,partial:t*r*Math.pow(10,s),rowIndex:s}))}function cb(t,e){return t.reduce((r,s)=>r+s.partial.toString().length,0)+e.toString().length}function db(t,e,n){const r=t.split("_"),s=r[0];if(s==="partial"&&r.length===3){const o=parseInt(r[1],10),i=parseInt(r[2],10);if(isNaN(o)||isNaN(i))return null;const a=e[o]?.partial;if(a===void 0)return null;const l=a.toString().split("").reverse();return l[i]!==void 0?parseInt(l[i],10):null}if(s==="product"&&r.length===2){const o=parseInt(r[1],10);if(isNaN(o))return null;const i=n.toString().split("").reverse();return i[o]!==void 0?parseInt(i[o],10):null}return null}function ub(t,e){return Object.values(t).filter(r=>r.value!==null).length===e&&e>0}function tu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{multiplicand:s,multiplier:o}=e,i=x.useRef(n),[a,l]=x.useState(n);x.useEffect(()=>{i.current=a},[a]);const c=x.useMemo(()=>s*o,[s,o]),d=x.useMemo(()=>lb(s,o),[s,o]),f=x.useMemo(()=>cb(d,c),[d,c]),g=x.useCallback((y,b)=>{const w=i.current,v=db(y,d,c),_={value:b,status:b===null?"pending":b!==null&&b===v?"correct":"incorrect"},A={...w,[y]:_};i.current=A,l(A),r?.(A)},[d,c,r]),h=x.useCallback(y=>a[y]?.status||"pending",[a]),m=x.useMemo(()=>ub(a,f),[a,f]),p=x.useCallback(()=>{l({}),i.current={}},[]);return{answers:a,updateAnswer:g,getCellStatus:h,partialProducts:d,correctProduct:c,isComplete:m,reset:p}}function fb(t,e){if(t===0)return[{index:0,dividend:0,quotient:0,remainder:0,product:0}];const n=t.toString(),r=[];let s=0;for(let o=0;o<n.length;o++){s=s*10+parseInt(n[o],10);const i=Math.floor(s/e),a=s%e,l=i*e;r.push({index:o,dividend:s,quotient:i,remainder:a,product:l}),s=a}return r}function nu(t){const{config:e,initialAnswers:n={},onAnswerChange:r}=t,{dividend:s,divisor:o}=e,i=x.useRef(n),[a,l]=x.useState(n),c=x.useMemo(()=>Math.floor(s/o),[s,o]),d=x.useMemo(()=>s%o,[s,o]),f=x.useMemo(()=>fb(s,o),[s,o]);x.useEffect(()=>{i.current=a},[a]);const g=(b,w)=>{if(b<0)return null;const v=b.toString();return w>=v.length?null:parseInt(v[v.length-1-w],10)},h=x.useCallback((b,w)=>{const v=i.current,S=b.split("_");if(S.length<2)return;let _=S[0],A;if(b.startsWith("div_q_"))_="quotient",A=parseInt(S[2],10);else if(b.startsWith("div_s")){_="product";const D=S[1].substring(1);A=parseInt(D,10)-1}else A=parseInt(S[1],10);if(isNaN(A)||A<0||A>=f.length)return;const C=f[A];let R=null,N=!1;if(_==="quotient")R=C.quotient,N=w!==null&&w===R;else if(_==="product")if(S.length===3){const D=parseInt(S[2],10);isNaN(D)||(R=g(C.product,D),N=w!==null&&w===R)}else R=C.product,N=w!==null&&w===R;else if(_==="remainder")if(S.length===3){const D=parseInt(S[2],10);isNaN(D)||(R=g(C.remainder,D),N=w!==null&&w===R)}else R=C.remainder,N=w!==null&&w===R;const M={value:w,status:w===null?"pending":N?"correct":"incorrect"},F={...v,[b]:M};i.current=F,l(F),r?.(F)},[f,r]),m=x.useCallback(b=>a[b]?.status||"pending",[a]),p=x.useMemo(()=>{const b=f.length*3;return Object.values(a).filter(v=>v.value!==null).length===b},[a,f]),y=x.useCallback(()=>{l({}),i.current={}},[]);return{answers:a,updateAnswer:h,getCellStatus:m,steps:f,quotient:c,remainder:d,isComplete:p,reset:y}}const ru=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,readonly:i=!1}=e,{number:a,rows:l}=n,c=x.useCallback((f,g)=>{const h=g.trim()===""?null:parseInt(g,10);g.trim()!==""&&isNaN(h)||s(f,h)},[s]),d=x.useCallback(f=>{const g=`factor_${f}_0`,h=`factor_${f}_1`,m=r[g],p=r[h],y=o(g),b=o(h),w=v=>{const S="w-16 h-10 text-center border-2 rounded focus:outline-none focus:ring-2";switch(v){case"correct":return`${S} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${S} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${S} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}};return u.jsxs("div",{className:"contents",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:m?.value??"",readOnly:i,onChange:v=>c(g,v.target.value),className:w(y),"aria-label":`第 ${f+1} 行左侧因数`,"data-cell-id":g}),u.jsx("span",{className:"text-gray-500 font-medium select-none",children:"×"})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:p?.value??"",readOnly:i,onChange:v=>c(h,v.target.value),className:w(b),"aria-label":`第 ${f+1} 行右侧因数`,"data-cell-id":h}),u.jsx("span",{className:"text-gray-500 font-medium select-none",children:"="}),u.jsx("span",{className:"text-gray-700 font-semibold min-w-[2rem] select-none",children:a})]})]},f)},[r,o,c,i,a]);return u.jsxs("div",{className:"inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`因数表:分解 ${a}`,children:[u.jsx("div",{className:"mb-4 text-center",children:u.jsxs("span",{className:"text-lg font-semibold text-gray-800",children:["找出 ",a," 的所有因数对"]})}),u.jsx("div",{className:"grid grid-cols-2 gap-x-8 gap-y-3",role:"grid","aria-label":`${a} 的因数表`,children:Array.from({length:l},(f,g)=>d(g))})]})});ru.displayName="FactorTableView";const Di=t=>{const{config:e,initialAnswers:n={},onAnswerChange:r,onValidationChange:s,readonly:o=!1}=t,{answers:i,updateAnswer:a,getCellStatus:l,validation:c,isComplete:d,reset:f}=Qd({config:e,initialAnswers:n,onAnswerChange:r,onValidationChange:s});x.useEffect(()=>{d&&r&&r(i)},[d,i,r]);const g=o||e.mode!=="edit";return u.jsx(ru,{config:e,answers:i,onCellChange:a,getCellStatus:l,readonly:g})};Di.displayName="FactorTable";const su=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,readonly:i=!1}=e,{dividend:a,divisor:l,steps:c}=n,d=x.useCallback((h,m)=>{const p=m.trim();if(p===""){s(h,null);return}const y=parseInt(p,10);isNaN(y)||s(h,y)},[s]),f=h=>{const m="w-12 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-medium";switch(h){case"correct":return`${m} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${m} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${m} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}},g=x.useCallback(h=>{const m=`quotient_${h}`,p=`remainder_${h}`,y=r[m],b=r[p],w=o(m),v=o(p);return u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:y?.value??"",readOnly:i,onChange:S=>d(m,S.target.value),className:f(w),"aria-label":`第 ${h+1} 步的商`,"data-cell-id":m}),u.jsx("span",{className:"text-gray-400 select-none",children:"..."}),u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:b?.value??"",readOnly:i,onChange:S=>d(p,S.target.value),className:f(v),"aria-label":`第 ${h+1} 步的余数`,"data-cell-id":p})]},h)},[r,o,d,i]);return u.jsx("div",{className:"mathwiz-short-division inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`短除法:${a} ÷ ${l}`,children:u.jsxs("div",{className:"flex items-start gap-4",children:[u.jsxs("div",{className:"flex flex-col items-center pt-2",children:[u.jsx("span",{className:"text-xl font-bold text-gray-800",children:l}),u.jsx("div",{className:"w-8 h-0.5 bg-gray-400 my-1"})]}),u.jsxs("div",{className:"flex flex-col gap-2",children:[u.jsx("div",{className:"text-xl font-bold text-gray-800 text-right border-b-2 border-gray-400 pb-1",children:a}),u.jsx("div",{className:"flex flex-col gap-2 pt-2",children:Array.from({length:c},(h,m)=>g(m))})]})]})})});su.displayName="ShortDivisionView";const Li=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,stepResults:l,isComplete:c}=eu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{c&&r&&r(o)},[c,o,r]),u.jsx(su,{config:e,answers:o,onCellChange:i,getCellStatus:a,stepResults:l,readonly:s})};Li.displayName="ShortDivision";function hb(t){const e=t.trim()===""?null:parseInt(t,10);return t.trim()!==""&&isNaN(e)?null:e}function gb(t){const e="w-8 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-semibold";switch(t){case"correct":return`${e} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${e} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${e} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}}function mb(t,e,n){return Math.max(t.toString().length,e.toString().length+1,n.toString().length)}const Ya=({digits:t,prefix:e,className:n=""})=>u.jsxs("div",{className:`flex justify-end items-center gap-1 ${n}`,children:[e,t.map((r,s)=>u.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-800",children:r},s))]}),Ka=({width:t})=>u.jsx("div",{className:"border-t-2 border-gray-400 my-2",style:{width:t},"aria-hidden":"true"}),ou=({cellId:t,value:e,status:n,readonly:r,ariaLabel:s,onChange:o})=>u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:e??"",readOnly:r,onChange:i=>o(t,i.target.value),className:gb(n),"aria-label":s,"data-cell-id":t}),pb=({rowIndex:t,partial:e,maxDigits:n,answers:r,getCellStatus:s,readonly:o,onChange:i})=>{const a=e.toString().split(""),l=n-a.length;return u.jsxs("div",{className:"flex justify-end items-center gap-1 mb-1",children:[Array.from({length:l}).map((c,d)=>u.jsx("span",{className:"w-8"},d)),[...a].reverse().map((c,d)=>{const f=`partial_${t}_${d}`;return u.jsx(ou,{cellId:f,value:r[f]?.value??null,status:s(f),readonly:o,ariaLabel:`第 ${t+1} 行中间积第 ${d+1} 位`,onChange:i},f)})]},`p-${t}`)},yb=({correctProduct:t,maxDigits:e,answers:n,getCellStatus:r,readonly:s,onChange:o})=>{const i=t.toString().split(""),a=e-i.length;return u.jsxs("div",{className:"flex justify-end items-center gap-1",children:[Array.from({length:a}).map((l,c)=>u.jsx("span",{className:"w-8"},c)),[...i].reverse().map((l,c)=>{const d=`product_${c}`;return u.jsx(ou,{cellId:d,value:n[d]?.value??null,status:r(d),readonly:s,ariaLabel:`乘积第 ${c+1} 位`,onChange:o},d)})]})},iu=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,partialProducts:i,correctProduct:a,readonly:l=!1}=e,{multiplicand:c,multiplier:d}=n,f=mb(c,d,a),g=x.useCallback((h,m)=>s(h,hb(m)),[s]);return u.jsx("div",{className:"inline-block p-6 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`乘法竖式:${c} × ${d}`,children:u.jsxs("div",{className:"flex flex-col items-end",children:[u.jsx(Ya,{digits:c.toString().split(""),className:"mb-1"}),u.jsx(Ya,{digits:d.toString().split(""),prefix:u.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-600 select-none",children:"×"}),className:"mb-2"}),u.jsx(Ka,{width:`${f*2.25}rem`}),i.map((h,m)=>u.jsx(pb,{rowIndex:m,partial:h.partial,maxDigits:f,answers:r,getCellStatus:o,readonly:l,onChange:g},m)),u.jsx(Ka,{width:`${f*2.25}rem`}),u.jsx(yb,{correctProduct:a,maxDigits:f,answers:r,getCellStatus:o,readonly:l,onChange:g})]})})});iu.displayName="VerticalMultiplicationView";const zi=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,partialProducts:l,correctProduct:c,isComplete:d}=tu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{d&&r&&r(o)},[d,o,r]),u.jsx(iu,{config:e,answers:o,onCellChange:i,getCellStatus:a,partialProducts:l,correctProduct:c,readonly:s})};zi.displayName="VerticalMultiplication";const bb=Us({base:["border rounded text-center font-medium transition-colors duration-150","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent","text-lg"],variants:{size:{digit:"w-10 h-10",standard:"min-w-12 h-10 px-2"},status:{normal:"border-gray-300 bg-white text-gray-900",correct:"border-emerald-500 bg-emerald-50 text-emerald-700",incorrect:"border-red-500 bg-red-50 text-red-700 line-through",idle:"border-dashed border-gray-400 bg-gray-50 text-gray-500"},type:{input:"",label:"font-bold bg-gray-100 cursor-default",result:"font-semibold bg-blue-50",placeholder:"opacity-0 pointer-events-none"},disabled:{true:"cursor-not-allowed opacity-60",false:""},readonly:{true:"cursor-default",false:""}},defaultVariants:{size:"digit",status:"normal",type:"input",disabled:!1,readonly:!1}});Us({base:"inline-flex items-center gap-1"});const Vi=x.memo(function(e){const{type:n,value:r,readonly:s=!1,status:o,autoTab:i=!1,place:a,onChange:l,className:c,cellId:d,onAutoTab:f}=e,g=x.useRef(null),[h,m]=x.useState(r?.toString()||"");x.useEffect(()=>{m(r?.toString()||"")},[r]);const p=a===void 0||a!==null,y=x.useMemo(()=>bb({size:p?"digit":"standard",status:o||"normal",type:n,readonly:s,disabled:s}),[p,o,n,s]),b=x.useCallback(v=>{if(s)return;let S=v.target.value;S=S.replace(/[^0-9]/g,""),p&&(S=S.slice(-1)),m(S);const _=S===""?null:Number(S);l?.(_),p&&i&&S&&d&&f&&f(d,"next")},[s,p,i,d,l,f]),w=x.useCallback(v=>{s||v.key==="Backspace"&&h===""&&d&&f&&f(d,"prev")},[s,h,d,f]);return n==="placeholder"?u.jsx("div",{className:`${y} ${c||""}`,"aria-hidden":"true","data-cell-id":d}):n==="label"||n==="result"||s?u.jsx("div",{className:`${y} ${c||""}`,role:"text","aria-label":d?`单元格 ${d}:${r||""}`:`值:${r||""}`,"aria-readonly":"true","data-cell-id":d,"data-place":a,"data-testid":d?`mathcell-${d}`:"mathcell",children:r||""}):u.jsx("input",{ref:g,type:"text",inputMode:"numeric",pattern:"[0-9]*",value:h,onChange:b,onKeyDown:w,className:`${y} ${c||""}`,disabled:s,"aria-label":d?`输入单元格 ${d}`:"数学输入","aria-invalid":o==="incorrect",maxLength:p?1:void 0,"data-cell-id":d,"data-place":a,"data-testid":d?`mathcell-input-${d}`:"mathcell-input"})});Vi.displayName="MathCell";function xb(t){return{display:"grid",gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${t.rows}, auto)`,gap:"0.1rem",justifyItems:"center",alignItems:"center"}}function vb(t,e){const{dividend:n,divisor:r}=t,o=n.toString().split("").map(Number);r.toString().split("").map(Number);const a=o.length+1;let l=2;for(let g=0;g<e.length;g++)l+=3;const c=[];for(let g=0;g<e.length;g++){const h=e[g];c.push({id:`div_q_${g}`,type:"quotient",value:h.quotient,place:g,readonly:!1,position:{row:0,col:g+1}})}c.push({id:"divisor",type:"divisor",value:r,readonly:!0,position:{row:1,col:0},className:"text-right pr-2 self-end pb-1"});for(let g=0;g<o.length;g++){const m=g===0?"div-bracket-left pt-2 mt-2":"div-bracket-top pt-2 mt-2";c.push({id:`dividend_${g}`,type:"dividend",value:o[g],readonly:!0,position:{row:1,col:g+1},className:m,dataAttrs:{"data-digit-index":g.toString()}})}let d=2;const f=o.length-e.length;for(let g=0;g<e.length;g++){const h=e[g],m=g+1;h.dividend.toString().split("").map(Number).length;const w=h.product.toString().split("").map(Number),v=w.length,_=h.remainder.toString().split("").map(Number),A=_.length,C=f+g+1,R=C-v+1;for(let N=0;N<v;N++)c.push({id:`div_s${m}_${N}`,type:"product",value:w[N],place:N,readonly:!1,position:{row:d,col:R+N}});if(d++,c.push({id:`hline_${g}`,type:"horizontalLine",value:null,readonly:!0,position:{row:d,col:R,colspan:v},className:"border-t-2 border-neutral-800 my-1"}),d++,g<e.length-1){const F=e[g+1].dividend.toString().split("").map(Number),D=C+1,P=D-A;for(let O=0;O<A;O++)c.push({id:`remainder_${g}_${O}`,type:"remainderWithBringDown",value:_[O],readonly:!0,position:{row:d,col:P+O}});const $=F[F.length-1];c.push({id:`bringdown_${g}`,type:"remainderWithBringDown",value:$,readonly:!0,position:{row:d,col:D}})}else{const N=C-A+1;for(let M=0;M<A;M++)c.push({id:`remainder_${g}_${M}`,type:"remainder",value:_[M],readonly:!0,position:{row:d,col:N+M}})}d+=1}return l=d,{columns:a,rows:l,cells:c,divisorPosition:[1,0],dividendStartPosition:[1,1],quotientStartPosition:[0,1]}}const au=x.memo(function(e){const{config:n,answers:r,onCellChange:s,getCellStatus:o,steps:i,readonly:a=!1}=e;x.useEffect(()=>{if(document.getElementById("mathwiz-long-division-styles"))return;const g=document.createElement("style");return g.id="mathwiz-long-division-styles",g.textContent=`
17
17
  .div-bracket-top {
18
18
  border-top: 2px solid #1b2b4c;
19
19
  position: relative;
@@ -41,10 +41,43 @@ Received: ${JSON.stringify(r)}`)}case"shear":{const r=t.params,s=De(r.shearX,e),
41
41
  border-top-right-radius: 12px 40%;
42
42
  border-bottom-right-radius: 12px 40%;
43
43
  }
44
- `,document.head.appendChild(g),()=>{const h=document.getElementById("mathwiz-long-division-styles");h&&h.remove()}},[]);const l=x.useMemo(()=>fb(n,i),[n,i]),c=(g,h)=>{s(g,h)},d=g=>{switch(g){case"correct":return"correct";case"incorrect":return"incorrect";case"pending":return"idle";default:return"idle"}},f=g=>{const{id:h,type:m,value:p,place:y,readonly:b=!1,position:w,className:v,dataAttrs:S}=g;let _="input",A=a||b;switch(m){case"quotient":case"product":case"remainder":_="input";break;case"dividend":case"divisor":_="label",A=!0;break;case"horizontalLine":_=null,A=!0;break;case"remainderWithBringDown":_="label",A=!0;break;case"placeholder":_="placeholder",A=!0;break;default:_="placeholder",A=!0;break}const C=d(o(h));let R=`${w.row+1}`,k=`${w.col+1}`;w.colspan&&w.colspan>1&&(k=`${w.col+1} / span ${w.colspan}`),w.rowspan&&w.rowspan>1&&(R=`${w.row+1} / span ${w.rowspan}`);const M={gridRow:R,gridColumn:k,...g.type==="horizontalLine"?{justifySelf:"stretch",alignSelf:"center"}:{}};return u.jsx("div",{className:v,style:M,"data-cell-id":h,...S,children:_!==null&&u.jsx(Vi,{type:_,value:p!==null?p:void 0,readonly:A,status:C,place:y,onChange:F=>c(h,F),cellId:h,autoTab:!A&&y!==null})},h)};return u.jsxs("div",{className:"mathwiz-long-division p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`长除法:${n.dividend} ÷ ${n.divisor}`,children:[u.jsx("div",{className:"text-lg font-bold text-primary-500 mb-4",children:"长除法竖式"}),u.jsx("div",{className:"long-division-grid",style:{...ub(l),paddingLeft:"1.5rem",overflow:"visible"},children:l.cells.map(f)})]})});au.displayName="LongDivisionView";const Gi=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,steps:l,quotient:c,remainder:d,isComplete:f}=nu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{f&&r&&r(o)},[f,o,r]),u.jsx(au,{config:e,answers:o,onCellChange:i,getCellStatus:a,steps:l,readonly:s})};Gi.displayName="LongDivision";const hb=({block:t,onInteraction:e})=>{const{containerType:n,config:r,onAnswerChange:s}=t,o=x.useCallback(i=>{e?.({type:"answerChange",answers:i}),s?.(i)},[e,s]);switch(n){case"factorTable":return u.jsx(Di,{config:r,onAnswerChange:o});case"shortDivision":return u.jsx(Li,{config:r,onAnswerChange:o});case"verticalMultiplication":return u.jsx(zi,{config:r,onAnswerChange:o});case"longDivision":return u.jsx(Gi,{config:r,onAnswerChange:o});default:return null}},gb=({headers:t,values:e,colors:n={}})=>{const{headerBg:r="#f1f5f9",valueBg:s="#ffffff",borderColor:o="#e2e8f0"}=n;return t.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):u.jsxs("div",{className:"place-value-chart",style:{display:"inline-block",border:`1px solid ${o}`,borderRadius:"8px",overflow:"hidden",fontFamily:"system-ui, sans-serif",fontSize:"14px",lineHeight:"1.4"},children:[u.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${o}`},children:t.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:r,fontWeight:"600",textAlign:"center",borderRight:a<t.length-1?`1px solid ${o}`:"none",color:"#1e293b"},children:i},a))}),u.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"12px",backgroundColor:s,textAlign:"center",borderRight:a<e.length-1?`1px solid ${o}`:"none",color:"#0f172a",fontSize:"16px",fontWeight:"500"},children:i},a))})]})},lu=({content:t,onInteraction:e,interactionValues:n={}})=>{const r=(s,o)=>{if(s.enabled===!1)return null;const i=`${s.type}-${o}`,a=l=>{e?.(i,l)};switch(s.type){case"text":return u.jsx(Kd,{content:s.content,style:s.style,onInteraction:a},i);case"formula":const l=s;return u.jsx(Xd,{parts:l.parts||[],displayMode:l.displayMode,style:s.style},i);case"graph":const c=s;return u.jsx(Zd,{shapes:c.shapes||[],width:c.width,height:c.height,showGrid:c.showGrid,showAxis:c.showAxis,boundingBox:c.boardConfig?.boundingBox,autoBoundingBox:!c.boardConfig?.boundingBox,animation:c.animation,animationProgress:c.animationProgress,showAnimationControls:c.showAnimationControls,onAnimationChange:c.onAnimationChange},i);case"hundredGrid":const d=s;return u.jsx(Ii,{...d.props},i);case"placeValueChart":const f=s;return u.jsx(gb,{...f.props},i);case"geometryTransform":const g=s;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:g.metadata,config:g.metadata?.config,hasConfig:!!g.metadata?.config,configKeys:g.metadata?.config?Object.keys(g.metadata.config):[],configShapes:g.metadata?.config?.shapes,configShapesAnimatedLength:g.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:g.metadata?.config?.shapes?.static?.length,configBase:g.metadata?.config?.base,configHeight:g.metadata?.config?.height,configUnit:g.metadata?.config?.unit,configTransform:g.metadata?.config?.transform}),u.jsx(Fi,{config:g.metadata.config,onTransformChange:y=>a({type:"transformChange",progress:y}),onTransformComplete:()=>a({type:"transformComplete"}),onError:y=>a({type:"error",error:y})},i);case"optionGroup":const h=s,m=h.metadata?.optionGroupId;return u.jsx(Xy,{options:h.options,correctAnswers:h.correctAnswers,answerType:h.answerType,layout:h.layout,variant:h.variant,value:n[m]??[],onChange:y=>a({type:"optionChange",value:y,optionGroupId:m})},i);case"mathContainer":const p=s;return u.jsx(hb,{block:p,onInteraction:a},i);default:return u.jsx("div",{onClick:()=>a({type:"click"}),children:s.content},i)}};return u.jsx(u.Fragment,{children:t.map(r)})},Be=({data:t,scene:e="question",layout:n={type:"card"},renderer:r={mode:"default"},theme:s="light",onContentInteraction:o,interactionValues:i,className:a="",children:l})=>{const c=Hd(t,e),d={data:c,scene:e,layout:c.layout||n,renderer:c.renderer||r,theme:s,onContentInteraction:o},f=c.layout||n,g=(()=>{switch(f.type){case"grid":return qd;case"flow":return Yd;default:return Wd}})(),h=(()=>{const m={className:a,theme:s,"data-testid":"mathcard-v2-container"};switch(f.type){case"grid":return{...m,columns:f.columns||2,gap:f.gap||"16px",responsive:f.responsive!==!1};case"flow":return{...m,direction:f.direction||"vertical",gap:f.gap||"16px",wrap:f.wrap!==!1};default:return{...m,padding:f.padding||"24px",shadow:f.shadow!==!1,border:f.border!==!1}}})();return u.jsx(Ly.Provider,{value:d,children:u.jsx(g,{...h,children:l||u.jsx(lu,{content:c.content,layout:c.layout||n,onInteraction:o,interactionValues:i})})})};Be.CardLayout=Wd;Be.GridLayout=qd;Be.FlowLayout=Yd;Be.TextContent=Kd;Be.FormulaContent=Xd;Be.GraphContent=Zd;Be.GeometryTransformContent=Fi;Be.ContentRenderer=lu;const cu=t=>{const{ixlConfig:e,enableIXLStyle:n,isMobile:r}=t,s=x.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),o=x.useMemo(()=>{if(e.tagColor)return e.tagColor;const d={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return d[e.type]||d.remember},[e.tagColor,e.type]),i=x.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=x.useMemo(()=>{if(!n)return{};const d={backgroundColor:o,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return r?Object.assign(d,{height:"var(--ixl-mobile-tag-height, 32px)",borderRadius:"var(--ixl-mobile-tag-border-radius, 8px 8px 0 0)",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",zIndex:1}):Object.assign(d,{width:"var(--ixl-tag-width, 40px)",borderRadius:"var(--ixl-tag-border-radius, 8px 0 0 8px)",height:"100%",position:"absolute",left:0,top:0,display:"flex",alignItems:"center",justifyContent:"center",writingMode:"vertical-rl",textOrientation:"mixed",transform:"rotate(0deg)"}),d},[n,o,i,r]),l=x.useMemo(()=>!n||r?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[n,r]);return{ixlClassName:x.useMemo(()=>{if(!n)return"";const d=["ixl-styled"];return d.push(`ixl-type-${e.type}`),r?d.push("ixl-mobile-layout"):d.push("ixl-desktop-layout"),d.join(" ")},[n,e.type,r]),tagStyle:a,contentStyle:l,tagText:s,tagColor:o,tagTextColor:i}},mb=(t,e)=>{let n=null;return(...r)=>{n&&clearTimeout(n),n=setTimeout(()=>{t(...r)},e)}},du=(t={})=>{const e=typeof t=="number"?t:t.breakpoint||768,n=typeof t=="number"?!0:t.enabled!==!1,[r,s]=x.useState(()=>typeof window<"u"?window.innerWidth:1024),[o,i]=x.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=x.useRef(new Set),l=x.useCallback(()=>{if(typeof window>"u")return;const g=window.innerWidth,h=g<e;s(g),i(h),a.current.forEach(m=>{try{m()}catch(p){console.error("Error in resize listener:",p)}})},[e]),c=x.useCallback(mb(l,150),[l]);x.useEffect(()=>{if(!(!n||typeof window>"u"))return l(),window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c)}},[n,c,l]);const d=x.useCallback(g=>(a.current.add(g),()=>{a.current.delete(g)}),[]),f=x.useCallback(g=>{a.current.delete(g)},[]);return{isMobile:o,viewportWidth:r,addResizeListener:d,removeResizeListener:f}},jn=({cardProps:t,ixlConfig:e,enableIXLStyle:n=!0,wrapperMode:r="mathcard",mobileBreakpoint:s=768,className:o="",style:i,children:a,onResponsiveChange:l})=>{const c=du(s),d=cu({ixlConfig:e,enableIXLStyle:n,isMobile:c.isMobile});x.useEffect(()=>{l?.(c.isMobile)},[c.isMobile,l]);const f=x.useMemo(()=>{const m=["ixl-style-card-container"];return n&&m.push(d.ixlClassName),o&&m.push(o),c.isMobile?m.push("ixl-mobile"):m.push("ixl-desktop"),m.join(" ")},[n,d.ixlClassName,o,c.isMobile]),g=x.useMemo(()=>{const m={...i};return n&&!c.isMobile?{...m,paddingLeft:d.contentStyle.paddingLeft}:m},[n,c.isMobile,d.contentStyle,i]),h=x.useMemo(()=>{if(r!=="mathcard"||!t)return"";const m=[t.className||""];return n&&m.push("ixl-adjusted"),m.filter(Boolean).join(" ")},[r,t?.className,n]);return u.jsxs("div",{className:f,style:g,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":n,"data-responsive-mode":c.isMobile?"mobile":"desktop",children:[n&&e.showTag!==!1&&u.jsx("div",{className:"ixl-tag",style:d.tagStyle,"data-testid":"ixl-tag",children:u.jsx("span",{className:"ixl-tag-text",children:d.tagText})}),r==="mathcard"&&t?u.jsx(Be,{...t,className:h}):a]})};jn.displayName="IXLStyleCard";const pb={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},yb={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},bb={remember:"速记",review:"回顾",solve:"解答"},xb=({grades:t,onGradeSelect:e,selectedGrade:n})=>u.jsxs("div",{className:"grade-navigation",children:[u.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),u.jsx("div",{className:"grade-navigation__grid",children:t.map(r=>u.jsxs("div",{className:`grade-card ${n===r.id?"grade-card--selected":""}`,style:{borderLeftColor:r.color},onClick:()=>e?.(r.id),children:[u.jsx("div",{className:"grade-card__level",children:r.level}),u.jsx("div",{className:"grade-card__name",children:r.name}),u.jsx("div",{className:"grade-card__description",children:r.description})]},r.id))})]}),uu=({abilities:t,width:e=400,height:n=400})=>{const r=()=>t.length===0?"":t.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*t.indexOf(i)/t.length,l=i.score/i.maxScore*40+10,c=50+l*Math.sin(a),d=50-l*Math.cos(a);return`${c},${d}`}).join(" "),s=i=>{const a=Math.PI*2*i/Math.max(t.length,1),l=50+40*Math.sin(a),c=50-40*Math.cos(a);return{x2:l,y2:c}},o=i=>{const a=Math.PI*2*i/Math.max(t.length,1),l=50+45*Math.sin(a),c=50-45*Math.cos(a);let d="middle";return a>Math.PI*.25&&a<Math.PI*.75&&(d="start"),a>Math.PI*1.25&&a<Math.PI*1.75&&(d="end"),{x:l,y:c,textAnchor:d}};return u.jsxs("svg",{"data-testid":"radar-chart",width:e,height:n,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[u.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),t.map((i,a)=>{const{x2:l,y2:c}=s(a);return u.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:l,y2:c,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),t.length>2&&u.jsx("polygon",{"data-testid":"radar-polygon",points:r(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),t.map((i,a)=>{let l,c;if(i.svgPoint)l=i.svgPoint.x,c=i.svgPoint.y;else{const d=Math.PI*2*a/t.length,f=i.score/i.maxScore*40+10;l=50+f*Math.sin(d),c=50-f*Math.cos(d)}return u.jsx("circle",{"data-testid":"data-point",cx:l,cy:c,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),t.map((i,a)=>{const{x:l,y:c,textAnchor:d}=o(a);return u.jsx("text",{x:l,y:c,textAnchor:d,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},Xa={overallRating:"优秀",generalRecommendation:"你的空间想象力和逻辑推理能力非常出色!若能进一步提升在复杂图形下的专注力,你将所向披靡。建议尝试我们‘专注力挑战’系列游戏。",abilities:[{name:"空间想象力",score:7.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:50,y:17.5},recommendation:"通过观察三维物体在不同角度的投影,或尝试构建复杂结构的游戏,能有效提升空间想象力。",recommendationLink:"#spatial-challenges"},{name:"逻辑推理",score:8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:82,y:35},recommendation:"解决数独、迷宫或逻辑谜题,能够持续锻炼你的逻辑思维,尝试挑战更高难度的推理游戏。",recommendationLink:"#logic-puzzles"},{name:"图形辨识",score:9,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:85,y:65},recommendation:"你在这方面表现出色!可以尝试在更复杂、干扰因素更多的图形中进行辨识训练,保持敏锐。",recommendationLink:"#graphic-training"},{name:"专注力",score:7,maxScore:10,progressBarColor:"bg-orange-400",svgPoint:{x:50,y:80},recommendation:"在长时间的游戏中保持专注对你来说是一个挑战,建议尝试我们‘专注力挑战’系列游戏,逐渐延长专注时间。",recommendationLink:"#focus-challenges"},{name:"观察力",score:8.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:15,y:65},recommendation:"你的观察力非常敏锐,在细节发现上尤为突出。尝试在限时模式下进行观察力训练,提高反应速度。",recommendationLink:"#observation-drills"},{name:"抗压性",score:7.8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:18,y:35},recommendation:"面对高压挑战时,保持冷静是关键。通过模拟竞赛或限时任务来提升抗压能力,逐步适应压力。",recommendationLink:"#stress-games"}]};class vb{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),Xa):(await Se.get(`${this.API_BASE_URL}/assessment`)).data}catch(e){if(console.error("Failed to fetch radar ability data:",e),process.env.NODE_ENV==="test")throw new Error("获取能力评估数据失败");return Xa}}static async submitFeedback(e){try{await Se.post(`${this.API_BASE_URL}/feedback`,e)}catch(n){throw console.error("Failed to submit feedback:",n),new Error("提交反馈失败")}}}const wb=Dn.create((t,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){t({loading:!0,error:null});try{const n=await vb.fetchRadarAbilityData();t({data:n,loading:!1})}catch(n){const r=n instanceof Error?n.message:"获取数据失败";t({error:r,loading:!1})}}},setData:n=>{t({data:n,error:null,loading:!1})},setError:n=>{t({error:n,loading:!1})},reset:()=>{t({data:null,loading:!1,error:null})}})),fu=({ability:t})=>{const e=t.score/t.maxScore*100;return u.jsxs("div",{className:"ability-progress-bar-item","data-ability":t.name,"data-testid":"progress-bar-container",children:[u.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[u.jsx("span",{className:"text-gray-700 font-medium",children:t.name}),u.jsxs("span",{className:"text-gray-600",children:[t.score,"/",t.maxScore]})]}),u.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:u.jsx("div",{className:`${t.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":t.score,"aria-valuemin":0,"aria-valuemax":t.maxScore,"aria-label":`${t.name} progress: ${t.score} out of ${t.maxScore}`})})]})},hu=({generalRecommendation:t})=>u.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:u.jsxs("div",{className:"flex items-start",children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),u.jsxs("div",{className:"ml-3",children:[u.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),u.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:t})]})]})}),gu=({ability:t,customLinkTexts:e={}})=>{const n=r=>{const s={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[r]||s[r]||"开始挑战"};return u.jsx(H.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":t.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:u.jsx(H.CardBody,{className:"p-5",children:u.jsxs("div",{className:"flex flex-col gap-3",children:[u.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[t.name,": 专项提高"]}),u.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:t.recommendation}),u.jsx(H.Button,{as:"a",href:t.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:u.jsx(Z.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${t.name}专项提高页面`,children:n(t.name)})]})})})},_b="_dashboardLayout_10wqn_5",Sb="_upperSection_10wqn_19",Cb="_lowerSection_10wqn_33",Rb="_radarChartArea_10wqn_51",Wr={dashboardLayout:_b,upperSection:Sb,lowerSection:Cb,radarChartArea:Rb},Ab=()=>{const{data:t,loading:e,error:n,fetchData:r}=wb();return x.useEffect(()=>{r()},[r]),e?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),u.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):n?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[u.jsx("div",{className:"text-red-500 mb-4",children:u.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),u.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),u.jsx("p",{className:"text-gray-600 mb-4",children:n}),u.jsx("button",{onClick:r,className:"bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2","aria-label":"重试加载数据",children:"重试"})]}):t?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 animate-fade-in","data-component":"AbilityAssessmentDashboard",role:"main","aria-label":"能力评估雷达图展示",children:[u.jsxs("div",{className:"flex justify-between items-center mb-6",children:[u.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),u.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${t.overallRating}`,children:["综合评级: ",t.overallRating]})]}),u.jsxs("div",{className:Wr.dashboardLayout,children:[u.jsxs("div",{className:Wr.upperSection,children:[u.jsx("div",{className:Wr.radarChartArea,children:u.jsx(uu,{abilities:t.abilities})}),u.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:t.abilities.map(s=>u.jsx(fu,{ability:s},s.name))})]}),u.jsxs("div",{className:Wr.lowerSection,children:[u.jsx(hu,{generalRecommendation:t.generalRecommendation}),u.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.abilities.map(s=>u.jsx(gu,{ability:s},s.name))})]})]})]}):u.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:u.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},mr={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},kb={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},Eb={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Tr={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},Nb=[{id:"g3",label:"三年级",status:"new",onClick:()=>console.log("三年级 clicked")},{id:"g4",label:"四年级",status:"2%",onClick:()=>console.log("四年级 clicked")},{id:"g5",label:"五年级",status:"进行中",onClick:()=>console.log("五年级 clicked")},{id:"g6",label:"六年级",status:"new",onClick:()=>console.log("六年级 clicked")},{id:"g7",label:"七年级",status:"new",onClick:()=>console.log("七年级 clicked")},{id:"g8",label:"八年级",status:"new",onClick:()=>console.log("八年级 clicked")},{id:"alg_topic",label:"代数专题",status:"new",onClick:()=>console.log("代数专题 clicked")},{id:"calc_topic",label:"计算专题",status:"new",onClick:()=>console.log("计算专题 clicked")},{id:"geo_topic",label:"几何专题",status:"new",onClick:()=>console.log("几何专题 clicked")},{id:"olym_topic",label:"奥数专题",status:"new",onClick:()=>console.log("奥数专题 clicked")}],Tb="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",Re={id:"g5",title:"小学数学五年级",level:5,subject:"数学",units:[{id:"unit_1",title:"小数乘法",description:"学习小数乘法的计算方法及应用",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit1_lesson1",title:"小数乘整数",duration:40,knowledgeItems:[{id:"unit1_lesson1_k1",title:"小数乘整数的意义",description:"理解小数乘整数的意义与整数乘法相同",progress:0,contentUrl:""},{id:"unit1_lesson1_k2",title:"小数乘整数的计算方法",description:"掌握小数乘整数的计算方法:先按整数乘法计算,再看因数中有几位小数,就从积的右边起数出几位点上小数点",progress:0,contentUrl:""}]},{id:"unit1_lesson2",title:"小数乘小数",duration:40,knowledgeItems:[{id:"unit1_lesson2_k1",title:"小数乘小数的计算方法",description:"掌握小数乘小数的计算方法:先按整数乘法算出积,再给积点上小数点",progress:0,contentUrl:""},{id:"unit1_lesson2_k2",title:"积的小数位数确定",description:"理解积的小数位数等于两个因数的小数位数之和",progress:0,contentUrl:""}]},{id:"unit1_lesson3",title:"积的近似数",duration:40,knowledgeItems:[{id:"unit1_lesson3_k1",title:'用"四舍五入"法求积的近似数',description:'掌握用"四舍五入"法求积的近似数的方法',progress:0,contentUrl:""}]},{id:"unit1_lesson4",title:"整数乘法运算定律推广到小数",duration:40,knowledgeItems:[{id:"unit1_lesson4_k1",title:"乘法运算定律在小数中的适用性",description:"理解整数乘法运算定律对于小数乘法同样适用",progress:0,contentUrl:""},{id:"unit1_lesson4_k2",title:"运用运算定律进行简便计算",description:"能运用乘法运算定律进行小数乘法的简便计算",progress:0,contentUrl:""}]},{id:"unit1_lesson5",title:"解决问题",duration:40,knowledgeItems:[{id:"unit1_lesson5_k1",title:"用小数乘法解决实际问题",description:"能运用小数乘法解决购物、面积计算等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_2",title:"小数除法",description:"学习小数除法的计算方法及应用",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit2_lesson1",title:"小数除以整数",duration:40,knowledgeItems:[{id:"unit2_lesson1_k1",title:"小数除以整数的计算方法",description:"掌握小数除以整数的计算方法:按照整数除法的方法计算,商的小数点要与被除数的小数点对齐",progress:0,contentUrl:""}]},{id:"unit2_lesson2",title:"一个数除以小数",duration:40,knowledgeItems:[{id:"unit2_lesson2_k1",title:"除数是小数的除法计算方法",description:"掌握除数是小数的除法计算方法:利用商不变的性质,将除数转化为整数",progress:0,contentUrl:""}]},{id:"unit2_lesson3",title:"商的近似数",duration:40,knowledgeItems:[{id:"unit2_lesson3_k1",title:'用"四舍五入"法求商的近似数',description:'掌握用"四舍五入"法求商的近似数的方法',progress:0,contentUrl:""}]},{id:"unit2_lesson4",title:"循环小数",duration:40,knowledgeItems:[{id:"unit2_lesson4_k1",title:"循环小数的概念",description:"理解循环小数的概念,认识循环节",progress:0,contentUrl:""},{id:"unit2_lesson4_k2",title:"循环小数的表示方法",description:"掌握循环小数的简便表示方法",progress:0,contentUrl:""}]},{id:"unit2_lesson5",title:"用计算器探索规律",duration:40,knowledgeItems:[{id:"unit2_lesson5_k1",title:"用计算器计算小数除法",description:"会用计算器计算较复杂的小数除法",progress:0,contentUrl:""},{id:"unit2_lesson5_k2",title:"发现商的变化规律",description:"能借助计算器发现商的变化规律",progress:0,contentUrl:""}]},{id:"unit2_lesson6",title:"解决问题",duration:40,knowledgeItems:[{id:"unit2_lesson6_k1",title:"用小数除法解决实际问题",description:"能运用小数除法解决购物、分配等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_3",title:"简易方程",description:"学习用字母表示数和解简易方程",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit3_lesson1",title:"用字母表示数",duration:40,knowledgeItems:[{id:"unit3_lesson1_k1",title:"用字母表示数",description:"初步理解用字母表示数的意义和作用",progress:0,contentUrl:""},{id:"unit3_lesson1_k2",title:"用字母表示运算定律和计算公式",description:"会用字母表示运算定律和计算公式",progress:0,contentUrl:""}]},{id:"unit3_lesson2",title:"方程的意义",duration:40,knowledgeItems:[{id:"unit3_lesson2_k1",title:"方程的概念",description:"理解方程的意义,知道方程与等式的区别和联系",progress:0,contentUrl:""}]},{id:"unit3_lesson3",title:"等式的性质",duration:40,knowledgeItems:[{id:"unit3_lesson3_k1",title:"等式的性质1",description:"理解等式的性质1:等式两边加上或减去同一个数,左右两边仍然相等",progress:0,contentUrl:""},{id:"unit3_lesson3_k2",title:"等式的性质2",description:"理解等式的性质2:等式两边乘同一个数,或除以同一个不为0的数,左右两边仍然相等",progress:0,contentUrl:""}]},{id:"unit3_lesson4",title:"解简易方程",duration:40,knowledgeItems:[{id:"unit3_lesson4_k1",title:"利用等式的性质解方程",description:"会利用等式的性质解形如x±a=b、ax=b、x÷a=b、a-x=b、a÷x=b的方程",progress:0,contentUrl:""}]},{id:"unit3_lesson5",title:"实际问题与方程",duration:40,knowledgeItems:[{id:"unit3_lesson5_k1",title:"列方程解决实际问题",description:"初步学会列方程解决一些简单的实际问题",progress:0,contentUrl:""}]}]},{id:"unit_4",title:"多边形的面积",description:"学习平行四边形、三角形、梯形和组合图形的面积计算",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit4_lesson1",title:"平行四边形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson1_k1",title:"平行四边形面积公式的推导",description:"通过割补法理解平行四边形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson1_k2",title:"平行四边形面积的计算",description:"掌握平行四边形面积计算公式:S=ah,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson2",title:"三角形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson2_k1",title:"三角形面积公式的推导",description:"通过拼摆法理解三角形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson2_k2",title:"三角形面积的计算",description:"掌握三角形面积计算公式:S=ah÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson3",title:"梯形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson3_k1",title:"梯形面积公式的推导",description:"通过拼摆法理解梯形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson3_k2",title:"梯形面积的计算",description:"掌握梯形面积计算公式:S=(a+b)h÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson4",title:"组合图形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson4_k1",title:"认识组合图形",description:"认识组合图形,会把组合图形分解成已学过的平面图形",progress:0,contentUrl:""},{id:"unit4_lesson4_k2",title:"计算组合图形的面积",description:"掌握计算组合图形面积的多种方法",progress:0,contentUrl:""}]}]},{id:"unit_5",title:"因数与倍数",description:"学习因数、倍数、质数、合数等概念",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit5_lesson1",title:"因数和倍数",duration:40,knowledgeItems:[{id:"unit5_lesson1_k1",title:"因数和倍数的意义",description:"理解因数和倍数的意义,掌握找一个数的因数和倍数的方法",progress:0,contentUrl:""},{id:"unit5_lesson1_k2",title:"因数和倍数的特征",description:"了解一个数的因数的个数是有限的,倍数的个数是无限的",progress:0,contentUrl:""}]},{id:"unit5_lesson2",title:"2、5、3的倍数的特征",duration:40,knowledgeItems:[{id:"unit5_lesson2_k1",title:"2、5的倍数的特征",description:"掌握2、5的倍数的特征,理解奇数和偶数的意义",progress:0,contentUrl:""},{id:"unit5_lesson2_k2",title:"3的倍数的特征",description:"掌握3的倍数的特征,能判断一个数是不是3的倍数",progress:0,contentUrl:""}]},{id:"unit5_lesson3",title:"质数和合数",duration:40,knowledgeItems:[{id:"unit5_lesson3_k1",title:"质数和合数的意义",description:"理解质数和合数的意义,能判断一个数是质数还是合数",progress:0,contentUrl:""},{id:"unit5_lesson3_k2",title:"制作100以内的质数表",description:"会制作100以内的质数表,熟记20以内的质数",progress:0,contentUrl:""}]}]},{id:"unit_6",title:"长方体和正方体",description:"学习长方体和正方体的特征、表面积和体积计算",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit6_lesson1",title:"长方体和正方体的认识",duration:40,knowledgeItems:[{id:"unit6_lesson1_k1",title:"长方体的特征",description:"认识长方体的特征,了解长方体的长、宽、高",progress:0,contentUrl:""},{id:"unit6_lesson1_k2",title:"正方体的特征",description:"认识正方体的特征,理解正方体是特殊的长方体",progress:0,contentUrl:""}]},{id:"unit6_lesson2",title:"长方体和正方体的表面积",duration:40,knowledgeItems:[{id:"unit6_lesson2_k1",title:"表面积的意义",description:"理解表面积的意义,掌握长方体和正方体表面积的计算方法",progress:0,contentUrl:""},{id:"unit6_lesson2_k2",title:"表面积的实际应用",description:"能运用表面积知识解决一些实际问题",progress:0,contentUrl:""}]},{id:"unit6_lesson3",title:"长方体和正方体的体积",duration:40,knowledgeItems:[{id:"unit6_lesson3_k1",title:"体积和体积单位",description:"理解体积的意义,认识常用的体积单位",progress:0,contentUrl:""},{id:"unit6_lesson3_k2",title:"长方体和正方体体积的计算",description:"掌握长方体和正方体体积的计算公式",progress:0,contentUrl:""},{id:"unit6_lesson3_k3",title:"体积单位间的进率",description:"掌握体积单位之间的进率和换算",progress:0,contentUrl:""}]},{id:"unit6_lesson4",title:"容积和容积单位",duration:40,knowledgeItems:[{id:"unit6_lesson4_k1",title:"容积和容积单位",description:"理解容积的意义,认识常用的容积单位",progress:0,contentUrl:""},{id:"unit6_lesson4_k2",title:"容积和体积的关系",description:"掌握容积和体积之间的关系",progress:0,contentUrl:""}]}]},{id:"unit_7",title:"分数的意义和性质",description:"学习分数的意义、性质和约分、通分等方法",estimatedDuration:"4周",totalLessons:16,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit7_lesson1",title:"分数的意义",duration:40,knowledgeItems:[{id:"unit7_lesson1_k1",title:"分数的产生和意义",description:"理解分数的产生和意义,明确分数与除法的关系",progress:0,contentUrl:""},{id:"unit7_lesson1_k2",title:"分数单位",description:"认识分数单位,能说出一个分数中有几个这样的分数单位",progress:0,contentUrl:""}]},{id:"unit7_lesson2",title:"分数与除法",duration:40,knowledgeItems:[{id:"unit7_lesson2_k1",title:"分数与除法的关系",description:"理解分数与除法的关系,会用分数表示两个数相除的商",progress:0,contentUrl:""}]},{id:"unit7_lesson3",title:"真分数和假分数",duration:40,knowledgeItems:[{id:"unit7_lesson3_k1",title:"真分数和假分数的意义",description:"理解真分数和假分数的意义和特征",progress:0,contentUrl:""},{id:"unit7_lesson3_k2",title:"带分数",description:"认识带分数,会进行假分数与整数、带分数的互化",progress:0,contentUrl:""}]},{id:"unit7_lesson4",title:"分数的基本性质",duration:40,knowledgeItems:[{id:"unit7_lesson4_k1",title:"分数的基本性质",description:"理解分数的基本性质,能运用分数的基本性质进行分数的变形",progress:0,contentUrl:""}]},{id:"unit7_lesson5",title:"约分",duration:40,knowledgeItems:[{id:"unit7_lesson5_k1",title:"最大公因数",description:"理解公因数和最大公因数的意义,掌握求两个数的最大公因数的方法",progress:0,contentUrl:""},{id:"unit7_lesson5_k2",title:"约分的方法",description:"掌握约分的方法,能正确地进行约分",progress:0,contentUrl:""}]},{id:"unit7_lesson6",title:"通分",duration:40,knowledgeItems:[{id:"unit7_lesson6_k1",title:"最小公倍数",description:"理解公倍数和最小公倍数的意义,掌握求两个数的最小公倍数的方法",progress:0,contentUrl:""},{id:"unit7_lesson6_k2",title:"通分的方法",description:"掌握通分的方法,能正确地进行通分",progress:0,contentUrl:""}]},{id:"unit7_lesson7",title:"分数和小数的互化",duration:40,knowledgeItems:[{id:"unit7_lesson7_k1",title:"分数化成小数",description:"掌握分数化成小数的方法",progress:0,contentUrl:""},{id:"unit7_lesson7_k2",title:"小数化成分数",description:"掌握小数化成分数的方法",progress:0,contentUrl:""}]}]},{id:"unit_8",title:"分数的加法和减法",description:"学习同分母分数、异分母分数的加法和减法",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit8_lesson1",title:"同分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson1_k1",title:"同分母分数加法的计算方法",description:"掌握同分母分数加法的计算方法",progress:0,contentUrl:""},{id:"unit8_lesson1_k2",title:"同分母分数减法的计算方法",description:"掌握同分母分数减法的计算方法",progress:0,contentUrl:""}]},{id:"unit8_lesson2",title:"异分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson2_k1",title:"异分母分数加法的计算方法",description:"掌握异分母分数加法的计算方法:先通分,然后按照同分母分数加法进行计算",progress:0,contentUrl:""},{id:"unit8_lesson2_k2",title:"异分母分数减法的计算方法",description:"掌握异分母分数减法的计算方法:先通分,然后按照同分母分数减法进行计算",progress:0,contentUrl:""}]},{id:"unit8_lesson3",title:"分数加减混合运算",duration:40,knowledgeItems:[{id:"unit8_lesson3_k1",title:"分数加减混合运算的顺序",description:"掌握分数加减混合运算的运算顺序",progress:0,contentUrl:""},{id:"unit8_lesson3_k2",title:"整数加法运算定律推广到分数加法",description:"理解整数加法运算定律对于分数加法同样适用,能运用运算定律进行简便计算",progress:0,contentUrl:""}]}]},{id:"unit_9",title:"折线统计图",description:"学习单式折线统计图和复式折线统计图的认识和制作",estimatedDuration:"2周",totalLessons:6,moduleCategory:"Probability and Statistics",lessons:[{id:"unit9_lesson1",title:"单式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson1_k1",title:"单式折线统计图的特点",description:"认识单式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson1_k2",title:"绘制单式折线统计图",description:"能根据数据绘制单式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson2",title:"复式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson2_k1",title:"复式折线统计图的特点",description:"认识复式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson2_k2",title:"绘制复式折线统计图",description:"能根据数据绘制复式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson3",title:"数据分析",duration:40,knowledgeItems:[{id:"unit9_lesson3_k1",title:"根据统计图进行数据分析",description:"能根据折线统计图进行简单的数据分析,作出合理的判断和预测",progress:0,contentUrl:""}]}]}]},Mb=Nb,$b=Tr;class jb{baseURL;token;constructor(e="/api/v1",n=Tb){this.baseURL=e,this.token=n}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,n={}){const r=await fetch(e,{...n,headers:{...this.getAuthHeaders(),...n.headers}});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return r}async getCourseData(e){return(await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}`)).json()}async getUserGradeUnitsNav(e){const n=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(n)).json()}async getUnitProgress(e,n){const r=n?`${this.baseURL}/content/courses/${e}/units/${n}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(r)).json()}async batchUpdateLessonProgress(e,n){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(n)})).json()}async updateLessonProgress(e,n,r,s){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${n}/lessons/${r}/progress`,{method:"POST",body:JSON.stringify({status:s})})}setToken(e){this.token=e}getToken(){return this.token}}const qr=new jb;class wt extends Error{constructor(e,n,r){super(e),this.code=n,this.originalError=r,this.name="DataSourceError"}}class Ob{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},qr.setToken(this.config.token)}async getUserGradeUnitsNav(e,n){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${n}`),await this.withRetry(()=>qr.getUserGradeUnitsNav(e))}catch(r){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",r),new wt(`获取年级单元导航数据失败: ${r instanceof Error?r.message:"未知错误"}`,"GET_USER_GRADE_UNITS_NAV_FAILED",r instanceof Error?r:void 0)}}async getUserProfile(e){try{return console.log(`[ApiDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}catch(n){throw console.error("[ApiDataSource] 获取用户个人信息失败:",n),new wt(`获取用户个人信息失败: ${n instanceof Error?n.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",n instanceof Error?n:void 0)}}async getExploreMenu(){try{return console.log("[ApiDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}catch(e){throw console.error("[ApiDataSource] 获取探索菜单数据失败:",e),new wt(`获取探索菜单数据失败: ${e instanceof Error?e.message:"未知错误"}`,"GET_EXPLORE_MENU_FAILED",e instanceof Error?e:void 0)}}async updateLessonProgress(e){try{console.log("[ApiDataSource] 更新课时进度:",e),await this.withRetry(()=>qr.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(n){throw console.error("[ApiDataSource] 更新课时进度失败:",n),new wt(`更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async batchUpdateLessonProgress(e,n){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,n),await this.withRetry(()=>qr.batchUpdateLessonProgress(e,n))}catch(r){throw console.error("[ApiDataSource] 批量更新课时进度失败:",r),new wt(`批量更新课时进度失败: ${r instanceof Error?r.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",r instanceof Error?r:void 0)}}async withRetry(e){let n;for(let r=1;r<=this.config.retryCount;r++)try{return await e()}catch(s){n=s instanceof Error?s:new Error(String(s)),r<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${r}次重试...`,n.message),await this.delay(this.config.retryDelay))}throw n}delay(e){return new Promise(n=>setTimeout(n,e))}getConfig(){return{...this.config}}}class Ib{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,n){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${n}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${n}`),new wt("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${n}`),{userId:n,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:Re.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:Re.units.map((s,o)=>({unitId:s.id,title:s.title,description:s.description,moduleCategory:s.moduleCategory,estimatedDuration:s.estimatedDuration,totalLessons:s.lessons.length,completedLessons:o<2?Math.floor(s.lessons.length*.5):0,progressPercentage:o<2?50:0,status:o<2?"in-progress":"not-started",lastAccessed:o<2?new Date().toISOString():void 0,isActive:o===0,route:`/math/grade-5/unit/${s.id}`,icon:mr[s.moduleCategory]||mr.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:获取用户个人信息失败","MOCK_GET_USER_PROFILE_FAILED");return console.log(`[MockDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}async getExploreMenu(){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:获取探索菜单数据失败","MOCK_GET_EXPLORE_MENU_FAILED");return console.log("[MockDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}async updateLessonProgress(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,n){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,n),{success:!0,results:n.map(s=>({lessonId:s.lessonId,success:!0,status:s.status}))}}async simulateDelay(){this.config.delay&&this.config.delay>0&&await new Promise(e=>setTimeout(e,this.config.delay))}shouldSimulateError(){return this.config.simulateError?Math.random()<(this.config.errorProbability||.1):!1}getConfig(){return{...this.config}}getCourseData(){return Re}getLessonsData(){const e={};return Re.units.forEach(n=>{e[n.id]=n.lessons.map(r=>({id:r.id,title:r.title,duration:r.duration,knowledgeItems:r.knowledgeItems.map(s=>({...s,progress:0}))}))}),e}}class Pb{static instances=new Map;static createDataSource(e){const{type:n,config:r,customDataSourceClass:s}=e,o=this.getInstanceKey(n,r);if(this.instances.has(o))return this.instances.get(o);let i;switch(n){case"api":i=new Ob(r);break;case"mock":i=new Ib(r);break;case"custom":if(!s)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new s(r);break;default:throw new Error(`不支持的数据源类型: ${n}`)}return this.instances.set(o,i),console.log(`[DataSourceFactory] 创建数据源: type=${n}, name=${r.name}`),i}static createApiDataSource(e){return this.createDataSource({type:"api",config:e})}static createMockDataSource(e={}){return this.createDataSource({type:"mock",config:{name:"MockDataSource",...e}})}static createDefaultDataSource(){const e=typeof window<"u";let n=!1,r=!1,s=!1;try{typeof process<"u"&&process.env?(n=process.env.NODE_ENV==="development",r=process.env.NODE_ENV==="test",s=process.env.REACT_APP_USE_MOCK==="true"):(n=!0,s=!0)}catch(o){console.warn("无法检测环境变量,使用默认配置:",o),n=!0,s=!0}return n||r||s?this.createMockDataSource({name:"DefaultMockDataSource",delay:300}):this.createApiDataSource({name:"DefaultApiDataSource",baseURL:"/api/v1",token:e&&localStorage.getItem("authToken")||""})}static clearCache(){this.instances.clear(),console.log("[DataSourceFactory] 已清除所有数据源实例缓存")}static getCachedInstanceCount(){return this.instances.size}static getInstanceKey(e,n){return`${e}:${n.name}:${JSON.stringify(n)}`}}function Fb(){return Pb.createDefaultDataSource()}function Db(t={}){const{dataSource:e=Fb(),fallbackStrategy:n="mock",errorHandling:r={},performance:s={},theme:o={},debug:i=!1,enableDevTools:a=!1}=t;return{dataSource:e,fallbackStrategy:n,errorHandling:{showUserFriendlyErrors:!0,logErrors:!0,autoRetry:!0,maxRetries:3,retryDelay:1e3,...r},performance:{enableVirtualization:!0,lazyLoadImages:!0,debounceSearch:300,enableCaching:!0,cacheTTL:3e5,...s},theme:{primaryColor:"#1865f2",borderRadius:"8px",spacing:"16px",fontSize:"14px",enableDarkMode:!1,...o},debug:i,enableDevTools:a}}function Lb(t,e){return{...t,...e,errorHandling:{...t.errorHandling,...e.errorHandling},performance:{...t.performance,...e.performance},theme:{...t.theme,...e.theme}}}const mu=x.createContext(null),pu=()=>{const t=x.useContext(mu);if(!t)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return t},yu=({children:t,config:e})=>{const[n,r]=x.useState(()=>Db(e)),[s,o]=x.useState(null),[i,a]=x.useState([]),[l,c]=x.useState(null),[d,f]=x.useState({}),[g,h]=x.useState(!1),[m,p]=x.useState(null),[y,b]=x.useState(null),[w,v]=x.useState([]),S=x.useCallback(async(k,M)=>{h(!0),p(null);try{process.env.NODE_ENV!=="test"&&await new Promise(P=>setTimeout(P,100));const F=await n.dataSource.getUserGradeUnitsNav(k,M);c(F);const D={};Re.units.forEach(P=>{D[P.id]=P.lessons.map(j=>({id:j.id,title:j.title,duration:j.duration,knowledgeItems:j.knowledgeItems.map(O=>({...O,progress:0}))}))}),console.log("Lessons data loaded:",D),f(D);try{const P=await n.dataSource.getUserProfile(M);o(P)}catch(P){console.warn("获取用户信息失败,使用默认数据:",P),o({id:M,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const P=await n.dataSource.getExploreMenu();a(P)}catch(P){console.warn("获取探索菜单失败,使用默认数据:",P),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(F){if(console.error("数据加载错误:",F),n.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const D={userId:M,courseId:k,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:Re.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:Re.units.map((j,O)=>({unitId:j.id,title:j.title,description:j.description,moduleCategory:j.moduleCategory,estimatedDuration:j.estimatedDuration,totalLessons:j.lessons.length,completedLessons:O<2?Math.floor(j.lessons.length*.5):0,progressPercentage:O<2?50:0,status:O<2?"in-progress":"not-started",lastAccessed:O<2?new Date().toISOString():void 0,isActive:O===0,route:`/math/grade-5/unit/${j.id}`,icon:mr[j.moduleCategory]||mr.Default}))};c(D);const P={};Re.units.forEach(j=>{P[j.id]=j.lessons.map(O=>({id:O.id,title:O.title,duration:O.duration,knowledgeItems:O.knowledgeItems.map(T=>({...T,progress:0}))}))}),f(P),o({id:M,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else p(F instanceof Error?F.message:"数据加载失败"),c(null)}finally{h(!1)}},[n]),_=x.useCallback(k=>{v(M=>M.includes(k)?M.filter(F=>F!==k):[...M,k])},[]),A=x.useCallback(k=>{b(k)},[]),C=x.useCallback(k=>{r(M=>Lb(M,k))},[]);x.useEffect(()=>{if(console.log("unitsData state updated:",l),console.log("unitsData?.units:",l?.units),console.log("unitsData?.units?.length:",l?.units?.length),l&&l.units.length>0){console.log("Looking for active unit...");const k=l.units.find(F=>F.isActive);console.log("Found active unit:",k);const M=k?.unitId||l.units[0].unitId;console.log("Setting default active unit:",M),b(M),console.log("Default active unit set after state update:",M)}else console.log("No units data available for setting default active unit")},[l]);const R={userInfo:s,exploreMenu:i,unitsData:l,lessons:d,loading:g,error:m,activeUnitId:y,activeLessonIds:w,config:n,theme:n.theme,enableVirtualization:n.performance?.enableVirtualization,setLoading:h,setError:p,setActiveUnit:A,toggleLesson:_,loadPageData:S,updateConfig:C};return u.jsx(mu.Provider,{value:R,children:t})},zb=({gradeId:t,userId:e,onLearnAction:n,className:r,userInfo:s,exploreMenu:o})=>{const{userInfo:i,exploreMenu:a,unitsData:l,lessons:c,loading:d,error:f,activeUnitId:g,activeLessonIds:h,setActiveUnit:m,toggleLesson:p,loadPageData:y}=pu(),b=s??i,w=o??a;x.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",t,"userId:",e),y(t,e)},[t,e,y]),x.useEffect(()=>{console.log("activeUnitId from context:",g),console.log("lessons from context:",c);const _=l?.units?.find(C=>C.unitId===g)||null,A=_&&g&&c[g]?{id:_.unitId,title:_.title,description:_.description,estimatedDuration:_.estimatedDuration,totalLessons:_.totalLessons,moduleCategory:_.moduleCategory,lessons:c[g]}:null;console.log("activeUnit computed:",A)},[g,c,l]);const v=l?.units?.find(_=>_.unitId===g)||null,S=v&&g&&c[g]?{id:v.unitId,title:v.title,description:v.description,estimatedDuration:v.estimatedDuration,totalLessons:v.totalLessons,moduleCategory:v.moduleCategory,lessons:c[g]}:null;return d?u.jsx("div",{className:`grade-unit-browser-page loading ${r||""}`,"data-testid":"grade-unit-browser-page",children:u.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):f?u.jsxs("div",{className:`grade-unit-browser-page error ${r||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"error-message","data-testid":"error-message",children:f}),u.jsx(Pt,{onClick:()=>y(t,e),intent:"retry",useNewClassName:!0,className:"retry-button",children:"重试"})]}):u.jsxs("div",{className:`grade-unit-browser-page ${r||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"header-area",children:u.jsx(ld,{userData:b||void 0,exploreItems:w})}),u.jsx("div",{className:"sidebar-area",children:u.jsx(Dc,{data:l,activeUnitId:g,onUnitSelect:m,loading:d})}),u.jsx("div",{className:"content-area",children:u.jsx(Fc,{unit:S,activeLessonIds:h,onToggleLesson:p,onLearnAction:n||(()=>{}),loading:d})})]})},Vb=t=>u.jsx(yu,{config:t.config,children:u.jsx(zb,{...t})});function Gb(t){return t.steps!==void 0}function Ub(t){if(Gb(t))return t;if(Array.isArray(t)){if(t.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=t[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const r=t.map(s=>({id:s.id,type:s.type,title:s.content.title||"",description:s.content.description||"",chartConfig:s.content.chartConfig,videoUrl:s.content.videoUrl,commonErrors:s.content.commonErrors,difficulty:s.content.difficulty}));return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}else return{steps:t,total_steps:t.length,strategy:"step_by_step",estimated_time:t.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}function bu(t){return Array.isArray(t)}const Bb=(t,e,n=.1)=>{if(!t.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const r=parseFloat(t);if(isNaN(r))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(r<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const o=Math.abs(r-e)<=n;return{isValid:!0,isCorrect:o,errorMessage:o?void 0:"答案不正确,请再试一次"}},Hb=()=>Dn.create((t,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:n=>{t({problemData:n,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:n=>{t({userAnswer:n,validationError:null})},updateChoiceAnswer:n=>{t({userAnswer:n,validationError:null})},submitAnswer:n=>{const r=e();if(!r.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}let s=r.userAnswer;if((Array.isArray(n)||n!==void 0)&&(s=n),bu(s)){const d=s.map(h=>h.id),f=r.problemData.answer_info?.correctAnswers||[];process.env.NODE_ENV==="development"&&console.log("[答案验证]",{selectedIds:d,correctAnswers:f,answerInfo:r.problemData.answer_info});const g=d.length===f.length&&d.every(h=>f.includes(h));t({isCorrect:g,showAnswerForm:!1,validationError:null,currentScene:g?"success":"explanation"});return}const o=typeof s=="string"?s:"",i=r.problemData.answer_info?.value??r.problemData.answer.value,a=Number(i),l=r.problemData.answer_info?.tolerance??.1,c=Bb(o,a,l);if(!c.isValid){t({userAnswer:s,validationError:c.errorMessage||"答案格式错误"});return}t({userAnswer:s,isCorrect:c.isCorrect,showAnswerForm:!1,validationError:null,currentScene:c.isCorrect?"success":"explanation"})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),Kt=Hb(),Ui=()=>Kt(t=>t.currentScene),Bi=()=>Kt(t=>t.userAnswer),Wb=()=>Kt(t=>t.isCorrect),Hi=()=>Kt(t=>t.showAnswerForm),xu=()=>Kt(t=>t.validationError),qb=()=>Kt(t=>t.problemData),Wi=()=>Kt(bn.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,updateChoiceAnswer:t.updateChoiceAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),Yb=x.createContext(null),Mr=()=>{const t=x.useContext(Yb);if(!t)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return t},Kb=()=>{const t=Mr(),e=x.useCallback(n=>n.currentScene,[]);return t(e)},Xb=()=>{const t=Mr(),e=x.useCallback(n=>n.userAnswer,[]);return t(e)},Jb=()=>{const t=Mr(),e=x.useCallback(n=>n.showAnswerForm,[]);return t(e)},Zb=()=>{const t=Mr(),e=x.useCallback(n=>n.validationError,[]);return t(e)},Qb=()=>Mr()(bn.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,updateChoiceAnswer:e.updateChoiceAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),qs=()=>{try{return Kb()}catch{return Ui()}},Ys=()=>{try{return Xb()}catch{return Bi()}},Ks=()=>{try{return Jb()}catch{return Hi()}},Xs=()=>{try{return Zb()}catch{return xu()}},Js=()=>{try{return Qb()}catch{return Wi()}},xn=({problemData:t,userAnswer:e,showAnswerForm:n,onAnswerSubmit:r,onAnswerChange:s,validationError:o,noBorder:i=!1})=>{const a=x.useCallback((g,h)=>{h.type==="optionChange"&&s(h.value)},[s]),l=x.useMemo(()=>Array.isArray(e)?(t.scenes?.question?.items??[]).reduce((h,m)=>(m.type==="optionGroup"&&m.metadata?.optionGroupId&&(h[m.metadata.optionGroupId]=e),h),{}):{},[e,t]),c=Array.isArray(e)||t.scenes?.question?.items?.some(g=>g.type==="optionGroup"),d=g=>{g.preventDefault(),r(e)},f=g=>{s(g)};return u.jsx("div",{className:"question-scene-container",children:u.jsxs("div",{className:"question-scene-card",children:[u.jsx("div",{className:"question-display-area",children:u.jsx(Be,{data:{id:t.id,grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1},onContentInteraction:a,interactionValues:l})}),n&&u.jsxs("div",{className:"answer-form-container",children:[u.jsxs("form",{onSubmit:d,className:"answer-form",children:[!c&&u.jsxs(u.Fragment,{children:[u.jsx("label",{className:"answer-label",children:"答案"}),u.jsx("input",{type:"number",value:typeof e=="string"?e:"",onChange:g=>f(g.target.value),className:`answer-input ${o?"error":"normal"}`,placeholder:"?",required:!0}),u.jsx("span",{className:"answer-unit",children:t.basicInfo.answerUnit||t.basicInfo.areaUnit})]}),u.jsx(Pt,{type:"submit",size:"lg",intent:"submit",useNewClassName:!0,className:"submit-button",children:"提交答案"})]}),o&&u.jsxs("div",{className:"validation-error",children:[u.jsx("span",{children:"⚠️"}),u.jsx("span",{children:o})]})]})]})})},vu=({problemData:t,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",t),console.log("🔍 RememberModule scenes.remember:",t?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",t?.scenes?.remember?.content);const r=(()=>{const o=t.scenes?.review?.items;if(o&&Array.isArray(o)&&o.length>0)return console.log("🔍 RememberModule 使用 review.items"),o;const i=t.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=t.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const l=t.scenes?.remember?.content;return l&&Array.isArray(l)&&l.length>0?(console.log("🔍 RememberModule 使用 remember.content"),l):(console.log("🔍 RememberModule 未找到任何内容"),[])})();if(r.length===0){const o=u.jsx("div",{className:"remember-module-content",children:u.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?u.jsx(jn,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})}const s=u.jsx("div",{className:"remember-module-content",children:r.map((o,i)=>{const{type:a,content:l,style:c,parts:d}=o;switch(a){case"text":return u.jsx("p",{className:"remember-module-text-block",style:c,children:l},i);case"formula":return u.jsx("div",{className:"remember-module-formula-block",children:u.jsx(Be,{data:{id:`formula-${i}`,grade:t.grade,unit:t.unit,content:[{type:"formula",content:l,parts:d||[l]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return u.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?u.jsx(jn,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})},qi=({problemData:t,userAnswer:e,enableIXLStyle:n=!0})=>{const r=x.useMemo(()=>bu(e)?e.length===0?"未选择":e.map(i=>i.contentType==="formula"?i.content:i.content||i.id).join("、"):e||"--",[e]),s=u.jsxs("div",{className:"review-module-content",children:[u.jsx("p",{className:"review-module-question",children:t.basicInfo.question}),u.jsx("div",{className:"review-module-graph",children:u.jsx(Be,{data:{id:"review-problem",grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:n?"ixl-adjusted":""})}),u.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",u.jsx("span",{className:"review-module-user-answer-value",children:r})]})]});return n?u.jsx(jn,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:s}):u.jsxs("div",{className:"review-module-container",children:[u.jsx("h4",{className:"review-module-title",children:"复习"}),s]})},ex=t=>[{color:"var(--mc-step-color-ident)",bg:"var(--mc-step-bg-ident)"},{color:"var(--mc-step-color-calc)",bg:"var(--mc-step-bg-calc)"},{color:"var(--mc-step-color-res)",bg:"var(--mc-step-bg-res)"}][t%3],tx=({step:t,problemData:e,stepNumber:n})=>{const{title:r,description:s,chartConfig:o}=t.content,i=!!o,a=ex(n-1),l=[{type:"text",content:s.replace(/<br>/g,`
45
- `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return u.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[u.jsxs("h3",{className:"explanation-step-title",children:[u.jsx("span",{className:"explanation-step-number",children:n}),u.jsx("span",{children:r})]}),u.jsxs("div",{className:"explanation-step-content",children:[u.jsx(Be,{data:{id:`${t.id}-description`,grade:e.grade,unit:e.unit,content:l},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&o.type&&u.jsx("div",{className:"explanation-step-chart-container",children:o.type==="hundredGrid"?u.jsx(Ii,{rows:o.rows||2,cols:o.cols||6,cellSize:o.cellSize||36,mode:o.mode||"readonly",value:o.value,fillColor:o.fillColor,baseColor:o.baseColor,className:"mathwiz-hundredgrid-explanation"}):o.type==="geometryTransform"&&(o.config||o.metadata?.config)?u.jsx(Fi,{config:o.config||o.metadata?.config,onTransformChange:c=>console.log("Transform progress:",c),onTransformComplete:()=>console.log("Transform complete"),onError:c=>console.error("Geometry transform error:",c)}):o.shapes&&o.shapes.length>0?u.jsx(Nr,{shapes:o.shapes,width:o.width||400,height:o.height||300,boundingBox:o.boundingBox||[-10,10,10,-10],showGrid:o.showGrid||!1,showAxis:o.showAxis||!1,mode:"view",className:"mx-auto"}):null})]})]})},Yi=({problemData:t,enableIXLStyle:e=!0})=>{const[n,r]=x.useState(!1),s=t?.scenes?.solve?.items||t?.scenes?.solve?.content,o=Array.isArray(s)&&s.length>0,i=x.useMemo(()=>s&&s.map(f=>f.type==="geometryTransform"&&f.metadata?.config&&!f.config?{...f,config:f.metadata.config}:f),[s]),a=x.useMemo(()=>Ub(t.explanation),[t.explanation]),l=a.steps.length>0,c=x.useMemo(()=>l?a.steps.map(f=>({...f,content:{title:f.title,description:f.description,chartConfig:f.chartConfig?{...f.chartConfig,boundingBox:f.chartConfig.type==="graph"&&Array.isArray(f.chartConfig.boundingBox)&&f.chartConfig.boundingBox.length===4?[f.chartConfig.boundingBox[0],f.chartConfig.boundingBox[1],f.chartConfig.boundingBox[2],f.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[l,a.steps]),d=u.jsxs("div",{className:"solve-module-content",children:[o?u.jsxs(u.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",s),s?.forEach?.((f,g)=>{if(f.type==="geometryTransform"){const h=i?.[g];console.log(`🔍 SolveModule: geometryTransform block [${g}] =`,{type:f.type,hasMetadata:!!f.metadata,metadata:f.metadata,hasMetadataConfig:!!f.metadata?.config,metadataConfig:f.metadata?.config,hasConfig:!!f.config,config:f.config,hasShapes:!!f.shapes,shapes:f.shapes,hasTransform:!!f.transform,transform:f.transform,fixedBlockHasConfig:!!h?.config,fixedBlockConfig:h?.config,fixedBlockHasMetadataConfig:!!h?.metadata?.config,fixedBlockMetadataConfig:h?.metadata?.config,isConfigFixed:!f.config&&!!h?.config})}}),u.jsx(Be,{data:{id:"solve-steps",grade:t.grade,unit:t.unit,content:i},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):u.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),u.jsx("div",{className:"solve-module-button-container",children:u.jsx(Pt,{intent:"solve",variant:"light",useNewClassName:!0,onClick:()=>r(f=>!f),className:"solve-module-button",children:n?"收起详细解题步骤":"查看详细解题步骤"})}),n&&u.jsxs("div",{className:"solve-module-detailed-container",children:[u.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),l?u.jsx("div",{className:"solve-module-detailed-list",children:c.map((f,g)=>u.jsx(tx,{step:f,problemData:t,stepNumber:g+1},f.id))}):u.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?u.jsx(jn,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:d}):u.jsxs("div",{className:"solve-module-container",children:[u.jsx("h4",{className:"solve-module-title",children:"解题"}),d]})},nx=t=>{if(t.answer_info?.displayValue)return t.answer_info.displayValue;const e=t.answer_info?.value;if(e!=null)return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e);const n=t.answer?.value;return n!=null?String(n):"--"},Un=({problemData:t,userAnswer:e,onNextQuestion:n})=>{console.log("🔍 ExplanationScene problemData:",t),console.log("🔍 ExplanationScene scenes.remember:",t?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",t?.scenes?.remember?.content);const r=x.useMemo(()=>nx(t),[t]);return u.jsxs("div",{children:[u.jsx("div",{className:"explanation-error-banner",children:u.jsxs("div",{className:"explanation-inner-container",children:[u.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),u.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[u.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),u.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[u.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),u.jsx("div",{className:"correct-answer-value-container",children:u.jsx("span",{className:"correct-answer-value",children:u.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r})})})]})]}),u.jsx("div",{className:"explanation-button-container",children:u.jsx(Pt,{onClick:n,size:"lg",intent:"next",useNewClassName:!0,className:"explanation-next-button",children:"明白了"})})]})}),u.jsxs("div",{className:"explanation-content-area",children:[u.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),u.jsx(qi,{problemData:t,userAnswer:e}),u.jsx(vu,{problemData:t}),u.jsx(Yi,{problemData:t})]}),u.jsx("div",{className:"explanation-bottom-area",children:u.jsx(Pt,{onClick:n,size:"md",intent:"next",useNewClassName:!0,children:"明白了"})})]})},vn=({problemData:t,onNextQuestion:e})=>u.jsxs("div",{className:"success-scene-container",children:[u.jsx("h3",{className:"success-message-title",children:"正确!"}),u.jsx("p",{className:"success-message-description",children:"你做得很好!"}),u.jsx("div",{className:"concept-review-container",children:u.jsx(Be,{data:{id:"review-concepts",grade:t.grade,unit:t.unit,content:t.scenes?.review?.items||t.scenes?.review?.content||t.scenes?.remember?.items||t.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),u.jsx(Pt,{onClick:e,size:"lg",intent:"next",useNewClassName:!0,className:"next-button",children:"下一题"})]}),It={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};let Nn=class extends Error{code;details;constructor(e,n,r){super(n),this.name="AdapterError",this.code=e,this.details=r}};const rx={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},sx={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},he={DESIGN_TOKEN:"design_token",STYLE_REF:"style_ref",GEOMETRY_REF:"geometry_ref",TRANSFORM_REF:"transform_ref",LAYOUT_REF:"layout_ref",ANIMATION_REF:"animation_ref",BOARD_REF:"board_ref",GEOMETRY_TRANSFORM_REF:"geometry_transform_ref",SLIDER_REF:"slider_ref"},re={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};class Ee extends Error{code;details;constructor(e,n,r){super(n),this.name="AdapterError",this.code=e,this.details=r}}const ps={id:"fallback-triangle-problem",title:"三角形面积计算",grade:5,unit:"三角形面积计算",lesson:"锐角三角形的面积",skill:"已知锐角三角形的底和高,求三角形面积",objective:"掌握锐角三角形面积公式 A=½bh",knowledgePoints:["三角形面积公式 A=½bh"],difficulty:1,metadata:{topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","三角形面积公式"]},basicInfo:{question:"以下三角形面积是多少?",base:6,height:4,baseUnit:"cm",heightUnit:"cm",answerUnit:"cm²"},scenes:{question:{content:[],layout:{type:"card"}},solve:{content:[],layout:{type:"card"}},review:{content:[],layout:{type:"card"}}},explanation:{steps:[]},answer:{value:12,unit:"cm²",explanation:"三角形面积公式为 A = ½ × 底 × 高 = ½ × 6 × 4 = 12"}},Ja={[re.INVALID_INPUT]:"输入数据无效",[re.MISSING_REQUIRED_FIELD]:"缺少必需字段",[re.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[re.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[re.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[re.STYLE_REF_NOT_FOUND]:"样式引用未找到",[re.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[re.BOARD_REF_NOT_FOUND]:"画板引用未找到",[re.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[re.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[re.TRANSFORMATION_FAILED]:"数据转换失败",[re.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},en={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Co={RAW_DATA:["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective","knowledge_points","difficulty","basic_info","scenes","explanation","answer_info"],BASIC_INFO:["question"],ANSWER_INFO:["value","unit","explanation_text"]},wu=["question","solve","review","remember"],we={DESIGN_TOKEN:/^\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)$/,STYLE_REF:/^styleRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_REF:/^geometryRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,TRANSFORM_REF:/^transformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,LAYOUT_REF:/^layoutRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,ANIMATION_REF:/^animationRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_TRANSFORM_REF:/^geometryTransformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,SLIDER_REF:/^sliderRef:([a-zA-Z_][a-zA-Z0-9_]*)$/},je={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},_u={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.5rem",heading_normal:"1.25rem",body:"1.2rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},Su={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_secondary",fontSize:"$fonts.heading_normal",fontWeight:"600",lineHeight:1.5,letterSpacing:"0.01em"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"},hundredGrid_primary:{id:"hundredGrid_primary",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.primary",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_highlight:{id:"hundredGrid_highlight",baseColor:"$colors.background_lighter",borderColor:"$colors.primary",selectedColor:"$colors.success",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_solve:{id:"hundredGrid_solve",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.highlight_yellow",textColor:"$colors.text_primary",fontSize:"$fonts.body"}}},Cu={geometry_presets:{acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[[100,300],[300,100],[500,300]],styleRef:"primary",description:"锐角三角形"},right_triangle:{id:"right_triangle",type:"triangle",vertices:[[100,100],[100,300],[300,300]],styleRef:"secondary",description:"直角三角形"},equilateral_triangle:{id:"equilateral_triangle",type:"triangle",vertices:[[200,100],[100,273],[300,273]],styleRef:"highlight",description:"等边三角形"},rectangle:{id:"rectangle",type:"rectangle",dimensions:{width:200,height:100},styleRef:"primary",description:"矩形"},parallelogram:{id:"parallelogram",type:"parallelogram",vertices:[[100,100],[300,100],[250,200],[50,200]],styleRef:"secondary",description:"平行四边形"},horizontal_line:{id:"horizontal_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"primary",description:"水平线段模板"},vertical_line:{id:"vertical_line",type:"segment",endpoints:[[0,0],[0,100]],styleRef:"primary",description:"垂直线段模板"},arrow_line:{id:"arrow_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"error",description:"箭头线段模板"},label_point:{id:"label_point",type:"point",position:[50,20],styleRef:"text_primary",description:"标签位置点模板"},center_point:{id:"center_point",type:"point",position:[50,50],styleRef:"primary",description:"中心点模板"},vertex_point:{id:"vertex_point",type:"point",position:[0,0],styleRef:"primary",description:"顶点点模板"},marker_point:{id:"marker_point",type:"point",position:[0,0],styleRef:"highlight",description:"标记点模板"},left_triangle:{id:"left_triangle",type:"polygon",vertices:[[100,100],[100,300],[250,300]],styleRef:"highlight_left",description:"左三角形模板"}}},Ru={layout_presets:{card:{id:"card",type:"card",padding:"$spacing.large",theme:"light"},vertical_centered:{id:"vertical_centered",type:"vertical",spacing:"$spacing.large",alignment:"center"},vertical_spaced:{id:"vertical_spaced",type:"vertical",spacing:"$spacing.medium",alignment:"start"},grid_2col:{id:"grid_2col",type:"grid",columns:2,spacing:"$spacing.medium"}}},Au={transform_definitions:{left_rotation:{id:"left_rotation",type:"rotation",angle:-90,origin:[0,0],description:"向左旋转90度"},right_rotation:{id:"right_rotation",type:"rotation",angle:90,origin:[0,0],description:"向右旋转90度"},translation:{id:"translation",type:"translation",dx:0,dy:0,description:"平移变换"},scale:{id:"scale",type:"scale",factor:1,origin:[0,0],description:"缩放变换"}}},kn={slider_definitions:{slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}}},ku={board_definitions:{default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}}},cn={designTokens:_u.design_tokens,stylePresets:Su.style_presets,geometryPresets:Cu.geometry_presets,layoutPresets:Ru.layout_presets,transformDefinitions:Au.transform_definitions,animationDefinitions:kn.slider_definitions,animationConfigs:kn.slider_definitions,boardDefinitions:ku.board_definitions};function Eu(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!kn,sliderDefinitionsKeys:kn.slider_definitions?Object.keys(kn.slider_definitions):[]});const t=kn.slider_definitions;return{designTokens:_u.design_tokens,stylePresets:Su.style_presets,geometryPresets:Cu.geometry_presets,layoutPresets:Ru.layout_presets,transformDefinitions:Au.transform_definitions,animationDefinitions:t,animationConfigs:t,boardDefinitions:ku.board_definitions}}class tt{static canResolve(e){return we.DESIGN_TOKEN.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const r=e.substring(1);return this.resolvePath(r,n.designTokens)}static resolvePath(e,n){const r=e.split(".");let s=n;for(const o of r){if(s==null)throw new Error(`设计令牌路径不存在: ${e} (在 ${o} 处中断)`);if(typeof s!="object")throw new Error(`设计令牌路径无效: ${e} (${o} 不是对象)`);s=s[o]}if(s===void 0)throw new Error(`设计令牌未找到: ${e}`);return s}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`设计令牌解析失败: ${s}`,o)}return r}static extractDesignTokenRefs(e){const n=[],r=s=>{typeof s=="string"?this.canResolve(s)&&n.push(s):Array.isArray(s)?s.forEach(r):typeof s=="object"&&s!==null&&Object.values(s).forEach(r)};return r(e),n}static replaceDesignTokenRefs(e,n,r){const s=o=>{if(typeof o=="string"){if(this.canResolve(o))try{return this.resolve(o,n)}catch(d){if(r)return r(o);throw d}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,l=0;const c=[];for(;(a=i.exec(o))!==null;){a.index>l&&c.push(o.substring(l,a.index));const d=a[0];try{const f=this.resolve(d,n);c.push(String(f))}catch{r?c.push(String(r(d))):c.push(d)}l=a.index+d.length}return l<o.length&&c.push(o.substring(l)),c.length>1?c.join(""):o}else{if(Array.isArray(o))return o.map(s);if(typeof o=="object"&&o!==null){const i={};for(const[a,l]of Object.entries(o))i[a]=s(l);return i}}return o};return s(e)}}function ox(){return{type:he.DESIGN_TOKEN,canResolve:tt.canResolve.bind(tt),resolve:tt.resolve.bind(tt)}}class yt{static canResolve(e,n){if(typeof e!="string"||e.length===0)return!1;if(we.GEOMETRY_REF.test(e)||[/^point_[a-zA-Z0-9_]+$/,/^segment_[a-zA-Z0-9_]+$/,/^line_[a-zA-Z0-9_]+$/,/^triangle_[a-zA-Z0-9_]+$/,/^polygon_[a-zA-Z0-9_]+$/,/^circle_[a-zA-Z0-9_]+$/,/^angle_[a-zA-Z0-9_]+$/,/^vector_[a-zA-Z0-9_]+$/,/^arc_[a-zA-Z0-9_]+$/,/^ray_[a-zA-Z0-9_]+$/].some(o=>o.test(e)))return!0;if(n&&n.geometryPresets){let o;const i=e.match(we.GEOMETRY_REF);return i?o=i[1]:o=e,o in n.geometryPresets}return["acute_triangle","right_triangle","equilateral_triangle","rectangle","parallelogram","horizontal_line","vertical_line","arrow_line","label_point","center_point","vertex_point","marker_point","left_triangle","right_triangle","base_segment","height_segment","base_arrow","height_arrow","full_rectangle"].includes(e)}static resolveVertexReference(e,n){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!n.geometryPresets,pointFound:!!n.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const r=e.$ref;if(n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return console.error(`✅ 解析顶点引用 ${r}: 使用 position`,s.position),[s.position.x,s.position.y];if("x"in s&&"y"in s)return console.error(`✅ 解析顶点引用 ${r}: 使用 x/y`,{x:s.x,y:s.y}),[s.x,s.y]}return console.warn(`无法解析顶点引用: ${r}`),e}return Array.isArray(e)&&e.length===2?e:e&&typeof e=="object"&&"x"in e&&"y"in e?[e.x,e.y]:e}static resolve(e,n){if(!this.canResolve(e,n))throw new Error(`无法解析的几何引用: ${e}`);let r;const s=e.match(we.GEOMETRY_REF);s?r=s[1]:r=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${r}"`),console.error(" Available geometryPresets:",Object.keys(n.geometryPresets||{}));const o=n.geometryPresets[r];if(!o)throw console.error(`❌ Geometry preset not found: ${r} in`,n.geometryPresets),new Error(`几何预设未找到: ${r}`);console.error("✅ Geometry resolved:",{name:r,type:o.type,hasVertices:"vertices"in o,verticesCount:o.vertices?o.vertices.length:0,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,geometryKeys:Object.keys(o)});const i={...o};return i.vertices&&Array.isArray(i.vertices)&&(i.vertices=i.vertices.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,n):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(l){return console.warn("顶点引用解析失败:",l),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,l)=>({index:l,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})),i.endpoints&&Array.isArray(i.endpoints)&&(i.endpoints=i.endpoints.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,n):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(l){return console.warn("端点引用解析失败:",l),a}})),i}static validate(e,n){if(!this.canResolve(e,n))return!1;let r;const s=e.match(we.GEOMETRY_REF);return s?r=s[1]:r=e,r in n.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,n){const r=this.resolve(e,n);if(r.styleRef&&n.stylePresets[r.styleRef]){const s=n.stylePresets[r.styleRef];return{...r,style:{...s}}}return r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`几何引用解析失败: ${s}`,o)}return r}static extractGeometryRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.geometryRef&&typeof s.geometryRef=="string"&&n.push(s.geometryRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.geometryRef&&typeof o.geometryRef=="string"&&n.push(o.geometryRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function ix(){return{type:he.GEOMETRY_REF,canResolve:yt.canResolve.bind(yt),resolve:yt.resolve.bind(yt),validate:yt.validate.bind(yt)}}class qe{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.TRANSFORM_REF.test(e)?!0:/_(rotation|translation|scale|transform|reflection|shear|mirror)$/i.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let r;const s=e.match(we.TRANSFORM_REF);if(s?r=s[1]:r=e,n.transformDefinitions&&n.transformDefinitions[r])return{...n.transformDefinitions[r]};const o=this.createDefaultTransform(r);if(o)return console.warn(`⚠️ 使用智能默认变换: ${r}`,o),o;throw new Error(`变换定义未找到: ${r}`)}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.TRANSFORM_REF);return s?r=s[1]:r=e,n.transformDefinitions&&n.transformDefinitions[r]?!0:this.createDefaultTransform(r)!==null}static applyTransform(e,n){if(!n||!e)return e;const r={...e};switch(n.type){case"rotation":r.vertices=this.applyRotation(e.vertices,n.angle,n.origin);break;case"translation":r.vertices=this.applyTranslation(e.vertices,n.dx,n.dy);break;case"scale":r.vertices=this.applyScale(e.vertices,n.factor,n.origin);break;default:console.warn(`未知的变换类型: ${n.type}`)}return r}static applyRotation(e,n,r){if(!e||!Array.isArray(e))return e;const[s,o]=r,i=n*Math.PI/180,a=Math.cos(i),l=Math.sin(i);return e.map(([c,d])=>{const f=c-s,g=d-o;return[s+f*a-g*l,o+f*l+g*a]})}static applyTranslation(e,n,r){return!e||!Array.isArray(e)?e:e.map(([s,o])=>[s+n,o+r])}static applyScale(e,n,r){if(!e||!Array.isArray(e))return e;const[s,o]=r;return e.map(([i,a])=>{const l=i-s,c=a-o;return[s+l*n,o+c*n]})}static createDefaultTransform(e){const n=e.toLowerCase();if(n.includes("rotation")||n.includes("rotate")){let r=0,s=Math.PI,o="clockwise";return n.includes("left")?(o="clockwise",s=Math.PI):n.includes("right")?(o="counterclockwise",s=Math.PI):n.includes("half")||n.includes("180")?s=Math.PI:n.includes("full")||n.includes("360")?s=2*Math.PI:(n.includes("quarter")||n.includes("90"))&&(s=Math.PI/2),{type:"rotation",config:{center:[0,0],startAngle:r,endAngle:s,direction:o}}}else if(n.includes("translation")||n.includes("translate")||n.includes("move")){let r=[0,0],s=0;return n.includes("left")||n.includes("west")?(r=[-1,0],s=10):n.includes("right")||n.includes("east")?(r=[1,0],s=10):n.includes("up")||n.includes("north")?(r=[0,1],s=10):n.includes("down")||n.includes("south")?(r=[0,-1],s=10):n.includes("horizontal")?(r="horizontal",s=10):n.includes("vertical")&&(r="vertical",s=10),{type:"translation",config:{direction:r,distance:s}}}else if(n.includes("scale")||n.includes("zoom")){let r=1,s=1;return n.includes("enlarge")||n.includes("bigger")||n.includes("up")?s=2:(n.includes("shrink")||n.includes("smaller")||n.includes("down"))&&(s=.5),{type:"scale",config:{center:[0,0],startScale:r,endScale:s,uniform:!0}}}else if(n.includes("transform")||n.includes("main")||n.includes("default")||n.includes("primary"))return{type:"translation",config:{direction:"horizontal",distance:0}};return null}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`变换引用解析失败: ${s}`,o)}return r}static extractTransformRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.transformRef&&typeof s.transformRef=="string"&&n.push(s.transformRef),Array.isArray(s.transformations)&&s.transformations.forEach(o=>{o.transformRef&&typeof o.transformRef=="string"&&n.push(o.transformRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function ax(){return{type:he.TRANSFORM_REF,canResolve:qe.canResolve.bind(qe),resolve:qe.resolve.bind(qe),validate:qe.validate.bind(qe)}}class ze{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.STYLE_REF.test(e)?!0:["primary","secondary","transparent","highlight","error","success","dashed","text_primary","text_heading_large","base_highlight","label_position","highlight_left","highlight_right","label_error"].includes(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let r;const s=e.match(we.STYLE_REF);s?r=s[1]:r=e;const o=n.stylePresets[r];if(!o)throw new Error(`样式预设未找到: ${r}`);return this.resolveStylePreset(o,n)}static resolveStylePreset(e,n){const r={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(tt.canResolve(o))try{r[s]=tt.resolve(o,n)}catch(i){console.warn(`样式中的设计令牌解析失败: ${s}=${o}`,i),r[s]=o}}else o&&typeof o=="object"&&(r[s]=this.resolveStylePreset(o,n));return r}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.STYLE_REF);return s?r=s[1]:r=e,r in n.stylePresets}static applyStyle(e,n){if(!e||!n)return e;const r={...e};return r.style=r.style?{...r.style,...n}:{...n},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(o=>{n[o]!==void 0&&(r[o]=n[o])}),r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`样式引用解析失败: ${s}`,o)}return r}static extractStyleRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.styleRef&&typeof s.styleRef=="string"&&n.push(s.styleRef),s.style&&typeof s.style=="object"&&s.style.styleRef&&typeof s.style.styleRef=="string"&&n.push(s.style.styleRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.styleRef&&typeof o.styleRef=="string"&&n.push(o.styleRef),o.style&&o.style.styleRef&&typeof o.style.styleRef=="string"&&n.push(o.style.styleRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function lx(){return{type:he.STYLE_REF,canResolve:ze.canResolve.bind(ze),resolve:ze.resolve.bind(ze),validate:ze.validate.bind(ze)}}class bt{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let r;const s=e.match(we.LAYOUT_REF);if(s?r=s[1]:r=e,n.layoutPresets&&n.layoutPresets[r]){const i=n.layoutPresets[r];return this.resolveLayoutPreset(i,n)}const o={card:{type:"card",padding:"20px",theme:"light"},vertical:{type:"vertical",spacing:"15px",alignment:"start"},horizontal:{type:"horizontal",spacing:"15px",alignment:"center"}};if(o[r])return{...o[r]};throw new Error(`布局预设未找到: ${r}`)}static resolveLayoutPreset(e,n){const r={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(tt.canResolve(o))try{r[s]=tt.resolve(o,n)}catch(i){console.warn(`布局中的设计令牌解析失败: ${s}=${o}`,i),r[s]=o}}else o&&typeof o=="object"&&(r[s]=this.resolveLayoutPreset(o,n));return r}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.LAYOUT_REF);return s?r=s[1]:r=e,n.layoutPresets&&n.layoutPresets[r]?!0:["card","vertical","horizontal"].includes(r)}static applyLayout(e,n){if(!e||!n)return e;const r={...e};return r.layout?r.layout={...r.layout,...n}:r.layout={...n},r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`布局引用解析失败: ${s}`,o)}return r}static extractLayoutRefs(e){const n=[];for(const r of Object.values(e))if(r.layout&&r.layout.type&&typeof r.layout.type=="string"&&this.isLayoutRef(r.layout.type)&&n.push(r.layout.type),r.layout&&typeof r.layout=="object")for(const s of Object.values(r.layout))typeof s=="string"&&this.isLayoutRef(s)&&n.push(s);return[...new Set(n)]}static isLayoutRef(e){return we.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function cx(){return{type:he.LAYOUT_REF,canResolve:bt.canResolve.bind(bt),resolve:bt.resolve.bind(bt),validate:bt.validate.bind(bt)}}class sn{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.ANIMATION_REF.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const r=e.match(we.ANIMATION_REF);if(!r)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const s=r[1],o=n.animationConfigs?.[s];if(!o)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${s}`);return this.resolveAnimationConfig(s,o,n)}static resolveAnimationConfig(e,n,r){if(!n.transforms||!Array.isArray(n.transforms))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const s=n.transforms.map((a,l)=>{if(!a.id)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 id 字段`);if(!a.type)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] targetShapes 不能为空`);a.targetShapes.forEach((f,g)=>{if(typeof f!="string"||f.trim()==="")throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}].targetShapes[${g}] 必须是有效的字符串 ID`)});const c=Hy(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:c,targetShapes:a.targetShapes,usesControl:d}}),o={id:e,control:n.control,transforms:s,visualEffects:n.visualEffects||[],progressControl:n.progressControl},i=Wy(o);if(!i.valid)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
44
+ `,document.head.appendChild(g),()=>{const h=document.getElementById("mathwiz-long-division-styles");h&&h.remove()}},[]);const l=x.useMemo(()=>vb(n,i),[n,i]),c=(g,h)=>{s(g,h)},d=g=>{switch(g){case"correct":return"correct";case"incorrect":return"incorrect";case"pending":return"idle";default:return"idle"}},f=g=>{const{id:h,type:m,value:p,place:y,readonly:b=!1,position:w,className:v,dataAttrs:S}=g;let _="input",A=a||b;switch(m){case"quotient":case"product":case"remainder":_="input";break;case"dividend":case"divisor":_="label",A=!0;break;case"horizontalLine":_=null,A=!0;break;case"remainderWithBringDown":_="label",A=!0;break;case"placeholder":_="placeholder",A=!0;break;default:_="placeholder",A=!0;break}const C=d(o(h));let R=`${w.row+1}`,N=`${w.col+1}`;w.colspan&&w.colspan>1&&(N=`${w.col+1} / span ${w.colspan}`),w.rowspan&&w.rowspan>1&&(R=`${w.row+1} / span ${w.rowspan}`);const M={gridRow:R,gridColumn:N,...g.type==="horizontalLine"?{justifySelf:"stretch",alignSelf:"center"}:{}};return u.jsx("div",{className:v,style:M,"data-cell-id":h,...S,children:_!==null&&u.jsx(Vi,{type:_,value:p!==null?p:void 0,readonly:A,status:C,place:y,onChange:F=>c(h,F),cellId:h,autoTab:!A&&y!==null})},h)};return u.jsxs("div",{className:"mathwiz-long-division p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`长除法:${n.dividend} ÷ ${n.divisor}`,children:[u.jsx("div",{className:"text-lg font-bold text-primary-500 mb-4",children:"长除法竖式"}),u.jsx("div",{className:"long-division-grid",style:{...xb(l),paddingLeft:"1.5rem",overflow:"visible"},children:l.cells.map(f)})]})});au.displayName="LongDivisionView";const Gi=t=>{const{config:e,initialAnswers:n,onAnswerChange:r,readonly:s}=t,{answers:o,updateAnswer:i,getCellStatus:a,steps:l,quotient:c,remainder:d,isComplete:f}=nu({config:e,initialAnswers:n,onAnswerChange:r});return x.useEffect(()=>{f&&r&&r(o)},[f,o,r]),u.jsx(au,{config:e,answers:o,onCellChange:i,getCellStatus:a,steps:l,readonly:s})};Gi.displayName="LongDivision";const wb=({block:t,onInteraction:e})=>{const{containerType:n,config:r,onAnswerChange:s}=t,o=x.useCallback(i=>{e?.({type:"answerChange",answers:i}),s?.(i)},[e,s]);switch(n){case"factorTable":return u.jsx(Di,{config:r,onAnswerChange:o});case"shortDivision":return u.jsx(Li,{config:r,onAnswerChange:o});case"verticalMultiplication":return u.jsx(zi,{config:r,onAnswerChange:o});case"longDivision":return u.jsx(Gi,{config:r,onAnswerChange:o});default:return null}},_b=({headers:t,values:e,colors:n={}})=>{const{headerBg:r="#f1f5f9",valueBg:s="#ffffff",borderColor:o="#e2e8f0"}=n;return t.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):u.jsxs("div",{className:"place-value-chart",style:{display:"inline-block",border:`1px solid ${o}`,borderRadius:"8px",overflow:"hidden",fontFamily:"system-ui, sans-serif",fontSize:"14px",lineHeight:"1.4"},children:[u.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${o}`},children:t.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:r,fontWeight:"600",textAlign:"center",borderRight:a<t.length-1?`1px solid ${o}`:"none",color:"#1e293b"},children:i},a))}),u.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"12px",backgroundColor:s,textAlign:"center",borderRight:a<e.length-1?`1px solid ${o}`:"none",color:"#0f172a",fontSize:"16px",fontWeight:"500"},children:i},a))})]})},lu=({content:t,onInteraction:e,interactionValues:n={}})=>{const r=(s,o)=>{if(s.enabled===!1)return null;const i=`${s.type}-${o}`,a=l=>{e?.(i,l)};switch(s.type){case"text":return u.jsx(Kd,{content:s.content,style:s.style,onInteraction:a},i);case"formula":const l=s;return u.jsx(Xd,{parts:l.parts||[],displayMode:l.displayMode,style:s.style},i);case"graph":const c=s;return u.jsx(Zd,{shapes:c.shapes||[],width:c.width,height:c.height,showGrid:c.showGrid,showAxis:c.showAxis,boundingBox:c.boardConfig?.boundingBox,autoBoundingBox:!c.boardConfig?.boundingBox,animation:c.animation,animationProgress:c.animationProgress,showAnimationControls:c.showAnimationControls,onAnimationChange:c.onAnimationChange},i);case"hundredGrid":const d=s;return u.jsx(Ii,{...d.props},i);case"placeValueChart":const f=s;return u.jsx(_b,{...f.props},i);case"geometryTransform":const g=s;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:g.metadata,config:g.metadata?.config,hasConfig:!!g.metadata?.config,configKeys:g.metadata?.config?Object.keys(g.metadata.config):[],configShapes:g.metadata?.config?.shapes,configShapesAnimatedLength:g.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:g.metadata?.config?.shapes?.static?.length,configBase:g.metadata?.config?.base,configHeight:g.metadata?.config?.height,configUnit:g.metadata?.config?.unit,configTransform:g.metadata?.config?.transform}),u.jsx(Fi,{config:g.metadata.config,onTransformChange:y=>a({type:"transformChange",progress:y}),onTransformComplete:()=>a({type:"transformComplete"}),onError:y=>a({type:"error",error:y})},i);case"optionGroup":const h=s,m=h.metadata?.optionGroupId;return u.jsx(sb,{options:h.options,correctAnswers:h.correctAnswers,answerType:h.answerType,layout:h.layout,variant:h.variant,value:n[m]??[],onChange:y=>a({type:"optionChange",value:y,optionGroupId:m})},i);case"mathContainer":const p=s;return u.jsx(wb,{block:p,onInteraction:a},i);default:return u.jsx("div",{onClick:()=>a({type:"click"}),children:s.content},i)}};return u.jsx(u.Fragment,{children:t.map(r)})},Be=({data:t,scene:e="question",layout:n={type:"card"},renderer:r={mode:"default"},theme:s="light",onContentInteraction:o,interactionValues:i,className:a="",children:l})=>{const c=Hd(t,e),d={data:c,scene:e,layout:c.layout||n,renderer:c.renderer||r,theme:s,onContentInteraction:o},f=c.layout||n,g=(()=>{switch(f.type){case"grid":return qd;case"flow":return Yd;default:return Wd}})(),h=(()=>{const m={className:a,theme:s,"data-testid":"mathcard-v2-container"};switch(f.type){case"grid":return{...m,columns:f.columns||2,gap:f.gap||"16px",responsive:f.responsive!==!1};case"flow":return{...m,direction:f.direction||"vertical",gap:f.gap||"16px",wrap:f.wrap!==!1};default:return{...m,padding:f.padding||"24px",shadow:f.shadow!==!1,border:f.border!==!1}}})();return u.jsx(qy.Provider,{value:d,children:u.jsx(g,{...h,children:l||u.jsx(lu,{content:c.content,layout:c.layout||n,onInteraction:o,interactionValues:i})})})};Be.CardLayout=Wd;Be.GridLayout=qd;Be.FlowLayout=Yd;Be.TextContent=Kd;Be.FormulaContent=Xd;Be.GraphContent=Zd;Be.GeometryTransformContent=Fi;Be.ContentRenderer=lu;const cu=t=>{const{ixlConfig:e,enableIXLStyle:n,isMobile:r}=t,s=x.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),o=x.useMemo(()=>{if(e.tagColor)return e.tagColor;const d={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return d[e.type]||d.remember},[e.tagColor,e.type]),i=x.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=x.useMemo(()=>{if(!n)return{};const d={backgroundColor:o,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return r?Object.assign(d,{height:"var(--ixl-mobile-tag-height, 32px)",borderRadius:"var(--ixl-mobile-tag-border-radius, 8px 8px 0 0)",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",zIndex:1}):Object.assign(d,{width:"var(--ixl-tag-width, 40px)",borderRadius:"var(--ixl-tag-border-radius, 8px 0 0 8px)",height:"100%",position:"absolute",left:0,top:0,display:"flex",alignItems:"center",justifyContent:"center",writingMode:"vertical-rl",textOrientation:"mixed",transform:"rotate(0deg)"}),d},[n,o,i,r]),l=x.useMemo(()=>!n||r?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[n,r]);return{ixlClassName:x.useMemo(()=>{if(!n)return"";const d=["ixl-styled"];return d.push(`ixl-type-${e.type}`),r?d.push("ixl-mobile-layout"):d.push("ixl-desktop-layout"),d.join(" ")},[n,e.type,r]),tagStyle:a,contentStyle:l,tagText:s,tagColor:o,tagTextColor:i}},Sb=(t,e)=>{let n=null;return(...r)=>{n&&clearTimeout(n),n=setTimeout(()=>{t(...r)},e)}},du=(t={})=>{const e=typeof t=="number"?t:t.breakpoint||768,n=typeof t=="number"?!0:t.enabled!==!1,[r,s]=x.useState(()=>typeof window<"u"?window.innerWidth:1024),[o,i]=x.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=x.useRef(new Set),l=x.useCallback(()=>{if(typeof window>"u")return;const g=window.innerWidth,h=g<e;s(g),i(h),a.current.forEach(m=>{try{m()}catch(p){console.error("Error in resize listener:",p)}})},[e]),c=x.useCallback(Sb(l,150),[l]);x.useEffect(()=>{if(!(!n||typeof window>"u"))return l(),window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c)}},[n,c,l]);const d=x.useCallback(g=>(a.current.add(g),()=>{a.current.delete(g)}),[]),f=x.useCallback(g=>{a.current.delete(g)},[]);return{isMobile:o,viewportWidth:r,addResizeListener:d,removeResizeListener:f}},$n=({cardProps:t,ixlConfig:e,enableIXLStyle:n=!0,wrapperMode:r="mathcard",mobileBreakpoint:s=768,className:o="",style:i,children:a,onResponsiveChange:l})=>{const c=du(s),d=cu({ixlConfig:e,enableIXLStyle:n,isMobile:c.isMobile});x.useEffect(()=>{l?.(c.isMobile)},[c.isMobile,l]);const f=x.useMemo(()=>{const m=["ixl-style-card-container"];return n&&m.push(d.ixlClassName),o&&m.push(o),c.isMobile?m.push("ixl-mobile"):m.push("ixl-desktop"),m.join(" ")},[n,d.ixlClassName,o,c.isMobile]),g=x.useMemo(()=>{const m={...i};return n&&!c.isMobile?{...m,paddingLeft:d.contentStyle.paddingLeft}:m},[n,c.isMobile,d.contentStyle,i]),h=x.useMemo(()=>{if(r!=="mathcard"||!t)return"";const m=[t.className||""];return n&&m.push("ixl-adjusted"),m.filter(Boolean).join(" ")},[r,t?.className,n]);return u.jsxs("div",{className:f,style:g,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":n,"data-responsive-mode":c.isMobile?"mobile":"desktop",children:[n&&e.showTag!==!1&&u.jsx("div",{className:"ixl-tag",style:d.tagStyle,"data-testid":"ixl-tag",children:u.jsx("span",{className:"ixl-tag-text",children:d.tagText})}),r==="mathcard"&&t?u.jsx(Be,{...t,className:h}):a]})};$n.displayName="IXLStyleCard";const Cb={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},Rb={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},Ab={remember:"速记",review:"回顾",solve:"解答"},Nb=({grades:t,onGradeSelect:e,selectedGrade:n})=>u.jsxs("div",{className:"grade-navigation",children:[u.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),u.jsx("div",{className:"grade-navigation__grid",children:t.map(r=>u.jsxs("div",{className:`grade-card ${n===r.id?"grade-card--selected":""}`,style:{borderLeftColor:r.color},onClick:()=>e?.(r.id),children:[u.jsx("div",{className:"grade-card__level",children:r.level}),u.jsx("div",{className:"grade-card__name",children:r.name}),u.jsx("div",{className:"grade-card__description",children:r.description})]},r.id))})]}),uu=({abilities:t,width:e=400,height:n=400})=>{const r=()=>t.length===0?"":t.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*t.indexOf(i)/t.length,l=i.score/i.maxScore*40+10,c=50+l*Math.sin(a),d=50-l*Math.cos(a);return`${c},${d}`}).join(" "),s=i=>{const a=Math.PI*2*i/Math.max(t.length,1),l=50+40*Math.sin(a),c=50-40*Math.cos(a);return{x2:l,y2:c}},o=i=>{const a=Math.PI*2*i/Math.max(t.length,1),l=50+45*Math.sin(a),c=50-45*Math.cos(a);let d="middle";return a>Math.PI*.25&&a<Math.PI*.75&&(d="start"),a>Math.PI*1.25&&a<Math.PI*1.75&&(d="end"),{x:l,y:c,textAnchor:d}};return u.jsxs("svg",{"data-testid":"radar-chart",width:e,height:n,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[u.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),t.map((i,a)=>{const{x2:l,y2:c}=s(a);return u.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:l,y2:c,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),t.length>2&&u.jsx("polygon",{"data-testid":"radar-polygon",points:r(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),t.map((i,a)=>{let l,c;if(i.svgPoint)l=i.svgPoint.x,c=i.svgPoint.y;else{const d=Math.PI*2*a/t.length,f=i.score/i.maxScore*40+10;l=50+f*Math.sin(d),c=50-f*Math.cos(d)}return u.jsx("circle",{"data-testid":"data-point",cx:l,cy:c,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),t.map((i,a)=>{const{x:l,y:c,textAnchor:d}=o(a);return u.jsx("text",{x:l,y:c,textAnchor:d,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},Xa={overallRating:"优秀",generalRecommendation:"你的空间想象力和逻辑推理能力非常出色!若能进一步提升在复杂图形下的专注力,你将所向披靡。建议尝试我们‘专注力挑战’系列游戏。",abilities:[{name:"空间想象力",score:7.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:50,y:17.5},recommendation:"通过观察三维物体在不同角度的投影,或尝试构建复杂结构的游戏,能有效提升空间想象力。",recommendationLink:"#spatial-challenges"},{name:"逻辑推理",score:8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:82,y:35},recommendation:"解决数独、迷宫或逻辑谜题,能够持续锻炼你的逻辑思维,尝试挑战更高难度的推理游戏。",recommendationLink:"#logic-puzzles"},{name:"图形辨识",score:9,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:85,y:65},recommendation:"你在这方面表现出色!可以尝试在更复杂、干扰因素更多的图形中进行辨识训练,保持敏锐。",recommendationLink:"#graphic-training"},{name:"专注力",score:7,maxScore:10,progressBarColor:"bg-orange-400",svgPoint:{x:50,y:80},recommendation:"在长时间的游戏中保持专注对你来说是一个挑战,建议尝试我们‘专注力挑战’系列游戏,逐渐延长专注时间。",recommendationLink:"#focus-challenges"},{name:"观察力",score:8.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:15,y:65},recommendation:"你的观察力非常敏锐,在细节发现上尤为突出。尝试在限时模式下进行观察力训练,提高反应速度。",recommendationLink:"#observation-drills"},{name:"抗压性",score:7.8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:18,y:35},recommendation:"面对高压挑战时,保持冷静是关键。通过模拟竞赛或限时任务来提升抗压能力,逐步适应压力。",recommendationLink:"#stress-games"}]};class Eb{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),Xa):(await Se.get(`${this.API_BASE_URL}/assessment`)).data}catch(e){if(console.error("Failed to fetch radar ability data:",e),process.env.NODE_ENV==="test")throw new Error("获取能力评估数据失败");return Xa}}static async submitFeedback(e){try{await Se.post(`${this.API_BASE_URL}/feedback`,e)}catch(n){throw console.error("Failed to submit feedback:",n),new Error("提交反馈失败")}}}const kb=Dn.create((t,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){t({loading:!0,error:null});try{const n=await Eb.fetchRadarAbilityData();t({data:n,loading:!1})}catch(n){const r=n instanceof Error?n.message:"获取数据失败";t({error:r,loading:!1})}}},setData:n=>{t({data:n,error:null,loading:!1})},setError:n=>{t({error:n,loading:!1})},reset:()=>{t({data:null,loading:!1,error:null})}})),fu=({ability:t})=>{const e=t.score/t.maxScore*100;return u.jsxs("div",{className:"ability-progress-bar-item","data-ability":t.name,"data-testid":"progress-bar-container",children:[u.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[u.jsx("span",{className:"text-gray-700 font-medium",children:t.name}),u.jsxs("span",{className:"text-gray-600",children:[t.score,"/",t.maxScore]})]}),u.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:u.jsx("div",{className:`${t.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":t.score,"aria-valuemin":0,"aria-valuemax":t.maxScore,"aria-label":`${t.name} progress: ${t.score} out of ${t.maxScore}`})})]})},hu=({generalRecommendation:t})=>u.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:u.jsxs("div",{className:"flex items-start",children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),u.jsxs("div",{className:"ml-3",children:[u.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),u.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:t})]})]})}),gu=({ability:t,customLinkTexts:e={}})=>{const n=r=>{const s={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[r]||s[r]||"开始挑战"};return u.jsx(H.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":t.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:u.jsx(H.CardBody,{className:"p-5",children:u.jsxs("div",{className:"flex flex-col gap-3",children:[u.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[t.name,": 专项提高"]}),u.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:t.recommendation}),u.jsx(H.Button,{as:"a",href:t.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:u.jsx(Z.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${t.name}专项提高页面`,children:n(t.name)})]})})})},Tb="_dashboardLayout_10wqn_5",Mb="_upperSection_10wqn_19",jb="_lowerSection_10wqn_33",$b="_radarChartArea_10wqn_51",Wr={dashboardLayout:Tb,upperSection:Mb,lowerSection:jb,radarChartArea:$b},Ob=()=>{const{data:t,loading:e,error:n,fetchData:r}=kb();return x.useEffect(()=>{r()},[r]),e?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),u.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):n?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[u.jsx("div",{className:"text-red-500 mb-4",children:u.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),u.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),u.jsx("p",{className:"text-gray-600 mb-4",children:n}),u.jsx("button",{onClick:r,className:"bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2","aria-label":"重试加载数据",children:"重试"})]}):t?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 animate-fade-in","data-component":"AbilityAssessmentDashboard",role:"main","aria-label":"能力评估雷达图展示",children:[u.jsxs("div",{className:"flex justify-between items-center mb-6",children:[u.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),u.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${t.overallRating}`,children:["综合评级: ",t.overallRating]})]}),u.jsxs("div",{className:Wr.dashboardLayout,children:[u.jsxs("div",{className:Wr.upperSection,children:[u.jsx("div",{className:Wr.radarChartArea,children:u.jsx(uu,{abilities:t.abilities})}),u.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:t.abilities.map(s=>u.jsx(fu,{ability:s},s.name))})]}),u.jsxs("div",{className:Wr.lowerSection,children:[u.jsx(hu,{generalRecommendation:t.generalRecommendation}),u.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.abilities.map(s=>u.jsx(gu,{ability:s},s.name))})]})]})]}):u.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:u.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},mr={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},Ib={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},Pb={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Tr={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},Fb=[{id:"g3",label:"三年级",status:"new",onClick:()=>console.log("三年级 clicked")},{id:"g4",label:"四年级",status:"2%",onClick:()=>console.log("四年级 clicked")},{id:"g5",label:"五年级",status:"进行中",onClick:()=>console.log("五年级 clicked")},{id:"g6",label:"六年级",status:"new",onClick:()=>console.log("六年级 clicked")},{id:"g7",label:"七年级",status:"new",onClick:()=>console.log("七年级 clicked")},{id:"g8",label:"八年级",status:"new",onClick:()=>console.log("八年级 clicked")},{id:"alg_topic",label:"代数专题",status:"new",onClick:()=>console.log("代数专题 clicked")},{id:"calc_topic",label:"计算专题",status:"new",onClick:()=>console.log("计算专题 clicked")},{id:"geo_topic",label:"几何专题",status:"new",onClick:()=>console.log("几何专题 clicked")},{id:"olym_topic",label:"奥数专题",status:"new",onClick:()=>console.log("奥数专题 clicked")}],Db="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",Re={id:"g5",title:"小学数学五年级",level:5,subject:"数学",units:[{id:"unit_1",title:"小数乘法",description:"学习小数乘法的计算方法及应用",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit1_lesson1",title:"小数乘整数",duration:40,knowledgeItems:[{id:"unit1_lesson1_k1",title:"小数乘整数的意义",description:"理解小数乘整数的意义与整数乘法相同",progress:0,contentUrl:""},{id:"unit1_lesson1_k2",title:"小数乘整数的计算方法",description:"掌握小数乘整数的计算方法:先按整数乘法计算,再看因数中有几位小数,就从积的右边起数出几位点上小数点",progress:0,contentUrl:""}]},{id:"unit1_lesson2",title:"小数乘小数",duration:40,knowledgeItems:[{id:"unit1_lesson2_k1",title:"小数乘小数的计算方法",description:"掌握小数乘小数的计算方法:先按整数乘法算出积,再给积点上小数点",progress:0,contentUrl:""},{id:"unit1_lesson2_k2",title:"积的小数位数确定",description:"理解积的小数位数等于两个因数的小数位数之和",progress:0,contentUrl:""}]},{id:"unit1_lesson3",title:"积的近似数",duration:40,knowledgeItems:[{id:"unit1_lesson3_k1",title:'用"四舍五入"法求积的近似数',description:'掌握用"四舍五入"法求积的近似数的方法',progress:0,contentUrl:""}]},{id:"unit1_lesson4",title:"整数乘法运算定律推广到小数",duration:40,knowledgeItems:[{id:"unit1_lesson4_k1",title:"乘法运算定律在小数中的适用性",description:"理解整数乘法运算定律对于小数乘法同样适用",progress:0,contentUrl:""},{id:"unit1_lesson4_k2",title:"运用运算定律进行简便计算",description:"能运用乘法运算定律进行小数乘法的简便计算",progress:0,contentUrl:""}]},{id:"unit1_lesson5",title:"解决问题",duration:40,knowledgeItems:[{id:"unit1_lesson5_k1",title:"用小数乘法解决实际问题",description:"能运用小数乘法解决购物、面积计算等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_2",title:"小数除法",description:"学习小数除法的计算方法及应用",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit2_lesson1",title:"小数除以整数",duration:40,knowledgeItems:[{id:"unit2_lesson1_k1",title:"小数除以整数的计算方法",description:"掌握小数除以整数的计算方法:按照整数除法的方法计算,商的小数点要与被除数的小数点对齐",progress:0,contentUrl:""}]},{id:"unit2_lesson2",title:"一个数除以小数",duration:40,knowledgeItems:[{id:"unit2_lesson2_k1",title:"除数是小数的除法计算方法",description:"掌握除数是小数的除法计算方法:利用商不变的性质,将除数转化为整数",progress:0,contentUrl:""}]},{id:"unit2_lesson3",title:"商的近似数",duration:40,knowledgeItems:[{id:"unit2_lesson3_k1",title:'用"四舍五入"法求商的近似数',description:'掌握用"四舍五入"法求商的近似数的方法',progress:0,contentUrl:""}]},{id:"unit2_lesson4",title:"循环小数",duration:40,knowledgeItems:[{id:"unit2_lesson4_k1",title:"循环小数的概念",description:"理解循环小数的概念,认识循环节",progress:0,contentUrl:""},{id:"unit2_lesson4_k2",title:"循环小数的表示方法",description:"掌握循环小数的简便表示方法",progress:0,contentUrl:""}]},{id:"unit2_lesson5",title:"用计算器探索规律",duration:40,knowledgeItems:[{id:"unit2_lesson5_k1",title:"用计算器计算小数除法",description:"会用计算器计算较复杂的小数除法",progress:0,contentUrl:""},{id:"unit2_lesson5_k2",title:"发现商的变化规律",description:"能借助计算器发现商的变化规律",progress:0,contentUrl:""}]},{id:"unit2_lesson6",title:"解决问题",duration:40,knowledgeItems:[{id:"unit2_lesson6_k1",title:"用小数除法解决实际问题",description:"能运用小数除法解决购物、分配等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_3",title:"简易方程",description:"学习用字母表示数和解简易方程",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit3_lesson1",title:"用字母表示数",duration:40,knowledgeItems:[{id:"unit3_lesson1_k1",title:"用字母表示数",description:"初步理解用字母表示数的意义和作用",progress:0,contentUrl:""},{id:"unit3_lesson1_k2",title:"用字母表示运算定律和计算公式",description:"会用字母表示运算定律和计算公式",progress:0,contentUrl:""}]},{id:"unit3_lesson2",title:"方程的意义",duration:40,knowledgeItems:[{id:"unit3_lesson2_k1",title:"方程的概念",description:"理解方程的意义,知道方程与等式的区别和联系",progress:0,contentUrl:""}]},{id:"unit3_lesson3",title:"等式的性质",duration:40,knowledgeItems:[{id:"unit3_lesson3_k1",title:"等式的性质1",description:"理解等式的性质1:等式两边加上或减去同一个数,左右两边仍然相等",progress:0,contentUrl:""},{id:"unit3_lesson3_k2",title:"等式的性质2",description:"理解等式的性质2:等式两边乘同一个数,或除以同一个不为0的数,左右两边仍然相等",progress:0,contentUrl:""}]},{id:"unit3_lesson4",title:"解简易方程",duration:40,knowledgeItems:[{id:"unit3_lesson4_k1",title:"利用等式的性质解方程",description:"会利用等式的性质解形如x±a=b、ax=b、x÷a=b、a-x=b、a÷x=b的方程",progress:0,contentUrl:""}]},{id:"unit3_lesson5",title:"实际问题与方程",duration:40,knowledgeItems:[{id:"unit3_lesson5_k1",title:"列方程解决实际问题",description:"初步学会列方程解决一些简单的实际问题",progress:0,contentUrl:""}]}]},{id:"unit_4",title:"多边形的面积",description:"学习平行四边形、三角形、梯形和组合图形的面积计算",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit4_lesson1",title:"平行四边形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson1_k1",title:"平行四边形面积公式的推导",description:"通过割补法理解平行四边形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson1_k2",title:"平行四边形面积的计算",description:"掌握平行四边形面积计算公式:S=ah,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson2",title:"三角形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson2_k1",title:"三角形面积公式的推导",description:"通过拼摆法理解三角形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson2_k2",title:"三角形面积的计算",description:"掌握三角形面积计算公式:S=ah÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson3",title:"梯形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson3_k1",title:"梯形面积公式的推导",description:"通过拼摆法理解梯形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson3_k2",title:"梯形面积的计算",description:"掌握梯形面积计算公式:S=(a+b)h÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson4",title:"组合图形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson4_k1",title:"认识组合图形",description:"认识组合图形,会把组合图形分解成已学过的平面图形",progress:0,contentUrl:""},{id:"unit4_lesson4_k2",title:"计算组合图形的面积",description:"掌握计算组合图形面积的多种方法",progress:0,contentUrl:""}]}]},{id:"unit_5",title:"因数与倍数",description:"学习因数、倍数、质数、合数等概念",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit5_lesson1",title:"因数和倍数",duration:40,knowledgeItems:[{id:"unit5_lesson1_k1",title:"因数和倍数的意义",description:"理解因数和倍数的意义,掌握找一个数的因数和倍数的方法",progress:0,contentUrl:""},{id:"unit5_lesson1_k2",title:"因数和倍数的特征",description:"了解一个数的因数的个数是有限的,倍数的个数是无限的",progress:0,contentUrl:""}]},{id:"unit5_lesson2",title:"2、5、3的倍数的特征",duration:40,knowledgeItems:[{id:"unit5_lesson2_k1",title:"2、5的倍数的特征",description:"掌握2、5的倍数的特征,理解奇数和偶数的意义",progress:0,contentUrl:""},{id:"unit5_lesson2_k2",title:"3的倍数的特征",description:"掌握3的倍数的特征,能判断一个数是不是3的倍数",progress:0,contentUrl:""}]},{id:"unit5_lesson3",title:"质数和合数",duration:40,knowledgeItems:[{id:"unit5_lesson3_k1",title:"质数和合数的意义",description:"理解质数和合数的意义,能判断一个数是质数还是合数",progress:0,contentUrl:""},{id:"unit5_lesson3_k2",title:"制作100以内的质数表",description:"会制作100以内的质数表,熟记20以内的质数",progress:0,contentUrl:""}]}]},{id:"unit_6",title:"长方体和正方体",description:"学习长方体和正方体的特征、表面积和体积计算",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit6_lesson1",title:"长方体和正方体的认识",duration:40,knowledgeItems:[{id:"unit6_lesson1_k1",title:"长方体的特征",description:"认识长方体的特征,了解长方体的长、宽、高",progress:0,contentUrl:""},{id:"unit6_lesson1_k2",title:"正方体的特征",description:"认识正方体的特征,理解正方体是特殊的长方体",progress:0,contentUrl:""}]},{id:"unit6_lesson2",title:"长方体和正方体的表面积",duration:40,knowledgeItems:[{id:"unit6_lesson2_k1",title:"表面积的意义",description:"理解表面积的意义,掌握长方体和正方体表面积的计算方法",progress:0,contentUrl:""},{id:"unit6_lesson2_k2",title:"表面积的实际应用",description:"能运用表面积知识解决一些实际问题",progress:0,contentUrl:""}]},{id:"unit6_lesson3",title:"长方体和正方体的体积",duration:40,knowledgeItems:[{id:"unit6_lesson3_k1",title:"体积和体积单位",description:"理解体积的意义,认识常用的体积单位",progress:0,contentUrl:""},{id:"unit6_lesson3_k2",title:"长方体和正方体体积的计算",description:"掌握长方体和正方体体积的计算公式",progress:0,contentUrl:""},{id:"unit6_lesson3_k3",title:"体积单位间的进率",description:"掌握体积单位之间的进率和换算",progress:0,contentUrl:""}]},{id:"unit6_lesson4",title:"容积和容积单位",duration:40,knowledgeItems:[{id:"unit6_lesson4_k1",title:"容积和容积单位",description:"理解容积的意义,认识常用的容积单位",progress:0,contentUrl:""},{id:"unit6_lesson4_k2",title:"容积和体积的关系",description:"掌握容积和体积之间的关系",progress:0,contentUrl:""}]}]},{id:"unit_7",title:"分数的意义和性质",description:"学习分数的意义、性质和约分、通分等方法",estimatedDuration:"4周",totalLessons:16,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit7_lesson1",title:"分数的意义",duration:40,knowledgeItems:[{id:"unit7_lesson1_k1",title:"分数的产生和意义",description:"理解分数的产生和意义,明确分数与除法的关系",progress:0,contentUrl:""},{id:"unit7_lesson1_k2",title:"分数单位",description:"认识分数单位,能说出一个分数中有几个这样的分数单位",progress:0,contentUrl:""}]},{id:"unit7_lesson2",title:"分数与除法",duration:40,knowledgeItems:[{id:"unit7_lesson2_k1",title:"分数与除法的关系",description:"理解分数与除法的关系,会用分数表示两个数相除的商",progress:0,contentUrl:""}]},{id:"unit7_lesson3",title:"真分数和假分数",duration:40,knowledgeItems:[{id:"unit7_lesson3_k1",title:"真分数和假分数的意义",description:"理解真分数和假分数的意义和特征",progress:0,contentUrl:""},{id:"unit7_lesson3_k2",title:"带分数",description:"认识带分数,会进行假分数与整数、带分数的互化",progress:0,contentUrl:""}]},{id:"unit7_lesson4",title:"分数的基本性质",duration:40,knowledgeItems:[{id:"unit7_lesson4_k1",title:"分数的基本性质",description:"理解分数的基本性质,能运用分数的基本性质进行分数的变形",progress:0,contentUrl:""}]},{id:"unit7_lesson5",title:"约分",duration:40,knowledgeItems:[{id:"unit7_lesson5_k1",title:"最大公因数",description:"理解公因数和最大公因数的意义,掌握求两个数的最大公因数的方法",progress:0,contentUrl:""},{id:"unit7_lesson5_k2",title:"约分的方法",description:"掌握约分的方法,能正确地进行约分",progress:0,contentUrl:""}]},{id:"unit7_lesson6",title:"通分",duration:40,knowledgeItems:[{id:"unit7_lesson6_k1",title:"最小公倍数",description:"理解公倍数和最小公倍数的意义,掌握求两个数的最小公倍数的方法",progress:0,contentUrl:""},{id:"unit7_lesson6_k2",title:"通分的方法",description:"掌握通分的方法,能正确地进行通分",progress:0,contentUrl:""}]},{id:"unit7_lesson7",title:"分数和小数的互化",duration:40,knowledgeItems:[{id:"unit7_lesson7_k1",title:"分数化成小数",description:"掌握分数化成小数的方法",progress:0,contentUrl:""},{id:"unit7_lesson7_k2",title:"小数化成分数",description:"掌握小数化成分数的方法",progress:0,contentUrl:""}]}]},{id:"unit_8",title:"分数的加法和减法",description:"学习同分母分数、异分母分数的加法和减法",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit8_lesson1",title:"同分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson1_k1",title:"同分母分数加法的计算方法",description:"掌握同分母分数加法的计算方法",progress:0,contentUrl:""},{id:"unit8_lesson1_k2",title:"同分母分数减法的计算方法",description:"掌握同分母分数减法的计算方法",progress:0,contentUrl:""}]},{id:"unit8_lesson2",title:"异分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson2_k1",title:"异分母分数加法的计算方法",description:"掌握异分母分数加法的计算方法:先通分,然后按照同分母分数加法进行计算",progress:0,contentUrl:""},{id:"unit8_lesson2_k2",title:"异分母分数减法的计算方法",description:"掌握异分母分数减法的计算方法:先通分,然后按照同分母分数减法进行计算",progress:0,contentUrl:""}]},{id:"unit8_lesson3",title:"分数加减混合运算",duration:40,knowledgeItems:[{id:"unit8_lesson3_k1",title:"分数加减混合运算的顺序",description:"掌握分数加减混合运算的运算顺序",progress:0,contentUrl:""},{id:"unit8_lesson3_k2",title:"整数加法运算定律推广到分数加法",description:"理解整数加法运算定律对于分数加法同样适用,能运用运算定律进行简便计算",progress:0,contentUrl:""}]}]},{id:"unit_9",title:"折线统计图",description:"学习单式折线统计图和复式折线统计图的认识和制作",estimatedDuration:"2周",totalLessons:6,moduleCategory:"Probability and Statistics",lessons:[{id:"unit9_lesson1",title:"单式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson1_k1",title:"单式折线统计图的特点",description:"认识单式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson1_k2",title:"绘制单式折线统计图",description:"能根据数据绘制单式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson2",title:"复式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson2_k1",title:"复式折线统计图的特点",description:"认识复式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson2_k2",title:"绘制复式折线统计图",description:"能根据数据绘制复式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson3",title:"数据分析",duration:40,knowledgeItems:[{id:"unit9_lesson3_k1",title:"根据统计图进行数据分析",description:"能根据折线统计图进行简单的数据分析,作出合理的判断和预测",progress:0,contentUrl:""}]}]}]},Lb=Fb,zb=Tr;class Vb{baseURL;token;constructor(e="/api/v1",n=Db){this.baseURL=e,this.token=n}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,n={}){const r=await fetch(e,{...n,headers:{...this.getAuthHeaders(),...n.headers}});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return r}async getCourseData(e){return(await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}`)).json()}async getUserGradeUnitsNav(e){const n=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(n)).json()}async getUnitProgress(e,n){const r=n?`${this.baseURL}/content/courses/${e}/units/${n}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(r)).json()}async batchUpdateLessonProgress(e,n){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(n)})).json()}async updateLessonProgress(e,n,r,s){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${n}/lessons/${r}/progress`,{method:"POST",body:JSON.stringify({status:s})})}setToken(e){this.token=e}getToken(){return this.token}}const qr=new Vb;class wt extends Error{constructor(e,n,r){super(e),this.code=n,this.originalError=r,this.name="DataSourceError"}}class Gb{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},qr.setToken(this.config.token)}async getUserGradeUnitsNav(e,n){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${n}`),await this.withRetry(()=>qr.getUserGradeUnitsNav(e))}catch(r){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",r),new wt(`获取年级单元导航数据失败: ${r instanceof Error?r.message:"未知错误"}`,"GET_USER_GRADE_UNITS_NAV_FAILED",r instanceof Error?r:void 0)}}async getUserProfile(e){try{return console.log(`[ApiDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}catch(n){throw console.error("[ApiDataSource] 获取用户个人信息失败:",n),new wt(`获取用户个人信息失败: ${n instanceof Error?n.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",n instanceof Error?n:void 0)}}async getExploreMenu(){try{return console.log("[ApiDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}catch(e){throw console.error("[ApiDataSource] 获取探索菜单数据失败:",e),new wt(`获取探索菜单数据失败: ${e instanceof Error?e.message:"未知错误"}`,"GET_EXPLORE_MENU_FAILED",e instanceof Error?e:void 0)}}async updateLessonProgress(e){try{console.log("[ApiDataSource] 更新课时进度:",e),await this.withRetry(()=>qr.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(n){throw console.error("[ApiDataSource] 更新课时进度失败:",n),new wt(`更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async batchUpdateLessonProgress(e,n){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,n),await this.withRetry(()=>qr.batchUpdateLessonProgress(e,n))}catch(r){throw console.error("[ApiDataSource] 批量更新课时进度失败:",r),new wt(`批量更新课时进度失败: ${r instanceof Error?r.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",r instanceof Error?r:void 0)}}async withRetry(e){let n;for(let r=1;r<=this.config.retryCount;r++)try{return await e()}catch(s){n=s instanceof Error?s:new Error(String(s)),r<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${r}次重试...`,n.message),await this.delay(this.config.retryDelay))}throw n}delay(e){return new Promise(n=>setTimeout(n,e))}getConfig(){return{...this.config}}}class Ub{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,n){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${n}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${n}`),new wt("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${n}`),{userId:n,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:Re.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:Re.units.map((s,o)=>({unitId:s.id,title:s.title,description:s.description,moduleCategory:s.moduleCategory,estimatedDuration:s.estimatedDuration,totalLessons:s.lessons.length,completedLessons:o<2?Math.floor(s.lessons.length*.5):0,progressPercentage:o<2?50:0,status:o<2?"in-progress":"not-started",lastAccessed:o<2?new Date().toISOString():void 0,isActive:o===0,route:`/math/grade-5/unit/${s.id}`,icon:mr[s.moduleCategory]||mr.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:获取用户个人信息失败","MOCK_GET_USER_PROFILE_FAILED");return console.log(`[MockDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}async getExploreMenu(){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:获取探索菜单数据失败","MOCK_GET_EXPLORE_MENU_FAILED");return console.log("[MockDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}async updateLessonProgress(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,n){if(await this.simulateDelay(),this.shouldSimulateError())throw new wt("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,n),{success:!0,results:n.map(s=>({lessonId:s.lessonId,success:!0,status:s.status}))}}async simulateDelay(){this.config.delay&&this.config.delay>0&&await new Promise(e=>setTimeout(e,this.config.delay))}shouldSimulateError(){return this.config.simulateError?Math.random()<(this.config.errorProbability||.1):!1}getConfig(){return{...this.config}}getCourseData(){return Re}getLessonsData(){const e={};return Re.units.forEach(n=>{e[n.id]=n.lessons.map(r=>({id:r.id,title:r.title,duration:r.duration,knowledgeItems:r.knowledgeItems.map(s=>({...s,progress:0}))}))}),e}}class Bb{static instances=new Map;static createDataSource(e){const{type:n,config:r,customDataSourceClass:s}=e,o=this.getInstanceKey(n,r);if(this.instances.has(o))return this.instances.get(o);let i;switch(n){case"api":i=new Gb(r);break;case"mock":i=new Ub(r);break;case"custom":if(!s)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new s(r);break;default:throw new Error(`不支持的数据源类型: ${n}`)}return this.instances.set(o,i),console.log(`[DataSourceFactory] 创建数据源: type=${n}, name=${r.name}`),i}static createApiDataSource(e){return this.createDataSource({type:"api",config:e})}static createMockDataSource(e={}){return this.createDataSource({type:"mock",config:{name:"MockDataSource",...e}})}static createDefaultDataSource(){const e=typeof window<"u";let n=!1,r=!1,s=!1;try{typeof process<"u"&&process.env?(n=process.env.NODE_ENV==="development",r=process.env.NODE_ENV==="test",s=process.env.REACT_APP_USE_MOCK==="true"):(n=!0,s=!0)}catch(o){console.warn("无法检测环境变量,使用默认配置:",o),n=!0,s=!0}return n||r||s?this.createMockDataSource({name:"DefaultMockDataSource",delay:300}):this.createApiDataSource({name:"DefaultApiDataSource",baseURL:"/api/v1",token:e&&localStorage.getItem("authToken")||""})}static clearCache(){this.instances.clear(),console.log("[DataSourceFactory] 已清除所有数据源实例缓存")}static getCachedInstanceCount(){return this.instances.size}static getInstanceKey(e,n){return`${e}:${n.name}:${JSON.stringify(n)}`}}function Hb(){return Bb.createDefaultDataSource()}function Wb(t={}){const{dataSource:e=Hb(),fallbackStrategy:n="mock",errorHandling:r={},performance:s={},theme:o={},debug:i=!1,enableDevTools:a=!1}=t;return{dataSource:e,fallbackStrategy:n,errorHandling:{showUserFriendlyErrors:!0,logErrors:!0,autoRetry:!0,maxRetries:3,retryDelay:1e3,...r},performance:{enableVirtualization:!0,lazyLoadImages:!0,debounceSearch:300,enableCaching:!0,cacheTTL:3e5,...s},theme:{primaryColor:"#1865f2",borderRadius:"8px",spacing:"16px",fontSize:"14px",enableDarkMode:!1,...o},debug:i,enableDevTools:a}}function qb(t,e){return{...t,...e,errorHandling:{...t.errorHandling,...e.errorHandling},performance:{...t.performance,...e.performance},theme:{...t.theme,...e.theme}}}const mu=x.createContext(null),pu=()=>{const t=x.useContext(mu);if(!t)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return t},yu=({children:t,config:e})=>{const[n,r]=x.useState(()=>Wb(e)),[s,o]=x.useState(null),[i,a]=x.useState([]),[l,c]=x.useState(null),[d,f]=x.useState({}),[g,h]=x.useState(!1),[m,p]=x.useState(null),[y,b]=x.useState(null),[w,v]=x.useState([]),S=x.useCallback(async(N,M)=>{h(!0),p(null);try{process.env.NODE_ENV!=="test"&&await new Promise(P=>setTimeout(P,100));const F=await n.dataSource.getUserGradeUnitsNav(N,M);c(F);const D={};Re.units.forEach(P=>{D[P.id]=P.lessons.map($=>({id:$.id,title:$.title,duration:$.duration,knowledgeItems:$.knowledgeItems.map(O=>({...O,progress:0}))}))}),console.log("Lessons data loaded:",D),f(D);try{const P=await n.dataSource.getUserProfile(M);o(P)}catch(P){console.warn("获取用户信息失败,使用默认数据:",P),o({id:M,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const P=await n.dataSource.getExploreMenu();a(P)}catch(P){console.warn("获取探索菜单失败,使用默认数据:",P),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(F){if(console.error("数据加载错误:",F),n.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const D={userId:M,courseId:N,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:Re.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:Re.units.map(($,O)=>({unitId:$.id,title:$.title,description:$.description,moduleCategory:$.moduleCategory,estimatedDuration:$.estimatedDuration,totalLessons:$.lessons.length,completedLessons:O<2?Math.floor($.lessons.length*.5):0,progressPercentage:O<2?50:0,status:O<2?"in-progress":"not-started",lastAccessed:O<2?new Date().toISOString():void 0,isActive:O===0,route:`/math/grade-5/unit/${$.id}`,icon:mr[$.moduleCategory]||mr.Default}))};c(D);const P={};Re.units.forEach($=>{P[$.id]=$.lessons.map(O=>({id:O.id,title:O.title,duration:O.duration,knowledgeItems:O.knowledgeItems.map(T=>({...T,progress:0}))}))}),f(P),o({id:M,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else p(F instanceof Error?F.message:"数据加载失败"),c(null)}finally{h(!1)}},[n]),_=x.useCallback(N=>{v(M=>M.includes(N)?M.filter(F=>F!==N):[...M,N])},[]),A=x.useCallback(N=>{b(N)},[]),C=x.useCallback(N=>{r(M=>qb(M,N))},[]);x.useEffect(()=>{if(console.log("unitsData state updated:",l),console.log("unitsData?.units:",l?.units),console.log("unitsData?.units?.length:",l?.units?.length),l&&l.units.length>0){console.log("Looking for active unit...");const N=l.units.find(F=>F.isActive);console.log("Found active unit:",N);const M=N?.unitId||l.units[0].unitId;console.log("Setting default active unit:",M),b(M),console.log("Default active unit set after state update:",M)}else console.log("No units data available for setting default active unit")},[l]);const R={userInfo:s,exploreMenu:i,unitsData:l,lessons:d,loading:g,error:m,activeUnitId:y,activeLessonIds:w,config:n,theme:n.theme,enableVirtualization:n.performance?.enableVirtualization,setLoading:h,setError:p,setActiveUnit:A,toggleLesson:_,loadPageData:S,updateConfig:C};return u.jsx(mu.Provider,{value:R,children:t})},Yb=({gradeId:t,userId:e,onLearnAction:n,className:r,userInfo:s,exploreMenu:o})=>{const{userInfo:i,exploreMenu:a,unitsData:l,lessons:c,loading:d,error:f,activeUnitId:g,activeLessonIds:h,setActiveUnit:m,toggleLesson:p,loadPageData:y}=pu(),b=s??i,w=o??a;x.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",t,"userId:",e),y(t,e)},[t,e,y]),x.useEffect(()=>{console.log("activeUnitId from context:",g),console.log("lessons from context:",c);const _=l?.units?.find(C=>C.unitId===g)||null,A=_&&g&&c[g]?{id:_.unitId,title:_.title,description:_.description,estimatedDuration:_.estimatedDuration,totalLessons:_.totalLessons,moduleCategory:_.moduleCategory,lessons:c[g]}:null;console.log("activeUnit computed:",A)},[g,c,l]);const v=l?.units?.find(_=>_.unitId===g)||null,S=v&&g&&c[g]?{id:v.unitId,title:v.title,description:v.description,estimatedDuration:v.estimatedDuration,totalLessons:v.totalLessons,moduleCategory:v.moduleCategory,lessons:c[g]}:null;return d?u.jsx("div",{className:`grade-unit-browser-page loading ${r||""}`,"data-testid":"grade-unit-browser-page",children:u.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):f?u.jsxs("div",{className:`grade-unit-browser-page error ${r||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"error-message","data-testid":"error-message",children:f}),u.jsx(Pt,{onClick:()=>y(t,e),intent:"retry",useNewClassName:!0,className:"retry-button",children:"重试"})]}):u.jsxs("div",{className:`grade-unit-browser-page ${r||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"header-area",children:u.jsx(ld,{userData:b||void 0,exploreItems:w})}),u.jsx("div",{className:"sidebar-area",children:u.jsx(Dc,{data:l,activeUnitId:g,onUnitSelect:m,loading:d})}),u.jsx("div",{className:"content-area",children:u.jsx(Fc,{unit:S,activeLessonIds:h,onToggleLesson:p,onLearnAction:n||(()=>{}),loading:d})})]})},Kb=t=>u.jsx(yu,{config:t.config,children:u.jsx(Yb,{...t})}),Xb={streak:{emoji:"🔥",bgColor:"bg-orange-50",textColor:"text-orange-600"},coin:{emoji:"💰",bgColor:"bg-yellow-50",textColor:"text-yellow-600"},gem:{emoji:"💎",bgColor:"bg-blue-50",textColor:"text-blue-600"},star:{emoji:"⭐",bgColor:"bg-purple-50",textColor:"text-purple-600"}},Jb={sm:{text:"text-sm",padding:"px-2 py-1",gap:"gap-1"},md:{text:"text-base",padding:"px-3 py-1.5",gap:"gap-1.5"}};function Zb(t){return typeof t=="string"?t:t.toLocaleString("en-US")}const si=({type:t,value:e,label:n,size:r="md",isAnimated:s=!1,onClick:o})=>{const i=Xb[t],a=Jb[r],l=f=>{o&&(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),o())},c=["inline-flex","items-center","rounded-full","font-medium","transition-all","duration-200",a.padding,a.gap,a.text,i.bgColor,i.textColor,s?"animate-bounce":"",o?"cursor-pointer hover:opacity-80":""].join(" "),d=u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"select-none",role:"img","aria-label":t,children:i.emoji}),u.jsx("span",{className:"font-semibold",children:Zb(e)}),n&&u.jsx("span",{className:"text-gray-500 text-xs",children:n})]});return o?u.jsx("button",{type:"button",className:c,onClick:o,onKeyDown:l,tabIndex:0,role:"button",children:d}):u.jsx("span",{className:c,children:d})};function bu({userName:t,userLevel:e,userAvatar:n,streakDays:r,coins:s,notifications:o=0,onSearch:i,onLanguageSwitch:a,onNotificationClick:l,onProfileClick:c,className:d=""}){const[f,g]=x.useState(""),h=m=>{const p=m.target.value;g(p),i?.(p)};return u.jsxs("header",{className:`h-[72px] bg-white/80 backdrop-blur-md px-8 flex justify-between items-center border-b border-gray-100 ${d}`,role:"banner",children:[u.jsxs("div",{className:"flex items-center gap-4 w-1/3",children:[u.jsx("h1",{className:"text-xl font-extrabold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-purple-600","data-testid":"logo",children:"MathWiz"}),u.jsxs("div",{className:"relative w-64 hidden md:block",children:[u.jsx(Z.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",size:16}),u.jsx(H.Input,{type:"text",placeholder:"Search skills, topics... / 搜索技能、知识点...",value:f,onChange:h,classNames:{input:"bg-gray-100 rounded-full py-2 pl-10 pr-4 text-sm",inputWrapper:"bg-gray-100 rounded-full h-10"},tabIndex:0,"aria-label":"Search skills and topics"})]})]}),u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsxs("p",{className:"hidden xl:block text-sm font-semibold text-gray-500 max-w-[180px] truncate",children:["Welcome back, ",t]}),u.jsxs(H.Button,{variant:"light",size:"sm",className:"text-gray-500 hover:text-blue-600",onPress:a,tabIndex:0,"aria-label":"Switch language",children:[u.jsx(Z.Globe,{size:16,className:"mr-1"}),"EN/中"]}),u.jsx("div",{className:"h-6 w-px bg-gray-200"}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx(si,{type:"streak",value:r,label:"Day Streak",size:"md"}),u.jsx(si,{type:"coin",value:s,size:"md"})]}),u.jsx("div",{className:"h-6 w-px bg-gray-200"}),u.jsxs("button",{className:"flex items-center gap-3 cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-600 rounded-lg p-1",onClick:c,tabIndex:0,"aria-label":"User profile",children:[u.jsx("img",{src:n,alt:t,className:"w-10 h-10 rounded-full border-2 border-blue-100"}),u.jsxs("div",{className:"hidden lg:block text-left",children:[u.jsx("div",{className:"font-bold text-sm text-gray-900",children:t}),u.jsx("div",{className:"text-xs text-gray-500",children:e})]})]}),u.jsxs("button",{className:"relative ml-2 text-gray-400 hover:text-gray-600 p-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600",onClick:l,tabIndex:0,"aria-label":"Notifications",children:[u.jsx(Z.Bell,{size:20}),o>0&&u.jsx("span",{className:"absolute top-0 right-0 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-white","data-testid":"notification-badge"})]})]})]})}const Qb=[{id:"home",label:"Home",icon:Z.Home},{id:"browse",label:"Browse",icon:Z.LayoutGrid},{id:"analytics",label:"Analytics",icon:Z.BarChart3},{id:"settings",label:"Settings",icon:Z.Settings}];function xu({activeItemId:t="home",onNavigate:e,className:n=""}){const r=s=>{s!==t&&e?.(s)};return u.jsxs("aside",{className:`w-20 bg-white shadow-sm flex flex-col items-center py-6 gap-8 z-20 shrink-0 ${n}`,role:"complementary","aria-label":"Sidebar",children:[u.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-2xl flex items-center justify-center text-white font-bold text-xl shadow-md","data-testid":"logo",children:"M"}),u.jsx("nav",{className:"flex flex-col gap-6 w-full items-center",role:"navigation","aria-label":"Main navigation",children:Qb.map(s=>{const o=s.icon,i=s.id===t;return u.jsx("button",{onClick:()=>r(s.id),tabIndex:0,"aria-label":s.label,className:`
45
+ w-12 h-12 rounded-2xl flex items-center justify-center transition-colors
46
+ ${i?"bg-blue-50 text-blue-600":"text-gray-400 hover:bg-gray-50 hover:text-gray-600"}
47
+ `,"aria-current":i?"page":void 0,children:u.jsx(o,{size:24})},s.id)})})]})}const ex=()=>u.jsx("div",{className:"flex items-center justify-center w-full h-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("div",{className:"flex gap-0.5",children:[u.jsx("div",{className:"w-4 h-6 bg-green-500 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"})]}),u.jsx("span",{className:"font-bold text-gray-400 mx-1",children:"+"}),u.jsxs("div",{className:"flex gap-0.5",children:[u.jsx("div",{className:"w-4 h-6 bg-green-500 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"})]})]})});function vu({courseCategory:t,lessonTitleEn:e,lessonTitleZh:n,visualNode:r,onAction:s,className:o=""}){const i=()=>{s?.()},a=()=>{s?.()},l=d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),s?.())},c=`Continue lesson: ${e} - ${n}`;return u.jsx("div",{"data-testid":"action-hero-card",role:s?"button":void 0,tabIndex:s?0:void 0,"aria-label":s?c:void 0,onClick:i,onKeyDown:l,className:`
48
+ bg-white rounded-2xl p-6
49
+ border border-gray-200
50
+ shadow-sm
51
+ hover:-translate-y-[3px] hover:shadow-lg hover:border-blue-100
52
+ transition-all duration-200 ease-out
53
+ cursor-pointer
54
+ h-full min-h-[240px]
55
+ ${o}
56
+ `.trim(),children:u.jsxs("div",{className:"flex flex-col md:flex-row gap-8 flex-1 h-full",children:[u.jsxs("div",{className:"flex-1 min-w-0 flex flex-col",children:[u.jsxs("div",{className:"inline-flex items-center gap-2 bg-blue-500 text-white px-4 py-1.5 rounded-full text-sm font-bold shadow-sm mb-3 w-fit group-hover:bg-blue-600 transition-colors",children:[u.jsx("span",{children:"1-Click Continue"}),u.jsx("span",{className:"font-normal opacity-80 border-l border-white/30 pl-2 ml-1",children:"一键继续"})]}),u.jsx("p",{className:"text-gray-500 text-sm font-semibold tracking-wide mb-2",children:t}),u.jsx("h2",{className:"text-gray-900 text-2xl font-bold leading-loose tracking-wide mb-4",children:e}),u.jsx("p",{className:"text-gray-500 text-lg leading-loose tracking-wide",children:n})]}),u.jsxs("div",{"data-testid":"visual-container",className:"w-full md:w-[44%] md:max-w-[240px] shrink-0 bg-gray-50 rounded-2xl p-4 border border-gray-100 flex flex-col items-center justify-between gap-4",children:[u.jsx("div",{className:"flex-1 flex items-center justify-center w-full min-h-[80px]",children:r||u.jsx(ex,{})}),u.jsxs(H.Button,{color:"primary",variant:"solid",radius:"full",fullWidth:!0,onPress:a,className:"font-medium bg-blue-600 hover:bg-blue-500",children:["Try this ",">"]})]})]})})}const tx="#3B82F6",Ja=15.9155,nx=1e3,Co=60;function wu({value:t,size:e="sm",color:n=tx,titleEn:r,subTitleZh:s,maxLabel:o,centerContent:i,isAnimated:a=!0,className:l=""}){const c=x.useMemo(()=>t<0?0:t>100?100:t,[t]),[d,f]=x.useState(a?0:c),g=x.useMemo(()=>e==="lg"?{containerClass:"w-32 h-32",strokeWidth:3,valueTextClass:"text-3xl font-bold",percentTextClass:"text-sm",maxLabelClass:"text-xs text-gray-500 mt-0.5"}:{containerClass:"w-16 h-16",strokeWidth:4,valueTextClass:"text-sm font-bold",percentTextClass:"text-xs",maxLabelClass:"hidden"},[e]);x.useEffect(()=>{if(!a){f(c);return}f(0);const m=c/Co,p=nx/Co;let y=0;const b=setInterval(()=>{y++,y>=Co?(f(c),clearInterval(b)):f(Math.round(m*y))},p);return()=>clearInterval(b)},[c,a]);const h=`${d}, 100`;return u.jsxs("div",{className:`radial-progress-wrapper flex flex-col items-center ${l}`,children:[u.jsxs("div",{className:`radial-progress-container relative ${g.containerClass}`,children:[u.jsxs("svg",{viewBox:"0 0 36 36",className:"w-full h-full block",style:{transform:"rotate(-90deg)"},children:[u.jsx("circle",{className:"radial-progress-bg text-gray-100",cx:"18",cy:"18",r:Ja,fill:"none",stroke:"currentColor",strokeWidth:g.strokeWidth}),u.jsx("circle",{className:"radial-progress-bar",cx:"18",cy:"18",r:Ja,fill:"none",stroke:n,strokeWidth:g.strokeWidth,strokeLinecap:"round",strokeDasharray:h,style:{transition:"stroke-dasharray 0.3s ease-out"}})]}),u.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:i||u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-baseline",children:[u.jsx("span",{className:g.valueTextClass,style:{color:n},children:d}),u.jsx("span",{className:`${g.percentTextClass} text-gray-400 ml-0.5`,children:"%"})]}),e==="lg"&&o&&u.jsx("span",{className:g.maxLabelClass,children:o})]})})]}),(r||s)&&u.jsxs("div",{className:"mt-2 text-center",children:[r&&u.jsx("div",{className:"text-sm font-semibold text-gray-800",children:r}),s&&u.jsx("div",{className:"text-xs text-gray-500",children:s})]})]})}const rx=()=>u.jsx("svg",{"data-testid":"checkmark-icon",className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})}),_u=({isCompleted:t,titleEn:e,titleZh:n,onToggle:r,isDisabled:s=!1,className:o=""})=>{const i=()=>{t||s||r?.(!0)},a=t?"bg-gray-50":"bg-white",l=t?"text-sm font-medium line-through text-gray-400 leading-loose":"text-sm font-medium text-gray-900 leading-loose",c=t?"text-xs text-gray-400 leading-loose":"text-xs text-gray-500 leading-loose",d=t?"w-5 h-5 rounded-full bg-brand-500 flex items-center justify-center":"w-5 h-5 rounded-full border-2 border-gray-300 hover:border-brand-500 flex items-center justify-center";return u.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-lg transition-colors ${a} ${o}`,"data-testid":"task-checkbox",children:[u.jsx("button",{type:"button",role:"button","aria-label":`${e} - ${n}`,"aria-pressed":t,disabled:s||t,onClick:i,className:"flex-shrink-0 mt-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2 rounded-full disabled:cursor-not-allowed",children:u.jsx("div",{"data-testid":"task-checkbox-icon",className:d,children:t&&u.jsx(rx,{})})}),u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("span",{className:l,children:e}),u.jsx("span",{className:c,children:n})]})]})},Su=({currentXP:t,targetXP:e,tasks:n,onTaskToggle:r,className:s=""})=>{const o=x.useMemo(()=>{if(e<=0)return 0;const a=Math.round(t/e*100);return Math.max(0,Math.min(100,a))},[t,e]),i=(a,l)=>{l||r?.(a,!0)};return u.jsxs("div",{"data-testid":"daily-milestones",className:`bg-white rounded-2xl shadow-sm p-6 relative overflow-hidden h-full ${s}`,children:[u.jsxs("div",{className:"flex items-center justify-between mb-6",children:[u.jsxs("div",{className:"flex items-baseline gap-2",children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 leading-loose",children:"Daily Milestones"}),u.jsx("span",{className:"text-sm text-gray-500 leading-loose",children:"/ 今日目标"})]}),u.jsx("span",{className:"text-4xl opacity-10 select-none","aria-hidden":"true",children:"🎉"})]}),u.jsxs("div",{"data-testid":"milestones-content",className:"flex flex-col md:flex-row items-start gap-6",children:[u.jsx(wu,{value:o,size:"lg",maxLabel:`/${e} XP`}),u.jsx("div",{"data-testid":"task-list",className:"flex-1 w-full flex flex-col gap-4",children:n.map(a=>u.jsx(_u,{isCompleted:a.isCompleted,titleEn:a.titleEn,titleZh:a.titleZh,onToggle:()=>i(a.id,a.isCompleted)},a.id))})]})]})},Cu=({tabs:t,activeId:e,onChange:n,size:r="lg",className:s="",isDisabled:o=!1,isFullWidth:i=!1,"aria-label":a})=>{const l=d=>{d!==e&&n(String(d))},c=d=>{if(o)return;const f=t.filter(h=>!h.isDisabled),g=f.findIndex(h=>h.id===e);switch(d.key){case"ArrowRight":{d.preventDefault();const h=(g+1)%f.length;n(f[h].id);break}case"ArrowLeft":{d.preventDefault();const h=g<=0?f.length-1:g-1;n(f[h].id);break}case"Home":{d.preventDefault(),f.length>0&&n(f[0].id);break}case"End":{d.preventDefault(),f.length>0&&n(f[f.length-1].id);break}}};return u.jsx(H.Tabs,{selectedKey:e,onSelectionChange:l,isDisabled:o,fullWidth:i,"aria-label":a,onKeyDown:c,variant:"bordered",color:"primary",radius:"full",children:t.map(d=>u.jsx(H.Tab,{title:u.jsx("span",{className:"text-sm font-medium",children:d.label}),isDisabled:d.isDisabled||o},d.id))})},sx=(t,e,n)=>Math.min(Math.max(t,e),n),ox=t=>{const e={sm:"pathway-node--sm",md:"pathway-node--md",lg:"pathway-node--lg"};return e[t]||e.md},Za=t=>{const e="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0";switch(t){case"completed":return`${e} bg-green-500`;case"current":return`${e} bg-brand-50`;case"locked":return`${e} bg-gray-300`;default:return e}},ix=t=>{const e="font-medium";switch(t){case"completed":return`${e} line-through text-gray-400`;case"current":return`${e} text-gray-900`;case"locked":return`${e} text-gray-400`;default:return`${e} text-gray-900`}},Ru=({status:t,title:e,subtitle:n,progress:r=0,avatarSrc:s,onAction:o,size:i="md",className:a="",showConnector:l=!1,isLast:c=!1})=>{const d=sx(r,0,100),f=ox(i),g=()=>{switch(t){case"completed":return u.jsx("div",{"data-testid":"pathway-node-icon-container",className:Za("completed"),children:u.jsx(Z.Check,{"data-testid":"pathway-node-check-icon",className:"w-5 h-5 text-white"})});case"locked":return u.jsx("div",{"data-testid":"pathway-node-icon-container",className:Za("locked"),children:u.jsx(Z.Lock,{"data-testid":"pathway-node-lock-icon",className:"w-5 h-5 text-white"})});default:return u.jsx("div",{"data-testid":"pathway-node-avatar-container",className:"w-10 h-10 rounded-full ring-2 ring-brand-500 flex items-center justify-center flex-shrink-0 overflow-hidden",children:s?u.jsx("img",{"data-testid":"pathway-node-avatar",src:s,alt:e,className:"w-full h-full object-cover"}):u.jsx("div",{"data-testid":"pathway-node-avatar",className:"w-full h-full bg-brand-100 flex items-center justify-center text-brand-600 font-bold",children:e.charAt(0).toUpperCase()})})}},h=()=>{const m=ix(t);return t==="current"?u.jsxs("div",{"data-testid":"pathway-node-card",role:"article","aria-label":`${e} - Current Progress`,className:"flex-1 bg-brand-50 rounded-lg p-4 border border-brand-100",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[u.jsx("span",{className:"text-xs font-semibold text-brand-600 tracking-wide",children:"CURRENT"}),u.jsx("span",{className:"text-xs text-brand-400",children:"/ 当前进度"})]}),u.jsxs("div",{className:"mb-3",children:[u.jsx("h3",{className:m,children:e}),n&&u.jsx("p",{className:"text-sm text-gray-500 mt-1",children:n})]}),u.jsxs("div",{"data-testid":"pathway-node-progress",className:"mb-3",children:[u.jsxs("div",{className:"flex items-center justify-between mb-1",children:[u.jsx("span",{className:"text-xs text-gray-500",children:"Progress"}),u.jsxs("span",{className:"text-xs font-semibold text-brand-600",children:[d,"%"]})]}),u.jsx("div",{className:"w-full h-2 bg-gray-200 rounded-full overflow-hidden",children:u.jsx("div",{className:"h-full bg-brand-500 rounded-full transition-all duration-300",style:{width:`${d}%`}})})]}),u.jsx("button",{type:"button",onClick:o,"aria-label":`Go to ${e}`,className:"w-full py-2 px-4 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2",children:"Go"})]}):u.jsxs("div",{className:"flex-1",children:[u.jsx("h3",{className:m,children:e}),n&&u.jsx("p",{className:"text-sm text-gray-500 mt-1",children:n})]})};return u.jsxs("div",{"data-testid":"pathway-node",className:`flex items-start gap-4 ${f} ${a}`,children:[g(),h(),l&&!c&&u.jsx("div",{"data-testid":"pathway-node-connector",className:"absolute left-5 top-14 w-0.5 h-8 bg-gray-200",style:{transform:"translateX(-50%)"}})]})};function Au({activeTab:t,lessons:e,title:n="Learning Pathways",onTabChange:r,onLessonAction:s,currentLessonId:o,isLoading:i=!1,emptyState:a,className:l=""}){const c=[{id:"curriculum",label:"Curriculum Track",icon:u.jsx(Z.BookOpen,{size:20})},{id:"skillTree",label:"Skill Tree",icon:u.jsx(Z.TreePine,{size:20})}],d=g=>{r?.(g)},f=g=>{s?.(g)};return i?u.jsx("div",{"data-testid":"learning-pathway-skeleton",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,children:u.jsxs("div",{className:"animate-pulse space-y-4",children:[u.jsx("div",{className:"h-6 bg-gray-200 rounded w-1/2"}),u.jsx("div",{className:"h-10 bg-gray-200 rounded-full"}),[1,2,3].map(g=>u.jsx("div",{"data-testid":"skeleton-item",className:"h-16 bg-gray-200 rounded-lg"},g))]})}):e.length===0?u.jsxs("div",{"data-testid":"learning-pathway",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,role:"region","aria-label":n,children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 mb-4",children:n}),a||u.jsx("div",{"data-testid":"empty-state",className:"text-center py-8 text-gray-500",children:"No lessons available"})]}):u.jsxs("div",{"data-testid":"learning-pathway",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,role:"region","aria-label":n,children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 mb-4 leading-loose",children:n}),u.jsx(Cu,{tabs:c,activeId:t,onChange:d,className:"mb-6","aria-label":"Learning pathway tabs"}),t==="curriculum"?u.jsx("div",{"data-testid":"curriculum-content",className:"flex flex-col gap-4 border-l-2 border-dashed border-gray-200 pl-4",role:"list","aria-label":"Curriculum lessons",children:e.map((g,h)=>{const p=o===g.id?"current":g.status;return u.jsx("div",{role:"listitem",children:u.jsx(Ru,{status:p,title:g.title,subtitle:g.subtitle,progress:g.progress,avatarSrc:g.avatarSrc,onAction:p==="current"?()=>f(g.id):void 0,isLast:h===e.length-1})},g.id)})}):u.jsxs("div",{"data-testid":"skill-tree-placeholder",className:"text-center py-12 text-gray-500",children:[u.jsx(Z.TreePine,{size:48,className:"mx-auto mb-4 opacity-50"}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Skill Tree"}),u.jsx("p",{children:"Visual skill progression map coming soon"})]})]})}const ax={weakness:{gradient:"from-blue-400 to-blue-700",buttonText:"text-blue-600",BadgeIcon:Z.Target,BackgroundIcon:Z.SquareRadical},challenge:{gradient:"from-orange-300 to-orange-600",buttonText:"text-orange-600",BadgeIcon:Z.Zap,BackgroundIcon:Z.Flame},explore:{gradient:"from-purple-500 to-indigo-600",buttonText:"text-purple-600",BadgeIcon:Z.Compass,BackgroundIcon:Z.Lightbulb}},Nu=({variant:t,badgeText:e,reasoning:n,title:r,contentNode:s,onAction:o,actionText:i="Try this >",className:a="",isDisabled:l=!1})=>{const c=ax[t],{BadgeIcon:d,BackgroundIcon:f}=c;return u.jsxs(H.Card,{"data-testid":"recommendation-card",className:`
57
+ h-56 w-full
58
+ bg-gradient-to-br ${c.gradient}
59
+ rounded-2xl
60
+ border-none
61
+ text-white
62
+ overflow-hidden
63
+ relative
64
+ transition-all duration-300 ease-out
65
+ hover:-translate-y-1 hover:shadow-xl
66
+ ${a}
67
+ `,children:[u.jsx("div",{"data-testid":"background-icon",className:"absolute top-4 right-4 opacity-10 pointer-events-none",children:u.jsx(f,{size:80,strokeWidth:1})}),u.jsxs(H.CardBody,{className:"p-5 flex flex-col justify-between h-full relative z-10",children:[u.jsxs("div",{"data-testid":"recommendation-badge",className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white/20 backdrop-blur-sm w-fit",children:[u.jsx(d,{size:14,className:"text-white"}),u.jsx("span",{className:"text-xs font-medium text-white",children:e})]}),u.jsxs("div",{className:"flex-1 flex flex-col justify-center gap-2",children:[u.jsx("p",{className:"text-xs text-white/80 leading-loose",children:n}),u.jsx("h3",{className:"text-lg font-bold text-white leading-loose",children:r}),s&&u.jsx("div",{className:"mt-2",children:s})]}),u.jsx("div",{className:"mt-auto",children:u.jsx(H.Button,{size:"sm",className:`
68
+ bg-white ${c.buttonText}
69
+ rounded-full
70
+ px-4 py-2
71
+ font-medium
72
+ text-sm
73
+ hover:opacity-90
74
+ transition-opacity
75
+ `,onPress:o,isDisabled:l,children:i})})]})]})};function Mr(t){return t+.5|0}const Gt=(t,e,n)=>Math.max(Math.min(t,n),e);function ar(t){return Gt(Mr(t*2.55),0,255)}function Ht(t){return Gt(Mr(t*255),0,255)}function $t(t){return Gt(Mr(t/2.55)/100,0,1)}function Qa(t){return Gt(Mr(t*100),0,100)}const ot={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},oi=[..."0123456789ABCDEF"],lx=t=>oi[t&15],cx=t=>oi[(t&240)>>4]+oi[t&15],Yr=t=>(t&240)>>4===(t&15),dx=t=>Yr(t.r)&&Yr(t.g)&&Yr(t.b)&&Yr(t.a);function ux(t){var e=t.length,n;return t[0]==="#"&&(e===4||e===5?n={r:255&ot[t[1]]*17,g:255&ot[t[2]]*17,b:255&ot[t[3]]*17,a:e===5?ot[t[4]]*17:255}:(e===7||e===9)&&(n={r:ot[t[1]]<<4|ot[t[2]],g:ot[t[3]]<<4|ot[t[4]],b:ot[t[5]]<<4|ot[t[6]],a:e===9?ot[t[7]]<<4|ot[t[8]]:255})),n}const fx=(t,e)=>t<255?e(t):"";function hx(t){var e=dx(t)?lx:cx;return t?"#"+e(t.r)+e(t.g)+e(t.b)+fx(t.a,e):void 0}const gx=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Eu(t,e,n){const r=e*Math.min(n,1-n),s=(o,i=(o+t/30)%12)=>n-r*Math.max(Math.min(i-3,9-i,1),-1);return[s(0),s(8),s(4)]}function mx(t,e,n){const r=(s,o=(s+t/60)%6)=>n-n*e*Math.max(Math.min(o,4-o,1),0);return[r(5),r(3),r(1)]}function px(t,e,n){const r=Eu(t,1,.5);let s;for(e+n>1&&(s=1/(e+n),e*=s,n*=s),s=0;s<3;s++)r[s]*=1-e-n,r[s]+=e;return r}function yx(t,e,n,r,s){return t===s?(e-n)/r+(e<n?6:0):e===s?(n-t)/r+2:(t-e)/r+4}function Ui(t){const n=t.r/255,r=t.g/255,s=t.b/255,o=Math.max(n,r,s),i=Math.min(n,r,s),a=(o+i)/2;let l,c,d;return o!==i&&(d=o-i,c=a>.5?d/(2-o-i):d/(o+i),l=yx(n,r,s,d,o),l=l*60+.5),[l|0,c||0,a]}function Bi(t,e,n,r){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,n,r)).map(Ht)}function Hi(t,e,n){return Bi(Eu,t,e,n)}function bx(t,e,n){return Bi(px,t,e,n)}function xx(t,e,n){return Bi(mx,t,e,n)}function ku(t){return(t%360+360)%360}function vx(t){const e=gx.exec(t);let n=255,r;if(!e)return;e[5]!==r&&(n=e[6]?ar(+e[5]):Ht(+e[5]));const s=ku(+e[2]),o=+e[3]/100,i=+e[4]/100;return e[1]==="hwb"?r=bx(s,o,i):e[1]==="hsv"?r=xx(s,o,i):r=Hi(s,o,i),{r:r[0],g:r[1],b:r[2],a:n}}function wx(t,e){var n=Ui(t);n[0]=ku(n[0]+e),n=Hi(n),t.r=n[0],t.g=n[1],t.b=n[2]}function _x(t){if(!t)return;const e=Ui(t),n=e[0],r=Qa(e[1]),s=Qa(e[2]);return t.a<255?`hsla(${n}, ${r}%, ${s}%, ${$t(t.a)})`:`hsl(${n}, ${r}%, ${s}%)`}const el={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},tl={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};function Sx(){const t={},e=Object.keys(tl),n=Object.keys(el);let r,s,o,i,a;for(r=0;r<e.length;r++){for(i=a=e[r],s=0;s<n.length;s++)o=n[s],a=a.replace(o,el[o]);o=parseInt(tl[i],16),t[a]=[o>>16&255,o>>8&255,o&255]}return t}let Kr;function Cx(t){Kr||(Kr=Sx(),Kr.transparent=[0,0,0,0]);const e=Kr[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:e.length===4?e[3]:255}}const Rx=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;function Ax(t){const e=Rx.exec(t);let n=255,r,s,o;if(e){if(e[7]!==r){const i=+e[7];n=e[8]?ar(i):Gt(i*255,0,255)}return r=+e[1],s=+e[3],o=+e[5],r=255&(e[2]?ar(r):Gt(r,0,255)),s=255&(e[4]?ar(s):Gt(s,0,255)),o=255&(e[6]?ar(o):Gt(o,0,255)),{r,g:s,b:o,a:n}}}function Nx(t){return t&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${$t(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`)}const Ro=t=>t<=.0031308?t*12.92:Math.pow(t,1/2.4)*1.055-.055,Cn=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Ex(t,e,n){const r=Cn($t(t.r)),s=Cn($t(t.g)),o=Cn($t(t.b));return{r:Ht(Ro(r+n*(Cn($t(e.r))-r))),g:Ht(Ro(s+n*(Cn($t(e.g))-s))),b:Ht(Ro(o+n*(Cn($t(e.b))-o))),a:t.a+n*(e.a-t.a)}}function Xr(t,e,n){if(t){let r=Ui(t);r[e]=Math.max(0,Math.min(r[e]+r[e]*n,e===0?360:1)),r=Hi(r),t.r=r[0],t.g=r[1],t.b=r[2]}}function Tu(t,e){return t&&Object.assign(e||{},t)}function nl(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Ht(t[3]))):(e=Tu(t,{r:0,g:0,b:0,a:1}),e.a=Ht(e.a)),e}function kx(t){return t.charAt(0)==="r"?Ax(t):vx(t)}class pr{constructor(e){if(e instanceof pr)return e;const n=typeof e;let r;n==="object"?r=nl(e):n==="string"&&(r=ux(e)||Cx(e)||kx(e)),this._rgb=r,this._valid=!!r}get valid(){return this._valid}get rgb(){var e=Tu(this._rgb);return e&&(e.a=$t(e.a)),e}set rgb(e){this._rgb=nl(e)}rgbString(){return this._valid?Nx(this._rgb):void 0}hexString(){return this._valid?hx(this._rgb):void 0}hslString(){return this._valid?_x(this._rgb):void 0}mix(e,n){if(e){const r=this.rgb,s=e.rgb;let o;const i=n===o?.5:n,a=2*i-1,l=r.a-s.a,c=((a*l===-1?a:(a+l)/(1+a*l))+1)/2;o=1-c,r.r=255&c*r.r+o*s.r+.5,r.g=255&c*r.g+o*s.g+.5,r.b=255&c*r.b+o*s.b+.5,r.a=i*r.a+(1-i)*s.a,this.rgb=r}return this}interpolate(e,n){return e&&(this._rgb=Ex(this._rgb,e._rgb,n)),this}clone(){return new pr(this.rgb)}alpha(e){return this._rgb.a=Ht(e),this}clearer(e){const n=this._rgb;return n.a*=1-e,this}greyscale(){const e=this._rgb,n=Mr(e.r*.3+e.g*.59+e.b*.11);return e.r=e.g=e.b=n,this}opaquer(e){const n=this._rgb;return n.a*=1+e,this}negate(){const e=this._rgb;return e.r=255-e.r,e.g=255-e.g,e.b=255-e.b,this}lighten(e){return Xr(this._rgb,2,e),this}darken(e){return Xr(this._rgb,2,-e),this}saturate(e){return Xr(this._rgb,1,e),this}desaturate(e){return Xr(this._rgb,1,-e),this}rotate(e){return wx(this._rgb,e),this}}function Et(){}const Tx=(()=>{let t=0;return()=>t++})();function xe(t){return t==null}function Oe(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return e.slice(0,7)==="[object"&&e.slice(-6)==="Array]"}function ie(t){return t!==null&&Object.prototype.toString.call(t)==="[object Object]"}function Ue(t){return(typeof t=="number"||t instanceof Number)&&isFinite(+t)}function ht(t,e){return Ue(t)?t:e}function pe(t,e){return typeof t>"u"?e:t}const Mx=(t,e)=>typeof t=="string"&&t.endsWith("%")?parseFloat(t)/100*e:+t;function Ne(t,e,n){if(t&&typeof t.call=="function")return t.apply(n,e)}function ge(t,e,n,r){let s,o,i;if(Oe(t))for(o=t.length,s=0;s<o;s++)e.call(n,t[s],s);else if(ie(t))for(i=Object.keys(t),o=i.length,s=0;s<o;s++)e.call(n,t[i[s]],i[s])}function ks(t,e){let n,r,s,o;if(!t||!e||t.length!==e.length)return!1;for(n=0,r=t.length;n<r;++n)if(s=t[n],o=e[n],s.datasetIndex!==o.datasetIndex||s.index!==o.index)return!1;return!0}function Ts(t){if(Oe(t))return t.map(Ts);if(ie(t)){const e=Object.create(null),n=Object.keys(t),r=n.length;let s=0;for(;s<r;++s)e[n[s]]=Ts(t[n[s]]);return e}return t}function Mu(t){return["__proto__","prototype","constructor"].indexOf(t)===-1}function jx(t,e,n,r){if(!Mu(t))return;const s=e[t],o=n[t];ie(s)&&ie(o)?yr(s,o,r):e[t]=Ts(o)}function yr(t,e,n){const r=Oe(e)?e:[e],s=r.length;if(!ie(t))return t;n=n||{};const o=n.merger||jx;let i;for(let a=0;a<s;++a){if(i=r[a],!ie(i))continue;const l=Object.keys(i);for(let c=0,d=l.length;c<d;++c)o(l[c],t,i,n)}return t}function ur(t,e){return yr(t,e,{merger:$x})}function $x(t,e,n){if(!Mu(t))return;const r=e[t],s=n[t];ie(r)&&ie(s)?ur(r,s):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=Ts(s))}const rl={"":t=>t,x:t=>t.x,y:t=>t.y};function Ox(t){const e=t.split("."),n=[];let r="";for(const s of e)r+=s,r.endsWith("\\")?r=r.slice(0,-1)+".":(n.push(r),r="");return n}function Ix(t){const e=Ox(t);return n=>{for(const r of e){if(r==="")break;n=n&&n[r]}return n}}function Ms(t,e){return(rl[e]||(rl[e]=Ix(e)))(t)}function Wi(t){return t.charAt(0).toUpperCase()+t.slice(1)}const js=t=>typeof t<"u",qt=t=>typeof t=="function",sl=(t,e)=>{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0};function Px(t){return t.type==="mouseup"||t.type==="click"||t.type==="contextmenu"}const Ge=Math.PI,St=2*Ge,Fx=St+Ge,$s=Number.POSITIVE_INFINITY,Dx=Ge/180,lt=Ge/2,en=Ge/4,ol=Ge*2/3,ju=Math.log10,On=Math.sign;function fr(t,e,n){return Math.abs(t-e)<n}function il(t){const e=Math.round(t);t=fr(t,e,t/1e3)?e:t;const n=Math.pow(10,Math.floor(ju(t))),r=t/n;return(r<=1?1:r<=2?2:r<=5?5:10)*n}function Lx(t){const e=[],n=Math.sqrt(t);let r;for(r=1;r<n;r++)t%r===0&&(e.push(r),e.push(t/r));return n===(n|0)&&e.push(n),e.sort((s,o)=>s-o).pop(),e}function zx(t){return typeof t=="symbol"||typeof t=="object"&&t!==null&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}function br(t){return!zx(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function Vx(t,e){const n=Math.round(t);return n-e<=t&&n+e>=t}function Gx(t,e,n){let r,s,o;for(r=0,s=t.length;r<s;r++)o=t[r][n],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function un(t){return t*(Ge/180)}function Ux(t){return t*(180/Ge)}function al(t){if(!Ue(t))return;let e=1,n=0;for(;Math.round(t*e)/e!==t;)e*=10,n++;return n}function Bx(t,e){const n=e.x-t.x,r=e.y-t.y,s=Math.sqrt(n*n+r*r);let o=Math.atan2(r,n);return o<-.5*Ge&&(o+=St),{angle:o,distance:s}}function ii(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Hx(t,e){return(t-e+Fx)%St-Ge}function pt(t){return(t%St+St)%St}function $u(t,e,n,r){const s=pt(t),o=pt(e),i=pt(n),a=pt(o-s),l=pt(i-s),c=pt(s-o),d=pt(s-i);return s===o||s===i||r&&o===i||a>l&&c<d}function it(t,e,n){return Math.max(e,Math.min(n,t))}function Wx(t){return it(t,-32768,32767)}function Ou(t,e,n,r=1e-6){return t>=Math.min(e,n)-r&&t<=Math.max(e,n)+r}function qi(t,e,n){n=n||(i=>t[i]<e);let r=t.length-1,s=0,o;for(;r-s>1;)o=s+r>>1,n(o)?s=o:r=o;return{lo:s,hi:r}}const fn=(t,e,n,r)=>qi(t,n,r?s=>{const o=t[s][e];return o<n||o===n&&t[s+1][e]===n}:s=>t[s][e]<n),qx=(t,e,n)=>qi(t,n,r=>t[r][e]>=n);function Yx(t,e,n){let r=0,s=t.length;for(;r<s&&t[r]<e;)r++;for(;s>r&&t[s-1]>n;)s--;return r>0||s<t.length?t.slice(r,s):t}const Iu=["push","pop","shift","splice","unshift"];function Kx(t,e){if(t._chartjs){t._chartjs.listeners.push(e);return}Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),Iu.forEach(n=>{const r="_onData"+Wi(n),s=t[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!1,value(...o){const i=s.apply(this,o);return t._chartjs.listeners.forEach(a=>{typeof a[r]=="function"&&a[r](...o)}),i}})})}function ll(t,e){const n=t._chartjs;if(!n)return;const r=n.listeners,s=r.indexOf(e);s!==-1&&r.splice(s,1),!(r.length>0)&&(Iu.forEach(o=>{delete t[o]}),delete t._chartjs)}function Xx(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const Pu=(function(){return typeof window>"u"?function(t){return t()}:window.requestAnimationFrame})();function Fu(t,e){let n=[],r=!1;return function(...s){n=s,r||(r=!0,Pu.call(window,()=>{r=!1,t.apply(e,n)}))}}function Jx(t,e){let n;return function(...r){return e?(clearTimeout(n),n=setTimeout(t,e,r)):t.apply(this,r),e}}const Zx=t=>t==="start"?"left":t==="end"?"right":"center",cl=(t,e,n)=>t==="start"?e:t==="end"?n:(e+n)/2;function Qx(t,e,n){const r=e.length;let s=0,o=r;if(t._sorted){const{iScale:i,vScale:a,_parsed:l}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=i.axis,{min:f,max:g,minDefined:h,maxDefined:m}=i.getUserBounds();if(h){if(s=Math.min(fn(l,d,f).lo,n?r:fn(e,d,i.getPixelForValue(f)).lo),c){const p=l.slice(0,s+1).reverse().findIndex(y=>!xe(y[a.axis]));s-=Math.max(0,p)}s=it(s,0,r-1)}if(m){let p=Math.max(fn(l,i.axis,g,!0).hi+1,n?0:fn(e,d,i.getPixelForValue(g),!0).hi+1);if(c){const y=l.slice(p-1).findIndex(b=>!xe(b[a.axis]));p+=Math.max(0,y)}o=it(p,s,r)-s}else o=r-s}return{start:s,count:o}}function e0(t){const{xScale:e,yScale:n,_scaleRanges:r}=t,s={xmin:e.min,xmax:e.max,ymin:n.min,ymax:n.max};if(!r)return t._scaleRanges=s,!0;const o=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==n.min||r.ymax!==n.max;return Object.assign(r,s),o}const Jr=t=>t===0||t===1,dl=(t,e,n)=>-(Math.pow(2,10*(t-=1))*Math.sin((t-e)*St/n)),ul=(t,e,n)=>Math.pow(2,-10*t)*Math.sin((t-e)*St/n)+1,hr={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>-Math.cos(t*lt)+1,easeOutSine:t=>Math.sin(t*lt),easeInOutSine:t=>-.5*(Math.cos(Ge*t)-1),easeInExpo:t=>t===0?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>t===1?1:-Math.pow(2,-10*t)+1,easeInOutExpo:t=>Jr(t)?t:t<.5?.5*Math.pow(2,10*(t*2-1)):.5*(-Math.pow(2,-10*(t*2-1))+2),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>Jr(t)?t:dl(t,.075,.3),easeOutElastic:t=>Jr(t)?t:ul(t,.075,.3),easeInOutElastic(t){return Jr(t)?t:t<.5?.5*dl(t*2,.1125,.45):.5+.5*ul(t*2-1,.1125,.45)},easeInBack(t){return t*t*((1.70158+1)*t-1.70158)},easeOutBack(t){return(t-=1)*t*((1.70158+1)*t+1.70158)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?.5*(t*t*(((e*=1.525)+1)*t-e)):.5*((t-=2)*t*(((e*=1.525)+1)*t+e)+2)},easeInBounce:t=>1-hr.easeOutBounce(1-t),easeOutBounce(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:t=>t<.5?hr.easeInBounce(t*2)*.5:hr.easeOutBounce(t*2-1)*.5+.5};function Yi(t){if(t&&typeof t=="object"){const e=t.toString();return e==="[object CanvasPattern]"||e==="[object CanvasGradient]"}return!1}function fl(t){return Yi(t)?t:new pr(t)}function Ao(t){return Yi(t)?t:new pr(t).saturate(.5).darken(.1).hexString()}const t0=["x","y","borderWidth","radius","tension"],n0=["color","borderColor","backgroundColor"];function r0(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:e=>e!=="onProgress"&&e!=="onComplete"&&e!=="fn"}),t.set("animations",{colors:{type:"color",properties:n0},numbers:{type:"number",properties:t0}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:e=>e|0}}}})}function s0(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}const hl=new Map;function o0(t,e){e=e||{};const n=t+JSON.stringify(e);let r=hl.get(n);return r||(r=new Intl.NumberFormat(t,e),hl.set(n,r)),r}function Du(t,e,n){return o0(e,n).format(t)}const i0={values(t){return Oe(t)?t:""+t},numeric(t,e,n){if(t===0)return"0";const r=this.chart.options.locale;let s,o=t;if(n.length>1){const c=Math.max(Math.abs(n[0].value),Math.abs(n[n.length-1].value));(c<1e-4||c>1e15)&&(s="scientific"),o=a0(t,n)}const i=ju(Math.abs(o)),a=isNaN(i)?1:Math.max(Math.min(-1*Math.floor(i),20),0),l={notation:s,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(l,this.options.ticks.format),Du(t,r,l)}};function a0(t,e){let n=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(n)>=1&&t!==Math.floor(t)&&(n=t-Math.floor(t)),n}var Lu={formatters:i0};function l0(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(e,n)=>n.lineWidth,tickColor:(e,n)=>n.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:Lu.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:e=>!e.startsWith("before")&&!e.startsWith("after")&&e!=="callback"&&e!=="parser",_indexable:e=>e!=="borderDash"&&e!=="tickBorderDash"&&e!=="dash"}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:e=>e!=="backdropPadding"&&e!=="callback",_indexable:e=>e!=="backdropPadding"})}const pn=Object.create(null),ai=Object.create(null);function gr(t,e){if(!e)return t;const n=e.split(".");for(let r=0,s=n.length;r<s;++r){const o=n[r];t=t[o]||(t[o]=Object.create(null))}return t}function No(t,e,n){return typeof e=="string"?yr(gr(t,e),n):yr(gr(t,""),e)}class c0{constructor(e,n){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=r=>r.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(r,s)=>Ao(s.backgroundColor),this.hoverBorderColor=(r,s)=>Ao(s.borderColor),this.hoverColor=(r,s)=>Ao(s.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(e),this.apply(n)}set(e,n){return No(this,e,n)}get(e){return gr(this,e)}describe(e,n){return No(ai,e,n)}override(e,n){return No(pn,e,n)}route(e,n,r,s){const o=gr(this,e),i=gr(this,r),a="_"+n;Object.defineProperties(o,{[a]:{value:o[n],writable:!0},[n]:{enumerable:!0,get(){const l=this[a],c=i[s];return ie(l)?Object.assign({},c,l):pe(l,c)},set(l){this[a]=l}}})}apply(e){e.forEach(n=>n(this))}}var Te=new c0({_scriptable:t=>!t.startsWith("on"),_indexable:t=>t!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[r0,s0,l0]);function d0(t){return!t||xe(t.size)||xe(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function gl(t,e,n,r,s){let o=e[s];return o||(o=e[s]=t.measureText(s).width,n.push(s)),o>r&&(r=o),r}function tn(t,e,n){const r=t.currentDevicePixelRatio,s=n!==0?Math.max(n/2,.5):0;return Math.round((e-s)*r)/r+s}function ml(t,e){!e&&!t||(e=e||t.getContext("2d"),e.save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function li(t,e,n,r){u0(t,e,n,r)}function u0(t,e,n,r,s){let o,i,a,l,c,d,f,g;const h=e.pointStyle,m=e.rotation,p=e.radius;let y=(m||0)*Dx;if(h&&typeof h=="object"&&(o=h.toString(),o==="[object HTMLImageElement]"||o==="[object HTMLCanvasElement]")){t.save(),t.translate(n,r),t.rotate(y),t.drawImage(h,-h.width/2,-h.height/2,h.width,h.height),t.restore();return}if(!(isNaN(p)||p<=0)){switch(t.beginPath(),h){default:t.arc(n,r,p,0,St),t.closePath();break;case"triangle":d=p,t.moveTo(n+Math.sin(y)*d,r-Math.cos(y)*p),y+=ol,t.lineTo(n+Math.sin(y)*d,r-Math.cos(y)*p),y+=ol,t.lineTo(n+Math.sin(y)*d,r-Math.cos(y)*p),t.closePath();break;case"rectRounded":c=p*.516,l=p-c,i=Math.cos(y+en)*l,f=Math.cos(y+en)*l,a=Math.sin(y+en)*l,g=Math.sin(y+en)*l,t.arc(n-f,r-a,c,y-Ge,y-lt),t.arc(n+g,r-i,c,y-lt,y),t.arc(n+f,r+a,c,y,y+lt),t.arc(n-g,r+i,c,y+lt,y+Ge),t.closePath();break;case"rect":if(!m){l=Math.SQRT1_2*p,d=l,t.rect(n-d,r-l,2*d,2*l);break}y+=en;case"rectRot":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+g,r-i),t.lineTo(n+f,r+a),t.lineTo(n-g,r+i),t.closePath();break;case"crossRot":y+=en;case"cross":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i);break;case"star":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i),y+=en,f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i);break;case"line":i=Math.cos(y)*p,a=Math.sin(y)*p,t.moveTo(n-i,r-a),t.lineTo(n+i,r+a);break;case"dash":t.moveTo(n,r),t.lineTo(n+Math.cos(y)*p,r+Math.sin(y)*p);break;case!1:t.closePath();break}t.fill(),e.borderWidth>0&&t.stroke()}}function xr(t,e,n){return n=n||.5,!e||t&&t.x>e.left-n&&t.x<e.right+n&&t.y>e.top-n&&t.y<e.bottom+n}function Ki(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function Xi(t){t.restore()}function f0(t,e,n,r,s){if(!e)return t.lineTo(n.x,n.y);if(s==="middle"){const o=(e.x+n.x)/2;t.lineTo(o,e.y),t.lineTo(o,n.y)}else s==="after"!=!!r?t.lineTo(e.x,n.y):t.lineTo(n.x,e.y);t.lineTo(n.x,n.y)}function h0(t,e,n,r){if(!e)return t.lineTo(n.x,n.y);t.bezierCurveTo(r?e.cp1x:e.cp2x,r?e.cp1y:e.cp2y,r?n.cp2x:n.cp1x,r?n.cp2y:n.cp1y,n.x,n.y)}function g0(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),xe(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}function m0(t,e,n,r,s){if(s.strikethrough||s.underline){const o=t.measureText(r),i=e-o.actualBoundingBoxLeft,a=e+o.actualBoundingBoxRight,l=n-o.actualBoundingBoxAscent,c=n+o.actualBoundingBoxDescent,d=s.strikethrough?(l+c)/2:c;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=s.decorationWidth||2,t.moveTo(i,d),t.lineTo(a,d),t.stroke()}}function p0(t,e){const n=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=n}function pl(t,e,n,r,s,o={}){const i=Oe(e)?e:[e],a=o.strokeWidth>0&&o.strokeColor!=="";let l,c;for(t.save(),t.font=s.string,g0(t,o),l=0;l<i.length;++l)c=i[l],o.backdrop&&p0(t,o.backdrop),a&&(o.strokeColor&&(t.strokeStyle=o.strokeColor),xe(o.strokeWidth)||(t.lineWidth=o.strokeWidth),t.strokeText(c,n,r,o.maxWidth)),t.fillText(c,n,r,o.maxWidth),m0(t,n,r,c,o),r+=Number(s.lineHeight);t.restore()}function yl(t,e){const{x:n,y:r,w:s,h:o,radius:i}=e;t.arc(n+i.topLeft,r+i.topLeft,i.topLeft,1.5*Ge,Ge,!0),t.lineTo(n,r+o-i.bottomLeft),t.arc(n+i.bottomLeft,r+o-i.bottomLeft,i.bottomLeft,Ge,lt,!0),t.lineTo(n+s-i.bottomRight,r+o),t.arc(n+s-i.bottomRight,r+o-i.bottomRight,i.bottomRight,lt,0,!0),t.lineTo(n+s,r+i.topRight),t.arc(n+s-i.topRight,r+i.topRight,i.topRight,0,-lt,!0),t.lineTo(n+i.topLeft,r)}const y0=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,b0=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function x0(t,e){const n=(""+t).match(y0);if(!n||n[1]==="normal")return e*1.2;switch(t=+n[2],n[3]){case"px":return t;case"%":t/=100;break}return e*t}const v0=t=>+t||0;function zu(t,e){const n={},r=ie(e),s=r?Object.keys(e):e,o=ie(t)?r?i=>pe(t[i],t[e[i]]):i=>t[i]:()=>t;for(const i of s)n[i]=v0(o(i));return n}function w0(t){return zu(t,{top:"y",right:"x",bottom:"y",left:"x"})}function ps(t){return zu(t,["topLeft","topRight","bottomLeft","bottomRight"])}function Yt(t){const e=w0(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function _t(t,e){t=t||{},e=e||Te.font;let n=pe(t.size,e.size);typeof n=="string"&&(n=parseInt(n,10));let r=pe(t.style,e.style);r&&!(""+r).match(b0)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const s={family:pe(t.family,e.family),lineHeight:x0(pe(t.lineHeight,e.lineHeight),n),size:n,style:r,weight:pe(t.weight,e.weight),string:""};return s.string=d0(s),s}function Zr(t,e,n,r){let s,o,i;for(s=0,o=t.length;s<o;++s)if(i=t[s],i!==void 0&&i!==void 0)return i}function _0(t,e,n){const{min:r,max:s}=t,o=Mx(e,(s-r)/2),i=(a,l)=>n&&a===0?0:a+l;return{min:i(r,-Math.abs(o)),max:i(s,o)}}function xn(t,e){return Object.assign(Object.create(t),e)}function Ji(t,e=[""],n,r,s=()=>t[0]){const o=n||t;typeof r>"u"&&(r=Bu("_fallback",t));const i={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:r,_getTarget:s,override:a=>Ji([a,...t],e,o,r)};return new Proxy(i,{deleteProperty(a,l){return delete a[l],delete a._keys,delete t[0][l],!0},get(a,l){return Gu(a,l,()=>T0(l,e,t,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(t[0])},has(a,l){return xl(a).includes(l)},ownKeys(a){return xl(a)},set(a,l,c){const d=a._storage||(a._storage=s());return a[l]=d[l]=c,delete a._keys,!0}})}function In(t,e,n,r){const s={_cacheable:!1,_proxy:t,_context:e,_subProxy:n,_stack:new Set,_descriptors:Vu(t,r),setContext:o=>In(t,o,n,r),override:o=>In(t.override(o),e,n,r)};return new Proxy(s,{deleteProperty(o,i){return delete o[i],delete t[i],!0},get(o,i,a){return Gu(o,i,()=>C0(o,i,a))},getOwnPropertyDescriptor(o,i){return o._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i)},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(o,i){return Reflect.has(t,i)},ownKeys(){return Reflect.ownKeys(t)},set(o,i,a){return t[i]=a,delete o[i],!0}})}function Vu(t,e={scriptable:!0,indexable:!0}){const{_scriptable:n=e.scriptable,_indexable:r=e.indexable,_allKeys:s=e.allKeys}=t;return{allKeys:s,scriptable:n,indexable:r,isScriptable:qt(n)?n:()=>n,isIndexable:qt(r)?r:()=>r}}const S0=(t,e)=>t?t+Wi(e):e,Zi=(t,e)=>ie(e)&&t!=="adapters"&&(Object.getPrototypeOf(e)===null||e.constructor===Object);function Gu(t,e,n){if(Object.prototype.hasOwnProperty.call(t,e)||e==="constructor")return t[e];const r=n();return t[e]=r,r}function C0(t,e,n){const{_proxy:r,_context:s,_subProxy:o,_descriptors:i}=t;let a=r[e];return qt(a)&&i.isScriptable(e)&&(a=R0(e,a,t,n)),Oe(a)&&a.length&&(a=A0(e,a,t,i.isIndexable)),Zi(e,a)&&(a=In(a,s,o&&o[e],i)),a}function R0(t,e,n,r){const{_proxy:s,_context:o,_subProxy:i,_stack:a}=n;if(a.has(t))throw new Error("Recursion detected: "+Array.from(a).join("->")+"->"+t);a.add(t);let l=e(o,i||r);return a.delete(t),Zi(t,l)&&(l=Qi(s._scopes,s,t,l)),l}function A0(t,e,n,r){const{_proxy:s,_context:o,_subProxy:i,_descriptors:a}=n;if(typeof o.index<"u"&&r(t))return e[o.index%e.length];if(ie(e[0])){const l=e,c=s._scopes.filter(d=>d!==l);e=[];for(const d of l){const f=Qi(c,s,t,d);e.push(In(f,o,i&&i[t],a))}}return e}function Uu(t,e,n){return qt(t)?t(e,n):t}const N0=(t,e)=>t===!0?e:typeof t=="string"?Ms(e,t):void 0;function E0(t,e,n,r,s){for(const o of e){const i=N0(n,o);if(i){t.add(i);const a=Uu(i._fallback,n,s);if(typeof a<"u"&&a!==n&&a!==r)return a}else if(i===!1&&typeof r<"u"&&n!==r)return null}return!1}function Qi(t,e,n,r){const s=e._rootScopes,o=Uu(e._fallback,n,r),i=[...t,...s],a=new Set;a.add(r);let l=bl(a,i,n,o||n,r);return l===null||typeof o<"u"&&o!==n&&(l=bl(a,i,o,l,r),l===null)?!1:Ji(Array.from(a),[""],s,o,()=>k0(e,n,r))}function bl(t,e,n,r,s){for(;n;)n=E0(t,e,n,r,s);return n}function k0(t,e,n){const r=t._getTarget();e in r||(r[e]={});const s=r[e];return Oe(s)&&ie(n)?n:s||{}}function T0(t,e,n,r){let s;for(const o of e)if(s=Bu(S0(o,t),n),typeof s<"u")return Zi(t,s)?Qi(n,r,t,s):s}function Bu(t,e){for(const n of e){if(!n)continue;const r=n[t];if(typeof r<"u")return r}}function xl(t){let e=t._keys;return e||(e=t._keys=M0(t._scopes)),e}function M0(t){const e=new Set;for(const n of t)for(const r of Object.keys(n).filter(s=>!s.startsWith("_")))e.add(r);return Array.from(e)}const j0=Number.EPSILON||1e-14,Pn=(t,e)=>e<t.length&&!t[e].skip&&t[e],Hu=t=>t==="x"?"y":"x";function $0(t,e,n,r){const s=t.skip?e:t,o=e,i=n.skip?e:n,a=ii(o,s),l=ii(i,o);let c=a/(a+l),d=l/(a+l);c=isNaN(c)?0:c,d=isNaN(d)?0:d;const f=r*c,g=r*d;return{previous:{x:o.x-f*(i.x-s.x),y:o.y-f*(i.y-s.y)},next:{x:o.x+g*(i.x-s.x),y:o.y+g*(i.y-s.y)}}}function O0(t,e,n){const r=t.length;let s,o,i,a,l,c=Pn(t,0);for(let d=0;d<r-1;++d)if(l=c,c=Pn(t,d+1),!(!l||!c)){if(fr(e[d],0,j0)){n[d]=n[d+1]=0;continue}s=n[d]/e[d],o=n[d+1]/e[d],a=Math.pow(s,2)+Math.pow(o,2),!(a<=9)&&(i=3/Math.sqrt(a),n[d]=s*i*e[d],n[d+1]=o*i*e[d])}}function I0(t,e,n="x"){const r=Hu(n),s=t.length;let o,i,a,l=Pn(t,0);for(let c=0;c<s;++c){if(i=a,a=l,l=Pn(t,c+1),!a)continue;const d=a[n],f=a[r];i&&(o=(d-i[n])/3,a[`cp1${n}`]=d-o,a[`cp1${r}`]=f-o*e[c]),l&&(o=(l[n]-d)/3,a[`cp2${n}`]=d+o,a[`cp2${r}`]=f+o*e[c])}}function P0(t,e="x"){const n=Hu(e),r=t.length,s=Array(r).fill(0),o=Array(r);let i,a,l,c=Pn(t,0);for(i=0;i<r;++i)if(a=l,l=c,c=Pn(t,i+1),!!l){if(c){const d=c[e]-l[e];s[i]=d!==0?(c[n]-l[n])/d:0}o[i]=a?c?On(s[i-1])!==On(s[i])?0:(s[i-1]+s[i])/2:s[i-1]:s[i]}O0(t,s,o),I0(t,o,e)}function Qr(t,e,n){return Math.max(Math.min(t,n),e)}function F0(t,e){let n,r,s,o,i,a=xr(t[0],e);for(n=0,r=t.length;n<r;++n)i=o,o=a,a=n<r-1&&xr(t[n+1],e),o&&(s=t[n],i&&(s.cp1x=Qr(s.cp1x,e.left,e.right),s.cp1y=Qr(s.cp1y,e.top,e.bottom)),a&&(s.cp2x=Qr(s.cp2x,e.left,e.right),s.cp2y=Qr(s.cp2y,e.top,e.bottom)))}function D0(t,e,n,r,s){let o,i,a,l;if(e.spanGaps&&(t=t.filter(c=>!c.skip)),e.cubicInterpolationMode==="monotone")P0(t,s);else{let c=r?t[t.length-1]:t[0];for(o=0,i=t.length;o<i;++o)a=t[o],l=$0(c,a,t[Math.min(o+1,i-(r?0:1))%i],e.tension),a.cp1x=l.previous.x,a.cp1y=l.previous.y,a.cp2x=l.next.x,a.cp2y=l.next.y,c=a}e.capBezierPoints&&F0(t,n)}function ea(){return typeof window<"u"&&typeof document<"u"}function ta(t){let e=t.parentNode;return e&&e.toString()==="[object ShadowRoot]"&&(e=e.host),e}function Os(t,e,n){let r;return typeof t=="string"?(r=parseInt(t,10),t.indexOf("%")!==-1&&(r=r/100*e.parentNode[n])):r=t,r}const qs=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function L0(t,e){return qs(t).getPropertyValue(e)}const z0=["top","right","bottom","left"];function gn(t,e,n){const r={};n=n?"-"+n:"";for(let s=0;s<4;s++){const o=z0[s];r[o]=parseFloat(t[e+"-"+o+n])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}const V0=(t,e,n)=>(t>0||e>0)&&(!n||!n.shadowRoot);function G0(t,e){const n=t.touches,r=n&&n.length?n[0]:t,{offsetX:s,offsetY:o}=r;let i=!1,a,l;if(V0(s,o,t.target))a=s,l=o;else{const c=e.getBoundingClientRect();a=r.clientX-c.left,l=r.clientY-c.top,i=!0}return{x:a,y:l,box:i}}function sn(t,e){if("native"in t)return t;const{canvas:n,currentDevicePixelRatio:r}=e,s=qs(n),o=s.boxSizing==="border-box",i=gn(s,"padding"),a=gn(s,"border","width"),{x:l,y:c,box:d}=G0(t,n),f=i.left+(d&&a.left),g=i.top+(d&&a.top);let{width:h,height:m}=e;return o&&(h-=i.width+a.width,m-=i.height+a.height),{x:Math.round((l-f)/h*n.width/r),y:Math.round((c-g)/m*n.height/r)}}function U0(t,e,n){let r,s;if(e===void 0||n===void 0){const o=t&&ta(t);if(!o)e=t.clientWidth,n=t.clientHeight;else{const i=o.getBoundingClientRect(),a=qs(o),l=gn(a,"border","width"),c=gn(a,"padding");e=i.width-c.width-l.width,n=i.height-c.height-l.height,r=Os(a.maxWidth,o,"clientWidth"),s=Os(a.maxHeight,o,"clientHeight")}}return{width:e,height:n,maxWidth:r||$s,maxHeight:s||$s}}const Ut=t=>Math.round(t*10)/10;function B0(t,e,n,r){const s=qs(t),o=gn(s,"margin"),i=Os(s.maxWidth,t,"clientWidth")||$s,a=Os(s.maxHeight,t,"clientHeight")||$s,l=U0(t,e,n);let{width:c,height:d}=l;if(s.boxSizing==="content-box"){const g=gn(s,"border","width"),h=gn(s,"padding");c-=h.width+g.width,d-=h.height+g.height}return c=Math.max(0,c-o.width),d=Math.max(0,r?c/r:d-o.height),c=Ut(Math.min(c,i,l.maxWidth)),d=Ut(Math.min(d,a,l.maxHeight)),c&&!d&&(d=Ut(c/2)),(e!==void 0||n!==void 0)&&r&&l.height&&d>l.height&&(d=l.height,c=Ut(Math.floor(d*r))),{width:c,height:d}}function vl(t,e,n){const r=e||1,s=Ut(t.height*r),o=Ut(t.width*r);t.height=Ut(t.height),t.width=Ut(t.width);const i=t.canvas;return i.style&&(n||!i.style.height&&!i.style.width)&&(i.style.height=`${t.height}px`,i.style.width=`${t.width}px`),t.currentDevicePixelRatio!==r||i.height!==s||i.width!==o?(t.currentDevicePixelRatio=r,i.height=s,i.width=o,t.ctx.setTransform(r,0,0,r,0,0),!0):!1}const H0=(function(){let t=!1;try{const e={get passive(){return t=!0,!1}};ea()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch{}return t})();function wl(t,e){const n=L0(t,e),r=n&&n.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function on(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:t.y+n*(e.y-t.y)}}function W0(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:r==="middle"?n<.5?t.y:e.y:r==="after"?n<1?t.y:e.y:n>0?e.y:t.y}}function q0(t,e,n,r){const s={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},i=on(t,s,n),a=on(s,o,n),l=on(o,e,n),c=on(i,a,n),d=on(a,l,n);return on(c,d,n)}const Y0=function(t,e){return{x(n){return t+t+e-n},setWidth(n){e=n},textAlign(n){return n==="center"?n:n==="right"?"left":"right"},xPlus(n,r){return n-r},leftForLtr(n,r){return n-r}}},K0=function(){return{x(t){return t},setWidth(t){},textAlign(t){return t},xPlus(t,e){return t+e},leftForLtr(t,e){return t}}};function Eo(t,e,n){return t?Y0(e,n):K0()}function X0(t,e){let n,r;(e==="ltr"||e==="rtl")&&(n=t.canvas.style,r=[n.getPropertyValue("direction"),n.getPropertyPriority("direction")],n.setProperty("direction",e,"important"),t.prevTextDirection=r)}function J0(t,e){e!==void 0&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Wu(t){return t==="angle"?{between:$u,compare:Hx,normalize:pt}:{between:Ou,compare:(e,n)=>e-n,normalize:e=>e}}function _l({start:t,end:e,count:n,loop:r,style:s}){return{start:t%n,end:e%n,loop:r&&(e-t+1)%n===0,style:s}}function Z0(t,e,n){const{property:r,start:s,end:o}=n,{between:i,normalize:a}=Wu(r),l=e.length;let{start:c,end:d,loop:f}=t,g,h;if(f){for(c+=l,d+=l,g=0,h=l;g<h&&i(a(e[c%l][r]),s,o);++g)c--,d--;c%=l,d%=l}return d<c&&(d+=l),{start:c,end:d,loop:f,style:t.style}}function qu(t,e,n){if(!n)return[t];const{property:r,start:s,end:o}=n,i=e.length,{compare:a,between:l,normalize:c}=Wu(r),{start:d,end:f,loop:g,style:h}=Z0(t,e,n),m=[];let p=!1,y=null,b,w,v;const S=()=>l(s,v,b)&&a(s,v)!==0,_=()=>a(o,b)===0||l(o,v,b),A=()=>p||S(),C=()=>!p||_();for(let R=d,N=d;R<=f;++R)w=e[R%i],!w.skip&&(b=c(w[r]),b!==v&&(p=l(b,s,o),y===null&&A()&&(y=a(b,s)===0?R:N),y!==null&&C()&&(m.push(_l({start:y,end:R,loop:g,count:i,style:h})),y=null),N=R,v=b));return y!==null&&m.push(_l({start:y,end:f,loop:g,count:i,style:h})),m}function Yu(t,e){const n=[],r=t.segments;for(let s=0;s<r.length;s++){const o=qu(r[s],t.points,e);o.length&&n.push(...o)}return n}function Q0(t,e,n,r){let s=0,o=e-1;if(n&&!r)for(;s<e&&!t[s].skip;)s++;for(;s<e&&t[s].skip;)s++;for(s%=e,n&&(o+=s);o>s&&t[o%e].skip;)o--;return o%=e,{start:s,end:o}}function ev(t,e,n,r){const s=t.length,o=[];let i=e,a=t[e],l;for(l=e+1;l<=n;++l){const c=t[l%s];c.skip||c.stop?a.skip||(r=!1,o.push({start:e%s,end:(l-1)%s,loop:r}),e=i=c.stop?l:null):(i=l,a.skip&&(e=l)),a=c}return i!==null&&o.push({start:e%s,end:i%s,loop:r}),o}function tv(t,e){const n=t.points,r=t.options.spanGaps,s=n.length;if(!s)return[];const o=!!t._loop,{start:i,end:a}=Q0(n,s,o,r);if(r===!0)return Sl(t,[{start:i,end:a,loop:o}],n,e);const l=a<i?a+s:a,c=!!t._fullLoop&&i===0&&a===s-1;return Sl(t,ev(n,i,l,c),n,e)}function Sl(t,e,n,r){return!r||!r.setContext||!n?e:nv(t,e,n,r)}function nv(t,e,n,r){const s=t._chart.getContext(),o=Cl(t.options),{_datasetIndex:i,options:{spanGaps:a}}=t,l=n.length,c=[];let d=o,f=e[0].start,g=f;function h(m,p,y,b){const w=a?-1:1;if(m!==p){for(m+=l;n[m%l].skip;)m-=w;for(;n[p%l].skip;)p+=w;m%l!==p%l&&(c.push({start:m%l,end:p%l,loop:y,style:b}),d=b,f=p%l)}}for(const m of e){f=a?f:m.start;let p=n[f%l],y;for(g=f+1;g<=m.end;g++){const b=n[g%l];y=Cl(r.setContext(xn(s,{type:"segment",p0:p,p1:b,p0DataIndex:(g-1)%l,p1DataIndex:g%l,datasetIndex:i}))),rv(y,d)&&h(f,g-1,m.loop,d),p=b,d=y}f<g-1&&h(f,g-1,m.loop,d)}return c}function Cl(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function rv(t,e){if(!e)return!1;const n=[],r=function(s,o){return Yi(o)?(n.includes(o)||n.push(o),n.indexOf(o)):o};return JSON.stringify(t,r)!==JSON.stringify(e,r)}function es(t,e,n){return t.options.clip?t[n]:e[n]}function sv(t,e){const{xScale:n,yScale:r}=t;return n&&r?{left:es(n,e,"left"),right:es(n,e,"right"),top:es(r,e,"top"),bottom:es(r,e,"bottom")}:e}function Ku(t,e){const n=e._clip;if(n.disabled)return!1;const r=sv(e,t.chartArea);return{left:n.left===!1?0:r.left-(n.left===!0?0:n.left),right:n.right===!1?t.width:r.right+(n.right===!0?0:n.right),top:n.top===!1?0:r.top-(n.top===!0?0:n.top),bottom:n.bottom===!1?t.height:r.bottom+(n.bottom===!0?0:n.bottom)}}class ov{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(e,n,r,s){const o=n.listeners[s],i=n.duration;o.forEach(a=>a({chart:e,initial:n.initial,numSteps:i,currentStep:Math.min(r-n.start,i)}))}_refresh(){this._request||(this._running=!0,this._request=Pu.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let n=0;this._charts.forEach((r,s)=>{if(!r.running||!r.items.length)return;const o=r.items;let i=o.length-1,a=!1,l;for(;i>=0;--i)l=o[i],l._active?(l._total>r.duration&&(r.duration=l._total),l.tick(e),a=!0):(o[i]=o[o.length-1],o.pop());a&&(s.draw(),this._notify(s,r,e,"progress")),o.length||(r.running=!1,this._notify(s,r,e,"complete"),r.initial=!1),n+=o.length}),this._lastDate=e,n===0&&(this._running=!1)}_getAnims(e){const n=this._charts;let r=n.get(e);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},n.set(e,r)),r}listen(e,n,r){this._getAnims(e).listeners[n].push(r)}add(e,n){!n||!n.length||this._getAnims(e).items.push(...n)}has(e){return this._getAnims(e).items.length>0}start(e){const n=this._charts.get(e);n&&(n.running=!0,n.start=Date.now(),n.duration=n.items.reduce((r,s)=>Math.max(r,s._duration),0),this._refresh())}running(e){if(!this._running)return!1;const n=this._charts.get(e);return!(!n||!n.running||!n.items.length)}stop(e){const n=this._charts.get(e);if(!n||!n.items.length)return;const r=n.items;let s=r.length-1;for(;s>=0;--s)r[s].cancel();n.items=[],this._notify(e,n,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var kt=new ov;const Rl="transparent",iv={boolean(t,e,n){return n>.5?e:t},color(t,e,n){const r=fl(t||Rl),s=r.valid&&fl(e||Rl);return s&&s.valid?s.mix(r,n).hexString():e},number(t,e,n){return t+(e-t)*n}};class av{constructor(e,n,r,s){const o=n[r];s=Zr([e.to,s,o,e.from]);const i=Zr([e.from,o,s]);this._active=!0,this._fn=e.fn||iv[e.type||typeof i],this._easing=hr[e.easing]||hr.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=n,this._prop=r,this._from=i,this._to=s,this._promises=void 0}active(){return this._active}update(e,n,r){if(this._active){this._notify(!1);const s=this._target[this._prop],o=r-this._start,i=this._duration-o;this._start=r,this._duration=Math.floor(Math.max(i,e.duration)),this._total+=o,this._loop=!!e.loop,this._to=Zr([e.to,n,s,e.from]),this._from=Zr([e.from,s,n])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const n=e-this._start,r=this._duration,s=this._prop,o=this._from,i=this._loop,a=this._to;let l;if(this._active=o!==a&&(i||n<r),!this._active){this._target[s]=a,this._notify(!0);return}if(n<0){this._target[s]=o;return}l=n/r%2,l=i&&l>1?2-l:l,l=this._easing(Math.min(1,Math.max(0,l))),this._target[s]=this._fn(o,a,l)}wait(){const e=this._promises||(this._promises=[]);return new Promise((n,r)=>{e.push({res:n,rej:r})})}_notify(e){const n=e?"res":"rej",r=this._promises||[];for(let s=0;s<r.length;s++)r[s][n]()}}class Xu{constructor(e,n){this._chart=e,this._properties=new Map,this.configure(n)}configure(e){if(!ie(e))return;const n=Object.keys(Te.animation),r=this._properties;Object.getOwnPropertyNames(e).forEach(s=>{const o=e[s];if(!ie(o))return;const i={};for(const a of n)i[a]=o[a];(Oe(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(e,n){const r=n.options,s=cv(e,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&lv(e.options.$animations,r).then(()=>{e.options=r},()=>{}),o}_createAnimations(e,n){const r=this._properties,s=[],o=e.$animations||(e.$animations={}),i=Object.keys(n),a=Date.now();let l;for(l=i.length-1;l>=0;--l){const c=i[l];if(c.charAt(0)==="$")continue;if(c==="options"){s.push(...this._animateOptions(e,n));continue}const d=n[c];let f=o[c];const g=r.get(c);if(f)if(g&&f.active()){f.update(g,d,a);continue}else f.cancel();if(!g||!g.duration){e[c]=d;continue}o[c]=f=new av(g,e,c,d),s.push(f)}return s}update(e,n){if(this._properties.size===0){Object.assign(e,n);return}const r=this._createAnimations(e,n);if(r.length)return kt.add(this._chart,r),!0}}function lv(t,e){const n=[],r=Object.keys(e);for(let s=0;s<r.length;s++){const o=t[r[s]];o&&o.active()&&n.push(o.wait())}return Promise.all(n)}function cv(t,e){if(!e)return;let n=t.options;if(!n){t.options=e;return}return n.$shared&&(t.options=n=Object.assign({},n,{$shared:!1,$animations:{}})),n}function Al(t,e){const n=t&&t.options||{},r=n.reverse,s=n.min===void 0?e:0,o=n.max===void 0?e:0;return{start:r?o:s,end:r?s:o}}function dv(t,e,n){if(n===!1)return!1;const r=Al(t,n),s=Al(e,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function uv(t){let e,n,r,s;return ie(t)?(e=t.top,n=t.right,r=t.bottom,s=t.left):e=n=r=s=t,{top:e,right:n,bottom:r,left:s,disabled:t===!1}}function Ju(t,e){const n=[],r=t._getSortedDatasetMetas(e);let s,o;for(s=0,o=r.length;s<o;++s)n.push(r[s].index);return n}function Nl(t,e,n,r={}){const s=t.keys,o=r.mode==="single";let i,a,l,c;if(e===null)return;let d=!1;for(i=0,a=s.length;i<a;++i){if(l=+s[i],l===n){if(d=!0,r.all)continue;break}c=t.values[l],Ue(c)&&(o||e===0||On(e)===On(c))&&(e+=c)}return!d&&!r.all?0:e}function fv(t,e){const{iScale:n,vScale:r}=e,s=n.axis==="x"?"x":"y",o=r.axis==="x"?"x":"y",i=Object.keys(t),a=new Array(i.length);let l,c,d;for(l=0,c=i.length;l<c;++l)d=i[l],a[l]={[s]:d,[o]:t[d]};return a}function ko(t,e){const n=t&&t.options.stacked;return n||n===void 0&&e.stack!==void 0}function hv(t,e,n){return`${t.id}.${e.id}.${n.stack||n.type}`}function gv(t){const{min:e,max:n,minDefined:r,maxDefined:s}=t.getUserBounds();return{min:r?e:Number.NEGATIVE_INFINITY,max:s?n:Number.POSITIVE_INFINITY}}function mv(t,e,n){const r=t[e]||(t[e]={});return r[n]||(r[n]={})}function El(t,e,n,r){for(const s of e.getMatchingVisibleMetas(r).reverse()){const o=t[s.index];if(n&&o>0||!n&&o<0)return s.index}return null}function kl(t,e){const{chart:n,_cachedMeta:r}=t,s=n._stacks||(n._stacks={}),{iScale:o,vScale:i,index:a}=r,l=o.axis,c=i.axis,d=hv(o,i,r),f=e.length;let g;for(let h=0;h<f;++h){const m=e[h],{[l]:p,[c]:y}=m,b=m._stacks||(m._stacks={});g=b[c]=mv(s,d,p),g[a]=y,g._top=El(g,i,!0,r.type),g._bottom=El(g,i,!1,r.type);const w=g._visualValues||(g._visualValues={});w[a]=y}}function To(t,e){const n=t.scales;return Object.keys(n).filter(r=>n[r].axis===e).shift()}function pv(t,e){return xn(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function yv(t,e,n){return xn(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:n,index:e,mode:"default",type:"data"})}function Jn(t,e){const n=t.controller.index,r=t.vScale&&t.vScale.axis;if(r){e=e||t._parsed;for(const s of e){const o=s._stacks;if(!o||o[r]===void 0||o[r][n]===void 0)return;delete o[r][n],o[r]._visualValues!==void 0&&o[r]._visualValues[n]!==void 0&&delete o[r]._visualValues[n]}}}const Mo=t=>t==="reset"||t==="none",Tl=(t,e)=>e?t:Object.assign({},t),bv=(t,e,n)=>t&&!e.hidden&&e._stacked&&{keys:Ju(n,!0),values:null};class Zu{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(e,n){this.chart=e,this._ctx=e.ctx,this.index=n,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=ko(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&Jn(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(f,g,h,m)=>f==="x"?g:f==="r"?m:h,o=n.xAxisID=pe(r.xAxisID,To(e,"x")),i=n.yAxisID=pe(r.yAxisID,To(e,"y")),a=n.rAxisID=pe(r.rAxisID,To(e,"r")),l=n.indexAxis,c=n.iAxisID=s(l,o,i,a),d=n.vAxisID=s(l,i,o,a);n.xScale=this.getScaleForId(o),n.yScale=this.getScaleForId(i),n.rScale=this.getScaleForId(a),n.iScale=this.getScaleForId(c),n.vScale=this.getScaleForId(d)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const n=this._cachedMeta;return e===n.iScale?n.vScale:n.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&ll(this._data,this),e._stacked&&Jn(e)}_dataCheck(){const e=this.getDataset(),n=e.data||(e.data=[]),r=this._data;if(ie(n)){const s=this._cachedMeta;this._data=fv(n,s)}else if(r!==n){if(r){ll(r,this);const s=this._cachedMeta;Jn(s),s._parsed=[]}n&&Object.isExtensible(n)&&Kx(n,this),this._syncList=[],this._data=n}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const n=this._cachedMeta,r=this.getDataset();let s=!1;this._dataCheck();const o=n._stacked;n._stacked=ko(n.vScale,n),n.stack!==r.stack&&(s=!0,Jn(n),n.stack=r.stack),this._resyncElements(e),(s||o!==n._stacked)&&(kl(this,n._parsed),n._stacked=ko(n.vScale,n))}configure(){const e=this.chart.config,n=e.datasetScopeKeys(this._type),r=e.getOptionScopes(this.getDataset(),n,!0);this.options=e.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,n){const{_cachedMeta:r,_data:s}=this,{iScale:o,_stacked:i}=r,a=o.axis;let l=e===0&&n===s.length?!0:r._sorted,c=e>0&&r._parsed[e-1],d,f,g;if(this._parsing===!1)r._parsed=s,r._sorted=!0,g=s;else{Oe(s[e])?g=this.parseArrayData(r,s,e,n):ie(s[e])?g=this.parseObjectData(r,s,e,n):g=this.parsePrimitiveData(r,s,e,n);const h=()=>f[a]===null||c&&f[a]<c[a];for(d=0;d<n;++d)r._parsed[d+e]=f=g[d],l&&(h()&&(l=!1),c=f);r._sorted=l}i&&kl(this,g)}parsePrimitiveData(e,n,r,s){const{iScale:o,vScale:i}=e,a=o.axis,l=i.axis,c=o.getLabels(),d=o===i,f=new Array(s);let g,h,m;for(g=0,h=s;g<h;++g)m=g+r,f[g]={[a]:d||o.parse(c[m],m),[l]:i.parse(n[m],m)};return f}parseArrayData(e,n,r,s){const{xScale:o,yScale:i}=e,a=new Array(s);let l,c,d,f;for(l=0,c=s;l<c;++l)d=l+r,f=n[d],a[l]={x:o.parse(f[0],d),y:i.parse(f[1],d)};return a}parseObjectData(e,n,r,s){const{xScale:o,yScale:i}=e,{xAxisKey:a="x",yAxisKey:l="y"}=this._parsing,c=new Array(s);let d,f,g,h;for(d=0,f=s;d<f;++d)g=d+r,h=n[g],c[d]={x:o.parse(Ms(h,a),g),y:i.parse(Ms(h,l),g)};return c}getParsed(e){return this._cachedMeta._parsed[e]}getDataElement(e){return this._cachedMeta.data[e]}applyStack(e,n,r){const s=this.chart,o=this._cachedMeta,i=n[e.axis],a={keys:Ju(s,!0),values:n._stacks[e.axis]._visualValues};return Nl(a,i,o.index,{mode:r})}updateRangeFromParsed(e,n,r,s){const o=r[n.axis];let i=o===null?NaN:o;const a=s&&r._stacks[n.axis];s&&a&&(s.values=a,i=Nl(s,o,this._cachedMeta.index)),e.min=Math.min(e.min,i),e.max=Math.max(e.max,i)}getMinMax(e,n){const r=this._cachedMeta,s=r._parsed,o=r._sorted&&e===r.iScale,i=s.length,a=this._getOtherScale(e),l=bv(n,r,this.chart),c={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=gv(a);let g,h;function m(){h=s[g];const p=h[a.axis];return!Ue(h[e.axis])||d>p||f<p}for(g=0;g<i&&!(!m()&&(this.updateRangeFromParsed(c,e,h,l),o));++g);if(o){for(g=i-1;g>=0;--g)if(!m()){this.updateRangeFromParsed(c,e,h,l);break}}return c}getAllParsedValues(e){const n=this._cachedMeta._parsed,r=[];let s,o,i;for(s=0,o=n.length;s<o;++s)i=n[s][e.axis],Ue(i)&&r.push(i);return r}getMaxOverflow(){return!1}getLabelAndValue(e){const n=this._cachedMeta,r=n.iScale,s=n.vScale,o=this.getParsed(e);return{label:r?""+r.getLabelForValue(o[r.axis]):"",value:s?""+s.getLabelForValue(o[s.axis]):""}}_update(e){const n=this._cachedMeta;this.update(e||"default"),n._clip=uv(pe(this.options.clip,dv(n.xScale,n.yScale,this.getMaxOverflow())))}update(e){}draw(){const e=this._ctx,n=this.chart,r=this._cachedMeta,s=r.data||[],o=n.chartArea,i=[],a=this._drawStart||0,l=this._drawCount||s.length-a,c=this.options.drawActiveElementsOnTop;let d;for(r.dataset&&r.dataset.draw(e,o,a,l),d=a;d<a+l;++d){const f=s[d];f.hidden||(f.active&&c?i.push(f):f.draw(e,o))}for(d=0;d<i.length;++d)i[d].draw(e,o)}getStyle(e,n){const r=n?"active":"default";return e===void 0&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(r):this.resolveDataElementOptions(e||0,r)}getContext(e,n,r){const s=this.getDataset();let o;if(e>=0&&e<this._cachedMeta.data.length){const i=this._cachedMeta.data[e];o=i.$context||(i.$context=yv(this.getContext(),e,i)),o.parsed=this.getParsed(e),o.raw=s.data[e],o.index=o.dataIndex=e}else o=this.$context||(this.$context=pv(this.chart.getContext(),this.index)),o.dataset=s,o.index=o.datasetIndex=this.index;return o.active=!!n,o.mode=r,o}resolveDatasetElementOptions(e){return this._resolveElementOptions(this.datasetElementType.id,e)}resolveDataElementOptions(e,n){return this._resolveElementOptions(this.dataElementType.id,n,e)}_resolveElementOptions(e,n="default",r){const s=n==="active",o=this._cachedDataOpts,i=e+"-"+n,a=o[i],l=this.enableOptionSharing&&js(r);if(a)return Tl(a,l);const c=this.chart.config,d=c.datasetElementScopeKeys(this._type,e),f=s?[`${e}Hover`,"hover",e,""]:[e,""],g=c.getOptionScopes(this.getDataset(),d),h=Object.keys(Te.elements[e]),m=()=>this.getContext(r,s,n),p=c.resolveNamedOptions(g,h,m,f);return p.$shared&&(p.$shared=l,o[i]=Object.freeze(Tl(p,l))),p}_resolveAnimations(e,n,r){const s=this.chart,o=this._cachedDataOpts,i=`animation-${n}`,a=o[i];if(a)return a;let l;if(s.options.animation!==!1){const d=this.chart.config,f=d.datasetAnimationScopeKeys(this._type,n),g=d.getOptionScopes(this.getDataset(),f);l=d.createResolver(g,this.getContext(e,r,n))}const c=new Xu(s,l&&l.animations);return l&&l._cacheable&&(o[i]=Object.freeze(c)),c}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,n){return!n||Mo(e)||this.chart._animationsDisabled}_getSharedOptions(e,n){const r=this.resolveDataElementOptions(e,n),s=this._sharedOptions,o=this.getSharedOptions(r),i=this.includeOptions(n,o)||o!==s;return this.updateSharedOptions(o,n,r),{sharedOptions:o,includeOptions:i}}updateElement(e,n,r,s){Mo(s)?Object.assign(e,r):this._resolveAnimations(n,s).update(e,r)}updateSharedOptions(e,n,r){e&&!Mo(n)&&this._resolveAnimations(void 0,n).update(e,r)}_setStyle(e,n,r,s){e.active=s;const o=this.getStyle(n,s);this._resolveAnimations(n,r,s).update(e,{options:!s&&this.getSharedOptions(o)||o})}removeHoverStyle(e,n,r){this._setStyle(e,r,"active",!1)}setHoverStyle(e,n,r){this._setStyle(e,r,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const n=this._data,r=this._cachedMeta.data;for(const[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];const s=r.length,o=n.length,i=Math.min(o,s);i&&this.parse(0,i),o>s?this._insertElements(s,o-s,e):o<s&&this._removeElements(o,s-o)}_insertElements(e,n,r=!0){const s=this._cachedMeta,o=s.data,i=e+n;let a;const l=c=>{for(c.length+=n,a=c.length-1;a>=i;a--)c[a]=c[a-n]};for(l(o),a=e;a<i;++a)o[a]=new this.dataElementType;this._parsing&&l(s._parsed),this.parse(e,n),r&&this.updateElements(o,e,n,"reset")}updateElements(e,n,r,s){}_removeElements(e,n){const r=this._cachedMeta;if(this._parsing){const s=r._parsed.splice(e,n);r._stacked&&Jn(r,s)}r.data.splice(e,n)}_sync(e){if(this._parsing)this._syncList.push(e);else{const[n,r,s]=e;this[n](r,s)}this.chart._dataChanges.push([this.index,...e])}_onDataPush(){const e=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-e,e])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(e,n){n&&this._sync(["_removeElements",e,n]);const r=arguments.length-2;r&&this._sync(["_insertElements",e,r])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}class xv extends Zu{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(e){const n=this._cachedMeta,{dataset:r,data:s=[],_dataset:o}=n,i=this.chart._animationsDisabled;let{start:a,count:l}=Qx(n,s,i);this._drawStart=a,this._drawCount=l,e0(n)&&(a=0,l=s.length),r._chart=this.chart,r._datasetIndex=this.index,r._decimated=!!o._decimated,r.points=s;const c=this.resolveDatasetElementOptions(e);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(r,void 0,{animated:!i,options:c},e),this.updateElements(s,a,l,e)}updateElements(e,n,r,s){const o=s==="reset",{iScale:i,vScale:a,_stacked:l,_dataset:c}=this._cachedMeta,{sharedOptions:d,includeOptions:f}=this._getSharedOptions(n,s),g=i.axis,h=a.axis,{spanGaps:m,segment:p}=this.options,y=br(m)?m:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||s==="none",w=n+r,v=e.length;let S=n>0&&this.getParsed(n-1);for(let _=0;_<v;++_){const A=e[_],C=b?A:{};if(_<n||_>=w){C.skip=!0;continue}const R=this.getParsed(_),N=xe(R[h]),M=C[g]=i.getPixelForValue(R[g],_),F=C[h]=o||N?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,R,l):R[h],_);C.skip=isNaN(M)||isNaN(F)||N,C.stop=_>0&&Math.abs(R[g]-S[g])>y,p&&(C.parsed=R,C.raw=c.data[_]),f&&(C.options=d||this.resolveDataElementOptions(_,A.active?"active":s)),b||this.updateElement(A,_,C,s),S=R}}getMaxOverflow(){const e=this._cachedMeta,n=e.dataset,r=n.options&&n.options.borderWidth||0,s=e.data||[];if(!s.length)return r;const o=s[0].size(this.resolveDataElementOptions(0)),i=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(r,o,i)/2}draw(){const e=this._cachedMeta;e.dataset.updateControlPoints(this.chart.chartArea,e.iScale.axis),super.draw()}}function nn(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class na{static override(e){Object.assign(na.prototype,e)}options;constructor(e){this.options=e||{}}init(){}formats(){return nn()}parse(){return nn()}format(){return nn()}add(){return nn()}diff(){return nn()}startOf(){return nn()}endOf(){return nn()}}var vv={_date:na};function wv(t,e,n,r){const{controller:s,data:o,_sorted:i}=t,a=s._cachedMeta.iScale,l=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(a&&e===a.axis&&e!=="r"&&i&&o.length){const c=a._reversePixels?qx:fn;if(r){if(s._sharedOptions){const d=o[0],f=typeof d.getRange=="function"&&d.getRange(e);if(f){const g=c(o,e,n-f),h=c(o,e,n+f);return{lo:g.lo,hi:h.hi}}}}else{const d=c(o,e,n);if(l){const{vScale:f}=s._cachedMeta,{_parsed:g}=t,h=g.slice(0,d.lo+1).reverse().findIndex(p=>!xe(p[f.axis]));d.lo-=Math.max(0,h);const m=g.slice(d.hi).findIndex(p=>!xe(p[f.axis]));d.hi+=Math.max(0,m)}return d}}return{lo:0,hi:o.length-1}}function Ys(t,e,n,r,s){const o=t.getSortedVisibleDatasetMetas(),i=n[e];for(let a=0,l=o.length;a<l;++a){const{index:c,data:d}=o[a],{lo:f,hi:g}=wv(o[a],e,i,s);for(let h=f;h<=g;++h){const m=d[h];m.skip||r(m,c,h)}}}function _v(t){const e=t.indexOf("x")!==-1,n=t.indexOf("y")!==-1;return function(r,s){const o=e?Math.abs(r.x-s.x):0,i=n?Math.abs(r.y-s.y):0;return Math.sqrt(Math.pow(o,2)+Math.pow(i,2))}}function jo(t,e,n,r,s){const o=[];return!s&&!t.isPointInArea(e)||Ys(t,n,e,function(a,l,c){!s&&!xr(a,t.chartArea,0)||a.inRange(e.x,e.y,r)&&o.push({element:a,datasetIndex:l,index:c})},!0),o}function Sv(t,e,n,r){let s=[];function o(i,a,l){const{startAngle:c,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=Bx(i,{x:e.x,y:e.y});$u(f,c,d)&&s.push({element:i,datasetIndex:a,index:l})}return Ys(t,n,e,o),s}function Cv(t,e,n,r,s,o){let i=[];const a=_v(n);let l=Number.POSITIVE_INFINITY;function c(d,f,g){const h=d.inRange(e.x,e.y,s);if(r&&!h)return;const m=d.getCenterPoint(s);if(!(!!o||t.isPointInArea(m))&&!h)return;const y=a(e,m);y<l?(i=[{element:d,datasetIndex:f,index:g}],l=y):y===l&&i.push({element:d,datasetIndex:f,index:g})}return Ys(t,n,e,c),i}function $o(t,e,n,r,s,o){return!o&&!t.isPointInArea(e)?[]:n==="r"&&!r?Sv(t,e,n,s):Cv(t,e,n,r,s,o)}function Ml(t,e,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return Ys(t,n,e,(l,c,d)=>{l[i]&&l[i](e[n],s)&&(o.push({element:l,datasetIndex:c,index:d}),a=a||l.inRange(e.x,e.y,s))}),r&&!a?[]:o}var Rv={modes:{index(t,e,n,r){const s=sn(e,t),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?jo(t,s,o,r,i):$o(t,s,o,!1,r,i),l=[];return a.length?(t.getSortedVisibleDatasetMetas().forEach(c=>{const d=a[0].index,f=c.data[d];f&&!f.skip&&l.push({element:f,datasetIndex:c.index,index:d})}),l):[]},dataset(t,e,n,r){const s=sn(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;let a=n.intersect?jo(t,s,o,r,i):$o(t,s,o,!1,r,i);if(a.length>0){const l=a[0].datasetIndex,c=t.getDatasetMeta(l).data;a=[];for(let d=0;d<c.length;++d)a.push({element:c[d],datasetIndex:l,index:d})}return a},point(t,e,n,r){const s=sn(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;return jo(t,s,o,r,i)},nearest(t,e,n,r){const s=sn(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;return $o(t,s,o,n.intersect,r,i)},x(t,e,n,r){const s=sn(e,t);return Ml(t,s,"x",n.intersect,r)},y(t,e,n,r){const s=sn(e,t);return Ml(t,s,"y",n.intersect,r)}}};const Qu=["left","top","right","bottom"];function Zn(t,e){return t.filter(n=>n.pos===e)}function jl(t,e){return t.filter(n=>Qu.indexOf(n.pos)===-1&&n.box.axis===e)}function Qn(t,e){return t.sort((n,r)=>{const s=e?r:n,o=e?n:r;return s.weight===o.weight?s.index-o.index:s.weight-o.weight})}function Av(t){const e=[];let n,r,s,o,i,a;for(n=0,r=(t||[]).length;n<r;++n)s=t[n],{position:o,options:{stack:i,stackWeight:a=1}}=s,e.push({index:n,box:s,pos:o,horizontal:s.isHorizontal(),weight:s.weight,stack:i&&o+i,stackWeight:a});return e}function Nv(t){const e={};for(const n of t){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!Qu.includes(s))continue;const i=e[r]||(e[r]={count:0,placed:0,weight:0,size:0});i.count++,i.weight+=o}return e}function Ev(t,e){const n=Nv(t),{vBoxMaxWidth:r,hBoxMaxHeight:s}=e;let o,i,a;for(o=0,i=t.length;o<i;++o){a=t[o];const{fullSize:l}=a.box,c=n[a.stack],d=c&&a.stackWeight/c.weight;a.horizontal?(a.width=d?d*r:l&&e.availableWidth,a.height=s):(a.width=r,a.height=d?d*s:l&&e.availableHeight)}return n}function kv(t){const e=Av(t),n=Qn(e.filter(c=>c.box.fullSize),!0),r=Qn(Zn(e,"left"),!0),s=Qn(Zn(e,"right")),o=Qn(Zn(e,"top"),!0),i=Qn(Zn(e,"bottom")),a=jl(e,"x"),l=jl(e,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(l).concat(i).concat(a),chartArea:Zn(e,"chartArea"),vertical:r.concat(s).concat(l),horizontal:o.concat(i).concat(a)}}function $l(t,e,n,r){return Math.max(t[n],e[n])+Math.max(t[r],e[r])}function ef(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function Tv(t,e,n,r){const{pos:s,box:o}=n,i=t.maxPadding;if(!ie(s)){n.size&&(t[s]-=n.size);const f=r[n.stack]||{size:0,count:1};f.size=Math.max(f.size,n.horizontal?o.height:o.width),n.size=f.size/f.count,t[s]+=n.size}o.getPadding&&ef(i,o.getPadding());const a=Math.max(0,e.outerWidth-$l(i,t,"left","right")),l=Math.max(0,e.outerHeight-$l(i,t,"top","bottom")),c=a!==t.w,d=l!==t.h;return t.w=a,t.h=l,n.horizontal?{same:c,other:d}:{same:d,other:c}}function Mv(t){const e=t.maxPadding;function n(r){const s=Math.max(e[r]-t[r],0);return t[r]+=s,s}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}function jv(t,e){const n=e.maxPadding;function r(s){const o={left:0,top:0,right:0,bottom:0};return s.forEach(i=>{o[i]=Math.max(e[i],n[i])}),o}return r(t?["left","right"]:["top","bottom"])}function lr(t,e,n,r){const s=[];let o,i,a,l,c,d;for(o=0,i=t.length,c=0;o<i;++o){a=t[o],l=a.box,l.update(a.width||e.w,a.height||e.h,jv(a.horizontal,e));const{same:f,other:g}=Tv(e,n,a,r);c|=f&&s.length,d=d||g,l.fullSize||s.push(a)}return c&&lr(s,e,n,r)||d}function ts(t,e,n,r,s){t.top=n,t.left=e,t.right=e+r,t.bottom=n+s,t.width=r,t.height=s}function Ol(t,e,n,r){const s=n.padding;let{x:o,y:i}=e;for(const a of t){const l=a.box,c=r[a.stack]||{placed:0,weight:1},d=a.stackWeight/c.weight||1;if(a.horizontal){const f=e.w*d,g=c.size||l.height;js(c.start)&&(i=c.start),l.fullSize?ts(l,s.left,i,n.outerWidth-s.right-s.left,g):ts(l,e.left+c.placed,i,f,g),c.start=i,c.placed+=f,i=l.bottom}else{const f=e.h*d,g=c.size||l.width;js(c.start)&&(o=c.start),l.fullSize?ts(l,o,s.top,g,n.outerHeight-s.bottom-s.top):ts(l,o,e.top+c.placed,g,f),c.start=o,c.placed+=f,o=l.right}}e.x=o,e.y=i}var ns={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(n){e.draw(n)}}]},t.boxes.push(e)},removeBox(t,e){const n=t.boxes?t.boxes.indexOf(e):-1;n!==-1&&t.boxes.splice(n,1)},configure(t,e,n){e.fullSize=n.fullSize,e.position=n.position,e.weight=n.weight},update(t,e,n,r){if(!t)return;const s=Yt(t.options.layout.padding),o=Math.max(e-s.width,0),i=Math.max(n-s.height,0),a=kv(t.boxes),l=a.vertical,c=a.horizontal;ge(t.boxes,p=>{typeof p.beforeLayout=="function"&&p.beforeLayout()});const d=l.reduce((p,y)=>y.box.options&&y.box.options.display===!1?p:p+1,0)||1,f=Object.freeze({outerWidth:e,outerHeight:n,padding:s,availableWidth:o,availableHeight:i,vBoxMaxWidth:o/2/d,hBoxMaxHeight:i/2}),g=Object.assign({},s);ef(g,Yt(r));const h=Object.assign({maxPadding:g,w:o,h:i,x:s.left,y:s.top},s),m=Ev(l.concat(c),f);lr(a.fullSize,h,f,m),lr(l,h,f,m),lr(c,h,f,m)&&lr(l,h,f,m),Mv(h),Ol(a.leftAndTop,h,f,m),h.x+=h.w,h.y+=h.h,Ol(a.rightAndBottom,h,f,m),t.chartArea={left:h.left,top:h.top,right:h.left+h.w,bottom:h.top+h.h,height:h.h,width:h.w},ge(a.chartArea,p=>{const y=p.box;Object.assign(y,t.chartArea),y.update(h.w,h.h,{left:0,top:0,right:0,bottom:0})})}};class tf{acquireContext(e,n){}releaseContext(e){return!1}addEventListener(e,n,r){}removeEventListener(e,n,r){}getDevicePixelRatio(){return 1}getMaximumSize(e,n,r,s){return n=Math.max(0,n||e.width),r=r||e.height,{width:n,height:Math.max(0,s?Math.floor(n/s):r)}}isAttached(e){return!0}updateConfig(e){}}class $v extends tf{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const ys="$chartjs",Ov={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Il=t=>t===null||t==="";function Iv(t,e){const n=t.style,r=t.getAttribute("height"),s=t.getAttribute("width");if(t[ys]={initial:{height:r,width:s,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",Il(s)){const o=wl(t,"width");o!==void 0&&(t.width=o)}if(Il(r))if(t.style.height==="")t.height=t.width/(e||2);else{const o=wl(t,"height");o!==void 0&&(t.height=o)}return t}const nf=H0?{passive:!0}:!1;function Pv(t,e,n){t&&t.addEventListener(e,n,nf)}function Fv(t,e,n){t&&t.canvas&&t.canvas.removeEventListener(e,n,nf)}function Dv(t,e){const n=Ov[t.type]||t.type,{x:r,y:s}=sn(t,e);return{type:n,chart:e,native:t,x:r!==void 0?r:null,y:s!==void 0?s:null}}function Is(t,e){for(const n of t)if(n===e||n.contains(e))return!0}function Lv(t,e,n){const r=t.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||Is(a.addedNodes,r),i=i&&!Is(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function zv(t,e,n){const r=t.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||Is(a.removedNodes,r),i=i&&!Is(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const vr=new Map;let Pl=0;function rf(){const t=window.devicePixelRatio;t!==Pl&&(Pl=t,vr.forEach((e,n)=>{n.currentDevicePixelRatio!==t&&e()}))}function Vv(t,e){vr.size||window.addEventListener("resize",rf),vr.set(t,e)}function Gv(t){vr.delete(t),vr.size||window.removeEventListener("resize",rf)}function Uv(t,e,n){const r=t.canvas,s=r&&ta(r);if(!s)return;const o=Fu((a,l)=>{const c=s.clientWidth;n(a,l),c<s.clientWidth&&n()},window),i=new ResizeObserver(a=>{const l=a[0],c=l.contentRect.width,d=l.contentRect.height;c===0&&d===0||o(c,d)});return i.observe(s),Vv(t,o),i}function Oo(t,e,n){n&&n.disconnect(),e==="resize"&&Gv(t)}function Bv(t,e,n){const r=t.canvas,s=Fu(o=>{t.ctx!==null&&n(Dv(o,t))},t);return Pv(r,e,s),s}class Hv extends tf{acquireContext(e,n){const r=e&&e.getContext&&e.getContext("2d");return r&&r.canvas===e?(Iv(e,n),r):null}releaseContext(e){const n=e.canvas;if(!n[ys])return!1;const r=n[ys].initial;["height","width"].forEach(o=>{const i=r[o];xe(i)?n.removeAttribute(o):n.setAttribute(o,i)});const s=r.style||{};return Object.keys(s).forEach(o=>{n.style[o]=s[o]}),n.width=n.width,delete n[ys],!0}addEventListener(e,n,r){this.removeEventListener(e,n);const s=e.$proxies||(e.$proxies={}),i={attach:Lv,detach:zv,resize:Uv}[n]||Bv;s[n]=i(e,n,r)}removeEventListener(e,n){const r=e.$proxies||(e.$proxies={}),s=r[n];if(!s)return;({attach:Oo,detach:Oo,resize:Oo}[n]||Fv)(e,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,n,r,s){return B0(e,n,r,s)}isAttached(e){const n=e&&ta(e);return!!(n&&n.isConnected)}}function Wv(t){return!ea()||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas?$v:Hv}class jr{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(e){const{x:n,y:r}=this.getProps(["x","y"],e);return{x:n,y:r}}hasValue(){return br(this.x)&&br(this.y)}getProps(e,n){const r=this.$animations;if(!n||!r)return this;const s={};return e.forEach(o=>{s[o]=r[o]&&r[o].active()?r[o]._to:this[o]}),s}}function qv(t,e){const n=t.options.ticks,r=Yv(t),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?Xv(e):[],i=o.length,a=o[0],l=o[i-1],c=[];if(i>s)return Jv(e,c,o,i/s),c;const d=Kv(o,e,s);if(i>0){let f,g;const h=i>1?Math.round((l-a)/(i-1)):null;for(rs(e,c,d,xe(h)?0:a-h,a),f=0,g=i-1;f<g;f++)rs(e,c,d,o[f],o[f+1]);return rs(e,c,d,l,xe(h)?e.length:l+h),c}return rs(e,c,d),c}function Yv(t){const e=t.options.offset,n=t._tickSize(),r=t._length/n+(e?0:1),s=t._maxLength/n;return Math.floor(Math.min(r,s))}function Kv(t,e,n){const r=Zv(t),s=e.length/n;if(!r)return Math.max(s,1);const o=Lx(r);for(let i=0,a=o.length-1;i<a;i++){const l=o[i];if(l>s)return l}return Math.max(s,1)}function Xv(t){const e=[];let n,r;for(n=0,r=t.length;n<r;n++)t[n].major&&e.push(n);return e}function Jv(t,e,n,r){let s=0,o=n[0],i;for(r=Math.ceil(r),i=0;i<t.length;i++)i===o&&(e.push(t[i]),s++,o=n[s*r])}function rs(t,e,n,r,s){const o=pe(r,0),i=Math.min(pe(s,t.length),t.length);let a=0,l,c,d;for(n=Math.ceil(n),s&&(l=s-r,n=l/Math.floor(l/n)),d=o;d<0;)a++,d=Math.round(o+a*n);for(c=Math.max(o,0);c<i;c++)c===d&&(e.push(t[c]),a++,d=Math.round(o+a*n))}function Zv(t){const e=t.length;let n,r;if(e<2)return!1;for(r=t[0],n=1;n<e;++n)if(t[n]-t[n-1]!==r)return!1;return r}const Qv=t=>t==="left"?"right":t==="right"?"left":t,Fl=(t,e,n)=>e==="top"||e==="left"?t[e]+n:t[e]-n,Dl=(t,e)=>Math.min(e||t,t);function Ll(t,e){const n=[],r=t.length/e,s=t.length;let o=0;for(;o<s;o+=r)n.push(t[Math.floor(o)]);return n}function ew(t,e,n){const r=t.ticks.length,s=Math.min(e,r-1),o=t._startPixel,i=t._endPixel,a=1e-6;let l=t.getPixelForTick(s),c;if(!(n&&(r===1?c=Math.max(l-o,i-l):e===0?c=(t.getPixelForTick(1)-l)/2:c=(l-t.getPixelForTick(s-1))/2,l+=s<e?c:-c,l<o-a||l>i+a)))return l}function tw(t,e){ge(t,n=>{const r=n.gc,s=r.length/2;let o;if(s>e){for(o=0;o<s;++o)delete n.data[r[o]];r.splice(0,s)}})}function er(t){return t.drawTicks?t.tickLength:0}function zl(t,e){if(!t.display)return 0;const n=_t(t.font,e),r=Yt(t.padding);return(Oe(t.text)?t.text.length:1)*n.lineHeight+r.height}function nw(t,e){return xn(t,{scale:e,type:"scale"})}function rw(t,e,n){return xn(t,{tick:n,index:e,type:"tick"})}function sw(t,e,n){let r=Zx(t);return(n&&e!=="right"||!n&&e==="right")&&(r=Qv(r)),r}function ow(t,e,n,r){const{top:s,left:o,bottom:i,right:a,chart:l}=t,{chartArea:c,scales:d}=l;let f=0,g,h,m;const p=i-s,y=a-o;if(t.isHorizontal()){if(h=cl(r,o,a),ie(n)){const b=Object.keys(n)[0],w=n[b];m=d[b].getPixelForValue(w)+p-e}else n==="center"?m=(c.bottom+c.top)/2+p-e:m=Fl(t,n,e);g=a-o}else{if(ie(n)){const b=Object.keys(n)[0],w=n[b];h=d[b].getPixelForValue(w)-y+e}else n==="center"?h=(c.left+c.right)/2-y+e:h=Fl(t,n,e);m=cl(r,i,s),f=n==="left"?-lt:lt}return{titleX:h,titleY:m,maxWidth:g,rotation:f}}class Un extends jr{constructor(e){super(),this.id=e.id,this.type=e.type,this.options=void 0,this.ctx=e.ctx,this.chart=e.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(e){this.options=e.setContext(this.getContext()),this.axis=e.axis,this._userMin=this.parse(e.min),this._userMax=this.parse(e.max),this._suggestedMin=this.parse(e.suggestedMin),this._suggestedMax=this.parse(e.suggestedMax)}parse(e,n){return e}getUserBounds(){let{_userMin:e,_userMax:n,_suggestedMin:r,_suggestedMax:s}=this;return e=ht(e,Number.POSITIVE_INFINITY),n=ht(n,Number.NEGATIVE_INFINITY),r=ht(r,Number.POSITIVE_INFINITY),s=ht(s,Number.NEGATIVE_INFINITY),{min:ht(e,r),max:ht(n,s),minDefined:Ue(e),maxDefined:Ue(n)}}getMinMax(e){let{min:n,max:r,minDefined:s,maxDefined:o}=this.getUserBounds(),i;if(s&&o)return{min:n,max:r};const a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;l<c;++l)i=a[l].controller.getMinMax(this,e),s||(n=Math.min(n,i.min)),o||(r=Math.max(r,i.max));return n=o&&n>r?r:n,r=s&&n>r?n:r,{min:ht(n,ht(r,n)),max:ht(r,ht(n,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){Ne(this.options.beforeUpdate,[this])}update(e,n,r){const{beginAtZero:s,grace:o,ticks:i}=this.options,a=i.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=n,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=_0(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?Ll(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=qv(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),l&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let e=this.options.reverse,n,r;this.isHorizontal()?(n=this.left,r=this.right):(n=this.top,r=this.bottom,e=!e),this._startPixel=n,this._endPixel=r,this._reversePixels=e,this._length=r-n,this._alignToPixels=this.options.alignToPixels}afterUpdate(){Ne(this.options.afterUpdate,[this])}beforeSetDimensions(){Ne(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){Ne(this.options.afterSetDimensions,[this])}_callHooks(e){this.chart.notifyPlugins(e,this.getContext()),Ne(this.options[e],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){Ne(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(e){const n=this.options.ticks;let r,s,o;for(r=0,s=e.length;r<s;r++)o=e[r],o.label=Ne(n.callback,[o.value,r,e],this)}afterTickToLabelConversion(){Ne(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){Ne(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const e=this.options,n=e.ticks,r=Dl(this.ticks.length,e.ticks.maxTicksLimit),s=n.minRotation||0,o=n.maxRotation;let i=s,a,l,c;if(!this._isVisible()||!n.display||s>=o||r<=1||!this.isHorizontal()){this.labelRotation=s;return}const d=this._getLabelSizes(),f=d.widest.width,g=d.highest.height,h=it(this.chart.width-f,0,this.maxWidth);a=e.offset?this.maxWidth/r:h/(r-1),f+6>a&&(a=h/(r-(e.offset?.5:1)),l=this.maxHeight-er(e.grid)-n.padding-zl(e.title,this.chart.options.font),c=Math.sqrt(f*f+g*g),i=Ux(Math.min(Math.asin(it((d.highest.height+6)/a,-1,1)),Math.asin(it(l/c,-1,1))-Math.asin(it(g/c,-1,1)))),i=Math.max(s,Math.min(o,i))),this.labelRotation=i}afterCalculateLabelRotation(){Ne(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){Ne(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:n,options:{ticks:r,title:s,grid:o}}=this,i=this._isVisible(),a=this.isHorizontal();if(i){const l=zl(s,n.options.font);if(a?(e.width=this.maxWidth,e.height=er(o)+l):(e.height=this.maxHeight,e.width=er(o)+l),r.display&&this.ticks.length){const{first:c,last:d,widest:f,highest:g}=this._getLabelSizes(),h=r.padding*2,m=un(this.labelRotation),p=Math.cos(m),y=Math.sin(m);if(a){const b=r.mirror?0:y*f.width+p*g.height;e.height=Math.min(this.maxHeight,e.height+b+h)}else{const b=r.mirror?0:p*f.width+y*g.height;e.width=Math.min(this.maxWidth,e.width+b+h)}this._calculatePadding(c,d,y,p)}}this._handleMargins(),a?(this.width=this._length=n.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=n.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,n,r,s){const{ticks:{align:o,padding:i},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){const d=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let g=0,h=0;l?c?(g=s*e.width,h=r*n.height):(g=r*e.height,h=s*n.width):o==="start"?h=n.width:o==="end"?g=e.width:o!=="inner"&&(g=e.width/2,h=n.width/2),this.paddingLeft=Math.max((g-d+i)*this.width/(this.width-d),0),this.paddingRight=Math.max((h-f+i)*this.width/(this.width-f),0)}else{let d=n.height/2,f=e.height/2;o==="start"?(d=0,f=e.height):o==="end"&&(d=n.height,f=0),this.paddingTop=d+i,this.paddingBottom=f+i}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){Ne(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:n}=this.options;return n==="top"||n==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let n,r;for(n=0,r=e.length;n<r;n++)xe(e[n].label)&&(e.splice(n,1),r--,n--);this.afterTickToLabelConversion()}_getLabelSizes(){let e=this._labelSizes;if(!e){const n=this.options.ticks.sampleSize;let r=this.ticks;n<r.length&&(r=Ll(r,n)),this._labelSizes=e=this._computeLabelSizes(r,r.length,this.options.ticks.maxTicksLimit)}return e}_computeLabelSizes(e,n,r){const{ctx:s,_longestTextCache:o}=this,i=[],a=[],l=Math.floor(n/Dl(n,r));let c=0,d=0,f,g,h,m,p,y,b,w,v,S,_;for(f=0;f<n;f+=l){if(m=e[f].label,p=this._resolveTickFontOptions(f),s.font=y=p.string,b=o[y]=o[y]||{data:{},gc:[]},w=p.lineHeight,v=S=0,!xe(m)&&!Oe(m))v=gl(s,b.data,b.gc,v,m),S=w;else if(Oe(m))for(g=0,h=m.length;g<h;++g)_=m[g],!xe(_)&&!Oe(_)&&(v=gl(s,b.data,b.gc,v,_),S+=w);i.push(v),a.push(S),c=Math.max(v,c),d=Math.max(S,d)}tw(o,n);const A=i.indexOf(c),C=a.indexOf(d),R=N=>({width:i[N]||0,height:a[N]||0});return{first:R(0),last:R(n-1),widest:R(A),highest:R(C),widths:i,heights:a}}getLabelForValue(e){return e}getPixelForValue(e,n){return NaN}getValueForPixel(e){}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const n=this._startPixel+e*this._length;return Wx(this._alignToPixels?tn(this.chart,n,0):n)}getDecimalForPixel(e){const n=(e-this._startPixel)/this._length;return this._reversePixels?1-n:n}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:n}=this;return e<0&&n<0?n:e>0&&n>0?e:0}getContext(e){const n=this.ticks||[];if(e>=0&&e<n.length){const r=n[e];return r.$context||(r.$context=rw(this.getContext(),e,r))}return this.$context||(this.$context=nw(this.chart.getContext(),this))}_tickSize(){const e=this.options.ticks,n=un(this.labelRotation),r=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n)),o=this._getLabelSizes(),i=e.autoSkipPadding||0,a=o?o.widest.width+i:0,l=o?o.highest.height+i:0;return this.isHorizontal()?l*r>a*s?a/r:l/s:l*s<a*r?l/r:a/s}_isVisible(){const e=this.options.display;return e!=="auto"?!!e:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(e){const n=this.axis,r=this.chart,s=this.options,{grid:o,position:i,border:a}=s,l=o.offset,c=this.isHorizontal(),f=this.ticks.length+(l?1:0),g=er(o),h=[],m=a.setContext(this.getContext()),p=m.display?m.width:0,y=p/2,b=function(T){return tn(r,T,p)};let w,v,S,_,A,C,R,N,M,F,D,P;if(i==="top")w=b(this.bottom),C=this.bottom-g,N=w-y,F=b(e.top)+y,P=e.bottom;else if(i==="bottom")w=b(this.top),F=e.top,P=b(e.bottom)-y,C=w+y,N=this.top+g;else if(i==="left")w=b(this.right),A=this.right-g,R=w-y,M=b(e.left)+y,D=e.right;else if(i==="right")w=b(this.left),M=e.left,D=b(e.right)-y,A=w+y,R=this.left+g;else if(n==="x"){if(i==="center")w=b((e.top+e.bottom)/2+.5);else if(ie(i)){const T=Object.keys(i)[0],B=i[T];w=b(this.chart.scales[T].getPixelForValue(B))}F=e.top,P=e.bottom,C=w+y,N=C+g}else if(n==="y"){if(i==="center")w=b((e.left+e.right)/2);else if(ie(i)){const T=Object.keys(i)[0],B=i[T];w=b(this.chart.scales[T].getPixelForValue(B))}A=w-y,R=A-g,M=e.left,D=e.right}const $=pe(s.ticks.maxTicksLimit,f),O=Math.max(1,Math.ceil(f/$));for(v=0;v<f;v+=O){const T=this.getContext(v),B=o.setContext(T),j=a.setContext(T),Q=B.lineWidth,oe=B.color,se=j.dash||[],ee=j.dashOffset,L=B.tickWidth,X=B.tickColor,ae=B.tickBorderDash||[],ve=B.tickBorderDashOffset;S=ew(this,v,l),S!==void 0&&(_=tn(r,S,Q),c?A=R=M=D=_:C=N=F=P=_,h.push({tx1:A,ty1:C,tx2:R,ty2:N,x1:M,y1:F,x2:D,y2:P,width:Q,color:oe,borderDash:se,borderDashOffset:ee,tickWidth:L,tickColor:X,tickBorderDash:ae,tickBorderDashOffset:ve}))}return this._ticksLength=f,this._borderValue=w,h}_computeLabelItems(e){const n=this.axis,r=this.options,{position:s,ticks:o}=r,i=this.isHorizontal(),a=this.ticks,{align:l,crossAlign:c,padding:d,mirror:f}=o,g=er(r.grid),h=g+d,m=f?-d:h,p=-un(this.labelRotation),y=[];let b,w,v,S,_,A,C,R,N,M,F,D,P="middle";if(s==="top")A=this.bottom-m,C=this._getXAxisLabelAlignment();else if(s==="bottom")A=this.top+m,C=this._getXAxisLabelAlignment();else if(s==="left"){const O=this._getYAxisLabelAlignment(g);C=O.textAlign,_=O.x}else if(s==="right"){const O=this._getYAxisLabelAlignment(g);C=O.textAlign,_=O.x}else if(n==="x"){if(s==="center")A=(e.top+e.bottom)/2+h;else if(ie(s)){const O=Object.keys(s)[0],T=s[O];A=this.chart.scales[O].getPixelForValue(T)+h}C=this._getXAxisLabelAlignment()}else if(n==="y"){if(s==="center")_=(e.left+e.right)/2-h;else if(ie(s)){const O=Object.keys(s)[0],T=s[O];_=this.chart.scales[O].getPixelForValue(T)}C=this._getYAxisLabelAlignment(g).textAlign}n==="y"&&(l==="start"?P="top":l==="end"&&(P="bottom"));const $=this._getLabelSizes();for(b=0,w=a.length;b<w;++b){v=a[b],S=v.label;const O=o.setContext(this.getContext(b));R=this.getPixelForTick(b)+o.labelOffset,N=this._resolveTickFontOptions(b),M=N.lineHeight,F=Oe(S)?S.length:1;const T=F/2,B=O.color,j=O.textStrokeColor,Q=O.textStrokeWidth;let oe=C;i?(_=R,C==="inner"&&(b===w-1?oe=this.options.reverse?"left":"right":b===0?oe=this.options.reverse?"right":"left":oe="center"),s==="top"?c==="near"||p!==0?D=-F*M+M/2:c==="center"?D=-$.highest.height/2-T*M+M:D=-$.highest.height+M/2:c==="near"||p!==0?D=M/2:c==="center"?D=$.highest.height/2-T*M:D=$.highest.height-F*M,f&&(D*=-1),p!==0&&!O.showLabelBackdrop&&(_+=M/2*Math.sin(p))):(A=R,D=(1-F)*M/2);let se;if(O.showLabelBackdrop){const ee=Yt(O.backdropPadding),L=$.heights[b],X=$.widths[b];let ae=D-ee.top,ve=0-ee.left;switch(P){case"middle":ae-=L/2;break;case"bottom":ae-=L;break}switch(C){case"center":ve-=X/2;break;case"right":ve-=X;break;case"inner":b===w-1?ve-=X:b>0&&(ve-=X/2);break}se={left:ve,top:ae,width:X+ee.width,height:L+ee.height,color:O.backdropColor}}y.push({label:S,font:N,textOffset:D,options:{rotation:p,color:B,strokeColor:j,strokeWidth:Q,textAlign:oe,textBaseline:P,translation:[_,A],backdrop:se}})}return y}_getXAxisLabelAlignment(){const{position:e,ticks:n}=this.options;if(-un(this.labelRotation))return e==="top"?"left":"right";let s="center";return n.align==="start"?s="left":n.align==="end"?s="right":n.align==="inner"&&(s="inner"),s}_getYAxisLabelAlignment(e){const{position:n,ticks:{crossAlign:r,mirror:s,padding:o}}=this.options,i=this._getLabelSizes(),a=e+o,l=i.widest.width;let c,d;return n==="left"?s?(d=this.right+o,r==="near"?c="left":r==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,r==="near"?c="right":r==="center"?(c="center",d-=l/2):(c="left",d=this.left)):n==="right"?s?(d=this.left+o,r==="near"?c="right":r==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,r==="near"?c="left":r==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,n=this.options.position;if(n==="left"||n==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(n==="top"||n==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:n},left:r,top:s,width:o,height:i}=this;n&&(e.save(),e.fillStyle=n,e.fillRect(r,s,o,i),e.restore())}getLineWidthForValue(e){const n=this.options.grid;if(!this._isVisible()||!n.display)return 0;const s=this.ticks.findIndex(o=>o.value===e);return s>=0?n.setContext(this.getContext(s)).lineWidth:0}drawGrid(e){const n=this.options.grid,r=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let o,i;const a=(l,c,d)=>{!d.width||!d.color||(r.save(),r.lineWidth=d.width,r.strokeStyle=d.color,r.setLineDash(d.borderDash||[]),r.lineDashOffset=d.borderDashOffset,r.beginPath(),r.moveTo(l.x,l.y),r.lineTo(c.x,c.y),r.stroke(),r.restore())};if(n.display)for(o=0,i=s.length;o<i;++o){const l=s[o];n.drawOnChartArea&&a({x:l.x1,y:l.y1},{x:l.x2,y:l.y2},l),n.drawTicks&&a({x:l.tx1,y:l.ty1},{x:l.tx2,y:l.ty2},{color:l.tickColor,width:l.tickWidth,borderDash:l.tickBorderDash,borderDashOffset:l.tickBorderDashOffset})}}drawBorder(){const{chart:e,ctx:n,options:{border:r,grid:s}}=this,o=r.setContext(this.getContext()),i=r.display?o.width:0;if(!i)return;const a=s.setContext(this.getContext(0)).lineWidth,l=this._borderValue;let c,d,f,g;this.isHorizontal()?(c=tn(e,this.left,i)-i/2,d=tn(e,this.right,a)+a/2,f=g=l):(f=tn(e,this.top,i)-i/2,g=tn(e,this.bottom,a)+a/2,c=d=l),n.save(),n.lineWidth=o.width,n.strokeStyle=o.color,n.beginPath(),n.moveTo(c,f),n.lineTo(d,g),n.stroke(),n.restore()}drawLabels(e){if(!this.options.ticks.display)return;const r=this.ctx,s=this._computeLabelArea();s&&Ki(r,s);const o=this.getLabelItems(e);for(const i of o){const a=i.options,l=i.font,c=i.label,d=i.textOffset;pl(r,c,0,d,l,a)}s&&Xi(r)}drawTitle(){const{ctx:e,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=_t(r.font),i=Yt(r.padding),a=r.align;let l=o.lineHeight/2;n==="bottom"||n==="center"||ie(n)?(l+=i.bottom,Oe(r.text)&&(l+=o.lineHeight*(r.text.length-1))):l+=i.top;const{titleX:c,titleY:d,maxWidth:f,rotation:g}=ow(this,l,n,a);pl(e,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:g,textAlign:sw(a,n,s),textBaseline:"middle",translation:[c,d]})}draw(e){this._isVisible()&&(this.drawBackground(),this.drawGrid(e),this.drawBorder(),this.drawTitle(),this.drawLabels(e))}_layers(){const e=this.options,n=e.ticks&&e.ticks.z||0,r=pe(e.grid&&e.grid.z,-1),s=pe(e.border&&e.border.z,0);return!this._isVisible()||this.draw!==Un.prototype.draw?[{z:n,draw:o=>{this.draw(o)}}]:[{z:r,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:n,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(e){const n=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",s=[];let o,i;for(o=0,i=n.length;o<i;++o){const a=n[o];a[r]===this.id&&(!e||a.type===e)&&s.push(a)}return s}_resolveTickFontOptions(e){const n=this.options.ticks.setContext(this.getContext(e));return _t(n.font)}_maxDigits(){const e=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/e}}class ss{constructor(e,n,r){this.type=e,this.scope=n,this.override=r,this.items=Object.create(null)}isForType(e){return Object.prototype.isPrototypeOf.call(this.type.prototype,e.prototype)}register(e){const n=Object.getPrototypeOf(e);let r;lw(n)&&(r=this.register(n));const s=this.items,o=e.id,i=this.scope+"."+o;if(!o)throw new Error("class does not have id: "+e);return o in s||(s[o]=e,iw(e,i,r),this.override&&Te.override(e.id,e.overrides)),i}get(e){return this.items[e]}unregister(e){const n=this.items,r=e.id,s=this.scope;r in n&&delete n[r],s&&r in Te[s]&&(delete Te[s][r],this.override&&delete pn[r])}}function iw(t,e,n){const r=yr(Object.create(null),[n?Te.get(n):{},Te.get(e),t.defaults]);Te.set(e,r),t.defaultRoutes&&aw(e,t.defaultRoutes),t.descriptors&&Te.describe(e,t.descriptors)}function aw(t,e){Object.keys(e).forEach(n=>{const r=n.split("."),s=r.pop(),o=[t].concat(r).join("."),i=e[n].split("."),a=i.pop(),l=i.join(".");Te.route(o,s,l,a)})}function lw(t){return"id"in t&&"defaults"in t}class cw{constructor(){this.controllers=new ss(Zu,"datasets",!0),this.elements=new ss(jr,"elements"),this.plugins=new ss(Object,"plugins"),this.scales=new ss(Un,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,n,r){[...n].forEach(s=>{const o=r||this._getRegistryForType(s);r||o.isForType(s)||o===this.plugins&&s.id?this._exec(e,o,s):ge(s,i=>{const a=r||this._getRegistryForType(i);this._exec(e,a,i)})})}_exec(e,n,r){const s=Wi(e);Ne(r["before"+s],[],r),n[e](r),Ne(r["after"+s],[],r)}_getRegistryForType(e){for(let n=0;n<this._typedRegistries.length;n++){const r=this._typedRegistries[n];if(r.isForType(e))return r}return this.plugins}_get(e,n,r){const s=n.get(e);if(s===void 0)throw new Error('"'+e+'" is not a registered '+r+".");return s}}var mt=new cw;class dw{constructor(){this._init=void 0}notify(e,n,r,s){if(n==="beforeInit"&&(this._init=this._createDescriptors(e,!0),this._notify(this._init,e,"install")),this._init===void 0)return;const o=s?this._descriptors(e).filter(s):this._descriptors(e),i=this._notify(o,e,n,r);return n==="afterDestroy"&&(this._notify(o,e,"stop"),this._notify(this._init,e,"uninstall"),this._init=void 0),i}_notify(e,n,r,s){s=s||{};for(const o of e){const i=o.plugin,a=i[r],l=[n,s,o.options];if(Ne(a,l,i)===!1&&s.cancelable)return!1}return!0}invalidate(){xe(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(e){if(this._cache)return this._cache;const n=this._cache=this._createDescriptors(e);return this._notifyStateChanges(e),n}_createDescriptors(e,n){const r=e&&e.config,s=pe(r.options&&r.options.plugins,{}),o=uw(r);return s===!1&&!n?[]:hw(e,o,s,n)}_notifyStateChanges(e){const n=this._oldCache||[],r=this._cache,s=(o,i)=>o.filter(a=>!i.some(l=>a.plugin.id===l.plugin.id));this._notify(s(n,r),e,"stop"),this._notify(s(r,n),e,"start")}}function uw(t){const e={},n=[],r=Object.keys(mt.plugins.items);for(let o=0;o<r.length;o++)n.push(mt.getPlugin(r[o]));const s=t.plugins||[];for(let o=0;o<s.length;o++){const i=s[o];n.indexOf(i)===-1&&(n.push(i),e[i.id]=!0)}return{plugins:n,localIds:e}}function fw(t,e){return!e&&t===!1?null:t===!0?{}:t}function hw(t,{plugins:e,localIds:n},r,s){const o=[],i=t.getContext();for(const a of e){const l=a.id,c=fw(r[l],s);c!==null&&o.push({plugin:a,options:gw(t.config,{plugin:a,local:n[l]},c,i)})}return o}function gw(t,{plugin:e,local:n},r,s){const o=t.pluginScopeKeys(e),i=t.getOptionScopes(r,o);return n&&e.defaults&&i.push(e.defaults),t.createResolver(i,s,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ci(t,e){const n=Te.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||n.indexAxis||"x"}function mw(t,e){let n=t;return t==="_index_"?n=e:t==="_value_"&&(n=e==="x"?"y":"x"),n}function pw(t,e){return t===e?"_index_":"_value_"}function Vl(t){if(t==="x"||t==="y"||t==="r")return t}function yw(t){if(t==="top"||t==="bottom")return"x";if(t==="left"||t==="right")return"y"}function di(t,...e){if(Vl(t))return t;for(const n of e){const r=n.axis||yw(n.position)||t.length>1&&Vl(t[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function Gl(t,e,n){if(n[e+"AxisID"]===t)return{axis:e}}function bw(t,e){if(e.data&&e.data.datasets){const n=e.data.datasets.filter(r=>r.xAxisID===t||r.yAxisID===t);if(n.length)return Gl(t,"x",n[0])||Gl(t,"y",n[0])}return{}}function xw(t,e){const n=pn[t.type]||{scales:{}},r=e.scales||{},s=ci(t.type,e),o=Object.create(null);return Object.keys(r).forEach(i=>{const a=r[i];if(!ie(a))return console.error(`Invalid scale configuration for scale: ${i}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${i}`);const l=di(i,a,bw(i,t),Te.scales[a.type]),c=pw(l,s),d=n.scales||{};o[i]=ur(Object.create(null),[{axis:l},a,d[l],d[c]])}),t.data.datasets.forEach(i=>{const a=i.type||t.type,l=i.indexAxis||ci(a,e),d=(pn[a]||{}).scales||{};Object.keys(d).forEach(f=>{const g=mw(f,l),h=i[g+"AxisID"]||g;o[h]=o[h]||Object.create(null),ur(o[h],[{axis:g},r[h],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];ur(a,[Te.scales[a.type],Te.scale])}),o}function sf(t){const e=t.options||(t.options={});e.plugins=pe(e.plugins,{}),e.scales=xw(t,e)}function of(t){return t=t||{},t.datasets=t.datasets||[],t.labels=t.labels||[],t}function vw(t){return t=t||{},t.data=of(t.data),sf(t),t}const Ul=new Map,af=new Set;function os(t,e){let n=Ul.get(t);return n||(n=e(),Ul.set(t,n),af.add(n)),n}const tr=(t,e,n)=>{const r=Ms(e,n);r!==void 0&&t.add(r)};class ww{constructor(e){this._config=vw(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=of(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),sf(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return os(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,n){return os(`${e}.transition.${n}`,()=>[[`datasets.${e}.transitions.${n}`,`transitions.${n}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,n){return os(`${e}-${n}`,()=>[[`datasets.${e}.elements.${n}`,`datasets.${e}`,`elements.${n}`,""]])}pluginScopeKeys(e){const n=e.id,r=this.type;return os(`${r}-plugin-${n}`,()=>[[`plugins.${n}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,n){const r=this._scopeCache;let s=r.get(e);return(!s||n)&&(s=new Map,r.set(e,s)),s}getOptionScopes(e,n,r){const{options:s,type:o}=this,i=this._cachedScopes(e,r),a=i.get(n);if(a)return a;const l=new Set;n.forEach(d=>{e&&(l.add(e),d.forEach(f=>tr(l,e,f))),d.forEach(f=>tr(l,s,f)),d.forEach(f=>tr(l,pn[o]||{},f)),d.forEach(f=>tr(l,Te,f)),d.forEach(f=>tr(l,ai,f))});const c=Array.from(l);return c.length===0&&c.push(Object.create(null)),af.has(n)&&i.set(n,c),c}chartOptionScopes(){const{options:e,type:n}=this;return[e,pn[n]||{},Te.datasets[n]||{},{type:n},Te,ai]}resolveNamedOptions(e,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=Bl(this._resolverCache,e,s);let l=i;if(Sw(i,n)){o.$shared=!1,r=qt(r)?r():r;const c=this.createResolver(e,r,a);l=In(i,r,c)}for(const c of n)o[c]=l[c];return o}createResolver(e,n,r=[""],s){const{resolver:o}=Bl(this._resolverCache,e,r);return ie(n)?In(o,n,void 0,s):o}}function Bl(t,e,n){let r=t.get(e);r||(r=new Map,t.set(e,r));const s=n.join();let o=r.get(s);return o||(o={resolver:Ji(e,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const _w=t=>ie(t)&&Object.getOwnPropertyNames(t).some(e=>qt(t[e]));function Sw(t,e){const{isScriptable:n,isIndexable:r}=Vu(t);for(const s of e){const o=n(s),i=r(s),a=(i||o)&&t[s];if(o&&(qt(a)||_w(a))||i&&Oe(a))return!0}return!1}var Cw="4.5.1";const Rw=["top","bottom","left","right","chartArea"];function Hl(t,e){return t==="top"||t==="bottom"||Rw.indexOf(t)===-1&&e==="x"}function Wl(t,e){return function(n,r){return n[t]===r[t]?n[e]-r[e]:n[t]-r[t]}}function ql(t){const e=t.chart,n=e.options.animation;e.notifyPlugins("afterRender"),Ne(n&&n.onComplete,[t],e)}function Aw(t){const e=t.chart,n=e.options.animation;Ne(n&&n.onProgress,[t],e)}function lf(t){return ea()&&typeof t=="string"?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const bs={},Yl=t=>{const e=lf(t);return Object.values(bs).filter(n=>n.canvas===e).pop()};function Nw(t,e,n){const r=Object.keys(t);for(const s of r){const o=+s;if(o>=e){const i=t[s];delete t[s],(n>0||o>e)&&(t[o+n]=i)}}}function Ew(t,e,n,r){return!n||t.type==="mouseout"?null:r?e:t}let Ks=class{static defaults=Te;static instances=bs;static overrides=pn;static registry=mt;static version=Cw;static getChart=Yl;static register(...e){mt.add(...e),Kl()}static unregister(...e){mt.remove(...e),Kl()}constructor(e,n){const r=this.config=new ww(n),s=lf(e),o=Yl(s);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const i=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||Wv(s)),this.platform.updateConfig(r);const a=this.platform.acquireContext(s,i.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=Tx(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,this._options=i,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new dw,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Jx(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],bs[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}kt.listen(this,"complete",ql),kt.listen(this,"progress",Aw),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:n},width:r,height:s,_aspectRatio:o}=this;return xe(e)?n&&o?o:s?r/s:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return mt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():vl(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return ml(this.canvas,this.ctx),this}stop(){return kt.stop(this),this}resize(e,n){kt.running(this)?this._resizeBeforeDraw={width:e,height:n}:this._resize(e,n)}_resize(e,n){const r=this.options,s=this.canvas,o=r.maintainAspectRatio&&this.aspectRatio,i=this.platform.getMaximumSize(s,e,n,o),a=r.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=i.width,this.height=i.height,this._aspectRatio=this.aspectRatio,vl(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),Ne(r.onResize,[this,i],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};ge(n,(r,s)=>{r.id=s})}buildOrUpdateScales(){const e=this.options,n=e.scales,r=this.scales,s=Object.keys(r).reduce((i,a)=>(i[a]=!1,i),{});let o=[];n&&(o=o.concat(Object.keys(n).map(i=>{const a=n[i],l=di(i,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),ge(o,i=>{const a=i.options,l=a.id,c=di(l,a),d=pe(a.type,i.dtype);(a.position===void 0||Hl(a.position,c)!==Hl(i.dposition))&&(a.position=i.dposition),s[l]=!0;let f=null;if(l in r&&r[l].type===d)f=r[l];else{const g=mt.getScale(d);f=new g({id:l,type:d,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(a,e)}),ge(s,(i,a)=>{i||delete r[a]}),ge(r,i=>{ns.configure(this,i,i.options),ns.addBox(this,i)})}_updateMetasets(){const e=this._metasets,n=this.data.datasets.length,r=e.length;if(e.sort((s,o)=>s.index-o.index),r>n){for(let s=n;s<r;++s)this._destroyDatasetMeta(s);e.splice(n,r-n)}this._sortedMetasets=e.slice(0).sort(Wl("order","index"))}_removeUnreferencedMetasets(){const{_metasets:e,data:{datasets:n}}=this;e.length>n.length&&delete this._stacks,e.forEach((r,s)=>{n.filter(o=>o===r._dataset).length===0&&this._destroyDatasetMeta(s)})}buildOrUpdateControllers(){const e=[],n=this.data.datasets;let r,s;for(this._removeUnreferencedMetasets(),r=0,s=n.length;r<s;r++){const o=n[r];let i=this.getDatasetMeta(r);const a=o.type||this.config.type;if(i.type&&i.type!==a&&(this._destroyDatasetMeta(r),i=this.getDatasetMeta(r)),i.type=a,i.indexAxis=o.indexAxis||ci(a,this.options),i.order=o.order||0,i.index=r,i.label=""+o.label,i.visible=this.isDatasetVisible(r),i.controller)i.controller.updateIndex(r),i.controller.linkScales();else{const l=mt.getController(a),{datasetElementType:c,dataElementType:d}=Te.datasets[a];Object.assign(l,{dataElementType:mt.getElement(d),datasetElementType:c&&mt.getElement(c)}),i.controller=new l(this,r),e.push(i.controller)}}return this._updateMetasets(),e}_resetElements(){ge(this.data.datasets,(e,n)=>{this.getDatasetMeta(n).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const n=this.config;n.update();const r=this._options=n.createResolver(n.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let i=0;for(let c=0,d=this.data.datasets.length;c<d;c++){const{controller:f}=this.getDatasetMeta(c),g=!s&&o.indexOf(f)===-1;f.buildOrUpdateElements(g),i=Math.max(+f.getMaxOverflow(),i)}i=this._minPadding=r.layout.autoPadding?i:0,this._updateLayout(i),s||ge(o,c=>{c.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(Wl("z","_idx"));const{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){ge(this.scales,e=>{ns.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(e.events);(!sl(n,r)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,n=this._getUniformDataChanges()||[];for(const{method:r,start:s,count:o}of n){const i=r==="_removeElements"?-o:o;Nw(e,s,i)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const n=this.data.datasets.length,r=o=>new Set(e.filter(i=>i[0]===o).map((i,a)=>a+","+i.splice(1).join(","))),s=r(0);for(let o=1;o<n;o++)if(!sl(s,r(o)))return;return Array.from(s).map(o=>o.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;ns.update(this,this.width,this.height,e);const n=this.chartArea,r=n.width<=0||n.height<=0;this._layers=[],ge(this.boxes,s=>{r&&s.position==="chartArea"||(s.configure&&s.configure(),this._layers.push(...s._layers()))},this),this._layers.forEach((s,o)=>{s._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let n=0,r=this.data.datasets.length;n<r;++n)this.getDatasetMeta(n).controller.configure();for(let n=0,r=this.data.datasets.length;n<r;++n)this._updateDataset(n,qt(e)?e({datasetIndex:n}):e);this.notifyPlugins("afterDatasetsUpdate",{mode:e})}}_updateDataset(e,n){const r=this.getDatasetMeta(e),s={meta:r,index:e,mode:n,cancelable:!0};this.notifyPlugins("beforeDatasetUpdate",s)!==!1&&(r.controller._update(n),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){this.notifyPlugins("beforeRender",{cancelable:!0})!==!1&&(kt.has(this)?this.attached&&!kt.running(this)&&kt.start(this):(this.draw(),ql({chart:this})))}draw(){let e;if(this._resizeBeforeDraw){const{width:r,height:s}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(r,s)}if(this.clear(),this.width<=0||this.height<=0||this.notifyPlugins("beforeDraw",{cancelable:!0})===!1)return;const n=this._layers;for(e=0;e<n.length&&n[e].z<=0;++e)n[e].draw(this.chartArea);for(this._drawDatasets();e<n.length;++e)n[e].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(e){const n=this._sortedMetasets,r=[];let s,o;for(s=0,o=n.length;s<o;++s){const i=n[s];(!e||i.visible)&&r.push(i)}return r}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0})===!1)return;const e=this.getSortedVisibleDatasetMetas();for(let n=e.length-1;n>=0;--n)this._drawDataset(e[n]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const n=this.ctx,r={meta:e,index:e.index,cancelable:!0},s=Ku(this,e);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(s&&Ki(n,s),e.controller.draw(),s&&Xi(n),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(e){return xr(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,n,r,s){const o=Rv.modes[n];return typeof o=="function"?o(this,e,r,s):[]}getDatasetMeta(e){const n=this.data.datasets[e],r=this._metasets;let s=r.filter(o=>o&&o._dataset===n).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:n&&n.order||0,index:e,_dataset:n,_parsed:[],_sorted:!1},r.push(s)),s}getContext(){return this.$context||(this.$context=xn(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const n=this.data.datasets[e];if(!n)return!1;const r=this.getDatasetMeta(e);return typeof r.hidden=="boolean"?!r.hidden:!n.hidden}setDatasetVisibility(e,n){const r=this.getDatasetMeta(e);r.hidden=!n}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,n,r){const s=r?"show":"hide",o=this.getDatasetMeta(e),i=o.controller._resolveAnimations(void 0,s);js(n)?(o.data[n].hidden=!r,this.update()):(this.setDatasetVisibility(e,r),i.update(o,{visible:r}),this.update(a=>a.datasetIndex===e?s:void 0))}hide(e,n){this._updateVisibility(e,n,!1)}show(e,n){this._updateVisibility(e,n,!0)}_destroyDatasetMeta(e){const n=this._metasets[e];n&&n.controller&&n.controller._destroy(),delete this._metasets[e]}_stop(){let e,n;for(this.stop(),kt.remove(this),e=0,n=this.data.datasets.length;e<n;++e)this._destroyDatasetMeta(e)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:e,ctx:n}=this;this._stop(),this.config.clearCache(),e&&(this.unbindEvents(),ml(e,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete bs[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...e){return this.canvas.toDataURL(...e)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const e=this._listeners,n=this.platform,r=(o,i)=>{n.addEventListener(this,o,i),e[o]=i},s=(o,i,a)=>{o.offsetX=i,o.offsetY=a,this._eventHandler(o)};ge(this.options.events,o=>r(o,s))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,n=this.platform,r=(l,c)=>{n.addEventListener(this,l,c),e[l]=c},s=(l,c)=>{e[l]&&(n.removeEventListener(this,l,c),delete e[l])},o=(l,c)=>{this.canvas&&this.resize(l,c)};let i;const a=()=>{s("attach",a),this.attached=!0,this.resize(),r("resize",o),r("detach",i)};i=()=>{this.attached=!1,s("resize",o),this._stop(),this._resize(0,0),r("attach",a)},n.isAttached(this.canvas)?a():i()}unbindEvents(){ge(this._listeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._listeners={},ge(this._responsiveListeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,n,r){const s=r?"set":"remove";let o,i,a,l;for(n==="dataset"&&(o=this.getDatasetMeta(e[0].datasetIndex),o.controller["_"+s+"DatasetHoverStyle"]()),a=0,l=e.length;a<l;++a){i=e[a];const c=i&&this.getDatasetMeta(i.datasetIndex).controller;c&&c[s+"HoverStyle"](i.element,i.datasetIndex,i.index)}}getActiveElements(){return this._active||[]}setActiveElements(e){const n=this._active||[],r=e.map(({datasetIndex:o,index:i})=>{const a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[i],index:i}});!ks(r,n)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,n))}notifyPlugins(e,n,r){return this._plugins.notify(this,e,n,r)}isPluginEnabled(e){return this._plugins._cache.filter(n=>n.plugin.id===e).length===1}_updateHoverStyles(e,n,r){const s=this.options.hover,o=(l,c)=>l.filter(d=>!c.some(f=>d.datasetIndex===f.datasetIndex&&d.index===f.index)),i=o(n,e),a=r?e:o(e,n);i.length&&this.updateHoverStyle(i,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(e,n){const r={event:e,replay:n,cancelable:!0,inChartArea:this.isPointInArea(e)},s=i=>(i.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",r,s)===!1)return;const o=this._handleEvent(e,n,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,s),(o||r.changed)&&this.render(),this}_handleEvent(e,n,r){const{_active:s=[],options:o}=this,i=n,a=this._getActiveElements(e,s,r,i),l=Px(e),c=Ew(e,this._lastEvent,r,l);r&&(this._lastEvent=null,Ne(o.onHover,[e,a,this],this),l&&Ne(o.onClick,[e,a,this],this));const d=!ks(a,s);return(d||n)&&(this._active=a,this._updateHoverStyles(a,s,n)),this._lastEvent=c,d}_getActiveElements(e,n,r,s){if(e.type==="mouseout")return[];if(!r)return n;const o=this.options.hover;return this.getElementsAtEventForMode(e,o.mode,o,s)}};function Kl(){return ge(Ks.instances,t=>t._plugins.invalidate())}function cf(t,e,n=e){t.lineCap=pe(n.borderCapStyle,e.borderCapStyle),t.setLineDash(pe(n.borderDash,e.borderDash)),t.lineDashOffset=pe(n.borderDashOffset,e.borderDashOffset),t.lineJoin=pe(n.borderJoinStyle,e.borderJoinStyle),t.lineWidth=pe(n.borderWidth,e.borderWidth),t.strokeStyle=pe(n.borderColor,e.borderColor)}function kw(t,e,n){t.lineTo(n.x,n.y)}function Tw(t){return t.stepped?f0:t.tension||t.cubicInterpolationMode==="monotone"?h0:kw}function df(t,e,n={}){const r=t.length,{start:s=0,end:o=r-1}=n,{start:i,end:a}=e,l=Math.max(s,i),c=Math.min(o,a),d=s<i&&o<i||s>a&&o>a;return{count:r,start:l,loop:e.loop,ilen:c<l&&!d?r+c-l:c-l}}function Mw(t,e,n,r){const{points:s,options:o}=e,{count:i,start:a,loop:l,ilen:c}=df(s,n,r),d=Tw(o);let{move:f=!0,reverse:g}=r||{},h,m,p;for(h=0;h<=c;++h)m=s[(a+(g?c-h:h))%i],!m.skip&&(f?(t.moveTo(m.x,m.y),f=!1):d(t,p,m,g,o.stepped),p=m);return l&&(m=s[(a+(g?c:0))%i],d(t,p,m,g,o.stepped)),!!l}function jw(t,e,n,r){const s=e.points,{count:o,start:i,ilen:a}=df(s,n,r),{move:l=!0,reverse:c}=r||{};let d=0,f=0,g,h,m,p,y,b;const w=S=>(i+(c?a-S:S))%o,v=()=>{p!==y&&(t.lineTo(d,y),t.lineTo(d,p),t.lineTo(d,b))};for(l&&(h=s[w(0)],t.moveTo(h.x,h.y)),g=0;g<=a;++g){if(h=s[w(g)],h.skip)continue;const S=h.x,_=h.y,A=S|0;A===m?(_<p?p=_:_>y&&(y=_),d=(f*d+S)/++f):(v(),t.lineTo(S,_),m=A,f=0,p=y=_),b=_}v()}function ui(t){const e=t.options,n=e.borderDash&&e.borderDash.length;return!t._decimated&&!t._loop&&!e.tension&&e.cubicInterpolationMode!=="monotone"&&!e.stepped&&!n?jw:Mw}function $w(t){return t.stepped?W0:t.tension||t.cubicInterpolationMode==="monotone"?q0:on}function Ow(t,e,n,r){let s=e._path;s||(s=e._path=new Path2D,e.path(s,n,r)&&s.closePath()),cf(t,e.options),t.stroke(s)}function Iw(t,e,n,r){const{segments:s,options:o}=e,i=ui(e);for(const a of s)cf(t,o,a.style),t.beginPath(),i(t,e,a,{start:n,end:n+r-1})&&t.closePath(),t.stroke()}const Pw=typeof Path2D=="function";function Fw(t,e,n,r){Pw&&!e.options.segment?Ow(t,e,n,r):Iw(t,e,n,r)}class Xs extends jr{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:e=>e!=="borderDash"&&e!=="fill"};constructor(e){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,e&&Object.assign(this,e)}updateControlPoints(e,n){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const s=r.spanGaps?this._loop:this._fullLoop;D0(this._points,r,e,s,n),this._pointsUpdated=!0}}set points(e){this._points=e,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=tv(this,this.options.segment))}first(){const e=this.segments,n=this.points;return e.length&&n[e[0].start]}last(){const e=this.segments,n=this.points,r=e.length;return r&&n[e[r-1].end]}interpolate(e,n){const r=this.options,s=e[n],o=this.points,i=Yu(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],l=$w(r);let c,d;for(c=0,d=i.length;c<d;++c){const{start:f,end:g}=i[c],h=o[f],m=o[g];if(h===m){a.push(h);continue}const p=Math.abs((s-h[n])/(m[n]-h[n])),y=l(h,m,p,r.stepped);y[n]=e[n],a.push(y)}return a.length===1?a[0]:a}pathSegment(e,n,r){return ui(this)(e,this,n,r)}path(e,n,r){const s=this.segments,o=ui(this);let i=this._loop;n=n||0,r=r||this.points.length-n;for(const a of s)i&=o(e,this,a,{start:n,end:n+r-1});return!!i}draw(e,n,r,s){const o=this.options||{};(this.points||[]).length&&o.borderWidth&&(e.save(),Fw(e,this,r,s),e.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function Xl(t,e,n,r){const s=t.options,{[n]:o}=t.getProps([n],r);return Math.abs(e-o)<s.radius+s.hitRadius}class Dw extends jr{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(e){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,e&&Object.assign(this,e)}inRange(e,n,r){const s=this.options,{x:o,y:i}=this.getProps(["x","y"],r);return Math.pow(e-o,2)+Math.pow(n-i,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(e,n){return Xl(this,e,"x",n)}inYRange(e,n){return Xl(this,e,"y",n)}getCenterPoint(e){const{x:n,y:r}=this.getProps(["x","y"],e);return{x:n,y:r}}size(e){e=e||this.options||{};let n=e.radius||0;n=Math.max(n,n&&e.hoverRadius||0);const r=n&&e.borderWidth||0;return(n+r)*2}draw(e,n){const r=this.options;this.skip||r.radius<.1||!xr(this,n,this.size(r)/2)||(e.strokeStyle=r.borderColor,e.lineWidth=r.borderWidth,e.fillStyle=r.backgroundColor,li(e,r,this.x,this.y))}getRange(){const e=this.options||{};return e.radius+e.hitRadius}}function Lw(t,e,n){const r=t.segments,s=t.points,o=e.points,i=[];for(const a of r){let{start:l,end:c}=a;c=Js(l,c,s);const d=fi(n,s[l],s[c],a.loop);if(!e.segments){i.push({source:a,target:d,start:s[l],end:s[c]});continue}const f=Yu(e,d);for(const g of f){const h=fi(n,o[g.start],o[g.end],g.loop),m=qu(a,s,h);for(const p of m)i.push({source:p,target:g,start:{[n]:Jl(d,h,"start",Math.max)},end:{[n]:Jl(d,h,"end",Math.min)}})}}return i}function fi(t,e,n,r){if(r)return;let s=e[t],o=n[t];return t==="angle"&&(s=pt(s),o=pt(o)),{property:t,start:s,end:o}}function zw(t,e){const{x:n=null,y:r=null}=t||{},s=e.points,o=[];return e.segments.forEach(({start:i,end:a})=>{a=Js(i,a,s);const l=s[i],c=s[a];r!==null?(o.push({x:l.x,y:r}),o.push({x:c.x,y:r})):n!==null&&(o.push({x:n,y:l.y}),o.push({x:n,y:c.y}))}),o}function Js(t,e,n){for(;e>t;e--){const r=n[e];if(!isNaN(r.x)&&!isNaN(r.y))break}return e}function Jl(t,e,n,r){return t&&e?r(t[n],e[n]):t?t[n]:e?e[n]:0}function uf(t,e){let n=[],r=!1;return Oe(t)?(r=!0,n=t):n=zw(t,e),n.length?new Xs({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function Zl(t){return t&&t.fill!==!1}function Vw(t,e,n){let s=t[e].fill;const o=[e];let i;if(!n)return s;for(;s!==!1&&o.indexOf(s)===-1;){if(!Ue(s))return s;if(i=t[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function Gw(t,e,n){const r=Ww(t);if(ie(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return Ue(s)&&Math.floor(s)===s?Uw(r[0],e,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function Uw(t,e,n,r){return(t==="-"||t==="+")&&(n=e+n),n===e||n<0||n>=r?!1:n}function Bw(t,e){let n=null;return t==="start"?n=e.bottom:t==="end"?n=e.top:ie(t)?n=e.getPixelForValue(t.value):e.getBasePixel&&(n=e.getBasePixel()),n}function Hw(t,e,n){let r;return t==="start"?r=n:t==="end"?r=e.options.reverse?e.min:e.max:ie(t)?r=t.value:r=e.getBaseValue(),r}function Ww(t){const e=t.options,n=e.fill;let r=pe(n&&n.target,n);return r===void 0&&(r=!!e.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function qw(t){const{scale:e,index:n,line:r}=t,s=[],o=r.segments,i=r.points,a=Yw(e,n);a.push(uf({x:null,y:e.bottom},r));for(let l=0;l<o.length;l++){const c=o[l];for(let d=c.start;d<=c.end;d++)Kw(s,i[d],a)}return new Xs({points:s,options:{}})}function Yw(t,e){const n=[],r=t.getMatchingVisibleMetas("line");for(let s=0;s<r.length;s++){const o=r[s];if(o.index===e)break;o.hidden||n.unshift(o.dataset)}return n}function Kw(t,e,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:l}=Xw(o,e,"x");if(!(!l||i&&a)){if(i)r.unshift(l);else if(t.push(l),!a)break}}t.push(...r)}function Xw(t,e,n){const r=t.interpolate(e,n);if(!r)return{};const s=r[n],o=t.segments,i=t.points;let a=!1,l=!1;for(let c=0;c<o.length;c++){const d=o[c],f=i[d.start][n],g=i[d.end][n];if(Ou(s,f,g)){a=s===f,l=s===g;break}}return{first:a,last:l,point:r}}class ff{constructor(e){this.x=e.x,this.y=e.y,this.radius=e.radius}pathSegment(e,n,r){const{x:s,y:o,radius:i}=this;return n=n||{start:0,end:St},e.arc(s,o,i,n.end,n.start,!0),!r.bounds}interpolate(e){const{x:n,y:r,radius:s}=this,o=e.angle;return{x:n+Math.cos(o)*s,y:r+Math.sin(o)*s,angle:o}}}function Jw(t){const{chart:e,fill:n,line:r}=t;if(Ue(n))return Zw(e,n);if(n==="stack")return qw(t);if(n==="shape")return!0;const s=Qw(t);return s instanceof ff?s:uf(s,r)}function Zw(t,e){const n=t.getDatasetMeta(e);return n&&t.isDatasetVisible(e)?n.dataset:null}function Qw(t){return(t.scale||{}).getPointPositionForValue?t_(t):e_(t)}function e_(t){const{scale:e={},fill:n}=t,r=Bw(n,e);if(Ue(r)){const s=e.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function t_(t){const{scale:e,fill:n}=t,r=e.options,s=e.getLabels().length,o=r.reverse?e.max:e.min,i=Hw(n,e,o),a=[];if(r.grid.circular){const l=e.getPointPositionForValue(0,o);return new ff({x:l.x,y:l.y,radius:e.getDistanceFromCenterForValue(i)})}for(let l=0;l<s;++l)a.push(e.getPointPositionForValue(l,i));return a}function Io(t,e,n){const r=Jw(e),{chart:s,index:o,line:i,scale:a,axis:l}=e,c=i.options,d=c.fill,f=c.backgroundColor,{above:g=f,below:h=f}=d||{},m=s.getDatasetMeta(o),p=Ku(s,m);r&&i.points.length&&(Ki(t,n),n_(t,{line:i,target:r,above:g,below:h,area:n,scale:a,axis:l,clip:p}),Xi(t))}function n_(t,e){const{line:n,target:r,above:s,below:o,area:i,scale:a,clip:l}=e,c=n._loop?"angle":e.axis;t.save();let d=o;o!==s&&(c==="x"?(Ql(t,r,i.top),Po(t,{line:n,target:r,color:s,scale:a,property:c,clip:l}),t.restore(),t.save(),Ql(t,r,i.bottom)):c==="y"&&(ec(t,r,i.left),Po(t,{line:n,target:r,color:o,scale:a,property:c,clip:l}),t.restore(),t.save(),ec(t,r,i.right),d=s)),Po(t,{line:n,target:r,color:d,scale:a,property:c,clip:l}),t.restore()}function Ql(t,e,n){const{segments:r,points:s}=e;let o=!0,i=!1;t.beginPath();for(const a of r){const{start:l,end:c}=a,d=s[l],f=s[Js(l,c,s)];o?(t.moveTo(d.x,d.y),o=!1):(t.lineTo(d.x,n),t.lineTo(d.x,d.y)),i=!!e.pathSegment(t,a,{move:i}),i?t.closePath():t.lineTo(f.x,n)}t.lineTo(e.first().x,n),t.closePath(),t.clip()}function ec(t,e,n){const{segments:r,points:s}=e;let o=!0,i=!1;t.beginPath();for(const a of r){const{start:l,end:c}=a,d=s[l],f=s[Js(l,c,s)];o?(t.moveTo(d.x,d.y),o=!1):(t.lineTo(n,d.y),t.lineTo(d.x,d.y)),i=!!e.pathSegment(t,a,{move:i}),i?t.closePath():t.lineTo(n,f.y)}t.lineTo(n,e.first().y),t.closePath(),t.clip()}function Po(t,e){const{line:n,target:r,property:s,color:o,scale:i,clip:a}=e,l=Lw(n,r,s);for(const{source:c,target:d,start:f,end:g}of l){const{style:{backgroundColor:h=o}={}}=c,m=r!==!0;t.save(),t.fillStyle=h,r_(t,i,a,m&&fi(s,f,g)),t.beginPath();const p=!!n.pathSegment(t,c);let y;if(m){p?t.closePath():tc(t,r,g,s);const b=!!r.pathSegment(t,d,{move:p,reverse:!0});y=p&&b,y||tc(t,r,f,s)}t.closePath(),t.fill(y?"evenodd":"nonzero"),t.restore()}}function r_(t,e,n,r){const s=e.chart.chartArea,{property:o,start:i,end:a}=r||{};if(o==="x"||o==="y"){let l,c,d,f;o==="x"?(l=i,c=s.top,d=a,f=s.bottom):(l=s.left,c=i,d=s.right,f=a),t.beginPath(),n&&(l=Math.max(l,n.left),d=Math.min(d,n.right),c=Math.max(c,n.top),f=Math.min(f,n.bottom)),t.rect(l,c,d-l,f-c),t.clip()}}function tc(t,e,n,r){const s=e.interpolate(n,r);s&&t.lineTo(s.x,s.y)}var s_={id:"filler",afterDatasetsUpdate(t,e,n){const r=(t.data.datasets||[]).length,s=[];let o,i,a,l;for(i=0;i<r;++i)o=t.getDatasetMeta(i),a=o.dataset,l=null,a&&a.options&&a instanceof Xs&&(l={visible:t.isDatasetVisible(i),index:i,fill:Gw(a,i,r),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:a}),o.$filler=l,s.push(l);for(i=0;i<r;++i)l=s[i],!(!l||l.fill===!1)&&(l.fill=Vw(s,i,n.propagate))},beforeDraw(t,e,n){const r=n.drawTime==="beforeDraw",s=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let i=s.length-1;i>=0;--i){const a=s[i].$filler;a&&(a.line.updateControlPoints(o,a.axis),r&&a.fill&&Io(t.ctx,a,o))}},beforeDatasetsDraw(t,e,n){if(n.drawTime!=="beforeDatasetsDraw")return;const r=t.getSortedVisibleDatasetMetas();for(let s=r.length-1;s>=0;--s){const o=r[s].$filler;Zl(o)&&Io(t.ctx,o,t.chartArea)}},beforeDatasetDraw(t,e,n){const r=e.meta.$filler;!Zl(r)||n.drawTime!=="beforeDatasetDraw"||Io(t.ctx,r,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const cr={average(t){if(!t.length)return!1;let e,n,r=new Set,s=0,o=0;for(e=0,n=t.length;e<n;++e){const a=t[e].element;if(a&&a.hasValue()){const l=a.tooltipPosition();r.add(l.x),s+=l.y,++o}}return o===0||r.size===0?!1:{x:[...r].reduce((a,l)=>a+l)/r.size,y:s/o}},nearest(t,e){if(!t.length)return!1;let n=e.x,r=e.y,s=Number.POSITIVE_INFINITY,o,i,a;for(o=0,i=t.length;o<i;++o){const l=t[o].element;if(l&&l.hasValue()){const c=l.getCenterPoint(),d=ii(e,c);d<s&&(s=d,a=l)}}if(a){const l=a.tooltipPosition();n=l.x,r=l.y}return{x:n,y:r}}};function gt(t,e){return e&&(Oe(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Tt(t){return(typeof t=="string"||t instanceof String)&&t.indexOf(`
76
+ `)>-1?t.split(`
77
+ `):t}function o_(t,e){const{element:n,datasetIndex:r,index:s}=e,o=t.getDatasetMeta(r).controller,{label:i,value:a}=o.getLabelAndValue(s);return{chart:t,label:i,parsed:o.getParsed(s),raw:t.data.datasets[r].data[s],formattedValue:a,dataset:o.getDataset(),dataIndex:s,datasetIndex:r,element:n}}function nc(t,e){const n=t.chart.ctx,{body:r,footer:s,title:o}=t,{boxWidth:i,boxHeight:a}=e,l=_t(e.bodyFont),c=_t(e.titleFont),d=_t(e.footerFont),f=o.length,g=s.length,h=r.length,m=Yt(e.padding);let p=m.height,y=0,b=r.reduce((S,_)=>S+_.before.length+_.lines.length+_.after.length,0);if(b+=t.beforeBody.length+t.afterBody.length,f&&(p+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),b){const S=e.displayColors?Math.max(a,l.lineHeight):l.lineHeight;p+=h*S+(b-h)*l.lineHeight+(b-1)*e.bodySpacing}g&&(p+=e.footerMarginTop+g*d.lineHeight+(g-1)*e.footerSpacing);let w=0;const v=function(S){y=Math.max(y,n.measureText(S).width+w)};return n.save(),n.font=c.string,ge(t.title,v),n.font=l.string,ge(t.beforeBody.concat(t.afterBody),v),w=e.displayColors?i+2+e.boxPadding:0,ge(r,S=>{ge(S.before,v),ge(S.lines,v),ge(S.after,v)}),w=0,n.font=d.string,ge(t.footer,v),n.restore(),y+=m.width,{width:y,height:p}}function i_(t,e){const{y:n,height:r}=e;return n<r/2?"top":n>t.height-r/2?"bottom":"center"}function a_(t,e,n,r){const{x:s,width:o}=r,i=n.caretSize+n.caretPadding;if(t==="left"&&s+o+i>e.width||t==="right"&&s-o-i<0)return!0}function l_(t,e,n,r){const{x:s,width:o}=n,{width:i,chartArea:{left:a,right:l}}=t;let c="center";return r==="center"?c=s<=(a+l)/2?"left":"right":s<=o/2?c="left":s>=i-o/2&&(c="right"),a_(c,t,e,n)&&(c="center"),c}function rc(t,e,n){const r=n.yAlign||e.yAlign||i_(t,n);return{xAlign:n.xAlign||e.xAlign||l_(t,e,n,r),yAlign:r}}function c_(t,e){let{x:n,width:r}=t;return e==="right"?n-=r:e==="center"&&(n-=r/2),n}function d_(t,e,n){let{y:r,height:s}=t;return e==="top"?r+=n:e==="bottom"?r-=s+n:r-=s/2,r}function sc(t,e,n,r){const{caretSize:s,caretPadding:o,cornerRadius:i}=t,{xAlign:a,yAlign:l}=n,c=s+o,{topLeft:d,topRight:f,bottomLeft:g,bottomRight:h}=ps(i);let m=c_(e,a);const p=d_(e,l,c);return l==="center"?a==="left"?m+=c:a==="right"&&(m-=c):a==="left"?m-=Math.max(d,g)+s:a==="right"&&(m+=Math.max(f,h)+s),{x:it(m,0,r.width-e.width),y:it(p,0,r.height-e.height)}}function is(t,e,n){const r=Yt(n.padding);return e==="center"?t.x+t.width/2:e==="right"?t.x+t.width-r.right:t.x+r.left}function oc(t){return gt([],Tt(t))}function u_(t,e,n){return xn(t,{tooltip:e,tooltipItems:n,type:"tooltip"})}function ic(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const hf={beforeTitle:Et,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,r=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex<r)return n[e.dataIndex]}return""},afterTitle:Et,beforeBody:Et,beforeLabel:Et,label(t){if(this&&this.options&&this.options.mode==="dataset")return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const n=t.formattedValue;return xe(n)||(e+=n),e},labelColor(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:n.borderColor,backgroundColor:n.backgroundColor,borderWidth:n.borderWidth,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:n.pointStyle,rotation:n.rotation}},afterLabel:Et,afterBody:Et,beforeFooter:Et,footer:Et,afterFooter:Et};function He(t,e,n,r){const s=t[e].call(n,r);return typeof s>"u"?hf[e].call(n,r):s}class ac extends jr{static positioners=cr;constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const n=this.chart,r=this.options.setContext(this.getContext()),s=r.enabled&&n.options.animation&&r.animations,o=new Xu(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=u_(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,n){const{callbacks:r}=n,s=He(r,"beforeTitle",this,e),o=He(r,"title",this,e),i=He(r,"afterTitle",this,e);let a=[];return a=gt(a,Tt(s)),a=gt(a,Tt(o)),a=gt(a,Tt(i)),a}getBeforeBody(e,n){return oc(He(n.callbacks,"beforeBody",this,e))}getBody(e,n){const{callbacks:r}=n,s=[];return ge(e,o=>{const i={before:[],lines:[],after:[]},a=ic(r,o);gt(i.before,Tt(He(a,"beforeLabel",this,o))),gt(i.lines,He(a,"label",this,o)),gt(i.after,Tt(He(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(e,n){return oc(He(n.callbacks,"afterBody",this,e))}getFooter(e,n){const{callbacks:r}=n,s=He(r,"beforeFooter",this,e),o=He(r,"footer",this,e),i=He(r,"afterFooter",this,e);let a=[];return a=gt(a,Tt(s)),a=gt(a,Tt(o)),a=gt(a,Tt(i)),a}_createItems(e){const n=this._active,r=this.chart.data,s=[],o=[],i=[];let a=[],l,c;for(l=0,c=n.length;l<c;++l)a.push(o_(this.chart,n[l]));return e.filter&&(a=a.filter((d,f,g)=>e.filter(d,f,g,r))),e.itemSort&&(a=a.sort((d,f)=>e.itemSort(d,f,r))),ge(a,d=>{const f=ic(e.callbacks,d);s.push(He(f,"labelColor",this,d)),o.push(He(f,"labelPointStyle",this,d)),i.push(He(f,"labelTextColor",this,d))}),this.labelColors=s,this.labelPointStyles=o,this.labelTextColors=i,this.dataPoints=a,a}update(e,n){const r=this.options.setContext(this.getContext()),s=this._active;let o,i=[];if(!s.length)this.opacity!==0&&(o={opacity:0});else{const a=cr[r.position].call(this,s,this._eventPosition);i=this._createItems(r),this.title=this.getTitle(i,r),this.beforeBody=this.getBeforeBody(i,r),this.body=this.getBody(i,r),this.afterBody=this.getAfterBody(i,r),this.footer=this.getFooter(i,r);const l=this._size=nc(this,r),c=Object.assign({},a,l),d=rc(this.chart,r,c),f=sc(r,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:f.x,y:f.y,width:l.width,height:l.height,caretX:a.x,caretY:a.y}}this._tooltipItems=i,this.$context=void 0,o&&this._resolveAnimations().update(this,o),e&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(e,n,r,s){const o=this.getCaretPosition(e,r,s);n.lineTo(o.x1,o.y1),n.lineTo(o.x2,o.y2),n.lineTo(o.x3,o.y3)}getCaretPosition(e,n,r){const{xAlign:s,yAlign:o}=this,{caretSize:i,cornerRadius:a}=r,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:f}=ps(a),{x:g,y:h}=e,{width:m,height:p}=n;let y,b,w,v,S,_;return o==="center"?(S=h+p/2,s==="left"?(y=g,b=y-i,v=S+i,_=S-i):(y=g+m,b=y+i,v=S-i,_=S+i),w=y):(s==="left"?b=g+Math.max(l,d)+i:s==="right"?b=g+m-Math.max(c,f)-i:b=this.caretX,o==="top"?(v=h,S=v-i,y=b-i,w=b+i):(v=h+p,S=v+i,y=b+i,w=b-i),_=v),{x1:y,x2:b,x3:w,y1:v,y2:S,y3:_}}drawTitle(e,n,r){const s=this.title,o=s.length;let i,a,l;if(o){const c=Eo(r.rtl,this.x,this.width);for(e.x=is(this,r.titleAlign,r),n.textAlign=c.textAlign(r.titleAlign),n.textBaseline="middle",i=_t(r.titleFont),a=r.titleSpacing,n.fillStyle=r.titleColor,n.font=i.string,l=0;l<o;++l)n.fillText(s[l],c.x(e.x),e.y+i.lineHeight/2),e.y+=i.lineHeight+a,l+1===o&&(e.y+=r.titleMarginBottom-a)}}_drawColorBox(e,n,r,s,o){const i=this.labelColors[r],a=this.labelPointStyles[r],{boxHeight:l,boxWidth:c}=o,d=_t(o.bodyFont),f=is(this,"left",o),g=s.x(f),h=l<d.lineHeight?(d.lineHeight-l)/2:0,m=n.y+h;if(o.usePointStyle){const p={radius:Math.min(c,l)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},y=s.leftForLtr(g,c)+c/2,b=m+l/2;e.strokeStyle=o.multiKeyBackground,e.fillStyle=o.multiKeyBackground,li(e,p,y,b),e.strokeStyle=i.borderColor,e.fillStyle=i.backgroundColor,li(e,p,y,b)}else{e.lineWidth=ie(i.borderWidth)?Math.max(...Object.values(i.borderWidth)):i.borderWidth||1,e.strokeStyle=i.borderColor,e.setLineDash(i.borderDash||[]),e.lineDashOffset=i.borderDashOffset||0;const p=s.leftForLtr(g,c),y=s.leftForLtr(s.xPlus(g,1),c-2),b=ps(i.borderRadius);Object.values(b).some(w=>w!==0)?(e.beginPath(),e.fillStyle=o.multiKeyBackground,yl(e,{x:p,y:m,w:c,h:l,radius:b}),e.fill(),e.stroke(),e.fillStyle=i.backgroundColor,e.beginPath(),yl(e,{x:y,y:m+1,w:c-2,h:l-2,radius:b}),e.fill()):(e.fillStyle=o.multiKeyBackground,e.fillRect(p,m,c,l),e.strokeRect(p,m,c,l),e.fillStyle=i.backgroundColor,e.fillRect(y,m+1,c-2,l-2))}e.fillStyle=this.labelTextColors[r]}drawBody(e,n,r){const{body:s}=this,{bodySpacing:o,bodyAlign:i,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=r,f=_t(r.bodyFont);let g=f.lineHeight,h=0;const m=Eo(r.rtl,this.x,this.width),p=function(R){n.fillText(R,m.x(e.x+h),e.y+g/2),e.y+=g+o},y=m.textAlign(i);let b,w,v,S,_,A,C;for(n.textAlign=i,n.textBaseline="middle",n.font=f.string,e.x=is(this,y,r),n.fillStyle=r.bodyColor,ge(this.beforeBody,p),h=a&&y!=="right"?i==="center"?c/2+d:c+2+d:0,S=0,A=s.length;S<A;++S){for(b=s[S],w=this.labelTextColors[S],n.fillStyle=w,ge(b.before,p),v=b.lines,a&&v.length&&(this._drawColorBox(n,e,S,m,r),g=Math.max(f.lineHeight,l)),_=0,C=v.length;_<C;++_)p(v[_]),g=f.lineHeight;ge(b.after,p)}h=0,g=f.lineHeight,ge(this.afterBody,p),e.y-=o}drawFooter(e,n,r){const s=this.footer,o=s.length;let i,a;if(o){const l=Eo(r.rtl,this.x,this.width);for(e.x=is(this,r.footerAlign,r),e.y+=r.footerMarginTop,n.textAlign=l.textAlign(r.footerAlign),n.textBaseline="middle",i=_t(r.footerFont),n.fillStyle=r.footerColor,n.font=i.string,a=0;a<o;++a)n.fillText(s[a],l.x(e.x),e.y+i.lineHeight/2),e.y+=i.lineHeight+r.footerSpacing}}drawBackground(e,n,r,s){const{xAlign:o,yAlign:i}=this,{x:a,y:l}=e,{width:c,height:d}=r,{topLeft:f,topRight:g,bottomLeft:h,bottomRight:m}=ps(s.cornerRadius);n.fillStyle=s.backgroundColor,n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.beginPath(),n.moveTo(a+f,l),i==="top"&&this.drawCaret(e,n,r,s),n.lineTo(a+c-g,l),n.quadraticCurveTo(a+c,l,a+c,l+g),i==="center"&&o==="right"&&this.drawCaret(e,n,r,s),n.lineTo(a+c,l+d-m),n.quadraticCurveTo(a+c,l+d,a+c-m,l+d),i==="bottom"&&this.drawCaret(e,n,r,s),n.lineTo(a+h,l+d),n.quadraticCurveTo(a,l+d,a,l+d-h),i==="center"&&o==="left"&&this.drawCaret(e,n,r,s),n.lineTo(a,l+f),n.quadraticCurveTo(a,l,a+f,l),n.closePath(),n.fill(),s.borderWidth>0&&n.stroke()}_updateAnimationTarget(e){const n=this.chart,r=this.$animations,s=r&&r.x,o=r&&r.y;if(s||o){const i=cr[e.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=nc(this,e),l=Object.assign({},i,this._size),c=rc(n,e,l),d=sc(e,l,c,n);(s._to!==d.x||o._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(e){const n=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(n);const s={width:this.width,height:this.height},o={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const i=Yt(n.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&a&&(e.save(),e.globalAlpha=r,this.drawBackground(o,e,s,n),X0(e,n.textDirection),o.y+=i.top,this.drawTitle(o,e,n),this.drawBody(o,e,n),this.drawFooter(o,e,n),J0(e,n.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,n){const r=this._active,s=e.map(({datasetIndex:a,index:l})=>{const c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),o=!ks(r,s),i=this._positionChanged(s,n);(o||i)&&(this._active=s,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,n,r=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,o=this._active||[],i=this._getActiveElements(e,o,n,r),a=this._positionChanged(i,e),l=n||!ks(i,o)||a;return l&&(this._active=i,(s.enabled||s.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,n))),l}_getActiveElements(e,n,r,s){const o=this.options;if(e.type==="mouseout")return[];if(!s)return n.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);const i=this.chart.getElementsAtEventForMode(e,o.mode,o,r);return o.reverse&&i.reverse(),i}_positionChanged(e,n){const{caretX:r,caretY:s,options:o}=this,i=cr[o.position].call(this,e,n);return i!==!1&&(r!==i.x||s!==i.y)}}var f_={id:"tooltip",_element:ac,positioners:cr,afterInit(t,e,n){n&&(t.tooltip=new ac({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:hf},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>t!=="filter"&&t!=="itemSort"&&t!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const h_=(t,e,n,r)=>(typeof e=="string"?(n=t.push(e)-1,r.unshift({index:n,label:e})):isNaN(e)&&(n=null),n);function g_(t,e,n,r){const s=t.indexOf(e);if(s===-1)return h_(t,e,n,r);const o=t.lastIndexOf(e);return s!==o?n:s}const m_=(t,e)=>t===null?null:it(Math.round(t),0,e);function lc(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}class p_ extends Un{static id="category";static defaults={ticks:{callback:lc}};constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){const n=this._addedLabels;if(n.length){const r=this.getLabels();for(const{index:s,label:o}of n)r[s]===o&&r.splice(s,1);this._addedLabels=[]}super.init(e)}parse(e,n){if(xe(e))return null;const r=this.getLabels();return n=isFinite(n)&&r[n]===e?n:g_(r,e,pe(n,e),this._addedLabels),m_(n,r.length-1)}determineDataLimits(){const{minDefined:e,maxDefined:n}=this.getUserBounds();let{min:r,max:s}=this.getMinMax(!0);this.options.bounds==="ticks"&&(e||(r=0),n||(s=this.getLabels().length-1)),this.min=r,this.max=s}buildTicks(){const e=this.min,n=this.max,r=this.options.offset,s=[];let o=this.getLabels();o=e===0&&n===o.length-1?o:o.slice(e,n+1),this._valueRange=Math.max(o.length-(r?0:1),1),this._startValue=this.min-(r?.5:0);for(let i=e;i<=n;i++)s.push({value:i});return s}getLabelForValue(e){return lc.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!="number"&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}function y_(t,e){const n=[],{bounds:s,step:o,min:i,max:a,precision:l,count:c,maxTicks:d,maxDigits:f,includeBounds:g}=t,h=o||1,m=d-1,{min:p,max:y}=e,b=!xe(i),w=!xe(a),v=!xe(c),S=(y-p)/(f+1);let _=il((y-p)/m/h)*h,A,C,R,N;if(_<1e-14&&!b&&!w)return[{value:p},{value:y}];N=Math.ceil(y/_)-Math.floor(p/_),N>m&&(_=il(N*_/m/h)*h),xe(l)||(A=Math.pow(10,l),_=Math.ceil(_*A)/A),s==="ticks"?(C=Math.floor(p/_)*_,R=Math.ceil(y/_)*_):(C=p,R=y),b&&w&&o&&Vx((a-i)/o,_/1e3)?(N=Math.round(Math.min((a-i)/_,d)),_=(a-i)/N,C=i,R=a):v?(C=b?i:C,R=w?a:R,N=c-1,_=(R-C)/N):(N=(R-C)/_,fr(N,Math.round(N),_/1e3)?N=Math.round(N):N=Math.ceil(N));const M=Math.max(al(_),al(C));A=Math.pow(10,xe(l)?M:l),C=Math.round(C*A)/A,R=Math.round(R*A)/A;let F=0;for(b&&(g&&C!==i?(n.push({value:i}),C<i&&F++,fr(Math.round((C+F*_)*A)/A,i,cc(i,S,t))&&F++):C<i&&F++);F<N;++F){const D=Math.round((C+F*_)*A)/A;if(w&&D>a)break;n.push({value:D})}return w&&g&&R!==a?n.length&&fr(n[n.length-1].value,a,cc(a,S,t))?n[n.length-1].value=a:n.push({value:a}):(!w||R===a)&&n.push({value:R}),n}function cc(t,e,{horizontal:n,minRotation:r}){const s=un(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*e*(""+t).length;return Math.min(e/o,i)}class b_ extends Un{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,n){return xe(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:n,maxDefined:r}=this.getUserBounds();let{min:s,max:o}=this;const i=l=>s=n?s:l,a=l=>o=r?o:l;if(e){const l=On(s),c=On(o);l<0&&c<0?a(0):l>0&&c>0&&i(0)}if(s===o){let l=o===0?1:Math.abs(o*.05);a(o+l),e||i(s-l)}this.min=s,this.max=o}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:n,stepSize:r}=e,s;return r?(s=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,s>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${s} ticks. Limiting to 1000.`),s=1e3)):(s=this.computeTickLimit(),n=n||11),n&&(s=Math.min(n,s)),s}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,n=e.ticks;let r=this.getTickLimit();r=Math.max(2,r);const s={maxTicks:r,bounds:e.bounds,min:e.min,max:e.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},o=this._range||this,i=y_(s,o);return e.bounds==="ticks"&&Gx(i,this,"value"),e.reverse?(i.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),i}configure(){const e=this.ticks;let n=this.min,r=this.max;if(super.configure(),this.options.offset&&e.length){const s=(r-n)/Math.max(e.length-1,1)/2;n-=s,r+=s}this._startValue=n,this._endValue=r,this._valueRange=r-n}getLabelForValue(e){return Du(e,this.chart.options.locale,this.options.ticks.format)}}class x_ extends b_{static id="linear";static defaults={ticks:{callback:Lu.formatters.numeric}};determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=Ue(e)?e:0,this.max=Ue(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),n=e?this.width:this.height,r=un(this.options.ticks.minRotation),s=(e?Math.sin(r):Math.cos(r))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,o.lineHeight/s))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}const Zs={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Ye=Object.keys(Zs);function dc(t,e){return t-e}function uc(t,e){if(xe(e))return null;const n=t._adapter,{parser:r,round:s,isoWeekday:o}=t._parseOpts;let i=e;return typeof r=="function"&&(i=r(i)),Ue(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(br(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function fc(t,e,n,r){const s=Ye.length;for(let o=Ye.indexOf(t);o<s-1;++o){const i=Zs[Ye[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-e)/(a*i.size))<=r)return Ye[o]}return Ye[s-1]}function v_(t,e,n,r,s){for(let o=Ye.length-1;o>=Ye.indexOf(n);o--){const i=Ye[o];if(Zs[i].common&&t._adapter.diff(s,r,i)>=e-1)return i}return Ye[n?Ye.indexOf(n):0]}function w_(t){for(let e=Ye.indexOf(t)+1,n=Ye.length;e<n;++e)if(Zs[Ye[e]].common)return Ye[e]}function hc(t,e,n){if(!n)t[e]=!0;else if(n.length){const{lo:r,hi:s}=qi(n,e),o=n[r]>=e?n[r]:n[s];t[o]=!0}}function __(t,e,n,r){const s=t._adapter,o=+s.startOf(e[0].value,r),i=e[e.length-1].value;let a,l;for(a=o;a<=i;a=+s.add(a,1,r))l=n[a],l>=0&&(e[l].major=!0);return e}function gc(t,e,n){const r=[],s={},o=e.length;let i,a;for(i=0;i<o;++i)a=e[i],s[a]=i,r.push({value:a,major:!1});return o===0||!n?r:__(t,r,s,n)}class mc extends Un{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,n={}){const r=e.time||(e.time={}),s=this._adapter=new vv._date(e.adapters.date);s.init(n),ur(r.displayFormats,s.formats()),this._parseOpts={parser:r.parser,round:r.round,isoWeekday:r.isoWeekday},super.init(e),this._normalized=n.normalized}parse(e,n){return e===void 0?null:uc(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const e=this.options,n=this._adapter,r=e.time.unit||"day";let{min:s,max:o,minDefined:i,maxDefined:a}=this.getUserBounds();function l(c){!i&&!isNaN(c.min)&&(s=Math.min(s,c.min)),!a&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!i||!a)&&(l(this._getLabelBounds()),(e.bounds!=="ticks"||e.ticks.source!=="labels")&&l(this.getMinMax(!1))),s=Ue(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=Ue(o)&&!isNaN(o)?o:+n.endOf(Date.now(),r)+1,this.min=Math.min(s,o-1),this.max=Math.max(s+1,o)}_getLabelBounds(){const e=this.getLabelTimestamps();let n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return e.length&&(n=e[0],r=e[e.length-1]),{min:n,max:r}}buildTicks(){const e=this.options,n=e.time,r=e.ticks,s=r.source==="labels"?this.getLabelTimestamps():this._generate();e.bounds==="ticks"&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const o=this.min,i=this.max,a=Yx(s,o,i);return this._unit=n.unit||(r.autoSkip?fc(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):v_(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:w_(this._unit),this.initOffsets(s),e.reverse&&a.reverse(),gc(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+e.value))}initOffsets(e=[]){let n=0,r=0,s,o;this.options.offset&&e.length&&(s=this.getDecimalForValue(e[0]),e.length===1?n=1-s:n=(this.getDecimalForValue(e[1])-s)/2,o=this.getDecimalForValue(e[e.length-1]),e.length===1?r=o:r=(o-this.getDecimalForValue(e[e.length-2]))/2);const i=e.length<3?.5:.25;n=it(n,0,i),r=it(r,0,i),this._offsets={start:n,end:r,factor:1/(n+1+r)}}_generate(){const e=this._adapter,n=this.min,r=this.max,s=this.options,o=s.time,i=o.unit||fc(o.minUnit,n,r,this._getLabelCapacity(n)),a=pe(s.ticks.stepSize,1),l=i==="week"?o.isoWeekday:!1,c=br(l)||l===!0,d={};let f=n,g,h;if(c&&(f=+e.startOf(f,"isoWeek",l)),f=+e.startOf(f,c?"day":i),e.diff(r,n,i)>1e5*a)throw new Error(n+" and "+r+" are too far apart with stepSize of "+a+" "+i);const m=s.ticks.source==="data"&&this.getDataTimestamps();for(g=f,h=0;g<r;g=+e.add(g,a,i),h++)hc(d,g,m);return(g===r||s.bounds==="ticks"||h===1)&&hc(d,g,m),Object.keys(d).sort(dc).map(p=>+p)}getLabelForValue(e){const n=this._adapter,r=this.options.time;return r.tooltipFormat?n.format(e,r.tooltipFormat):n.format(e,r.displayFormats.datetime)}format(e,n){const s=this.options.time.displayFormats,o=this._unit,i=n||s[o];return this._adapter.format(e,i)}_tickFormatFunction(e,n,r,s){const o=this.options,i=o.ticks.callback;if(i)return Ne(i,[e,n,r],this);const a=o.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],f=c&&a[c],g=r[n],h=c&&f&&g&&g.major;return this._adapter.format(e,s||(h?f:d))}generateTickLabels(e){let n,r,s;for(n=0,r=e.length;n<r;++n)s=e[n],s.label=this._tickFormatFunction(s.value,n,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){const n=this._offsets,r=this.getDecimalForValue(e);return this.getPixelForDecimal((n.start+r)*n.factor)}getValueForPixel(e){const n=this._offsets,r=this.getDecimalForPixel(e)/n.factor-n.end;return this.min+r*(this.max-this.min)}_getLabelSize(e){const n=this.options.ticks,r=this.ctx.measureText(e).width,s=un(this.isHorizontal()?n.maxRotation:n.minRotation),o=Math.cos(s),i=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:r*o+a*i,h:r*i+a*o}}_getLabelCapacity(e){const n=this.options.time,r=n.displayFormats,s=r[n.unit]||r.millisecond,o=this._tickFormatFunction(e,0,gc(this,[e],this._majorUnit),s),i=this._getLabelSize(o),a=Math.floor(this.isHorizontal()?this.width/i.w:this.height/i.h)-1;return a>0?a:1}getDataTimestamps(){let e=this._cache.data||[],n,r;if(e.length)return e;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(n=0,r=s.length;n<r;++n)e=e.concat(s[n].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){const e=this._cache.labels||[];let n,r;if(e.length)return e;const s=this.getLabels();for(n=0,r=s.length;n<r;++n)e.push(uc(this,s[n]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return Xx(e.sort(dc))}}function as(t,e,n){let r=0,s=t.length-1,o,i,a,l;n?(e>=t[r].pos&&e<=t[s].pos&&({lo:r,hi:s}=fn(t,"pos",e)),{pos:o,time:a}=t[r],{pos:i,time:l}=t[s]):(e>=t[r].time&&e<=t[s].time&&({lo:r,hi:s}=fn(t,"time",e)),{time:o,pos:a}=t[r],{time:i,pos:l}=t[s]);const c=i-o;return c?a+(l-a)*(e-o)/c:a}class N1 extends mc{static id="timeseries";static defaults=mc.defaults;constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(e);this._minPos=as(n,this.min),this._tableRange=as(n,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:n,max:r}=this,s=[],o=[];let i,a,l,c,d;for(i=0,a=e.length;i<a;++i)c=e[i],c>=n&&c<=r&&s.push(c);if(s.length<2)return[{time:n,pos:0},{time:r,pos:1}];for(i=0,a=s.length;i<a;++i)d=s[i+1],l=s[i-1],c=s[i],Math.round((d+l)/2)!==c&&o.push({time:c,pos:i/(a-1)});return o}_generate(){const e=this.min,n=this.max;let r=super.getDataTimestamps();return(!r.includes(e)||!r.length)&&r.splice(0,0,e),(!r.includes(n)||r.length===1)&&r.push(n),r.sort((s,o)=>s-o)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const n=this.getDataTimestamps(),r=this.getLabelTimestamps();return n.length&&r.length?e=this.normalize(n.concat(r)):e=n.length?n:r,e=this._cache.all=e,e}getDecimalForValue(e){return(as(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const n=this._offsets,r=this.getDecimalForPixel(e)/n.factor-n.end;return as(this._table,r*this._tableRange+this._minPos,!0)}}const gf="label";function pc(t,e){typeof t=="function"?t(e):t&&(t.current=e)}function S_(t,e){const n=t.options;n&&e&&Object.assign(n,e)}function mf(t,e){t.labels=e}function pf(t,e,n=gf){const r=[];t.datasets=e.map(s=>{const o=t.datasets.find(i=>i[n]===s[n]);return!o||!s.data||r.includes(o)?{...s}:(r.push(o),Object.assign(o,s),o)})}function C_(t,e=gf){const n={labels:[],datasets:[]};return mf(n,t.labels),pf(n,t.datasets,e),n}function R_(t,e){const{height:n=150,width:r=300,redraw:s=!1,datasetIdKey:o,type:i,data:a,options:l,plugins:c=[],fallbackContent:d,updateMode:f,...g}=t,h=x.useRef(null),m=x.useRef(null),p=()=>{h.current&&(m.current=new Ks(h.current,{type:i,data:C_(a,o),options:l&&{...l},plugins:c}),pc(e,m.current))},y=()=>{pc(e,null),m.current&&(m.current.destroy(),m.current=null)};return x.useEffect(()=>{!s&&m.current&&l&&S_(m.current,l)},[s,l]),x.useEffect(()=>{!s&&m.current&&mf(m.current.config.data,a.labels)},[s,a.labels]),x.useEffect(()=>{!s&&m.current&&a.datasets&&pf(m.current.config.data,a.datasets,o)},[s,a.datasets]),x.useEffect(()=>{m.current&&(s?(y(),setTimeout(p)):m.current.update(f))},[s,l,a.labels,a.datasets,f]),x.useEffect(()=>{m.current&&(y(),setTimeout(p))},[i]),x.useEffect(()=>(p(),()=>y()),[]),u.jsx("canvas",{ref:h,role:"img",height:n,width:r,...g,children:d})}const A_=x.forwardRef(R_);function N_(t,e){return Ks.register(e),x.forwardRef((n,r)=>u.jsx(A_,{...n,ref:r,type:t}))}const E_=N_("line",xv);Ks.register(p_,x_,Dw,Xs,s_,f_);function yf({data:t,growthPercentage:e,isLoading:n=!1,className:r=""}){if(n)return u.jsxs("div",{"data-testid":"activity-chart-skeleton",className:`animate-pulse bg-white rounded-2xl p-6 ${r}`,children:[u.jsx("div",{className:"h-6 bg-gray-200 rounded w-1/3 mb-2"}),u.jsx("div",{className:"h-4 bg-gray-200 rounded w-1/2 mb-8"}),u.jsx("div",{className:"h-40 bg-gray-200 rounded"})]});if(!t||t.length===0)return u.jsx("div",{className:`bg-white rounded-2xl p-6 text-center ${r}`,children:u.jsx("p",{className:"text-gray-500",children:"No activity data available"})});const s={labels:t.map(l=>l.day),datasets:[{label:"Questions Solved",data:t.map(l=>l.count),borderColor:"#2563EB",backgroundColor:l=>{const d=l.chart.ctx.createLinearGradient(0,0,0,160);return d.addColorStop(0,"rgba(37, 99, 235, 0.2)"),d.addColorStop(1,"rgba(37, 99, 235, 0)"),d},borderWidth:3,pointBackgroundColor:"#fff",pointBorderColor:"#2563EB",pointBorderWidth:2,pointRadius:4,pointHoverRadius:6,fill:!0,tension:.4}]},o={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{backgroundColor:"#1F2937",padding:10,cornerRadius:8,displayColors:!1}},scales:{x:{grid:{display:!1},ticks:{color:"#9CA3AF",font:{size:10}}},y:{grid:{color:"#F3F4F6",tickLength:0},ticks:{display:!1},beginAtZero:!0}},interaction:{mode:"index",intersect:!1}},i=(e??0)>=0,a=i?"text-green-500":"text-red-500";return u.jsxs("div",{"data-testid":"activity-chart-container",className:`bg-white rounded-2xl p-6 ${r}`,children:[u.jsxs("div",{className:"flex justify-between items-end mb-4",children:[u.jsxs("div",{children:[u.jsx("div",{className:"text-sm font-bold text-gray-900",children:"Recent Activity"}),u.jsx("div",{className:"text-xs text-gray-500",children:"Last 7 days practice questions"})]}),e!==void 0&&u.jsxs("div",{className:"text-right",children:[u.jsxs("div",{className:`text-sm font-bold ${a}`,children:[i?"+":"",e,"%"]}),u.jsx("div",{className:"text-xs text-gray-500",children:"vs last week"})]})]}),u.jsx("div",{className:"h-40 w-full relative",children:u.jsx("div",{"data-testid":"activity-chart-canvas",children:u.jsx(E_,{data:s,options:o})})})]})}function k_({nameEn:t,nameZh:e,percentage:n,color:r}){const a=2*Math.PI*29,l=a-n/100*a;return u.jsxs("div",{"data-testid":"skill-ring",className:"flex flex-col items-center",children:[u.jsxs("div",{className:"relative w-16 h-16 mb-2",children:[u.jsxs("svg",{width:64,height:64,viewBox:"0 0 64 64",children:[u.jsx("circle",{cx:64/2,cy:64/2,r:29,fill:"none",stroke:"#F3F4F6",strokeWidth:6}),u.jsx("circle",{cx:64/2,cy:64/2,r:29,fill:"none",stroke:r,strokeWidth:6,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:l,transform:`rotate(-90 ${64/2} ${64/2})`,style:{transition:"stroke-dashoffset 0.5s ease-in-out"}})]}),u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-sm font-bold",style:{color:r},children:[n,"%"]})]}),u.jsx("div",{className:"text-xs font-bold text-gray-900",children:t}),u.jsx("div",{className:"text-[10px] text-gray-500",children:e})]})}function bf({skills:t,isLoading:e=!1,className:n=""}){return e?u.jsxs("div",{"data-testid":"skill-rings-skeleton",className:`animate-pulse bg-white rounded-2xl p-6 ${n}`,children:[u.jsx("div",{className:"h-5 bg-gray-200 rounded w-1/3 mb-2"}),u.jsx("div",{className:"h-4 bg-gray-200 rounded w-1/4 mb-6"}),u.jsx("div",{className:"flex justify-around",children:[1,2,3].map(r=>u.jsxs("div",{className:"flex flex-col items-center",children:[u.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full mb-2"}),u.jsx("div",{className:"h-3 bg-gray-200 rounded w-12 mb-1"}),u.jsx("div",{className:"h-2 bg-gray-200 rounded w-8"})]},r))})]}):!t||t.length===0?u.jsx("div",{className:`bg-white rounded-2xl p-6 text-center ${n}`,children:u.jsx("p",{className:"text-gray-500",children:"No skills data available"})}):u.jsxs("div",{"data-testid":"skill-rings-container",className:`bg-white rounded-2xl p-6 h-full ${n}`,children:[u.jsx("div",{className:"text-sm font-bold text-gray-900 mb-1",children:"Skill Mastery"}),u.jsx("div",{className:"text-xs text-gray-500 mb-4",children:"能力雷达图"}),u.jsx("div",{className:"flex justify-around items-center",children:t.map((r,s)=>u.jsx(k_,{nameEn:r.nameEn,nameZh:r.nameZh,percentage:r.percentage,color:r.color},s))})]})}function T_({data:t,loading:e=!1,error:n=null,onContinueLearning:r,onLessonSelect:s,onTaskToggle:o}){const[i,a]=x.useState("home"),[l,c]=x.useState(t.learningPathway.activeTab);if(e)return u.jsxs("div",{"data-testid":"dashboard-skeleton",className:"flex h-screen overflow-hidden bg-[#E2F8EE]",children:[u.jsx("div",{className:"w-20 bg-white shadow-sm"}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsx("div",{className:"h-[72px] bg-white/80 backdrop-blur-md border-b border-gray-100"}),u.jsx("main",{className:"flex-1 overflow-y-auto scroll-smooth",children:u.jsxs("div",{className:"max-w-[1080px] w-full px-4 md:px-8 py-10 flex flex-col gap-12",children:[u.jsx("div",{className:"h-6 bg-gray-200 rounded w-64 animate-pulse"}),u.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[u.jsx("div",{className:"col-span-12 lg:col-span-8 h-64 bg-gray-200 rounded-2xl animate-pulse"}),u.jsx("div",{className:"col-span-12 lg:col-span-4 h-64 bg-gray-200 rounded-2xl animate-pulse"})]}),u.jsx("div",{className:"col-span-12 h-48 bg-gray-200 rounded-2xl animate-pulse"}),u.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[u.jsx("div",{className:"col-span-12 lg:col-span-4 h-96 bg-gray-200 rounded-2xl animate-pulse"}),u.jsx("div",{className:"col-span-12 lg:col-span-8 h-96 bg-gray-200 rounded-2xl animate-pulse"})]})]})})]})]});if(n)return u.jsx("div",{"data-testid":"dashboard-error",className:"flex h-screen overflow-hidden bg-[#E2F8EE]",children:u.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:u.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-2xl p-6 text-center",children:[u.jsx("h2",{className:"text-red-800 text-lg font-semibold mb-2",children:"Error Loading Dashboard"}),u.jsx("p",{className:"text-red-600",children:n.message})]})})});const{user:d,gamified:f,continueLearning:g,dailyMilestones:h,learningPathway:m,recommendations:p,activityData:y,skillData:b}=t;return u.jsxs("div",{"data-testid":"dashboard-container",className:"flex h-screen overflow-hidden bg-[#E2F8EE]",children:[u.jsx(xu,{activeItemId:i,onNavigate:w=>a(w)}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsx(bu,{userName:d.name,userLevel:`Level ${d.level} Explorer`,userAvatar:d.avatar,streakDays:f.streakDays,coins:f.coins,notifications:3,onSearch:w=>console.log("Search:",w),onLanguageSwitch:()=>console.log("Language switch"),onNotificationClick:()=>console.log("Notifications"),onProfileClick:()=>console.log("Profile")}),u.jsx("main",{"data-testid":"dashboard-content",className:"flex-1 overflow-y-auto scroll-smooth w-full flex flex-col items-center",children:u.jsxs("div",{className:"max-w-[1080px] w-full px-4 md:px-8 py-10 flex flex-col gap-12",children:[u.jsxs("p",{className:"text-xl font-semibold text-gray-500 !py-8",children:["Welcome back, ",d.name," ",u.jsxs("span",{className:"font-normal text-gray-400",children:["/ 欢迎回来,",d.name,"!"]})]}),u.jsxs("div",{"data-testid":"dashboard-grid",className:"grid grid-cols-12 gap-8 items-stretch",children:[u.jsx("div",{"data-testid":"hero-section",className:"col-span-12 lg:col-span-8",children:u.jsx(vu,{courseCategory:`${g.grade} - ${g.subject} / ${g.grade==="4th Grade"?"四年级":g.grade} - ${g.subject==="Fractions"?"分数":g.subject}`,lessonTitleEn:g.lessonTitle,lessonTitleZh:g.lessonTitleCn,onAction:r})}),u.jsx("div",{"data-testid":"milestones-section",className:"col-span-12 lg:col-span-4",children:u.jsx(Su,{currentXP:h.currentXP,targetXP:h.targetXP,tasks:h.tasks,onTaskToggle:o})})]}),u.jsxs("section",{"aria-labelledby":"rec-heading",className:"bg-white rounded-2xl p-6 shadow-sm",children:[u.jsxs("h3",{id:"rec-heading",className:"font-bold text-lg leading-loose mb-2",children:["Just For You ",u.jsx("span",{className:"text-sm font-normal text-gray-500 leading-loose",children:"/ AI 为您推荐"})]}),u.jsx("p",{className:"text-xs text-gray-500 leading-loose mb-6",children:"Adaptive AI Recommendations based on your recent activity."}),u.jsx("div",{"data-testid":"recommendations-grid",className:"grid grid-cols-1 md:grid-cols-3 gap-8",children:p.map(w=>u.jsx(Nu,{variant:w.variant,badgeText:w.badgeText,reasoning:w.reasoning,title:w.title,onAction:()=>{}},w.id))})]}),u.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[u.jsx("div",{"data-testid":"pathway-section",className:"col-span-12 lg:col-span-4",children:u.jsx(Au,{activeTab:l,lessons:m.lessons,onTabChange:w=>c(w),onLessonAction:s})}),u.jsxs("section",{"aria-labelledby":"journey-heading",className:"col-span-12 lg:col-span-8 bg-white rounded-2xl p-6 shadow-sm",children:[u.jsx("div",{className:"flex flex-col md:flex-row justify-between items-start md:items-center mb-6",children:u.jsxs("div",{children:[u.jsxs("h3",{id:"journey-heading",className:"font-bold text-lg",children:["Your Math Journey ",u.jsx("span",{className:"text-sm font-normal text-gray-500",children:"/ 学习状况可视化"})]}),u.jsx("p",{className:"text-xs text-gray-500",children:"Focused on engagement & growth. (NO errors displayed / 不展示负面错误率)"})]})}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8 divide-y md:divide-y-0 md:divide-x divide-gray-100",children:[u.jsx("div",{className:"pr-0 md:pr-8",children:u.jsx(yf,{data:y,growthPercentage:12})}),u.jsx("div",{className:"pt-6 md:pt-0 pl-0 md:pl-8 flex flex-col justify-center",children:u.jsx(bf,{skills:b})})]})]})]}),u.jsx("div",{className:"h-8"})]})})]})]})}function M_(t){return t.steps!==void 0}function j_(t){if(M_(t))return t;if(Array.isArray(t)){if(t.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=t[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const r=t.map(s=>({id:s.id,type:s.type,title:s.content.title||"",description:s.content.description||"",chartConfig:s.content.chartConfig,videoUrl:s.content.videoUrl,commonErrors:s.content.commonErrors,difficulty:s.content.difficulty}));return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}else return{steps:t,total_steps:t.length,strategy:"step_by_step",estimated_time:t.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}function xf(t){return Array.isArray(t)}const $_=(t,e,n=.1)=>{if(!t.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const r=parseFloat(t);if(isNaN(r))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(r<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const o=Math.abs(r-e)<=n;return{isValid:!0,isCorrect:o,errorMessage:o?void 0:"答案不正确,请再试一次"}},O_=()=>Dn.create((t,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:n=>{t({problemData:n,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:n=>{t({userAnswer:n,validationError:null})},updateChoiceAnswer:n=>{t({userAnswer:n,validationError:null})},submitAnswer:n=>{const r=e();if(!r.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}let s=r.userAnswer;if((Array.isArray(n)||n!==void 0)&&(s=n),xf(s)){const d=s.map(h=>h.id),f=r.problemData.answer_info?.correctAnswers||[];process.env.NODE_ENV==="development"&&console.log("[答案验证]",{selectedIds:d,correctAnswers:f,answerInfo:r.problemData.answer_info});const g=d.length===f.length&&d.every(h=>f.includes(h));t({isCorrect:g,showAnswerForm:!1,validationError:null,currentScene:g?"success":"explanation"});return}const o=typeof s=="string"?s:"",i=r.problemData.answer_info?.value??r.problemData.answer.value,a=Number(i),l=r.problemData.answer_info?.tolerance??.1,c=$_(o,a,l);if(!c.isValid){t({userAnswer:s,validationError:c.errorMessage||"答案格式错误"});return}t({userAnswer:s,isCorrect:c.isCorrect,showAnswerForm:!1,validationError:null,currentScene:c.isCorrect?"success":"explanation"})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),Kt=O_(),ra=()=>Kt(t=>t.currentScene),sa=()=>Kt(t=>t.userAnswer),I_=()=>Kt(t=>t.isCorrect),oa=()=>Kt(t=>t.showAnswerForm),vf=()=>Kt(t=>t.validationError),P_=()=>Kt(t=>t.problemData),ia=()=>Kt(bn.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,updateChoiceAnswer:t.updateChoiceAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),F_=x.createContext(null),$r=()=>{const t=x.useContext(F_);if(!t)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return t},D_=()=>{const t=$r(),e=x.useCallback(n=>n.currentScene,[]);return t(e)},L_=()=>{const t=$r(),e=x.useCallback(n=>n.userAnswer,[]);return t(e)},z_=()=>{const t=$r(),e=x.useCallback(n=>n.showAnswerForm,[]);return t(e)},V_=()=>{const t=$r(),e=x.useCallback(n=>n.validationError,[]);return t(e)},G_=()=>$r()(bn.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,updateChoiceAnswer:e.updateChoiceAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),Qs=()=>{try{return D_()}catch{return ra()}},eo=()=>{try{return L_()}catch{return sa()}},to=()=>{try{return z_()}catch{return oa()}},no=()=>{try{return V_()}catch{return vf()}},ro=()=>{try{return G_()}catch{return ia()}},vn=({problemData:t,userAnswer:e,showAnswerForm:n,onAnswerSubmit:r,onAnswerChange:s,validationError:o,noBorder:i=!1})=>{const a=x.useCallback((g,h)=>{h.type==="optionChange"&&s(h.value)},[s]),l=x.useMemo(()=>Array.isArray(e)?(t.scenes?.question?.items??[]).reduce((h,m)=>(m.type==="optionGroup"&&m.metadata?.optionGroupId&&(h[m.metadata.optionGroupId]=e),h),{}):{},[e,t]),c=Array.isArray(e)||t.scenes?.question?.items?.some(g=>g.type==="optionGroup"),d=g=>{g.preventDefault(),r(e)},f=g=>{s(g)};return u.jsx("div",{className:"question-scene-container",children:u.jsxs("div",{className:"question-scene-card",children:[u.jsx("div",{className:"question-display-area",children:u.jsx(Be,{data:{id:t.id,grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1},onContentInteraction:a,interactionValues:l})}),n&&u.jsxs("div",{className:"answer-form-container",children:[u.jsxs("form",{onSubmit:d,className:"answer-form",children:[!c&&u.jsxs(u.Fragment,{children:[u.jsx("label",{className:"answer-label",children:"答案"}),u.jsx("input",{type:"number",value:typeof e=="string"?e:"",onChange:g=>f(g.target.value),className:`answer-input ${o?"error":"normal"}`,placeholder:"?",required:!0}),u.jsx("span",{className:"answer-unit",children:t.basicInfo.answerUnit||t.basicInfo.areaUnit})]}),u.jsx(Pt,{type:"submit",size:"lg",intent:"submit",useNewClassName:!0,className:"submit-button",children:"提交答案"})]}),o&&u.jsxs("div",{className:"validation-error",children:[u.jsx("span",{children:"⚠️"}),u.jsx("span",{children:o})]})]})]})})},wf=({problemData:t,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",t),console.log("🔍 RememberModule scenes.remember:",t?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",t?.scenes?.remember?.content);const r=(()=>{const o=t.scenes?.review?.items;if(o&&Array.isArray(o)&&o.length>0)return console.log("🔍 RememberModule 使用 review.items"),o;const i=t.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=t.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const l=t.scenes?.remember?.content;return l&&Array.isArray(l)&&l.length>0?(console.log("🔍 RememberModule 使用 remember.content"),l):(console.log("🔍 RememberModule 未找到任何内容"),[])})();if(r.length===0){const o=u.jsx("div",{className:"remember-module-content",children:u.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?u.jsx($n,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})}const s=u.jsx("div",{className:"remember-module-content",children:r.map((o,i)=>{const{type:a,content:l,style:c,parts:d}=o;switch(a){case"text":return u.jsx("p",{className:"remember-module-text-block",style:c,children:l},i);case"formula":return u.jsx("div",{className:"remember-module-formula-block",children:u.jsx(Be,{data:{id:`formula-${i}`,grade:t.grade,unit:t.unit,content:[{type:"formula",content:l,parts:d||[l]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return u.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?u.jsx($n,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})},aa=({problemData:t,userAnswer:e,enableIXLStyle:n=!0})=>{const r=x.useMemo(()=>xf(e)?e.length===0?"未选择":e.map(i=>i.contentType==="formula"?i.content:i.content||i.id).join("、"):e||"--",[e]),s=u.jsxs("div",{className:"review-module-content",children:[u.jsx("p",{className:"review-module-question",children:t.basicInfo.question}),u.jsx("div",{className:"review-module-graph",children:u.jsx(Be,{data:{id:"review-problem",grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:n?"ixl-adjusted":""})}),u.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",u.jsx("span",{className:"review-module-user-answer-value",children:r})]})]});return n?u.jsx($n,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:s}):u.jsxs("div",{className:"review-module-container",children:[u.jsx("h4",{className:"review-module-title",children:"复习"}),s]})},U_=t=>[{color:"var(--mc-step-color-ident)",bg:"var(--mc-step-bg-ident)"},{color:"var(--mc-step-color-calc)",bg:"var(--mc-step-bg-calc)"},{color:"var(--mc-step-color-res)",bg:"var(--mc-step-bg-res)"}][t%3],B_=({step:t,problemData:e,stepNumber:n})=>{const{title:r,description:s,chartConfig:o}=t.content,i=!!o,a=U_(n-1),l=[{type:"text",content:s.replace(/<br>/g,`
78
+ `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return u.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[u.jsxs("h3",{className:"explanation-step-title",children:[u.jsx("span",{className:"explanation-step-number",children:n}),u.jsx("span",{children:r})]}),u.jsxs("div",{className:"explanation-step-content",children:[u.jsx(Be,{data:{id:`${t.id}-description`,grade:e.grade,unit:e.unit,content:l},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&o.type&&u.jsx("div",{className:"explanation-step-chart-container",children:o.type==="hundredGrid"?u.jsx(Ii,{rows:o.rows||2,cols:o.cols||6,cellSize:o.cellSize||36,mode:o.mode||"readonly",value:o.value,fillColor:o.fillColor,baseColor:o.baseColor,className:"mathwiz-hundredgrid-explanation"}):o.type==="geometryTransform"&&(o.config||o.metadata?.config)?u.jsx(Fi,{config:o.config||o.metadata?.config,onTransformChange:c=>console.log("Transform progress:",c),onTransformComplete:()=>console.log("Transform complete"),onError:c=>console.error("Geometry transform error:",c)}):o.shapes&&o.shapes.length>0?u.jsx(kr,{shapes:o.shapes,width:o.width||400,height:o.height||300,boundingBox:o.boundingBox||[-10,10,10,-10],showGrid:o.showGrid||!1,showAxis:o.showAxis||!1,mode:"view",className:"mx-auto"}):null})]})]})},la=({problemData:t,enableIXLStyle:e=!0})=>{const[n,r]=x.useState(!1),s=t?.scenes?.solve?.items||t?.scenes?.solve?.content,o=Array.isArray(s)&&s.length>0,i=x.useMemo(()=>s&&s.map(f=>f.type==="geometryTransform"&&f.metadata?.config&&!f.config?{...f,config:f.metadata.config}:f),[s]),a=x.useMemo(()=>j_(t.explanation),[t.explanation]),l=a.steps.length>0,c=x.useMemo(()=>l?a.steps.map(f=>({...f,content:{title:f.title,description:f.description,chartConfig:f.chartConfig?{...f.chartConfig,boundingBox:f.chartConfig.type==="graph"&&Array.isArray(f.chartConfig.boundingBox)&&f.chartConfig.boundingBox.length===4?[f.chartConfig.boundingBox[0],f.chartConfig.boundingBox[1],f.chartConfig.boundingBox[2],f.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[l,a.steps]),d=u.jsxs("div",{className:"solve-module-content",children:[o?u.jsxs(u.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",s),s?.forEach?.((f,g)=>{if(f.type==="geometryTransform"){const h=i?.[g];console.log(`🔍 SolveModule: geometryTransform block [${g}] =`,{type:f.type,hasMetadata:!!f.metadata,metadata:f.metadata,hasMetadataConfig:!!f.metadata?.config,metadataConfig:f.metadata?.config,hasConfig:!!f.config,config:f.config,hasShapes:!!f.shapes,shapes:f.shapes,hasTransform:!!f.transform,transform:f.transform,fixedBlockHasConfig:!!h?.config,fixedBlockConfig:h?.config,fixedBlockHasMetadataConfig:!!h?.metadata?.config,fixedBlockMetadataConfig:h?.metadata?.config,isConfigFixed:!f.config&&!!h?.config})}}),u.jsx(Be,{data:{id:"solve-steps",grade:t.grade,unit:t.unit,content:i},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):u.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),u.jsx("div",{className:"solve-module-button-container",children:u.jsx(Pt,{intent:"solve",variant:"light",useNewClassName:!0,onClick:()=>r(f=>!f),className:"solve-module-button",children:n?"收起详细解题步骤":"查看详细解题步骤"})}),n&&u.jsxs("div",{className:"solve-module-detailed-container",children:[u.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),l?u.jsx("div",{className:"solve-module-detailed-list",children:c.map((f,g)=>u.jsx(B_,{step:f,problemData:t,stepNumber:g+1},f.id))}):u.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?u.jsx($n,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:d}):u.jsxs("div",{className:"solve-module-container",children:[u.jsx("h4",{className:"solve-module-title",children:"解题"}),d]})},H_=t=>{if(t.answer_info?.displayValue)return t.answer_info.displayValue;const e=t.answer_info?.value;if(e!=null)return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e);const n=t.answer?.value;return n!=null?String(n):"--"},Bn=({problemData:t,userAnswer:e,onNextQuestion:n})=>{console.log("🔍 ExplanationScene problemData:",t),console.log("🔍 ExplanationScene scenes.remember:",t?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",t?.scenes?.remember?.content);const r=x.useMemo(()=>H_(t),[t]);return u.jsxs("div",{children:[u.jsx("div",{className:"explanation-error-banner",children:u.jsxs("div",{className:"explanation-inner-container",children:[u.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),u.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[u.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),u.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[u.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),u.jsx("div",{className:"correct-answer-value-container",children:u.jsx("span",{className:"correct-answer-value",children:u.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r})})})]})]}),u.jsx("div",{className:"explanation-button-container",children:u.jsx(Pt,{onClick:n,size:"lg",intent:"next",useNewClassName:!0,className:"explanation-next-button",children:"明白了"})})]})}),u.jsxs("div",{className:"explanation-content-area",children:[u.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),u.jsx(aa,{problemData:t,userAnswer:e}),u.jsx(wf,{problemData:t}),u.jsx(la,{problemData:t})]}),u.jsx("div",{className:"explanation-bottom-area",children:u.jsx(Pt,{onClick:n,size:"md",intent:"next",useNewClassName:!0,children:"明白了"})})]})},wn=({problemData:t,onNextQuestion:e})=>u.jsxs("div",{className:"success-scene-container",children:[u.jsx("h3",{className:"success-message-title",children:"正确!"}),u.jsx("p",{className:"success-message-description",children:"你做得很好!"}),u.jsx("div",{className:"concept-review-container",children:u.jsx(Be,{data:{id:"review-concepts",grade:t.grade,unit:t.unit,content:t.scenes?.review?.items||t.scenes?.review?.content||t.scenes?.remember?.items||t.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),u.jsx(Pt,{onClick:e,size:"lg",intent:"next",useNewClassName:!0,className:"next-button",children:"下一题"})]}),It={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};let kn=class extends Error{code;details;constructor(e,n,r){super(n),this.name="AdapterError",this.code=e,this.details=r}};const W_={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},q_={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},he={DESIGN_TOKEN:"design_token",STYLE_REF:"style_ref",GEOMETRY_REF:"geometry_ref",TRANSFORM_REF:"transform_ref",LAYOUT_REF:"layout_ref",ANIMATION_REF:"animation_ref",BOARD_REF:"board_ref",GEOMETRY_TRANSFORM_REF:"geometry_transform_ref",SLIDER_REF:"slider_ref"},re={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};class Ee extends Error{code;details;constructor(e,n,r){super(n),this.name="AdapterError",this.code=e,this.details=r}}const xs={id:"fallback-triangle-problem",title:"三角形面积计算",grade:5,unit:"三角形面积计算",lesson:"锐角三角形的面积",skill:"已知锐角三角形的底和高,求三角形面积",objective:"掌握锐角三角形面积公式 A=½bh",knowledgePoints:["三角形面积公式 A=½bh"],difficulty:1,metadata:{topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","三角形面积公式"]},basicInfo:{question:"以下三角形面积是多少?",base:6,height:4,baseUnit:"cm",heightUnit:"cm",answerUnit:"cm²"},scenes:{question:{content:[],layout:{type:"card"}},solve:{content:[],layout:{type:"card"}},review:{content:[],layout:{type:"card"}}},explanation:{steps:[]},answer:{value:12,unit:"cm²",explanation:"三角形面积公式为 A = ½ × 底 × 高 = ½ × 6 × 4 = 12"}},yc={[re.INVALID_INPUT]:"输入数据无效",[re.MISSING_REQUIRED_FIELD]:"缺少必需字段",[re.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[re.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[re.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[re.STYLE_REF_NOT_FOUND]:"样式引用未找到",[re.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[re.BOARD_REF_NOT_FOUND]:"画板引用未找到",[re.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[re.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[re.TRANSFORMATION_FAILED]:"数据转换失败",[re.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},rn={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Fo={RAW_DATA:["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective","knowledge_points","difficulty","basic_info","scenes","explanation","answer_info"],BASIC_INFO:["question"],ANSWER_INFO:["value","unit","explanation_text"]},_f=["question","solve","review","remember"],we={DESIGN_TOKEN:/^\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)$/,STYLE_REF:/^styleRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_REF:/^geometryRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,TRANSFORM_REF:/^transformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,LAYOUT_REF:/^layoutRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,ANIMATION_REF:/^animationRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_TRANSFORM_REF:/^geometryTransformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,SLIDER_REF:/^sliderRef:([a-zA-Z_][a-zA-Z0-9_]*)$/},$e={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},Sf={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.5rem",heading_normal:"1.25rem",body:"1.2rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},Cf={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_secondary",fontSize:"$fonts.heading_normal",fontWeight:"600",lineHeight:1.5,letterSpacing:"0.01em"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"},hundredGrid_primary:{id:"hundredGrid_primary",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.primary",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_highlight:{id:"hundredGrid_highlight",baseColor:"$colors.background_lighter",borderColor:"$colors.primary",selectedColor:"$colors.success",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_solve:{id:"hundredGrid_solve",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.highlight_yellow",textColor:"$colors.text_primary",fontSize:"$fonts.body"}}},Rf={geometry_presets:{acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[[100,300],[300,100],[500,300]],styleRef:"primary",description:"锐角三角形"},right_triangle:{id:"right_triangle",type:"triangle",vertices:[[100,100],[100,300],[300,300]],styleRef:"secondary",description:"直角三角形"},equilateral_triangle:{id:"equilateral_triangle",type:"triangle",vertices:[[200,100],[100,273],[300,273]],styleRef:"highlight",description:"等边三角形"},rectangle:{id:"rectangle",type:"rectangle",dimensions:{width:200,height:100},styleRef:"primary",description:"矩形"},parallelogram:{id:"parallelogram",type:"parallelogram",vertices:[[100,100],[300,100],[250,200],[50,200]],styleRef:"secondary",description:"平行四边形"},horizontal_line:{id:"horizontal_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"primary",description:"水平线段模板"},vertical_line:{id:"vertical_line",type:"segment",endpoints:[[0,0],[0,100]],styleRef:"primary",description:"垂直线段模板"},arrow_line:{id:"arrow_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"error",description:"箭头线段模板"},label_point:{id:"label_point",type:"point",position:[50,20],styleRef:"text_primary",description:"标签位置点模板"},center_point:{id:"center_point",type:"point",position:[50,50],styleRef:"primary",description:"中心点模板"},vertex_point:{id:"vertex_point",type:"point",position:[0,0],styleRef:"primary",description:"顶点点模板"},marker_point:{id:"marker_point",type:"point",position:[0,0],styleRef:"highlight",description:"标记点模板"},left_triangle:{id:"left_triangle",type:"polygon",vertices:[[100,100],[100,300],[250,300]],styleRef:"highlight_left",description:"左三角形模板"}}},Af={layout_presets:{card:{id:"card",type:"card",padding:"$spacing.large",theme:"light"},vertical_centered:{id:"vertical_centered",type:"vertical",spacing:"$spacing.large",alignment:"center"},vertical_spaced:{id:"vertical_spaced",type:"vertical",spacing:"$spacing.medium",alignment:"start"},grid_2col:{id:"grid_2col",type:"grid",columns:2,spacing:"$spacing.medium"}}},Nf={transform_definitions:{left_rotation:{id:"left_rotation",type:"rotation",angle:-90,origin:[0,0],description:"向左旋转90度"},right_rotation:{id:"right_rotation",type:"rotation",angle:90,origin:[0,0],description:"向右旋转90度"},translation:{id:"translation",type:"translation",dx:0,dy:0,description:"平移变换"},scale:{id:"scale",type:"scale",factor:1,origin:[0,0],description:"缩放变换"}}},Nn={slider_definitions:{slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}}},Ef={board_definitions:{default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}}},cn={designTokens:Sf.design_tokens,stylePresets:Cf.style_presets,geometryPresets:Rf.geometry_presets,layoutPresets:Af.layout_presets,transformDefinitions:Nf.transform_definitions,animationDefinitions:Nn.slider_definitions,animationConfigs:Nn.slider_definitions,boardDefinitions:Ef.board_definitions};function kf(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!Nn,sliderDefinitionsKeys:Nn.slider_definitions?Object.keys(Nn.slider_definitions):[]});const t=Nn.slider_definitions;return{designTokens:Sf.design_tokens,stylePresets:Cf.style_presets,geometryPresets:Rf.geometry_presets,layoutPresets:Af.layout_presets,transformDefinitions:Nf.transform_definitions,animationDefinitions:t,animationConfigs:t,boardDefinitions:Ef.board_definitions}}class tt{static canResolve(e){return we.DESIGN_TOKEN.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const r=e.substring(1);return this.resolvePath(r,n.designTokens)}static resolvePath(e,n){const r=e.split(".");let s=n;for(const o of r){if(s==null)throw new Error(`设计令牌路径不存在: ${e} (在 ${o} 处中断)`);if(typeof s!="object")throw new Error(`设计令牌路径无效: ${e} (${o} 不是对象)`);s=s[o]}if(s===void 0)throw new Error(`设计令牌未找到: ${e}`);return s}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`设计令牌解析失败: ${s}`,o)}return r}static extractDesignTokenRefs(e){const n=[],r=s=>{typeof s=="string"?this.canResolve(s)&&n.push(s):Array.isArray(s)?s.forEach(r):typeof s=="object"&&s!==null&&Object.values(s).forEach(r)};return r(e),n}static replaceDesignTokenRefs(e,n,r){const s=o=>{if(typeof o=="string"){if(this.canResolve(o))try{return this.resolve(o,n)}catch(d){if(r)return r(o);throw d}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,l=0;const c=[];for(;(a=i.exec(o))!==null;){a.index>l&&c.push(o.substring(l,a.index));const d=a[0];try{const f=this.resolve(d,n);c.push(String(f))}catch{r?c.push(String(r(d))):c.push(d)}l=a.index+d.length}return l<o.length&&c.push(o.substring(l)),c.length>1?c.join(""):o}else{if(Array.isArray(o))return o.map(s);if(typeof o=="object"&&o!==null){const i={};for(const[a,l]of Object.entries(o))i[a]=s(l);return i}}return o};return s(e)}}function Y_(){return{type:he.DESIGN_TOKEN,canResolve:tt.canResolve.bind(tt),resolve:tt.resolve.bind(tt)}}class yt{static canResolve(e,n){if(typeof e!="string"||e.length===0)return!1;if(we.GEOMETRY_REF.test(e)||[/^point_[a-zA-Z0-9_]+$/,/^segment_[a-zA-Z0-9_]+$/,/^line_[a-zA-Z0-9_]+$/,/^triangle_[a-zA-Z0-9_]+$/,/^polygon_[a-zA-Z0-9_]+$/,/^circle_[a-zA-Z0-9_]+$/,/^angle_[a-zA-Z0-9_]+$/,/^vector_[a-zA-Z0-9_]+$/,/^arc_[a-zA-Z0-9_]+$/,/^ray_[a-zA-Z0-9_]+$/].some(o=>o.test(e)))return!0;if(n&&n.geometryPresets){let o;const i=e.match(we.GEOMETRY_REF);return i?o=i[1]:o=e,o in n.geometryPresets}return["acute_triangle","right_triangle","equilateral_triangle","rectangle","parallelogram","horizontal_line","vertical_line","arrow_line","label_point","center_point","vertex_point","marker_point","left_triangle","right_triangle","base_segment","height_segment","base_arrow","height_arrow","full_rectangle"].includes(e)}static resolveVertexReference(e,n){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!n.geometryPresets,pointFound:!!n.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const r=e.$ref;if(n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return console.error(`✅ 解析顶点引用 ${r}: 使用 position`,s.position),[s.position.x,s.position.y];if("x"in s&&"y"in s)return console.error(`✅ 解析顶点引用 ${r}: 使用 x/y`,{x:s.x,y:s.y}),[s.x,s.y]}return console.warn(`无法解析顶点引用: ${r}`),e}return Array.isArray(e)&&e.length===2?e:e&&typeof e=="object"&&"x"in e&&"y"in e?[e.x,e.y]:e}static resolve(e,n){if(!this.canResolve(e,n))throw new Error(`无法解析的几何引用: ${e}`);let r;const s=e.match(we.GEOMETRY_REF);s?r=s[1]:r=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${r}"`),console.error(" Available geometryPresets:",Object.keys(n.geometryPresets||{}));const o=n.geometryPresets[r];if(!o)throw console.error(`❌ Geometry preset not found: ${r} in`,n.geometryPresets),new Error(`几何预设未找到: ${r}`);console.error("✅ Geometry resolved:",{name:r,type:o.type,hasVertices:"vertices"in o,verticesCount:o.vertices?o.vertices.length:0,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,geometryKeys:Object.keys(o)});const i={...o};return i.vertices&&Array.isArray(i.vertices)&&(i.vertices=i.vertices.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,n):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(l){return console.warn("顶点引用解析失败:",l),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,l)=>({index:l,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})),i.endpoints&&Array.isArray(i.endpoints)&&(i.endpoints=i.endpoints.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,n):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(l){return console.warn("端点引用解析失败:",l),a}})),i}static validate(e,n){if(!this.canResolve(e,n))return!1;let r;const s=e.match(we.GEOMETRY_REF);return s?r=s[1]:r=e,r in n.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,n){const r=this.resolve(e,n);if(r.styleRef&&n.stylePresets[r.styleRef]){const s=n.stylePresets[r.styleRef];return{...r,style:{...s}}}return r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`几何引用解析失败: ${s}`,o)}return r}static extractGeometryRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.geometryRef&&typeof s.geometryRef=="string"&&n.push(s.geometryRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.geometryRef&&typeof o.geometryRef=="string"&&n.push(o.geometryRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function K_(){return{type:he.GEOMETRY_REF,canResolve:yt.canResolve.bind(yt),resolve:yt.resolve.bind(yt),validate:yt.validate.bind(yt)}}class qe{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.TRANSFORM_REF.test(e)?!0:/_(rotation|translation|scale|transform|reflection|shear|mirror)$/i.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let r;const s=e.match(we.TRANSFORM_REF);if(s?r=s[1]:r=e,n.transformDefinitions&&n.transformDefinitions[r])return{...n.transformDefinitions[r]};const o=this.createDefaultTransform(r);if(o)return console.warn(`⚠️ 使用智能默认变换: ${r}`,o),o;throw new Error(`变换定义未找到: ${r}`)}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.TRANSFORM_REF);return s?r=s[1]:r=e,n.transformDefinitions&&n.transformDefinitions[r]?!0:this.createDefaultTransform(r)!==null}static applyTransform(e,n){if(!n||!e)return e;const r={...e};switch(n.type){case"rotation":r.vertices=this.applyRotation(e.vertices,n.angle,n.origin);break;case"translation":r.vertices=this.applyTranslation(e.vertices,n.dx,n.dy);break;case"scale":r.vertices=this.applyScale(e.vertices,n.factor,n.origin);break;default:console.warn(`未知的变换类型: ${n.type}`)}return r}static applyRotation(e,n,r){if(!e||!Array.isArray(e))return e;const[s,o]=r,i=n*Math.PI/180,a=Math.cos(i),l=Math.sin(i);return e.map(([c,d])=>{const f=c-s,g=d-o;return[s+f*a-g*l,o+f*l+g*a]})}static applyTranslation(e,n,r){return!e||!Array.isArray(e)?e:e.map(([s,o])=>[s+n,o+r])}static applyScale(e,n,r){if(!e||!Array.isArray(e))return e;const[s,o]=r;return e.map(([i,a])=>{const l=i-s,c=a-o;return[s+l*n,o+c*n]})}static createDefaultTransform(e){const n=e.toLowerCase();if(n.includes("rotation")||n.includes("rotate")){let r=0,s=Math.PI,o="clockwise";return n.includes("left")?(o="clockwise",s=Math.PI):n.includes("right")?(o="counterclockwise",s=Math.PI):n.includes("half")||n.includes("180")?s=Math.PI:n.includes("full")||n.includes("360")?s=2*Math.PI:(n.includes("quarter")||n.includes("90"))&&(s=Math.PI/2),{type:"rotation",config:{center:[0,0],startAngle:r,endAngle:s,direction:o}}}else if(n.includes("translation")||n.includes("translate")||n.includes("move")){let r=[0,0],s=0;return n.includes("left")||n.includes("west")?(r=[-1,0],s=10):n.includes("right")||n.includes("east")?(r=[1,0],s=10):n.includes("up")||n.includes("north")?(r=[0,1],s=10):n.includes("down")||n.includes("south")?(r=[0,-1],s=10):n.includes("horizontal")?(r="horizontal",s=10):n.includes("vertical")&&(r="vertical",s=10),{type:"translation",config:{direction:r,distance:s}}}else if(n.includes("scale")||n.includes("zoom")){let r=1,s=1;return n.includes("enlarge")||n.includes("bigger")||n.includes("up")?s=2:(n.includes("shrink")||n.includes("smaller")||n.includes("down"))&&(s=.5),{type:"scale",config:{center:[0,0],startScale:r,endScale:s,uniform:!0}}}else if(n.includes("transform")||n.includes("main")||n.includes("default")||n.includes("primary"))return{type:"translation",config:{direction:"horizontal",distance:0}};return null}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`变换引用解析失败: ${s}`,o)}return r}static extractTransformRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.transformRef&&typeof s.transformRef=="string"&&n.push(s.transformRef),Array.isArray(s.transformations)&&s.transformations.forEach(o=>{o.transformRef&&typeof o.transformRef=="string"&&n.push(o.transformRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function X_(){return{type:he.TRANSFORM_REF,canResolve:qe.canResolve.bind(qe),resolve:qe.resolve.bind(qe),validate:qe.validate.bind(qe)}}class ze{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.STYLE_REF.test(e)?!0:["primary","secondary","transparent","highlight","error","success","dashed","text_primary","text_heading_large","base_highlight","label_position","highlight_left","highlight_right","label_error"].includes(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let r;const s=e.match(we.STYLE_REF);s?r=s[1]:r=e;const o=n.stylePresets[r];if(!o)throw new Error(`样式预设未找到: ${r}`);return this.resolveStylePreset(o,n)}static resolveStylePreset(e,n){const r={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(tt.canResolve(o))try{r[s]=tt.resolve(o,n)}catch(i){console.warn(`样式中的设计令牌解析失败: ${s}=${o}`,i),r[s]=o}}else o&&typeof o=="object"&&(r[s]=this.resolveStylePreset(o,n));return r}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.STYLE_REF);return s?r=s[1]:r=e,r in n.stylePresets}static applyStyle(e,n){if(!e||!n)return e;const r={...e};return r.style=r.style?{...r.style,...n}:{...n},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(o=>{n[o]!==void 0&&(r[o]=n[o])}),r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`样式引用解析失败: ${s}`,o)}return r}static extractStyleRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.styleRef&&typeof s.styleRef=="string"&&n.push(s.styleRef),s.style&&typeof s.style=="object"&&s.style.styleRef&&typeof s.style.styleRef=="string"&&n.push(s.style.styleRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.styleRef&&typeof o.styleRef=="string"&&n.push(o.styleRef),o.style&&o.style.styleRef&&typeof o.style.styleRef=="string"&&n.push(o.style.styleRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function J_(){return{type:he.STYLE_REF,canResolve:ze.canResolve.bind(ze),resolve:ze.resolve.bind(ze),validate:ze.validate.bind(ze)}}class bt{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,n){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let r;const s=e.match(we.LAYOUT_REF);if(s?r=s[1]:r=e,n.layoutPresets&&n.layoutPresets[r]){const i=n.layoutPresets[r];return this.resolveLayoutPreset(i,n)}const o={card:{type:"card",padding:"20px",theme:"light"},vertical:{type:"vertical",spacing:"15px",alignment:"start"},horizontal:{type:"horizontal",spacing:"15px",alignment:"center"}};if(o[r])return{...o[r]};throw new Error(`布局预设未找到: ${r}`)}static resolveLayoutPreset(e,n){const r={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(tt.canResolve(o))try{r[s]=tt.resolve(o,n)}catch(i){console.warn(`布局中的设计令牌解析失败: ${s}=${o}`,i),r[s]=o}}else o&&typeof o=="object"&&(r[s]=this.resolveLayoutPreset(o,n));return r}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.LAYOUT_REF);return s?r=s[1]:r=e,n.layoutPresets&&n.layoutPresets[r]?!0:["card","vertical","horizontal"].includes(r)}static applyLayout(e,n){if(!e||!n)return e;const r={...e};return r.layout?r.layout={...r.layout,...n}:r.layout={...n},r}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`布局引用解析失败: ${s}`,o)}return r}static extractLayoutRefs(e){const n=[];for(const r of Object.values(e))if(r.layout&&r.layout.type&&typeof r.layout.type=="string"&&this.isLayoutRef(r.layout.type)&&n.push(r.layout.type),r.layout&&typeof r.layout=="object")for(const s of Object.values(r.layout))typeof s=="string"&&this.isLayoutRef(s)&&n.push(s);return[...new Set(n)]}static isLayoutRef(e){return we.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function Z_(){return{type:he.LAYOUT_REF,canResolve:bt.canResolve.bind(bt),resolve:bt.resolve.bind(bt),validate:bt.validate.bind(bt)}}class an{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.ANIMATION_REF.test(e)}static resolve(e,n){if(!this.canResolve(e))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const r=e.match(we.ANIMATION_REF);if(!r)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const s=r[1],o=n.animationConfigs?.[s];if(!o)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${s}`);return this.resolveAnimationConfig(s,o,n)}static resolveAnimationConfig(e,n,r){if(!n.transforms||!Array.isArray(n.transforms))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const s=n.transforms.map((a,l)=>{if(!a.id)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 id 字段`);if(!a.type)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}] targetShapes 不能为空`);a.targetShapes.forEach((f,g)=>{if(typeof f!="string"||f.trim()==="")throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${l}].targetShapes[${g}] 必须是有效的字符串 ID`)});const c=Qy(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:c,targetShapes:a.targetShapes,usesControl:d}}),o={id:e,control:n.control,transforms:s,visualEffects:n.visualEffects||[],progressControl:n.progressControl},i=eb(o);if(!i.valid)throw new Ee(re.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
46
79
  ${i.errors?.join(`
47
- `)}`);return o}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.ANIMATION_REF);return s?r=s[1]:r=e,r in(n.animationConfigs||{})}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`动画引用解析失败: ${s}`,o)}return r}static extractAnimationRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.animationRef&&typeof s.animationRef=="string"&&n.push(s.animationRef),s.chartConfig?.animationRef&&typeof s.chartConfig.animationRef=="string"&&n.push(s.chartConfig.animationRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function dx(){return{type:he.ANIMATION_REF,canResolve:sn.canResolve.bind(sn),resolve:sn.resolve.bind(sn),validate:sn.validate.bind(sn)}}class zt{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,n){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!n,contextKeys:Object.keys(n||{}),animationDefinitionsKeys:n.animationDefinitions?Object.keys(n.animationDefinitions):[],animationConfigsKeys:n.animationConfigs?Object.keys(n.animationConfigs):[]}),!this.canResolve(e))throw new Ee(re.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const r=e.match(we.SLIDER_REF),s=r?r[1]:e;let o=n.animationDefinitions?.[s];return!o&&n.animationConfigs&&(o=n.animationConfigs[s]),!o&&cn?.animationDefinitions&&(o=cn.animationDefinitions[s]),!o&&cn?.animationConfigs&&(o=cn.animationConfigs[s]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:s,hasRawConfig:!!o,rawConfig:o,animationDefinitions:n.animationDefinitions,animationConfigs:n.animationConfigs,hasGlobalContext:!!cn}),o?this.validateAndTransformConfig(s,o):(console.warn(`⚠️ 滑块配置未找到: ${s},使用默认配置`),{...ux,id:s})}static validateAndTransformConfig(e,n){if(!n.slider)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:r}=n,s=["position","length","orientation","min","max","step"];for(const o of s)if(!(o in r))throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${o} 字段`);if(!Array.isArray(r.position)||r.position.length!==2)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(r.orientation!=="horizontal"&&r.orientation!=="vertical")throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(r.min>=r.max)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(r.step<=0)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:r.position,length:r.length,orientation:r.orientation,min:r.min,max:r.max,step:r.step},progressIndicator:n.progressIndicator,duration:n.duration,easing:n.easing,description:n.description}}static validate(e,n){if(!this.canResolve(e))return!1;const r=e.match(we.SLIDER_REF),s=r?r[1]:e;return s in(n.animationDefinitions||{})||s in(n.animationConfigs||{}),!0}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`滑块引用解析失败: ${s}`,o)}return r}static extractSliderRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.sliderRef&&typeof s.sliderRef=="string"&&n.push(s.sliderRef),s.chartConfig?.sliderRef&&typeof s.chartConfig.sliderRef=="string"&&n.push(s.chartConfig.sliderRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}const ux={id:"default_slider",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"默认滑块配置(引用未找到时使用)"};function fx(){return{type:he.SLIDER_REF,canResolve:zt.canResolve.bind(zt),resolve:zt.resolve.bind(zt),validate:zt.validate.bind(zt)}}class on{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,n,r){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const s=e.match(we.GEOMETRY_TRANSFORM_REF),o=s?s[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${o}`,{hasGeometryTransformConfigs:!!n.geometryTransformConfigs,configKeys:n.geometryTransformConfigs?Object.keys(n.geometryTransformConfigs):[]});const i=n.geometryTransformConfigs?.[o];if(!i)throw new Ee(re.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${o}`,{reference:e,configId:o,availableConfigs:n.geometryTransformConfigs?Object.keys(n.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=r?this.applyOverride(i,r):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,n){const r={...e};for(const[s,o]of Object.entries(n))o!==void 0&&(r[s]=o);return n.shapes&&(r.shapes={static:[...r.shapes?.static||[]],animated:[...r.shapes?.animated||[]]},n.shapes.static&&(r.shapes.static=n.shapes.static),n.shapes.animated&&(r.shapes.animated=n.shapes.animated)),n.transform&&(r.transform={...r.transform,...n.transform}),r}static validate(e,n){if(!this.canResolve(e))return!1;const r=e.match(we.GEOMETRY_TRANSFORM_REF),s=r?r[1]:e;return!!n.geometryTransformConfigs?.[s]}static batchResolve(e,n,r){const s={};for(const o of e)if(this.canResolve(o)&&this.validate(o,n))try{const i=r?.[o];s[o]=this.resolve(o,n,i)}catch(i){console.warn(`几何变换引用解析失败: ${o}`,i)}return s}static extractFromContentBlock(e){return!e||typeof e!="object"?null:e.geometryTransformRef&&typeof e.geometryTransformRef=="string"?e.geometryTransformRef:null}static extractFromContentBlocks(e){const n=[];for(const r of e){const s=this.extractFromContentBlock(r);s&&n.push(s)}return[...new Set(n)]}}function hx(){return{type:he.GEOMETRY_TRANSFORM_REF,canResolve:on.canResolve.bind(on),resolve:on.resolve.bind(on),validate:on.validate.bind(on)}}const Ro={geometryRef:he.GEOMETRY_REF,styleRef:he.STYLE_REF,layoutRef:he.LAYOUT_REF,boardRef:he.BOARD_REF,animationRef:he.ANIMATION_REF,transformRef:he.TRANSFORM_REF,appearanceRef:he.STYLE_REF,geometryTransformRef:he.GEOMETRY_TRANSFORM_REF,sliderRef:he.SLIDER_REF,$ref:he.GEOMETRY_REF};class gx{static extractRefs(e){const n=[],r=new Set,s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o)){if(i in Ro){if(typeof a=="string"){const l=Ro[i],c=`${i}:${a}`;r.has(c)||(r.add(c),n.push({ref:a,type:l,path:i,value:a,fieldName:i,combined:c}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(c=>{const d=c;r.has(d)||(r.add(d),n.push({ref:c,type:he.DESIGN_TOKEN,path:"$ref",value:c,fieldName:"",combined:d}))});continue}if(Array.isArray(a)){a.forEach(l=>s(l));continue}typeof a=="object"&&s(a)}};return s(e),n}static extractDesignTokens(e){const n=[],r=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let s;for(;(s=r.exec(e))!==null;)n.push(s[0]);return n}static calculateStats(e){const n=this.extractRefs(e).map(o=>o.ref),r={},s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o))i in Ro?r[i]=(r[i]||0)+1:typeof a=="object"&&s(a)};return s(e),{totalRefs:n.length,uniqueRefs:new Set(n).size,fieldCounts:r}}}class An{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(ox()),this.register(ix()),this.register(ax()),this.register(lx()),this.register(cx()),this.register(dx()),this.register(fx()),this.register(hx())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(n=>n.type===e)}getResolverForRef(e){return this.resolvers.find(n=>n.canResolve(e))}resolve(e,n){if(typeof e!="string"){const s=this.getResolverByType(e.type);if(!s)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return s.resolve(e.value,n)}catch(o){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${o}`)}}const r=this.resolvers.filter(s=>s.canResolve(e));if(r.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const s of r)try{return s.resolve(e,n)}catch(o){console.debug(`解析器 ${s.type} 解析 ${e} 失败:`,o);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,n){const r={};for(const s of e)try{const o=this.resolve(s,n),i=typeof s=="string"?s:s.combined;r[i]=o}catch(o){const i=typeof s=="string"?s:s.combined;console.warn(`引用解析失败: ${i}`,o)}return r}extractAllRefsEnhanced(e){try{return gx.extractRefs(e)}catch(n){return console.warn("ReferenceExtractor 提取失败:",n),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(r=>r.combined)}extractAllRefsLegacy(e){const n=[],r=s=>{if(!(!s||typeof s!="object"))for(const[o,i]of Object.entries(s))if(o.endsWith("Ref")&&typeof i=="string")n.push(i);else if(typeof i=="string"&&i.includes("$")){const a=i.match(/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g);a&&n.push(...a)}else Array.isArray(i)?i.forEach(a=>r(a)):typeof i=="object"&&r(i)};return r(e),[...new Set(n)]}validate(e,n){const r=this.getResolverForRef(e);if(!r)return!1;if(r.validate)return r.validate(e,n);try{return r.resolve(e,n),!0}catch{return!1}}}function Nu(){return new An}class Yr{static transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 GraphTransformer.transform START for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o,contextGeometryKeys:Object.keys(n.geometryPresets||{})}),console.error("🎯 GraphTransformer.transform called for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o}),e.shapes&&Array.isArray(e.shapes)&&console.warn(`📊 GraphTransformer contentBlock shapes (${e.shapes.length}):`,e.shapes.map(a=>({id:a.id,type:a.type,geometryRef:a.geometryRef,styleRef:a.styleRef})));const i={...e,type:je.GRAPH};if(!s)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,n),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,l)=>(console.error(` 🎯 处理shape[${l}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,n,{strictMode:o})))),i.styleRef){try{const a=ze.resolve(i.styleRef,n);i.style=a}catch(a){if(o)throw a;console.warn(`图形样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}if(i.animationRef){console.warn(`🎬 GraphTransformer处理animationRef: ${i.animationRef}`);try{const a=i.animationRef.startsWith("animationRef:")?i.animationRef:`animationRef:${i.animationRef}`,l=sn.resolve(a,n);console.warn(" 动画配置解析结果:",{animationId:l.id,transformCount:l.transforms.length,hasControl:!!l.control,controlConfig:l.control,hasVisualEffects:!!l.visualEffects,visualEffectsCount:l.visualEffects?.length||0}),i.animation=l,i.transformDefinitions&&(console.warn(" 清理旧的 transformDefinitions(被 animation 替代)"),delete i.transformDefinitions)}catch(a){if(o)throw a;console.warn(`❌ 动画配置解析失败: ${i.animationRef}`,a)}delete i.animationRef}else i.animation&&(console.warn("🎬 GraphTransformer检测到内联动画配置:",{animationId:i.animation.id,transformCount:i.animation.transforms?.length||0}),i.animation.transforms&&Array.isArray(i.animation.transforms)?console.warn(` 内联动画配置有效,transforms 数量: ${i.animation.transforms.length}`):(console.warn(" ⚠️ 内联动画配置格式无效,缺少 transforms 数组"),delete i.animation));return i}catch(a){if(o)throw a;return console.warn("图形转换失败:",a),i}}static transformShape(e,n,r={}){const{strictMode:s=!1}=r;console.error("🔄 GraphTransformer.transformShape START for shape:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:"geometryRef"in e,geometryRef:e.geometryRef,hasStyleRef:"styleRef"in e,styleRef:e.styleRef,allShapeKeys:Object.keys(e),contextGeometryKeys:Object.keys(n.geometryPresets||{})}),(e.id==="base_line"||e.id==="height_line")&&console.error(`🔍 特别处理 ${e.id}:`,{id:e.id,type:e.type,geometryRef:e.geometryRef,styleRef:e.styleRef,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints)});let o={...e};e.type==="point"&&console.warn(`📌 GraphTransformer processing point ${e.id}:`,{id:e.id,type:e.type,position:e.position,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),shapeKeys:Object.keys(e)});try{if(o.geometryRef){console.warn(`🔄 GraphTransformer processing geometryRef: ${o.geometryRef} for shape ${o.id}`,{shapeId:o.id,shapeType:o.type,geometryRef:o.geometryRef,contextHasGeometryPresets:!!n.geometryPresets,geometryPresetKeys:n.geometryPresets?Object.keys(n.geometryPresets):[]});try{const i=yt.resolve(o.geometryRef,n);console.warn(` Geometry resolved for ${o.geometryRef}:`,{type:i.type,hasVertices:"vertices"in i,vertices:i.vertices,hasPosition:"position"in i,position:i.position,hasEndpoints:"endpoints"in i,endpoints:i.endpoints,endpointsIsArray:Array.isArray(i.endpoints),geometryKeys:Object.keys(i)});const a=o.type,l=o.content,c={...o};Object.assign(o,i),o.id=e.id,a!==void 0&&(o.type=a),l!==void 0&&(o.content=l),console.warn(` After merge for ${o.id}:`,{type:o.type,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:"undefined",position:o.position,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),transformedShapeKeys:Object.keys(o)});const d=o.type;let f=!1;const g=n.geometryPresets[o.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:o.geometryRef,originalGeometryExists:!!g,originalGeometryType:g?.type,originalGeometryKeys:g?Object.keys(g):[],hasVertices:g&&"vertices"in g,verticesIsArray:g&&Array.isArray(g.vertices),verticesLength:g?.vertices?.length,contextGeometryPresetsKeys:Object.keys(n.geometryPresets||{})}),g&&g.vertices&&Array.isArray(g.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:g.vertices,hasWithLabel:"withLabel"in g,withLabel:g.withLabel,hasLabel:"label"in g,label:g.label}),o.verticesConfig||(o.verticesConfig={}),g.vertices.forEach((h,m)=>{if(console.warn(`🔍 DEBUG: 检查顶点${m}:`,{vertex:h,isObject:h&&typeof h=="object",hasDollarRef:h&&typeof h=="object"&&"$ref"in h,refName:h?.$ref}),h&&typeof h=="object"&&"$ref"in h){const p=h.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${p},检查context.geometryPresets`),n.geometryPresets&&n.geometryPresets[p]){const y=n.geometryPresets[p];console.warn(`🔍 DEBUG: 找到点定义 ${p}:`,y),y.name?(o.verticesConfig[m]||(o.verticesConfig[m]={}),o.verticesConfig[m].name=y.name,console.warn(`✅ 从原始几何定义提取顶点${m}名字: ${y.name}`)):console.warn(`⚠️ 点定义 ${p} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${p}`)}else console.warn(`⚠️ 顶点${m}不是$ref对象`)}),g.withLabel!==void 0&&(o.verticesConfig.withLabel=g.withLabel),g.label&&typeof g.label=="object"){const h=g.label;h.offset&&Array.isArray(h.offset)&&h.offset.length>=2&&(o.verticesConfig.offset=h.offset),h.fontSize!==void 0&&(o.verticesConfig.fontSize=h.fontSize),h.color&&(o.verticesConfig.color=h.color),h.anchorX&&(o.verticesConfig.anchorX=h.anchorX),h.anchorY&&(o.verticesConfig.anchorY=h.anchorY)}console.warn("✅ 构建的verticesConfig:",o.verticesConfig)}if(d==="segment"||d==="line"?f="endpoints"in o&&Array.isArray(o.endpoints):d==="point"?f="position"in o&&o.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?f="vertices"in o&&Array.isArray(o.vertices):f="vertices"in o&&Array.isArray(o.vertices)||"endpoints"in o&&Array.isArray(o.endpoints)||"position"in o&&o.position!==void 0,f||(console.error(`❌ ERROR: After geometryRef merge, shape ${o.id} (type: ${d}) has no valid geometry properties!`),console.error(" geometry keys:",Object.keys(i)),console.error(" geometry.type:",i.type),console.error(" transformedShape keys:",Object.keys(o))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const h=ze.resolve(i.styleRef,n);console.error(" 几何样式解析结果:",h),o.style=h}}catch(i){if(s)throw i;console.error(`❌ 图形几何解析失败: ${o.geometryRef}`,i),console.error(` shape id: ${o.id}, type: ${o.type}`),console.error(" context.geometryPresets keys:",n.geometryPresets?Object.keys(n.geometryPresets):"undefined")}delete o.geometryRef}if(o.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${o.styleRef}, shape id: ${o.id}`);try{const i=ze.resolve(o.styleRef,n);console.error(" 形状样式解析成功:",i);const{id:a,...l}=i;o={...o,...l,style:{...o.style,...i}}}catch(i){if(s)throw i;console.warn(`图形元素样式解析失败: ${o.styleRef}`,i),delete o.style}delete o.styleRef}if(Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(i=>this.transformTransform(i,n,{strictMode:s}))),o.label&&typeof o.label=="object"&&(o.label=this.transformLabel(o.label,n)),console.warn(`🔍 Checking segment conversion for ${o.id}:`,{type:o.type,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,shapeKeys:Object.keys(o)}),o=this.convertShapeCoordinates(o,n),o.type==="segment"&&Array.isArray(o.endpoints)&&o.endpoints.length>=2){console.warn(`🔄 Converting segment to line for ${o.id}:`,{originalType:o.type,endpoints:o.endpoints}),o.type="line";const i=this.resolvePointReference(o.endpoints[0],n),a=this.resolvePointReference(o.endpoints[1],n);Array.isArray(i)&&i.length>=2?o.start={x:i[0],y:i[1]}:i&&typeof i=="object"&&"x"in i&&"y"in i?o.start=i:o.start=o.endpoints[0],Array.isArray(a)&&a.length>=2?o.end={x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?o.end=a:o.end=o.endpoints[1],delete o.endpoints}return console.warn(`✅ GraphTransformer finished transforming shape ${o.id} (${o.type}):`,{id:o.id,type:o.type,hasVertices:"vertices"in o,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:0,hasVerticesConfig:"verticesConfig"in o,verticesConfig:o.verticesConfig,verticesConfigKeys:o.verticesConfig?Object.keys(o.verticesConfig):[],hasPosition:"position"in o,position:o.position,hasStart:"start"in o,start:o.start,hasEnd:"end"in o,end:o.end,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,hasGeometryRef:"geometryRef"in o,geometryRef:o.geometryRef,keys:Object.keys(o)}),o}catch(i){if(s)throw i;return console.warn("图形元素转换失败:",i),o}}static resolvePointReference(e,n){if(!e||typeof e!="object")return e;if("$ref"in e){const r=e.$ref;if(n&&n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}if("geometryRef"in e){const r=e.geometryRef;if(n&&n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}return e}static convertShapeCoordinates(e,n){if(!e||typeof e!="object")return e;console.warn("🔄 GraphTransformer.convertShapeCoordinates START for shape:",{id:e.id,type:e.type,hasVertices:"vertices"in e,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e)});const r={...e};if(r.position){if(Array.isArray(r.position)&&r.position.length>=2)console.warn(`🔄 Converting position array to object for ${r.id}:`,{shapeId:r.id,positionArray:r.position,convertedTo:{x:r.position[0],y:r.position[1]}}),r.position={x:r.position[0],y:r.position[1]};else if(typeof r.position=="object"){const s=this.resolvePointReference(r.position,n);s&&typeof s=="object"&&(r.position=s)}}if(Array.isArray(r.vertices)){const s=r.verticesConfig?{...r.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!r.verticesConfig,existingKeys:r.verticesConfig?Object.keys(r.verticesConfig):[],verticesConfigKeys:Object.keys(s)}),r.vertices=r.vertices.map((o,i)=>{const a=this.resolvePointReference(o,n);let l=null;if(o&&typeof o=="object"&&"$ref"in o){const c=o.$ref;n&&n.geometryPresets&&n.geometryPresets[c]&&(l=n.geometryPresets[c],console.warn(`📌 Found point definition for ${c} at vertex ${i}:`,{hasWithLabel:"withLabel"in l,withLabel:l.withLabel,hasLabel:"label"in l,labelKeys:l.label?Object.keys(l.label):"none"}),l.name&&(s[i]||(s[i]={}),s[i].name=l.name))}return Array.isArray(a)&&a.length>=2?{x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?a:(o&&typeof o=="object"&&("$ref"in o||"geometryRef"in o),o)}),r.withLabel!==void 0||r.label){const o={withLabel:r.withLabel!==void 0?r.withLabel:!0};if(r.label&&typeof r.label=="object"){const a=r.label;a.offset&&Array.isArray(a.offset)&&a.offset.length>=2&&(o.offset=a.offset),a.fontSize!==void 0&&(o.fontSize=a.fontSize),a.color&&(o.color=a.color),a.anchorX&&(o.anchorX=a.anchorX),a.anchorY&&(o.anchorY=a.anchorY)}const i={...o};for(const a in s)isNaN(Number(a))||(i[a]||(i[a]={}),Object.assign(i[a],s[a]));r.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${r.id}:`,i)}else Object.keys(s).length>0&&(r.verticesConfig=s,console.warn(`✅ Added verticesConfig for polygon ${r.id}:`,s))}if(Array.isArray(r.endpoints)&&(r.endpoints=r.endpoints.map(s=>{const o=this.resolvePointReference(s,n);return Array.isArray(o)&&o.length>=2?{x:o[0],y:o[1]}:o&&typeof o=="object"&&"x"in o&&"y"in o?o:(s&&typeof s=="object"&&("$ref"in s||"geometryRef"in s),s)})),Array.isArray(r.center)&&r.center.length>=2)r.center={x:r.center[0],y:r.center[1]};else if(r.center&&typeof r.center=="object"){const s=this.resolvePointReference(r.center,n);s&&typeof s=="object"&&(r.center=s)}if(r.start){if(Array.isArray(r.start)&&r.start.length>=2)r.start={x:r.start[0],y:r.start[1]};else if(typeof r.start=="object"){const s=this.resolvePointReference(r.start,n);s&&typeof s=="object"&&(r.start=s)}}if(r.end){if(Array.isArray(r.end)&&r.end.length>=2)r.end={x:r.end[0],y:r.end[1]};else if(typeof r.end=="object"){const s=this.resolvePointReference(r.end,n);s&&typeof s=="object"&&(r.end=s)}}for(const[s,o]of Object.entries(r))Array.isArray(o)?r[s]=o.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,n):i):o&&typeof o=="object"&&(r[s]=this.convertShapeCoordinates(o,n));return r}static transformTransform(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.transformRef){try{const i=qe.resolve(o.transformRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformLabel(e,n){const r={...e};if(r.styleRef){try{const s=ze.resolve(r.styleRef,n);r.style=s}catch(s){console.warn(`标签样式解析失败: ${r.styleRef}`,s)}delete r.styleRef}return r}static resolveBoardConfig(e,n){if(n.boardDefinitions&&n.boardDefinitions[e])return n.boardDefinitions[e];const r={default:{originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1},extended:{originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1}};return r[e]||r.default}static validate(e){const n=[];return e?(e.type!==je.GRAPH&&n.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&n.push("图形内容块 shapes 数组不能为空"):n.push("图形内容块缺少 shapes 数组"),n):(n.push("图形内容块不能为空"),n)}static batchTransform(e,n,r={}){return e.filter(s=>s.type===je.GRAPH).map(s=>this.transform(s,n,r))}}function mx(){return{type:je.GRAPH,transform:Yr.transform.bind(Yr),validate:Yr.validate.bind(Yr)}}class Kr{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const n={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:n,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:n.static.length,animatedLength:n.animated.length}),n}static transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(s){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const d=on.resolve(e.geometryTransformRef,n,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const f={type:je.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",f.metadata.config),f.metadata.config&&typeof f.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),f.metadata.config=this.transformConfig(f.metadata.config,n,{strictMode:o})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",f),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",f.metadata.config),f}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:je.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(d){if(o)throw d;console.error("❌ 几何变换引用解析失败:",d),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",n.geometryTransformConfigs)}}const i=e.base||e.config?.base||n.basicInfo?.base||0,a=e.height||e.config?.height||n.basicInfo?.height||0,l=e.unit||e.config?.unit||n.basicInfo?.baseUnit||"cm",c={...e,type:je.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:l,...e.config||{},shapes:this.normalizeShapes(e.shapes||e.config?.shapes),transform:e.transform||e.config?.transform||{},animation:e.animation||e.config?.animation||{},boardConfig:e.boardConfig||e.config?.boardConfig||{}}}};if(console.error("🔍 GeometryTransformTransformer.transform: 转换后配置 =",{metadataConfig:c.metadata?.config,shapesAnimatedLength:c.metadata?.config?.shapes?.animated?.length,shapesStaticLength:c.metadata?.config?.shapes?.static?.length,base:c.metadata?.config?.base,height:c.metadata?.config?.height,unit:c.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete c.config,delete c.base,delete c.height,delete c.unit,delete c.shapes,delete c.transform,delete c.animation,delete c.boardConfig,!s)return c;try{if(c.geometryRef){try{const d=yt.resolve(c.geometryRef,n);if(c.metadata.config||(c.metadata.config={}),Object.assign(c.metadata.config,d),d.styleRef){const f=ze.resolve(d.styleRef,n);c.metadata.config.style=f}}catch(d){if(o)throw d;console.warn(`几何变换几何解析失败: ${c.geometryRef}`,d)}delete c.geometryRef}if(c.transformRef){try{const d=qe.resolve(c.transformRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.transform||(c.metadata.config.transform={}),Object.assign(c.metadata.config.transform,d)}catch(d){if(o)throw d;console.warn(`几何变换变换解析失败: ${c.transformRef}`,d)}delete c.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!c.metadata,hasConfig:!!c.metadata?.config,configType:c.metadata?.config?typeof c.metadata.config:"undefined",configIsObject:c.metadata?.config?typeof c.metadata.config=="object":!1,configKeys:c.metadata?.config?Object.keys(c.metadata.config):[]}),c.metadata?.config&&typeof c.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),c.metadata.config=this.transformConfig(c.metadata.config,n,{strictMode:o}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),c.styleRef){try{const d=ze.resolve(c.styleRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.style=d}catch(d){if(o)throw d;console.warn(`几何变换样式解析失败: ${c.styleRef}`,d)}delete c.styleRef}if(c.animationRef){try{const d=this.resolveAnimationConfig(c.animationRef,n,{strictMode:o});c.metadata.config||(c.metadata.config={}),c.metadata.config.animation={...d,...c.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层动画引用解析失败: ${c.animationRef}`,d)}delete c.animationRef}if(c.sliderRef){try{const d=zt.resolve(c.sliderRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.animation={...d,...c.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层滑块引用解析失败: ${c.sliderRef}`,d)}delete c.sliderRef}if(c.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:c.boardRef,hasMetadataConfig:!!c.metadata?.config,currentBoardConfig:c.metadata?.config?.boardConfig});try{const d=this.resolveBoardConfig(c.boardRef,n,{strictMode:o});console.error("🔍 解析后的 boardConfig:",d),c.metadata.config||(c.metadata.config={}),c.metadata.config.boardConfig={...d,...c.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",c.metadata.config.boardConfig)}catch(d){if(o)throw d;console.warn(`顶层画板引用解析失败: ${c.boardRef}`,d)}delete c.boardRef}if(c.metadata?.config?.boardConfig&&typeof c.metadata.config.boardConfig=="object"){const d=c.metadata.config.boardConfig;(!d.boundingBox||!Array.isArray(d.boundingBox)||d.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),d.boundingBox=[0,7,10,0],d.originX=d.originX??2,d.originY=d.originY??2,d.keepAspectRatio=d.keepAspectRatio??!0,d.showGrid=d.showGrid??!1,d.showAxis=d.showAxis??!1,d.description=d.description||"默认画板配置")}return console.error("🔍 GeometryTransformTransformer.transform: 最终转换结果 =",{type:c.type,metadataConfig:c.metadata?.config,shapesAnimatedLength:c.metadata?.config?.shapes?.animated?.length,shapesStaticLength:c.metadata?.config?.shapes?.static?.length,base:c.metadata?.config?.base,height:c.metadata?.config?.height,unit:c.metadata?.config?.unit,hasTransform:!!c.metadata?.config?.transform,transform:c.metadata?.config?.transform,hasAnimation:!!c.metadata?.config?.animation,animation:c.metadata?.config?.animation,hasBoardConfig:!!c.metadata?.config?.boardConfig,boardConfig:c.metadata?.config?.boardConfig}),c}catch(d){if(o)throw d;return console.warn("几何变换转换失败:",d),c}}static transformConfig(e,n,r={}){const{strictMode:s=!1}=r,o={...e},i={};if(o.shapes&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 shapes"),console.error(" transformedConfig.shapes:",o.shapes),o.shapes.static&&(console.error(` 处理 static shapes (${o.shapes.static.length}):`),o.shapes.static=o.shapes.static.map((a,l)=>{console.error(` 处理 static shape[${l}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const c=this.transformShape(a,n,{strictMode:s});return a.geometryRef&&c.id&&(i[a.geometryRef]=c.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${c.id}" (转换后)`)),console.error(` 转换后的 static shape[${l}]:`,{id:c.id,type:c.type,hasGeometryRef:!!c.geometryRef,geometryRef:c.geometryRef,hasVertices:!!c.vertices,vertices:c.vertices}),c})),o.shapes.animated&&(console.error(` 处理 animated shapes (${o.shapes.animated.length}):`),o.shapes.animated=o.shapes.animated.map((a,l)=>{console.error(` 处理 animated shape[${l}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const c=this.transformShape(a,n,{strictMode:s});return a.geometryRef&&c.id&&(i[a.geometryRef]=c.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${c.id}" (转换后)`)),console.error(` 转换后的 animated shape[${l}]:`,{id:c.id,type:c.type,hasGeometryRef:!!c.geometryRef,geometryRef:c.geometryRef,hasVertices:!!c.vertices,vertices:c.vertices}),c}))),o.transform){if(o.transform.transformRef)try{const a=qe.resolve(o.transform.transformRef,n);o.transform={...a,...o.transform,transformRef:void 0},console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transform 对象中的 transformRef",{originalTransformRef:o.transform.transformRef,resolvedTransform:a,mergedTransform:o.transform})}catch(a){if(s)throw a;console.warn(`Transform ref解析失败: ${o.transform.transformRef}`,a)}o.transform=this.normalizeTransformConfig(o.transform,i),Array.isArray(o.transform.transforms)&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transforms 数组",{transformsLength:o.transform.transforms.length,transforms:o.transform.transforms}),o.transform.transforms=o.transform.transforms.map((a,l)=>{if(console.error(`🔍 处理 transform[${l}]:`,{type:typeof a,isString:typeof a=="string",isObject:typeof a=="object"&&a!==null,transformItem:a,hasTransformRef:a&&typeof a=="object"&&"transformRef"in a,transformRef:a&&typeof a=="object"?a.transformRef:void 0}),typeof a=="string"){if(console.error(`🔍 transform[${l}] 是字符串格式`),a.startsWith("transformRef:")){const c=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${c}`);try{const d=qe.resolve(c,n);console.error(`🔍 transform[${l}] 解析成功:`,d);const f=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${l}] 标准化后:`,f),f}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${c}`,d),a}}try{const c=qe.resolve(a,n);return this.normalizeTransformConfig(c,i)}catch(c){if(s)throw c;return console.warn(`Transform ref解析失败: ${a}`,c),a}}else if(a&&typeof a=="object"&&a.transformRef){const c=a.transformRef;console.error(`🔍 transform[${l}] 是对象格式,refName=${c}`);try{const d=qe.resolve(c,n);console.error(`🔍 transform[${l}] 解析成功:`,d);const f={...d,...a,transformRef:void 0};console.error(`🔍 transform[${l}] 合并后:`,f);const g=this.normalizeTransformConfig(f,i);return console.error(`🔍 transform[${l}] 标准化后:`,g),g}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${c}`,d),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${l}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${l}] 未处理,返回原始值:`,a),a}))}if(o.geometry&&typeof o.geometry=="object"&&(o.geometry=this.transformGeometry(o.geometry,n,{strictMode:s})),Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(a=>{if(a.transformRef)try{const l=qe.resolve(a.transformRef,n);return{...a,...l,transformRef:void 0}}catch(l){if(s)throw l;return console.warn(`Transformations解析失败: ${a.transformRef}`,l),a}return a})),o.style&&typeof o.style=="object"&&(o.style=this.transformStyle(o.style,n,{strictMode:s})),o.animationRef){try{const a=this.resolveAnimationConfig(o.animationRef,n,{strictMode:s});o.animation={...a,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`动画引用解析失败: ${o.animationRef}`,a)}delete o.animationRef}if(o.sliderRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 sliderRef",{sliderRef:o.sliderRef,hasAnimationDefinitions:!!n.animationDefinitions,animationDefinitionKeys:n.animationDefinitions?Object.keys(n.animationDefinitions):[]});try{const a={...cn,...n,animationDefinitions:n.animationDefinitions||cn.animationDefinitions},l=zt.resolve(o.sliderRef,a);o.animation={...l,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`滑块引用解析失败: ${o.sliderRef}`,a)}delete o.sliderRef}if(o.boardRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 config 中的 boardRef",{boardRef:o.boardRef,currentBoardConfig:o.boardConfig});try{const a=this.resolveBoardConfig(o.boardRef,n,{strictMode:s});console.error("🔍 解析后的 boardConfig (config):",a),o.boardConfig={...a,...o.boardConfig||{}},console.error("🔍 设置后的 transformedConfig.boardConfig:",o.boardConfig)}catch(a){if(s)throw a;console.warn(`画板引用解析失败: ${o.boardRef}`,a)}delete o.boardRef}return o}static normalizeTransformConfig(e,n){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:n?Object.keys(n):[],geometryRefToShapeId:n});const r={...e};switch(!r.type&&r.config&&r.config.type&&(r.type=r.config.type),r.type){case"rotation":if(r.config){if(r.rotation={...r.config},r.rotation.center&&typeof r.rotation.center=="object"){const s=r.rotation.center;"x"in s&&"y"in s&&(r.rotation.center=[s.x,s.y])}delete r.config}break;case"translation":r.config&&(r.translation={...r.config},delete r.config);break;case"scale":if(r.config){if(r.scale={...r.config},r.scale.center&&typeof r.scale.center=="object"){const s=r.scale.center;"x"in s&&"y"in s&&(r.scale.center=[s.x,s.y])}delete r.config}break;case"composite":r.config&&Array.isArray(r.config.transforms)&&(r.composite=r.config.transforms.map(s=>this.normalizeTransformConfig(s,n)),delete r.config);break;default:if(r.config){const{type:s,...o}=r.config;Object.assign(r,o),delete r.config}}if(r.targetGroup&&n){const s=r.targetGroup;let o;if(n[s])o=n[s],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:s,mapped:o,type:"exact"});else{const i=Object.keys(n).find(a=>{if(a.startsWith(s+"_")||a===s||a.includes(s))return!0;const l=a.split("_"),c=s.split("_");return l.some(d=>c.includes(d))});i&&(o=n[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:s,geometryRef:i,mapped:o,type:"heuristic"}))}o?r.targetGroup=o:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:s,geometryRefToShapeId:n,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!r.targetGroup&&(r.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:r,hasRotation:!!r.rotation,hasTranslation:!!r.translation,hasScale:!!r.scale,hasComposite:!!r.composite}),r}static transformShape(e,n,r={}){console.error("🔍 transformShape 被调用:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasStyleRef:!!e.styleRef,styleRef:e.styleRef,shapeKeys:Object.keys(e),contextHasGeometryPresets:!!n.geometryPresets,contextGeometryPresetKeys:n.geometryPresets?Object.keys(n.geometryPresets):[]});const{strictMode:s=!1}=r,o={...e};if(o.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",o.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",n.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",n.geometryPresets?Object.keys(n.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=yt.resolve(o.geometryRef,n);console.error("🔍 transformShape: geometry 解析结果:",i),Object.assign(o,i),console.error("🔍 transformShape: 合并后的 shape:",o),o.vertices&&Array.isArray(o.vertices)&&console.error("🔍 transformShape: 顶点数据:",{count:o.vertices.length,sample:o.vertices.slice(0,3).map((a,l)=>({index:l,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})}catch(i){if(console.error("🔍 transformShape: geometryRef 解析错误:",i),s)throw i;console.warn(`Shape geometryRef解析失败: ${o.geometryRef}`,i)}delete o.geometryRef,console.error("🔍 transformShape: 删除 geometryRef 后的 shape:",o)}if(o.styleRef){try{const i=ze.resolve(o.styleRef,n);o.style=i}catch(i){if(s)throw i;console.warn(`Shape styleRef解析失败: ${o.styleRef}`,i)}delete o.styleRef}if(o.metadata||(o.metadata={}),!o.metadata.id&&o.id&&(o.metadata.id=o.id),o.withLabel!==void 0&&(o.metadata.showLabel=o.withLabel,delete o.withLabel),o.label&&(typeof o.label=="object"?o.metadata.label=o.label.text||o.metadata.id||"":typeof o.label=="string"&&(o.metadata.label=o.label),delete o.label),o.metadata.showLabel&&!o.metadata.label&&o.metadata.id&&(o.metadata.label=o.metadata.id),o.metadata.id&&(o.metadata.rotationGroup=o.metadata.id),o.type==="point"&&o.position){console.error("🔍 transformShape: 转换point为circle:",{shapeId:o.metadata?.id,position:o.position,originalType:o.type});const i=o.position.x,a=o.position.y,l=.1;o.type="circle",o.vertices=[[i,a],[i+l,a]],delete o.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:o.type,vertices:o.vertices})}return o}static transformGeometry(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.geometryRef){try{const i=yt.resolve(o.geometryRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`几何对象解析失败: ${o.geometryRef}`,i)}delete o.geometryRef}return o}static transformTransform(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.transformRef){try{const i=qe.resolve(o.transformRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换对象解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformStyle(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.styleRef){try{const i=ze.resolve(o.styleRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`样式对象解析失败: ${o.styleRef}`,i)}delete o.styleRef}return o}static resolveAnimationConfig(e,n,r={}){const{strictMode:s=!1}=r;if(!e||typeof e!="string"){if(s)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const o=e.replace("animationRef:","");if(n.animationDefinitions&&n.animationDefinitions[o])return{...n.animationDefinitions[o]};if(s)throw new Error(`动画引用未找到: ${o}`);const i=this.getFallbackAnimationConfig(o);return console.warn(`动画引用未在上下文中找到,使用回退配置: ${o}`),i}catch(o){if(s)throw o;return console.warn(`动画配置解析失败: ${e}`,o),{}}}static resolveBoardConfig(e,n,r={}){const{strictMode:s=!1}=r;if(!e||typeof e!="string"){if(s)throw new Error(`无效的画板引用: ${e}`);return console.warn(`无效的画板引用: ${e}`),{}}try{const o=e.replace("boardRef:","");if(console.error("🔍 GeometryTransformTransformer.resolveBoardConfig:",{boardRef:e,refName:o,hasContextBoardDefinitions:!!n.boardDefinitions,contextBoardDefinitionKeys:n.boardDefinitions?Object.keys(n.boardDefinitions):[],hasRefInContext:n.boardDefinitions&&!!n.boardDefinitions[o]}),n.boardDefinitions&&n.boardDefinitions[o]){const a={...n.boardDefinitions[o]};return console.error("🔍 从上下文获取画板配置:",a),a}if(s)throw new Error(`画板引用未找到: ${o}`);const i=this.getFallbackBoardConfig(o);return console.warn(`画板引用未在上下文中找到,使用回退配置: ${o}`),console.error("🔍 使用回退画板配置:",i),i}catch(o){if(s)throw o;return console.warn(`画板配置解析失败: ${e}`,o),{}}}static getFallbackAnimationConfig(e){const n={slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}};return n[e]||n.slider_horizontal}static getFallbackBoardConfig(e){const n={default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}};return n[e]||n.default}static validate(e){const n=[];return e?(e.type!==je.GEOMETRY_TRANSFORM&&n.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||n.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&n.push("几何变换内容块缺少 geometry 或 geometryRef"),n):(n.push("几何变换内容块不能为空"),n)}static batchTransform(e,n,r={}){return e.filter(s=>s.type===je.GEOMETRY_TRANSFORM).map(s=>this.transform(s,n,r))}}function px(){return{type:je.GEOMETRY_TRANSFORM,transform:Kr.transform.bind(Kr),validate:Kr.validate.bind(Kr)}}class Gt{static transformText(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${s}`);const i={...e,type:je.TEXT};if(!s)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,n,{strictMode:o})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,n,{strictMode:o})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=ze.resolve(i.styleRef,n);console.error(" StyleRefResolver解析结果:",a),i.style={...i.style,...a},console.error(" 合并后style:",i.style)}catch(a){if(o)throw a;console.warn(`文本样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("文本转换失败:",a),i}}static transformFormula(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r,i={...e,type:je.FORMULA};if(!s)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,n,{strictMode:o})),i.styleRef){try{const a=ze.resolve(i.styleRef,n);i.style={...i.style,...a}}catch(a){if(o)throw a;console.warn(`公式样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("公式转换失败:",a),i}}static resolveTextContent(e,n,r={}){const{strictMode:s=!1}=r;if(console.error(`📝 TextTransformer.resolveTextContent START: text="${e}", hasDesignTokens=${e.includes("$")}`),!e.includes("$"))return console.error(` resolveTextContent END (no design tokens): "${e}"`),e;let o=e,i;const a=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;for(;(i=a.exec(e))!==null;){const l=i[0],c=i[1];console.error(` 发现设计令牌: ${l}, path=${c}`);try{const d=tt.resolve(l,n);console.error(` 解析结果: ${l} -> ${d}`),o=o.replace(l,String(d))}catch(d){if(s)throw d;console.warn(`文本中的设计令牌解析失败: ${l}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${o}"`),o}static resolveStyle(e,n,r={}){const{strictMode:s=!1}=r;try{return tt.replaceDesignTokenRefs(e,n,o=>{if(s)throw new Error(`设计令牌未找到: ${o}`);return console.warn(`设计令牌未找到: ${o}`),o})}catch(o){if(s)throw o;return console.warn("样式解析失败:",o),e}}static validateText(e){const n=[];return e?(e.type!==je.TEXT&&n.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&n.push("文本内容块缺少 content 字段"),n):(n.push("文本内容块不能为空"),n)}static validateFormula(e){const n=[];return e?(e.type!==je.FORMULA&&n.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&n.push("公式内容块缺少 content 字段"),n):(n.push("公式内容块不能为空"),n)}static batchTransformText(e,n,r={}){return e.filter(s=>s.type===je.TEXT).map(s=>this.transformText(s,n,r))}static batchTransformFormula(e,n,r={}){return e.filter(s=>s.type===je.FORMULA).map(s=>this.transformFormula(s,n,r))}}function yx(){return{type:je.TEXT,transform:Gt.transformText.bind(Gt),validate:Gt.validateText.bind(Gt)}}function bx(){return{type:je.FORMULA,transform:Gt.transformFormula.bind(Gt),validate:Gt.validateFormula.bind(Gt)}}class xx{type="hundredGrid";transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 HundredChartTransformer.transform START for content block:",{blockType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,enableReferenceResolution:s,strictMode:o});try{const i=e.geometryRef;if(!i)throw new Nn(It.MISSING_REQUIRED_FIELD,"HundredGrid内容块缺少geometryRef字段");const a=this.extractShapeId(i),l=n.geometry_shapes?.[a]||n.geometryPresets?.[a];if(!l)throw new Nn(It.GEOMETRY_REF_NOT_FOUND,`HundredGrid引用未找到: ${i} (解析后shapeId: ${a})`);if(l.type!=="hundredGrid")throw new Nn(It.GEOMETRY_REF_NOT_FOUND,`引用${a}不是hundredGrid类型: ${l.type}`);const c=l.config||{},d=e.config||{},f=this.mergeConfigs(c,d),g=this.resolveStyle(l,n,f,s),h=this.mapToHundredChartProps(f,g),m={type:"hundredGrid",content:"",props:h,metadata:{shapeId:a,config:f,styleRef:l.styleRef}};return console.error("✅ HundredChartTransformer.transform SUCCESS:",{shapeId:a,propsKeys:Object.keys(h),hasHighlight:!!f.highlight?.numbers,highlightCount:f.highlight?.numbers?.length||0}),m}catch(i){if(console.error("❌ HundredChartTransformer.transform ERROR:",i),o)throw i;return e}}extractShapeId(e){return e.startsWith("geometryRef:")?e.replace("geometryRef:",""):e}mergeConfigs(e,n){const r={...e};return n.grid&&(r.grid={...e.grid,...n.grid}),n.highlight&&(r.highlight={...e.highlight,...n.highlight},n.highlight.numbers!==void 0&&(r.highlight.numbers=n.highlight.numbers)),n.interactive&&(r.interactive={...e.interactive,...n.interactive}),n.style&&(r.style={...e.style,...n.style}),r}resolveStyle(e,n,r,s){const o={};if(e.styleRef&&s)try{const i=e.styleRef.startsWith("styleRef:")?e.styleRef.replace("styleRef:",""):e.styleRef,a=n.stylePresets?.[i];a&&Object.entries(a).forEach(([l,c])=>{if(typeof c=="string"&&c.startsWith("$"))try{o[l]=tt.resolve(c,n)}catch(d){console.warn(`设计令牌解析失败: ${l}=${c}`,d),o[l]=c}else o[l]=c})}catch(i){console.warn(`样式引用解析失败: ${e.styleRef}`,i)}return r.style&&Object.entries(r.style).forEach(([i,a])=>{if(s&&typeof a=="string"&&a.startsWith("$"))try{o[i]=tt.resolve(a,n)}catch(l){console.warn(`设计令牌解析失败: ${i}=${a}`,l),o[i]=a}else o[i]=a}),o.baseColor||(o.baseColor="#f3f4f6"),o.selectedColor||(o.selectedColor="#3b82f6"),o.borderColor||(o.borderColor="#d1d5db"),o.textColor||(o.textColor="#333"),o.fontSize||(o.fontSize=14),o}mapToHundredChartProps(e,n){const r={};return r.rows=e.grid?.rows||10,r.cols=e.grid?.cols||10,r.cellSize=e.grid?.cellSize||36,r.mode=this.mapInteractiveMode(e.interactive?.mode),r.value=this.calculateValueFromHighlight(e.highlight?.numbers||[],r.rows,r.cols),r.fillColor=this.normalizeColor(n.selectedColor),r.baseColor=this.normalizeColor(n.baseColor),r.strokeColor=this.normalizeColor(n.borderColor),r.shadingDirection="ltr",r.hasShadow=!0,r.className="mathwiz-hundredgrid",r._config=e,r._style=n,r}mapInteractiveMode(e){return e==="readonly"?"readonly":"edit"}calculateValueFromHighlight(e,n=10,r=10){if(!e.length)return 0;const s=n*r;return e.length/s}normalizeColor(e){return typeof e!="string"?e:e.startsWith("#")?e.toLowerCase():e}validate(e){const n=[];return e.type||n.push("内容块缺少 type 字段"),e.type!=="hundredGrid"&&n.push(`内容块类型应为 hundredGrid,实际为 ${e.type}`),e.geometryRef||n.push("HundredGrid内容块缺少 geometryRef 字段"),n}}function vx(){return new xx}class wx{type="optionGroup";transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 OptionGroupTransformer.transform START for content block:",{blockType:e.type,hasOptionGroupRef:!!e.optionGroupRef,optionGroupRef:e.optionGroupRef,enableReferenceResolution:s,strictMode:o});try{const{optionGroupRef:i}=e;if(!i)throw new Nn(It.MISSING_REQUIRED_FIELD,"OptionGroup 内容块缺少 optionGroupRef 字段");const a=n.optionGroups?.[i];if(!a)throw new Nn(It.GEOMETRY_REF_NOT_FOUND,`OptionGroup 定义未找到: ${i}`);if(a.type!=="optionGroup")throw new Nn(It.GEOMETRY_REF_NOT_FOUND,`引用 ${i} 不是 optionGroup 类型: ${a.type}`);const l=a.options.map(d=>({id:d.id,content:d.content,contentType:d.contentType||"text",graphConfig:d.graphConfig})),c={type:"optionGroup",content:"",options:l,correctAnswers:a.correctAnswers,answerType:a.answerType,layout:a.layout||"vertical",variant:a.variant||"default",mode:e.mode||"question",showUserAnswer:e.showUserAnswer||!1,metadata:{optionGroupId:i,definition:a}};return console.error("✅ OptionGroupTransformer.transform SUCCESS:",{optionGroupRef:i,optionsCount:l.length,answerType:a.answerType,correctAnswers:a.correctAnswers}),c}catch(i){if(console.error("❌ OptionGroupTransformer.transform ERROR:",i),o)throw i;return e}}validate(e){const n=[];return e.type||n.push("内容块缺少 type 字段"),e.type!=="optionGroup"&&n.push(`内容块类型应为 optionGroup,实际为 ${e.type}`),e.optionGroupRef||n.push("OptionGroup 内容块缺少 optionGroupRef 字段"),n}}function _x(){return new wx}class Sx{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(mx()),this.register(px()),this.register(yx()),this.register(bx()),this.register(vx()),this.register(_x())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,n,r={}){if(!e||!e.type)throw new Error("内容块缺少 type 字段");const s=this.getTransformer(e.type);return s?(console.error(`🔄 TransformerRegistry.transform: type="${e.type}", transformer.type="${s.type}", enableReferenceResolution=${r.enableReferenceResolution}`),s.transform(e,n,r)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,n,r={}){return e.map(s=>this.transform(s,n,r))}transformScene(e,n,r={}){const s=e.items||e.content;if(!e||!Array.isArray(s))return{items:[],layout:e?.layout};const o=this.batchTransform(s,n,r);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,n,r);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=bt.resolve(e.layout,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:o,layout:i}}resolveLayoutReferences(e,n,r){if(!e||!r.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return bt.resolve(e,n)}catch(s){if(r.strictMode)throw s;return console.warn(`布局引用解析失败: ${e}`,s),e}if(typeof e=="object"){if(e.layoutRef&&typeof e.layoutRef=="string")try{const o=`layoutRef:${e.layoutRef}`,i=bt.resolve(o,n),{layoutRef:a,...l}=e;return{...i,...l}}catch(o){if(r.strictMode)throw o;console.warn(`布局引用解析失败: ${e.layoutRef}`,o)}const s=Array.isArray(e)?[]:{};for(const[o,i]of Object.entries(e))if(typeof i=="string"&&i.startsWith("layoutRef:"))try{s[o]=bt.resolve(i,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),s[o]=i}else if(typeof i=="string"&&i.startsWith("$"))try{s[o]=tt.resolve(i,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${o}=${i}`,a),s[o]=i}else i&&typeof i=="object"?s[o]=this.resolveLayoutReferences(i,n,r):s[o]=i;return s}return e}transformScenes(e,n,r={}){const s={};for(const[o,i]of Object.entries(e))s[o]=this.transformScene(i,n,r);return s}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const n=this.getTransformer(e.type);return!n||!n.validate?[]:n.validate(e)}batchValidate(e){return e.map(n=>({block:n,errors:this.validate(n)}))}}function Tu(){return new Sx}class si{static validate(e,n={}){const{strictMode:r=!1,skipOptionalFields:s=!1}=n,o=[],i=[];return!e||typeof e!="object"?(o.push("输入数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i,{skipOptionalFields:s}),this.validateFieldTypes(e,o,i),this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswerInfo(e,o,i),r&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,n,r,s){const{skipOptionalFields:o}=s;for(const i of Co.RAW_DATA)e[i]===void 0&&n.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Co.BASIC_INFO)e.basic_info[i]===void 0&&n.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Co.ANSWER_INFO)e.answer_info[i]===void 0&&n.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,n,r){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&n.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&n.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&n.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&n.push(`${a} 应为对象类型`)})}static validateScenes(e,n,r){if(!e.scenes||typeof e.scenes!="object"){n.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||n.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){n.push(`场景 ${o} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||n.push(`场景 ${o} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&n.push(`场景 ${o} 的 layout 应为对象类型`),wu.includes(o)||r.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,n,r){if(!e.basic_info||typeof e.basic_info!="object")return;const s=e.basic_info;["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&n.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&n.push(`basic_info.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&n.push("basic_info.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&n.push("basic_info.context 应为对象类型"),s.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(s.shape)&&r.push(`未知的形状类型: ${s.shape}`)}static validateAnswerInfo(e,n,r){if(!e.answer_info||typeof e.answer_info!="object")return;const s=e.answer_info;typeof s.value!="number"&&n.push("answer_info.value 应为数字类型"),typeof s.unit!="string"&&n.push("answer_info.unit 应为字符串类型"),typeof s.explanation_text!="string"&&n.push("answer_info.explanation_text 应为字符串类型"),s.value!==void 0&&(s.value<0&&r.push("answer_info.value 为负数,可能不正确"),s.value>1e4&&r.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,n,r){if(e.schema_version||r.push("建议添加 schema_version 字段"),e.config_version||r.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&r.push("knowledge_points 数组为空"),e.scenes)for(const[s,o]of Object.entries(e.scenes)){const i=o;i.content&&i.content.length===0&&r.push(`场景 ${s} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const n=["math_prob_id","title","basic_info","scenes","answer_info"];for(const r of n)if(e[r]===void 0)return!1;return!0}static validateAndClean(e,n={}){const{strictMode:r=!1,removeInvalidFields:s=!1}=n,o=this.validate(e,{strictMode:r});let i=e;return s&&!o.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(l=>{l in i&&delete i[l]})),{data:i,errors:o.errors,warnings:o.warnings}}}class oi{static validate(e,n={}){const{strictMode:r=!1,checkSceneContent:s=!0}=n,o=[],i=[];return!e||typeof e!="object"?(o.push("输出数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i),this.validateFieldTypes(e,o,i),s&&this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswer(e,o,i),this.validateExplanation(e,o,i),r&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,n,r){const s=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const o of s)e[o]===void 0&&n.push(`缺少必需字段: ${o}`)}static validateFieldTypes(e,n,r){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&n.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&n.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&n.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&n.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&n.push(`${i} 应为对象类型`)})}static validateScenes(e,n,r){if(!e.scenes||typeof e.scenes!="object"){n.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||n.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){n.push(`场景 ${o} 应为对象类型`);continue}const a=i,l=a.items||a.content;Array.isArray(l)?l.length===0&&r.push(`场景 ${o} 的内容数组为空`):n.push(`场景 ${o} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&n.push(`场景 ${o} 的 layout 应为对象类型`),wu.includes(o)||r.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,n,r){if(!e.basicInfo||typeof e.basicInfo!="object"){n.push("basicInfo 应为对象类型");return}const s=e.basicInfo;(s.question===void 0||typeof s.question!="string")&&n.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&n.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&n.push(`basicInfo.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&n.push("basicInfo.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&n.push("basicInfo.context 应为对象类型")}static validateAnswer(e,n,r){if(!e.answer||typeof e.answer!="object"){n.push("answer 应为对象类型");return}const s=e.answer;typeof s.value!="number"&&n.push("answer.value 应为数字类型"),typeof s.unit!="string"&&n.push("answer.unit 应为字符串类型"),typeof s.explanation!="string"&&n.push("answer.explanation 应为字符串类型"),s.value!==void 0&&(s.value<0&&r.push("answer.value 为负数,可能不正确"),s.value>1e4&&r.push("answer.value 过大,可能不正确"))}static validateExplanation(e,n,r){if(e.explanation===void 0){n.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){n.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&r.push("explanation 数组为空"),e.explanation.forEach((s,o)=>{(!s||typeof s!="object")&&n.push(`explanation[${o}] 应为对象类型`)})):e.explanation.steps===void 0?n.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||n.push("explanation.steps 应为数组类型")}static validateStrictMode(e,n,r){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||r.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&r.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&r.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&r.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const s=e.metadata;(!s.topic||typeof s.topic!="string")&&r.push("metadata.topic 应为字符串类型"),(!s.skill||typeof s.skill!="string")&&r.push("metadata.skill 应为字符串类型"),(!s.tags||!Array.isArray(s.tags))&&r.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const n=["id","title","basicInfo","scenes","answer"];for(const r of n)if(e[r]===void 0)return!1;return!(typeof e.title!="string"||e.basicInfo&&typeof e.basicInfo!="object"||e.scenes&&typeof e.scenes!="object"||e.answer&&typeof e.answer!="object")}static isValidMathPracticeProblemData(e){return this.validate(e,{strictMode:!1,checkSceneContent:!1}).isValid}}class pn{static validateInput(e,n={}){const{isValid:r,errors:s,warnings:o}=si.validate(e,n);return{isValid:r,errors:s,warnings:o,timestamp:Date.now()}}static validateOutput(e,n={}){const{isValid:r,errors:s,warnings:o}=oi.validate(e,n);return{isValid:r,errors:s,warnings:o,timestamp:Date.now()}}static validateComplete(e,n,r={}){const{inputStrictMode:s=!1,outputStrictMode:o=!1}=r,i=this.validateInput(e,{strictMode:s}),a=this.validateOutput(n,{strictMode:o}),l=[...i.errors,...a.errors],c=[...i.warnings,...a.warnings],d={isValid:i.isValid&&a.isValid,errors:l,warnings:c};return{input:i,output:a,overall:d}}static quickValidateInput(e){return si.quickValidate(e)}static quickValidateOutput(e){return oi.quickValidate(e)}static validateAndReport(e,n,r={}){const s=n==="input"?this.validateInput(e,r):this.validateOutput(e,r);console.group(`${n.toUpperCase()} 验证结果`),console.log(`有效性: ${s.isValid?"✅ 通过":"❌ 失败"}`),s.errors.length>0&&(console.group("❌ 错误:"),s.errors.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),s.warnings.length>0&&(console.group("⚠️ 警告:"),s.warnings.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),console.groupEnd()}}class ii{static extractAllReferences(e){const n=[],r=s=>{typeof s=="string"?n.push(s):Array.isArray(s)?s.forEach(r):s&&typeof s=="object"&&Object.values(s).forEach(r)};return r(e),[...new Set(n)]}static categorizeReferences(e,n){const r={[he.DESIGN_TOKEN]:[],[he.STYLE_REF]:[],[he.GEOMETRY_REF]:[],[he.TRANSFORM_REF]:[],[he.LAYOUT_REF]:[]},s=new An;for(const o of e){const i=s.getResolverForRef(o);i&&r[i.type].push(o)}return r}static batchResolveReferences(e,n,r={}){const{strictMode:s=!1,onMissing:o}=r,i=new An,a={};for(const l of e){const c=i.getResolverForRef(l);if(c)try{a[l]=c.resolve(l,n)}catch(d){if(s)throw d;console.warn(`引用解析失败: ${l}`,d),o&&(a[l]=o(l))}}return a}static replaceReferences(e,n,r={}){const{strictMode:s=!1,onMissing:o,maxDepth:i=10}=r,a=new An,l=new Set(["geometryRef","styleRef","transformRef","layoutRef","boardRef","animationRef","appearanceRef","position","vertices","endpoints","center","start","end","type","theme","strategy","content","description","title","question","answer","unit","id","name","label","config","metadata","layout","renderer","padding","component","inputType","placeholder","submitButton","targetGroup","direction","executionMode","transformSource","rotationGroup","isMovable","isStatic","shapes","animated","static","transform","chartConfig","steps","value","tolerance","validation","explanation_text","solution_steps","variables","originX","originY","areaUnit","baseUnit","heightUnit","answerUnit","base","height","displayMode","parts","fontSize","fontWeight","anchorX"]),c=(d,f=0,g)=>{if(f>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(g&&l.has(g))return console.warn(`🛡️ 跳过保留字段 "${g}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const m=a.getResolverForRef(d);if(m)try{return m.resolve(d,n)}catch(p){if(s)throw p;return console.warn(`引用解析失败: ${d}`,p),o?o(d):d}return d}else{if(Array.isArray(d))return d.map(h=>c(h,f+1,void 0));if(d&&typeof d=="object"){const h={};for(const[m,p]of Object.entries(d))h[m]=c(p,f+1,m);return h}}return d};return c(e)}static calculateReferenceStats(e,n){const r=new An,s={total:e.length,resolved:0,failed:0,byType:{}};Object.values(he).forEach(o=>{s.byType[o]={total:0,resolved:0,failed:0}}),console.log("🔍 calculateReferenceStats: 开始处理引用,总数=",e.length);for(const o of e){console.log("🔍 处理引用:",o);const i=r.getResolverForRef(o);if(i){const a=i.type;s.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const l=i.resolve(o,n);console.log(`🔍 引用解析成功: ${o} =>`,l),s.resolved++,s.byType[a].resolved++}catch(l){console.error(`🔍 引用解析失败: ${o}`,l),s.failed++,s.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${o}`)}return s}static checkReferenceExists(e,n){const s=new An().getResolverForRef(e);if(!s)return!1;if(s.validate)return s.validate(e,n);try{return s.resolve(e,n),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const n=e.match(/^(\w+):(\w+)$/);return n?[n[1],n[2]]:[e]}static createReference(e,n){switch(e){case he.DESIGN_TOKEN:return`$${n.join(".")}`;case he.STYLE_REF:return`styleRef:${n[0]}`;case he.GEOMETRY_REF:return`geometryRef:${n[0]}`;case he.TRANSFORM_REF:return`transformRef:${n[0]}`;case he.LAYOUT_REF:return`layoutRef:${n[0]}`;default:return n.join(":")}}static flattenNestedReferences(e){const n=[],r=(s,o=[])=>{if(typeof s=="string")n.push(`${o.join(".")}=${s}`);else if(Array.isArray(s))s.forEach((i,a)=>{r(i,[...o,`[${a}]`])});else if(s&&typeof s=="object")for(const[i,a]of Object.entries(s))r(a,[...o,i])};return r(e),n}}class Mu{marks=new Map;stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0};memoryStart=0;constructor(){this.startMemoryTracking()}markStart(e){this.marks.set(e,{name:e,startTime:performance.now()})}markEnd(e){const n=this.marks.get(e);if(!n){console.warn(`性能标记未找到: ${e}`);return}const r=performance.now(),s=r-n.startTime;n.endTime=r,n.duration=s,this.updateStats(e,s)}updateStats(e,n){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=n;break;case"transformation":this.stats.transformationTime=n;break;case"validation":this.stats.validationTime=n;break;case"total":this.stats.totalTime=n;break}}startMemoryTracking(){typeof performance<"u"&&performance.memory&&(this.memoryStart=performance.memory.usedJSHeapSize)}endMemoryTracking(){if(typeof performance<"u"&&performance.memory){const e=performance.memory.usedJSHeapSize;this.stats.memoryUsage=e-this.memoryStart}}setReferenceCount(e){this.stats.referenceCount=e}getStats(){return this.endMemoryTracking(),{...this.stats}}getMarks(){return Array.from(this.marks.values())}checkPerformance(){const e=[];return this.stats.transformationTime>en.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${en.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>en.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${en.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>en.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${en.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>en.MAX_REFERENCE_DEPTH*10&&e.push(`引用数量较多: ${this.stats.referenceCount} (可能影响性能)`),{passed:e.length===0,warnings:e}}reset(){this.marks.clear(),this.stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0},this.startMemoryTracking()}}class Cx{static deepMerge(e,n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return Array.isArray(e)?e.map((s,o)=>o<n.length?this.deepMerge(s,n[o]):s):[...n];const r={...e};for(const[s,o]of Object.entries(n))o!==void 0&&(s in r&&typeof r[s]=="object"&&typeof o=="object"?r[s]=this.deepMerge(r[s],o):r[s]=o);return r}static deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n||typeof e!="object"||e===null||n===null||Array.isArray(e)!==Array.isArray(n))return!1;if(Array.isArray(e))return e.length!==n.length?!1:e.every((o,i)=>this.deepEqual(o,n[i]));const r=Object.keys(e),s=Object.keys(n);return r.length!==s.length?!1:r.every(o=>o in n?this.deepEqual(e[o],n[o]):!1)}static safeGet(e,n,r=void 0){const s=Array.isArray(n)?n:n.split(".");let o=e;for(const i of s){if(o==null||typeof o!="object")return r;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(o)){const l=parseInt(a[1],10);o=o[l]}else o=o[i]}return o!==void 0?o:r}static safeSet(e,n,r){const s=Array.isArray(n)?n:n.split("."),o=Array.isArray(e)?[...e]:{...e};let i=o;for(let c=0;c<s.length-1;c++){const d=s[c],f=d.match(/^\[(\d+)\]$/);if(f&&Array.isArray(i)){const g=parseInt(f[1],10);i[g]===void 0&&(i[g]={}),i=i[g]}else{if(i[d]===void 0){const h=s[c+1].match(/^\[(\d+)\]$/);i[d]=h?[]:{}}i=i[d]}}const a=s[s.length-1],l=a.match(/^\[(\d+)\]$/);if(l&&Array.isArray(i)){const c=parseInt(l[1],10);i[c]=r}else i[a]=r;return o}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,n){let r=0;return(...s)=>{const o=Date.now();o-r>=n&&(r=o,e(...s))}}static debounce(e,n){let r;return(...s)=>{clearTimeout(r),r=setTimeout(()=>e(...s),n)}}static formatBytes(e,n=2){if(e===0)return"0 Bytes";const r=1024,s=n<0?0:n,o=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,i)).toFixed(s))+" "+o[i]}static estimateObjectSize(e){const n=new Set,r=s=>n.has(s)?0:typeof s=="string"?s.length*2:typeof s=="number"?8:typeof s=="boolean"?4:s==null?0:Array.isArray(s)?(n.add(s),s.reduce((o,i)=>o+r(i),0)):typeof s=="object"?(n.add(s),Object.values(s).reduce((o,i)=>o+r(i),0)):0;return r(e)}}class Rx{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...sx,...e},this.referenceContext=Eu(),this.resolverRegistry=Nu(),this.transformerRegistry=Tu(),this.performanceMonitor=new Mu}adapt(e){console.error("🔧 SyncAdapter.adapt called with inputData:",{math_prob_id:e?.math_prob_id,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{this.performanceMonitor.markStart("validation");const n=this.validateInput(e);if(!n.isValid&&this.config.strictMode)throw new Ee(re.INVALID_INPUT,Ja[re.INVALID_INPUT],{errors:n.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const r=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let s=r;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),s=this.resolveReferences(r),this.performanceMonitor.markEnd("reference-resolution")),this.performanceMonitor.markStart("scene-transformation"),!this.referenceContext.basicInfo&&s.basicInfo&&(this.referenceContext.basicInfo=s.basicInfo);const o=this.transformScenes(s);this.performanceMonitor.markEnd("scene-transformation"),this.performanceMonitor.markStart("output-validation");const i=this.validateOutput(o);if(!i.isValid&&this.config.strictMode)throw new Ee(re.OUTPUT_VALIDATION_FAILED,Ja[re.OUTPUT_VALIDATION_FAILED],{errors:i.errors});this.performanceMonitor.markEnd("output-validation"),this.performanceMonitor.markEnd("total"),console.error("🔧 adapt: transformedData before buildResult:",o),console.error("🔧 adapt: transformedData.basicInfo:",o.basicInfo),console.error("🔧 adapt: transformedData.basicInfo?.answerUnit:",o.basicInfo?.answerUnit);const a=this.buildResult(o,{inputValidation:n,outputValidation:i,inputWarnings:n.warnings,outputWarnings:i.warnings},e);return console.error("🔧 adapt: result.data.basicInfo:",a.data.basicInfo),console.error("🔧 adapt: result.data.basicInfo?.answerUnit:",a.data.basicInfo?.answerUnit),a}catch(n){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw n;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",n),this.createFallbackResult(e,n);throw n}}validateInput(e){return pn.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(console.error("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([n,r])=>{if(r&&typeof r=="object"){console.error(` 🔍 Processing geometry shape ${n}:`,{id:r.id,type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),shapeKeys:Object.keys(r)});const s=this.convertGeometryShapeCoordinates(r);console.error(` 📍 ${n}:`,{type:r.type,position:r.position,vertices:r.vertices}),this.referenceContext.geometryPresets[n]=s}}),console.error("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):console.error("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&Object.entries(e.transform_definitions).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertTransformDefinitionCoordinates(r);this.referenceContext.transformDefinitions[n]=s}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(n=>{n&&n.content&&Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="graph"&&r.shapes&&this.extractPointCoordinatesFromShapes(r.shapes)})})}extractGeometryTransformConfigsFromInput(e){if(!e){console.error("⚠️ extractGeometryTransformConfigsFromInput: inputData is null or undefined");return}this.referenceContext.geometryTransformConfigs||(this.referenceContext.geometryTransformConfigs={}),e.geometry_transform_configs&&typeof e.geometry_transform_configs=="object"?(console.error("📦 Extracting geometry_transform_configs:",Object.keys(e.geometry_transform_configs)),Object.entries(e.geometry_transform_configs).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing geometry transform config ${n}:`,{id:r.id,strategy:r.strategy,hasBase:"base"in r,hasHeight:"height"in r,hasShapes:"shapes"in r,hasTransform:"transform"in r}),this.referenceContext.geometryTransformConfigs[n]=r)}),console.error("✅ geometryTransformConfigs after extraction:",Object.keys(this.referenceContext.geometryTransformConfigs))):console.error("⚠️ No geometry_transform_configs found in input data")}extractAnimationConfigsFromInput(e){if(!e){console.error("⚠️ extractAnimationConfigsFromInput: inputData is null or undefined");return}this.referenceContext.animationConfigs||(this.referenceContext.animationConfigs={}),e.animation_configs&&typeof e.animation_configs=="object"?(console.error("📦 Extracting animation_configs:",Object.keys(e.animation_configs)),Object.entries(e.animation_configs).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing animation config ${n}:`,{id:r.id,description:r.description,hasTransforms:"transforms"in r,hasVisualEffects:"visualEffects"in r}),this.referenceContext.animationConfigs[n]=r)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}extractOptionGroupsFromInput(e){if(!e){console.error("⚠️ extractOptionGroupsFromInput: inputData is null or undefined");return}this.referenceContext.optionGroups||(this.referenceContext.optionGroups={}),e.option_groups&&typeof e.option_groups=="object"?(console.error("📦 Extracting option_groups:",Object.keys(e.option_groups)),Object.entries(e.option_groups).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing option group ${n}:`,{id:r.id,type:r.type,answerType:r.answerType,optionsCount:r.options?.length||0}),this.referenceContext.optionGroups[n]=r)}),console.error("✅ optionGroups after extraction:",Object.keys(this.referenceContext.optionGroups))):console.error("⚠️ No option_groups found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;if(console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0}),e.type==="hundredGrid")return console.error(`✅ hundredGrid类型跳过坐标转换: ${e.id}`),e;const n={...e};n.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line"),Array.isArray(n.position)&&n.position.length>=2&&(n.position={x:n.position[0],y:n.position[1]}),Array.isArray(n.vertices)&&(n.vertices=n.vertices.map(r=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:r)),Array.isArray(n.endpoints)?(console.error(`🔄 Processing endpoints for shape ${n.id||"unknown"}:`,{endpointsLength:n.endpoints.length,firstEndpoint:n.endpoints[0],firstEndpointType:typeof n.endpoints[0],firstEndpointIsArray:Array.isArray(n.endpoints[0])}),n.endpoints=n.endpoints.map((r,s)=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:(console.error(` Endpoint ${s} is not array:`,r),r)),n.type==="segment"&&Array.isArray(n.endpoints)&&n.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line",n.start=n.endpoints[0],n.end=n.endpoints[1],delete n.endpoints)):"endpoints"in n&&console.error(`⚠️ Shape ${n.id||"unknown"} has endpoints but not array:`,{endpoints:n.endpoints,endpointsType:typeof n.endpoints});for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?n[r]=s:n[r]=this.convertGeometryShapeCoordinates(s));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),endpointsLength:n.endpoints?n.endpoints.length:0,keys:Object.keys(n)}),n}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const n={...e};if(n.config&&n.config.center){const r=n.config.center;r&&typeof r=="object"&&"x"in r&&"y"in r&&(n.config.center=[r.x,r.y])}for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(n[r]=this.convertTransformDefinitionCoordinates(s));return n}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(n=>{if(n&&n.type==="point"&&n.position&&Array.isArray(n.position)&&n.position.length>=2){const r=n.id||`point_${n.position[0]}_${n.position[1]}`;this.referenceContext.geometryPresets[r]={type:"point",position:{x:n.position[0],y:n.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e),this.extractOptionGroupsFromInput(e);const n={id:e.math_prob_id||Cx.generateId("triangle"),title:e.title,grade:this.parseGrade(e.grade_id),unit:e.unit_name,lesson:e.lesson_name,skill:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points||[],difficulty:e.difficulty||1,metadata:this.transformMetadata(e),description:e.description,scenes:this.transformScenesStructure(e.scenes),answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info)};["unit_id","lesson_id","module_id","skill_item_id","skill_id","created_at","updated_at","layout"].forEach(o=>{e[o]!==void 0&&(n[o]=e[o])}),console.error("🔧 transformBaseData: inputData.basic_info =",e.basic_info);const s=this.transformBasicInfo(e.basic_info);return console.error("🔧 transformBaseData: basicInfo after transform =",s),console.error("🔧 transformBaseData: basicInfo.answerUnit =",s?.answerUnit),this.referenceContext.basicInfo=s,n.basicInfo=s,console.error("🔧 transformBaseData: transformed.basicInfo set =",n.basicInfo),n.explanation=this.transformExplanation(e.explanation),n}parseGrade(e){const n=e.match(/g(\d+)/);return n?parseInt(n[1],10):5}transformMetadata(e){return e.metadata&&typeof e.metadata=="object"?e.metadata:{topic:e.unit_name||"三角形面积计算",skill:e.skill_description||"三角形面积求解技能",tags:e.knowledge_points||["三角形面积公式"]}}transformBasicInfo(e){if(console.error("🔄 transformBasicInfo called with:",e),!e||typeof e!="object")return console.error("⚠️ transformBasicInfo: basicInfo is empty, returning default"),{question:""};const n={...e};return console.error("🔄 transformBasicInfo: transformed copy:",n),n.question===void 0&&n.content!==void 0&&(n.question=n.content),n.question===void 0&&(n.question=""),console.error("🔄 transformBasicInfo: returning:",n),n}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const n={};return["question","solve","review"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];n[o]={...i,items:a},i.content!==void 0&&delete n[o].content}else n[o]={items:[]}}),["remember","explanation","success"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];n[o]={...i,items:a},i.content!==void 0&&delete n[o].content}}),n}transformExplanation(e){if(console.error("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&e.steps&&Array.isArray(e.steps),stepsCount:e&&e.steps?e.steps.length:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){console.error(`🔄 transformExplanation: processing ${e.steps.length} steps`);const n=e.steps.map((r,s)=>(console.error(` Step ${s}: hasChartConfig=${!!r.chartConfig}`),this.transformExplanationStep(r)));return{...e,steps:n}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const n=e.chartConfig,r=n.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${r}`),console.error(" chartConfig keys:",Object.keys(n)),r!=="graph"&&r!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${r},跳过转换`),e;try{const s={type:r,...n};console.error(" contentBlock keys:",Object.keys(s)),r==="graph"&&s.shapes&&(console.error(" shapes count:",s.shapes.length),s.shapes.length>0&&console.error(" first shape:",s.shapes[0])),console.error("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.error("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]);const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});console.error(" transformedBlock keys:",Object.keys(o)),r==="graph"&&o.shapes&&console.error(" transformed shapes count:",o.shapes.length);let i;if(r==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,console.error(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.error(` geometryTransform preserved: step.title=${e.title}`),console.error(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.error(" geometryTransform preserved: config=",i.metadata?.config);else if(r==="graph"&&o.boardConfig){const{boardConfig:a,...l}=o;i={...l,...a},console.error(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}resolveReferences(e){const n=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(n.length),this.resolverRegistry.batchResolve(n,this.referenceContext),ii.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:r=>(console.warn(`引用未找到: ${r}`),r)})}transformScenes(e){const n={...e};return n.scenes&&typeof n.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),n.scenes=this.transformerRegistry.transformScenes(n.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),n}validateOutput(e){return pn.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,n,r){const s=this.performanceMonitor.getStats(),o=this.performanceMonitor.checkPerformance(),i=[...n.inputValidation.warnings.map(d=>({code:re.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...n.outputValidation.warnings.map(d=>({code:re.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...o.warnings.map(d=>({code:re.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=r||e,l=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],c=ii.calculateReferenceStats(l,this.referenceContext);return{data:e,warnings:i,performance:s,referenceStats:{total:c.total,resolved:c.resolved,failed:c.failed,byType:c.byType}}}createFallbackResult(e,n){const r={...ps,id:e?.math_prob_id||ps.id,title:e?.title||ps.title},s={code:re.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${n.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:r,warnings:[s],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class $r{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...rx,...e},this.referenceContext=Eu(),this.resolverRegistry=Nu(),this.transformerRegistry=Tu(),this.performanceMonitor=new Mu,this.syncAdapter=new Rx(e)}adapt(e){this.config.enableLogging&&console.log("🔧 GeometryAdapter.adapt called with inputData (delegating to SyncAdapterCore):",{math_prob_id:e?.math_prob_id,schema_version:e?.schema_version,shape:e?.basic_info?.shape,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{const n=e,r=this.syncAdapter.adapt(n);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:r.data.id,hasBasicInfo:!!r.data.basicInfo,warningCount:r.warnings.length,referenceStats:r.referenceStats}),r}catch(n){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw n;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",n),this.createFallbackResult(e,n);throw n}}_validateInput(e){return pn.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){this.config.enableLogging&&console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(this.config.enableLogging&&console.log("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertGeometryShapeCoordinates(r);this.referenceContext.geometryPresets[n]=s}}),this.config.enableLogging&&console.log("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):this.config.enableLogging&&console.log("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&(this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),Object.entries(e.transform_definitions).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertTransformDefinitionCoordinates(r);this.referenceContext.transformDefinitions[n]=s}}))}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}transformExplanation(e){if(this.config.enableLogging&&console.log("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&!Array.isArray(e)&&e.steps&&Array.isArray(e.steps),stepsCount:e?Array.isArray(e)?e.length:e.steps?e.steps.length:0:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){this.config.enableLogging&&console.log(`🔄 transformExplanation: processing ${e.steps.length} steps`);const n=e.steps.map((r,s)=>(this.config.enableLogging&&console.log(` Step ${s}: hasChartConfig=${!!r.chartConfig}`),this.transformExplanationStep(r)));return{...e,steps:n}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const n=e.chartConfig,r=n.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${r}`),console.log(" chartConfig keys:",Object.keys(n))),r!=="graph"&&r!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${r},跳过转换`),e;try{const s={...n,type:r};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(s)),r==="graph"&&s.shapes&&(console.log(" shapes count:",s.shapes.length),s.shapes.length>0&&console.log(" first shape:",s.shapes[0]))),this.config.enableLogging&&(console.log("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.log("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]));const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});this.config.enableLogging&&(console.log(" transformedBlock keys:",Object.keys(o)),r==="graph"&&o.shapes&&console.log(" transformed shapes count:",o.shapes.length));let i;if(r==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,this.config.enableLogging&&(console.log(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.log(` geometryTransform preserved: step.title=${e.title}`),console.log(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.log(" geometryTransform preserved: config=",i.metadata?.config));else if(r==="graph"&&o.boardConfig){const{boardConfig:a,...l}=o;i={...l,...a},this.config.enableLogging&&console.log(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(this.config.enableLogging&&console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;this.config.enableLogging&&console.log("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const n={...e};n.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line"),Array.isArray(n.position)&&n.position.length>=2&&(n.position={x:n.position[0],y:n.position[1]}),Array.isArray(n.vertices)&&(n.vertices=n.vertices.map(r=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:r)),Array.isArray(n.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${n.id||"unknown"}:`,{endpointsLength:n.endpoints.length,firstEndpoint:n.endpoints[0],firstEndpointType:typeof n.endpoints[0],firstEndpointIsArray:Array.isArray(n.endpoints[0])}),n.endpoints=n.endpoints.map((r,s)=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:(this.config.enableLogging&&console.log(` Endpoint ${s} is not array:`,r),r)),n.type==="line"&&Array.isArray(n.endpoints)&&n.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line",n.start=n.endpoints[0],n.end=n.endpoints[1],delete n.endpoints)):"endpoints"in n&&this.config.enableLogging&&console.log(`⚠️ Shape ${n.id||"unknown"} has endpoints but not array:`,{endpoints:n.endpoints,endpointsType:typeof n.endpoints});for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?n[r]=s:n[r]=this.convertGeometryShapeCoordinates(s));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),endpointsLength:n.endpoints?n.endpoints.length:0,keys:Object.keys(n)}),n}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const n={...e};if(n.config&&n.config.center){const r=n.config.center;r&&typeof r=="object"&&"x"in r&&"y"in r&&(n.config.center=[r.x,r.y])}for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>typeof o=="object"&&o!==null?"id"in o&&"type"in o&&"config"in o?this.convertTransformDefinitionCoordinates(o):this.deepClone(o):o):s&&typeof s=="object"&&("id"in s&&"type"in s&&"config"in s?n[r]=this.convertTransformDefinitionCoordinates(s):n[r]=this.deepClone(s));return n}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.deepClone(r));const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=this.deepClone(e[r]));return n}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const n={id:e.math_prob_id,title:e.title,grade:parseInt(e.grade_id.replace("g",""))||5,unit:e.unit_name,lesson:e.lesson_name,skillDescription:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points,difficulty:e.difficulty,description:e.description,metadata:e.metadata,basicInfo:{question:e.basic_info.question,answerUnit:e.basic_info.answerUnit||e.basic_info.areaUnit,shape:e.basic_info.shape,base:e.basic_info.base,height:e.basic_info.height,baseUnit:e.basic_info.baseUnit,heightUnit:e.basic_info.heightUnit,topBase:e.basic_info.topBase,topBaseUnit:e.basic_info.topBaseUnit,length:e.basic_info.length,width:e.basic_info.width,lengthUnit:e.basic_info.lengthUnit,widthUnit:e.basic_info.widthUnit,side:e.basic_info.side,sideUnit:e.basic_info.sideUnit,variables:e.basic_info.variables,score:e.basic_info.score,context:e.basic_info.context},rawGeometryShapes:e.geometry_shapes,rawTransformDefinitions:e.transform_definitions,rawGeometryTransformConfigs:e.geometry_transform_configs,rawAnimationConfigs:e.animation_configs,rawScenes:e.scenes,rawExplanation:e.explanation,rawAnswerInfo:e.answer_info,answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info),explanation:this.transformExplanation(e.explanation),unitId:e.unit_id,lessonId:e.lesson_id,moduleId:e.module_id,skillItemId:e.skill_item_id,skillId:e.skill_id,createdAt:e.created_at,updatedAt:e.updated_at,layout:e.layout};return this.referenceContext.basicInfo=n.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),n}_resolveReferences(e){const n=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(n.length),this.resolverRegistry.batchResolve(n,this.referenceContext),ii.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:r=>(this.config.enableLogging&&console.warn(`引用未找到: ${r}`),r)})}_transformScenes(e){const n={...e};return n.scenes&&typeof n.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),n.scenes=this.transformerRegistry.transformScenes(n.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),n}_validateOutput(e){return pn.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,n,r){const s=this.performanceMonitor.getStats(),o=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(n.inputWarnings||[]).map(a=>({code:It.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(n.outputWarnings||[]).map(a=>({code:It.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?s:void 0,referenceStats:o}}createFallbackResult(e,n){return{data:{...ps,id:e?.math_prob_id||"geometry-fallback",title:e?.title||"几何问题(回退)",basicInfo:{question:e?.basic_info?.question||"计算下面几何图形的面积:",answerUnit:e?.basic_info?.answerUnit||"cm²",shape:e?.basic_info?.shape||"triangle",base:e?.basic_info?.base||6,height:e?.basic_info?.height||4,baseUnit:e?.basic_info?.baseUnit||"cm",heightUnit:e?.basic_info?.heightUnit||"cm"}},warnings:[{code:It.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${n instanceof Error?n.message:n}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new $r(e)}}function wn(t,e){return new $r(e).adapt(t)}async function Ki(t,e){return Promise.resolve(wn(t,e))}function $u(t,e){const n=typeof t=="function"?t():t;return wn(n,e)}async function ju(t,e){const n=typeof t=="function"?await t():t instanceof Promise?await t:t;return wn(n,e)}function Ou(t){return new $r(t)}function Iu(t){const e=new $r(t);return{adapt:n=>Promise.resolve(e.adapt(n))}}function Ax(t,e="input"){return e==="input"?pn.validateInput(t):pn.validateOutput(t)}function kx(t,e,n=100){const r=[];for(let l=0;l<n;l++){const c=performance.now();t.adapt(e);const d=performance.now();r.push(d-c)}const s=r.reduce((l,c)=>l+c,0)/n,o=Math.min(...r),i=Math.max(...r),a=process.memoryUsage?.().heapUsed||0;return{averageTime:s,minTime:o,maxTime:i,memoryUsage:a}}const Ex={adapt:(t,e)=>wn(t,e),adaptAsync:(t,e)=>Ki(t,e),create:t=>Ou(t)},Nx="4.0.0",Pu="4.0.0";function Tx(t="4.0.0"){return Pu>=t}function Fu(t){return t?.schema_version==="4.0.0"||t?.schema_version?.startsWith("4.")}function Mx(t){return Fu(t)&&(t.geometry_shapes||t.transform_definitions||t.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(t.basic_info.shape))}class Ao extends Error{constructor(e,n,r,s){super(`Failed to generate config for ${n}: ${e}`),this.shapeType=n,this.options=r,this.innerError=s,this.name="ConfigGenerationError"}}function $x(t){const e=[],n=[];if(t.shapes||e.push(J("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),t.transform||e.push(J("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),t.strategy||e.push(J("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:Qa(e),timestamp:new Date().toISOString()};t.shapes&&e.push(...jx(t.shapes));let r=!1;if(t.shapes?.animated){for(const s of t.shapes.animated)if(s.transform){r=!0;break}}return t.transform?e.push(...Ox(t.transform)):r||e.push(J("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...Ix(t)),e.push(...Px(t)),e.push(...Fx(t)),e.length>0&&n.push(...Qa(e)),{isValid:e.length===0,errors:e,fixes:n,timestamp:new Date().toISOString()}}function Du(t){if(!t||typeof t!="object"||!t.type||typeof t.type!="string"||!["rotation","translation","scale","composite"].includes(t.type))return!1;switch(t.type){case"rotation":if(!t.config||typeof t.config!="object")return!1;const n=t.config.center;if(n!=="auto"&&(!Array.isArray(n)||n.length!==2)||typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number"||t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical")return!1;break;case"translation":if(!t.config||typeof t.config!="object")return!1;const r=t.config.direction;if(Array.isArray(r)){if(r.length!==2||typeof r[0]!="number"||typeof r[1]!="number")return!1}else if(typeof r=="string"){if(r!=="horizontal"&&r!=="vertical")return!1}else return!1;if(typeof t.config.distance!="number"||t.config.distance<=0)return!1;break;case"scale":if(!t.config||typeof t.config!="object")return!1;const s=t.config.center;if(s!=="centroid"&&(!Array.isArray(s)||s.length!==2)||typeof t.config.startScale!="number"||typeof t.config.endScale!="number"||typeof t.config.uniform!="boolean")return!1;break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))return!1;for(const o of t.transforms)if(!Du(o))return!1;if(t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel")return!1;break}return!0}function Lu(t,e){const n=[];if(!t||typeof t!="object")return n.push(J("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,t,{type:"rotation"})),n;(!t.type||typeof t.type!="string")&&n.push(J("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,t.type,"rotation"));const r=["rotation","translation","scale","composite"];switch(t.type&&!r.includes(t.type)&&n.push(J("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${t.type}`,`${e}.type`,t.type,"rotation")),t.type){case"rotation":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,t.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const s=t.config.center;s!=="auto"&&(!Array.isArray(s)||s.length!==2)&&n.push(J("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,t.config.center,[0,0])),(typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,t.config,{startAngle:0,endAngle:Math.PI})),t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical"&&n.push(J("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,t.config.direction,"clockwise"))}break;case"translation":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,t.config,{direction:"horizontal",distance:1}));else{const s=t.config.direction;Array.isArray(s)?s.length!==2?n.push(J("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,s,[1,0])):(typeof s[0]!="number"||typeof s[1]!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,s,[1,0])):typeof s=="string"?s!=="horizontal"&&s!=="vertical"&&n.push(J("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,s,"horizontal")):n.push(J("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,s,"horizontal")),(typeof t.config.distance!="number"||t.config.distance<=0)&&n.push(J("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,t.config.distance,1))}break;case"scale":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,t.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const s=t.config.center;s!=="centroid"&&(!Array.isArray(s)||s.length!==2)&&n.push(J("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,t.config.center,"centroid")),(typeof t.config.startScale!="number"||typeof t.config.endScale!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,t.config,{startScale:1,endScale:2})),typeof t.config.uniform!="boolean"&&n.push(J("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,t.config.uniform,!0))}break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))n.push(J("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,t.transforms,[]));else for(let s=0;s<t.transforms.length;s++){const o=Lu(t.transforms[s],`${e}.transforms[${s}]`);n.push(...o)}t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel"&&n.push(J("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,t.executionMode,"sequential"));break}return n}function J(t,e,n,r,s){let o=s;if(s===void 0)switch(t){case"INVALID_TRIANGLE_TYPE":o="right_triangle";break;case"INVALID_BASE_VALUE":case"INVALID_HEIGHT_VALUE":o=1;break;case"INVALID_ORIGIN":o=0;break;case"MISSING_SHAPES":o={static:[],animated:[]};break;case"MISSING_TRANSFORM":o={type:"rotation"};break;case"STRATEGY_MISMATCH":o="single_rotation";break;case"UNIT_MISMATCH":o="in";break;default:o=void 0}return{code:t,message:e,path:n,value:r,suggestedValue:o}}function jx(t){const e=[];if(!t||typeof t!="object")return e.push(J("MISSING_SHAPES","形状定义无效或缺失","$.shapes",t)),e;if(!Array.isArray(t.static))e.push(J("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",t.static));else for(let n=0;n<t.static.length;n++){const r=t.static[n],s=Za(r,`$.shapes.static[${n}]`);e.push(...s)}if(!Array.isArray(t.animated))e.push(J("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",t.animated));else for(let n=0;n<t.animated.length;n++){const r=t.animated[n],s=Za(r,`$.shapes.animated[${n}]`);e.push(...s)}return e}function Za(t,e){const n=[];if(!t||typeof t!="object")return n.push(J("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,t)),n;if((!t.type||typeof t.type!="string")&&n.push(J("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,t.type)),!Array.isArray(t.vertices))n.push(J("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,t.vertices));else if(t.vertices.length===0)n.push(J("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,t.vertices));else for(let r=0;r<t.vertices.length;r++){const s=t.vertices[r];!Array.isArray(s)||s.length!==2?n.push(J("INVALID_SHAPE_VERTICES",`顶点 ${r} 必须是包含两个数字的数组`,`${e}.vertices[${r}]`,s)):(typeof s[0]!="number"||typeof s[1]!="number")&&n.push(J("INVALID_SHAPE_VERTICES",`顶点 ${r} 必须包含数字`,`${e}.vertices[${r}]`,s))}if(t.transform!==void 0){const r=Lu(t.transform,`${e}.transform`);n.push(...r)}return n}function Ox(t){const e=[];if(!t)return e.push(J("MISSING_TRANSFORM","变换配置缺失","$.transform",t)),e;const n=Array.isArray(t),r=n?t:[t],s="$.transform";for(let o=0;o<r.length;o++){const i=r[o],a=n?`${s}[${o}]`:s;Du(i)||e.push(J("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function Ix(t){const e=[];if(!t.strategy)return e;const{strategy:n}=t;let r=0;if(t.transform&&(Array.isArray(t.transform)?r+=t.transform.length:typeof t.transform=="object"&&(t.transform&&typeof t.transform=="object"&&"transforms"in t.transform?r+=t.transform.transforms.length:r+=1)),t.shapes?.animated)for(const o of t.shapes.animated)o.transform&&(r+=1);return n.includes("single")&&r!==1&&e.push(J("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${r} 个`,"$.strategy",n,r===0?"single_rotation":"double_rotation")),n.includes("double")&&r!==2&&e.push(J("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${r} 个`,"$.strategy",n,r===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(n)||e.push(J("STRATEGY_MISMATCH",`无效的策略名称: ${n}`,"$.strategy",n,"single_rotation")),e}function Px(t){const e=[];if(t.unit&&typeof t.unit!="string"&&e.push(J("UNIT_MISMATCH","单位必须是字符串","$.unit",t.unit,"in")),t.baseUnit&&typeof t.baseUnit!="string"&&e.push(J("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",t.baseUnit,t.unit||"in")),t.heightUnit&&typeof t.heightUnit!="string"&&e.push(J("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",t.heightUnit,t.unit||"in")),t.unit&&t.baseUnit&&t.baseUnit!==t.unit&&e.push(J("UNIT_MISMATCH",`底边单位 (${t.baseUnit}) 与主单位 (${t.unit}) 不一致`,"$.baseUnit",t.baseUnit,t.unit)),t.unit&&t.heightUnit&&t.heightUnit!==t.unit&&e.push(J("UNIT_MISMATCH",`高度单位 (${t.heightUnit}) 与主单位 (${t.unit}) 不一致`,"$.heightUnit",t.heightUnit,t.unit)),t.unit&&t.boardConfig&&t.boardConfig.boundingBox){const[n,r,s,o]=t.boardConfig.boundingBox,i=s-n,a=r-o,l=t.unit==="cm"?50:20;(i>l*5||a>l*5)&&e.push(J("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${t.unit})不匹配`,"$.boardConfig.boundingBox",t.boardConfig.boundingBox,void 0))}return e}function Fx(t){const e=[];if(t.shapes&&t.boardConfig&&t.boardConfig.boundingBox){const n=t.boardConfig.boundingBox,[r,s,o,i]=n,a=[...t.shapes.static||[],...t.shapes.animated||[]];for(let l=0;l<a.length;l++){const c=a[l];if(c&&c.vertices)for(let d=0;d<c.vertices.length;d++){const f=c.vertices[d];if(Array.isArray(f)&&f.length===2){const[g,h]=f;(g<r||g>o||h<i||h>s)&&e.push(J("GEOMETRY_INCONSISTENCY",`形状 ${l} 的顶点 ${d} (${g}, ${h}) 超出画板边界`,`$.shapes.${l<(t.shapes.static?.length||0)?"static":"animated"}[${l}].vertices[${d}]`,f,[Math.max(r,Math.min(g,o)),Math.max(i,Math.min(h,s))]))}}}}if(t.metadata&&t.metadata.base&&t.metadata.height){const n=.5*t.metadata.base*t.metadata.height;if(t.shapes?.static?.[0]?.vertices){const r=t.shapes.static[0].vertices;if(r.length===3){const[s,o]=r[0],[i,a]=r[1],[l,c]=r[2],d=.5*Math.abs((i-s)*(c-o)-(l-s)*(a-o));Math.abs(d-n)>.01&&e.push(J("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${n.toFixed(2)}) 不一致`,"$.metadata",{base:t.metadata.base,height:t.metadata.height,calculatedArea:d,expectedArea:n}))}}}return e}function Qa(t){const e=[];for(const n of t)switch(n.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:n.path,value:n.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${n.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:n.path,value:n.suggestedValue||1,description:`将底边长度修复为: ${n.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:n.path,value:n.suggestedValue||1,description:`将高度修复为: ${n.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:n.path,value:n.suggestedValue||0,description:`将原点坐标修复为: ${n.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:n.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:n.suggestedValue!==void 0&&e.push({action:"replace",path:n.path,value:n.suggestedValue,description:`修复 ${n.code} 错误`,isSafe:!1})}return e}function el(t){if(!Dx(t))throw new Ao("Invalid parallelogram config options","parallelogram",t);const{base:e,height:n,unit:r="in",layoutDensity:s="compact",theme:o="light"}=t,i=t.originX??0,a=t.originY??0,l=t.skew??e/3;try{const c=Lx(e,n,l,i,a,o),d=zx(e),f=Vx(s),g=Gx(e,n,l,i,a);return{ui:{layoutDensity:s},base:e,height:n,unit:r,shapes:c,transform:d,animation:f,boardConfig:g,strategy:"cut_and_paste",theme:o,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:n,unit:r,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(c){if(c instanceof Ao)throw c;const d=c instanceof Error?c.message:String(c);throw new Ao(d,"parallelogram",t,c instanceof Error?c:void 0)}}function Dx(t){if(!t||typeof t!="object")return!1;const e=["base","height"];for(const n of e)if(!(n in t))return!1;return!(typeof t.base!="number"||t.base<=0||typeof t.height!="number"||t.height<=0||t.skew!==void 0&&(typeof t.skew!="number"||t.skew<0)||t.originX!==void 0&&(typeof t.originX!="number"||!isFinite(t.originX))||t.originY!==void 0&&(typeof t.originY!="number"||!isFinite(t.originY)))}function Lx(t,e,n,r,s,o){const a=o==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},l=[[r+n,s],[r+t,s],[r+t+n,s+e],[r+n,s+e]],c=[[r,s],[r+n,s],[r+n,s+e]];return{static:[{type:"trapezoid",vertices:l,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:c,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function zx(t){return{type:"translation",config:{direction:[1,0],distance:t}}}function Vx(t){return{slider:{position:t==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function Gx(t,e,n,r,s){const o=Math.min(r,r+n,r+t,r+t+n),i=Math.max(r,r+n,r+t,r+t+n),a=Math.min(s,s+e),l=Math.max(s,s+e),c=3;return{boundingBox:[o-c,l+c,i+c,a-c],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function Ux(t){return{id:t.id||t.math_prob_id,title:t.title||"",grade:t.grade||5,unit:t.unit||t.unit_name||"",lesson:t.lesson||t.lesson_name||"",skill:t.skill||t.skill_description||"",objective:t.objective||"",knowledgePoints:Array.isArray(t.knowledge_points)?t.knowledge_points:Array.isArray(t.knowledgePoints)?t.knowledgePoints:[],difficulty:t.difficulty||1,description:t.description||"",metadata:t.metadata||{topic:"",skill:"",tags:[]},math_prob_id:t.math_prob_id,grade_id:t.grade_id,unit_id:t.unit_id,lesson_id:t.lesson_id,module_id:t.module_id,skill_item_id:t.skill_item_id,skill_id:t.skill_id,created_at:t.created_at,updated_at:t.updated_at,layout:t.layout||{type:"card",padding:"20px",theme:"light"}}}function Bx(t){const e=t||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function Hx(t,e,n){return{value:t,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:n}}function Wx(t){return t?{value:t.value,unit:t.unit,explanation:t.explanation_text||t.explanation||"正确答案"}:null}function qx(t){return t.answer?t.answer:t.answer_info?Wx(t.answer_info):null}function Yx(){return{question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}},review:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}}]}}}function Kx(){return{steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。"},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。"},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。"}],strategy:"visual_transformation",total_steps:3,estimated_time:120}}function Xx(t){return Array.isArray(t)||t&&t.steps?t:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function zu(t){const e=Ux(t),n=Bx(t.basic_info||t.basicInfo),r=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"];return{...e,id:e.id||"parallelogram-area-001",title:e.title||"平行四边形面积公式推导",grade:e.grade||5,unit:e.unit||"多边形的面积",lesson:e.lesson||"平行四边形的面积",skill:e.skill||"已知平行四边形的底和高,求平行四边形面积",objective:e.objective||"理解平行四边形面积公式 A=bh",knowledgePoints:e.knowledgePoints?.length?e.knowledgePoints:r,difficulty:e.difficulty||1,description:e.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:e.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...n,question:n.question||"计算下面平行四边形的面积:",answerUnit:n.answerUnit||"平方英寸",shape:n.shape||"parallelogram",base:n.base||9,height:n.height||6,baseUnit:n.baseUnit||"in",heightUnit:n.heightUnit||"in",variables:n.variables||{b:9,h:6,unit:"in"},context:n.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:Qx(t.scenes||Yx(),"parallelogram",n),explanation:Xx(t.explanation||Kx()),answer:qx(t)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:t.answer_info||Hx(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:t.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function Jx(t){return t?.config&&typeof t.config=="object"}function Zx(t){if(t.shapes?.static&&t.shapes?.animated)return console.log("🔍 JSON config already in system format"),t;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!t.transform,type:En(t.transform),distance:Ot(t.transform),direction:ys(t.transform)});try{const e={...t};if(t.shapes&&typeof t.shapes=="object"){const r=[],s=[];if(t.shapes.trapezoid){const o=t.shapes.trapezoid;Array.isArray(o)?r.push(...o.map(i=>({...i,metadata:{...i.metadata,isStatic:!0}}))):typeof o=="object"&&r.push({...o,metadata:{...o.metadata,isStatic:!0}})}if(t.shapes.triangle){const o=t.shapes.triangle;Array.isArray(o)?s.push(...o.map(i=>({...i,metadata:{...i.metadata,isMovable:!0}}))):typeof o=="object"&&s.push({...o,metadata:{...o.metadata,isMovable:!0}})}(r.length===0||s.length===0)&&Object.entries(t.shapes).forEach(([o,i])=>{const a=o.toLowerCase();a.includes("static")||a.includes("original")||a.includes("trapezoid")?Array.isArray(i)?r.push(...i):i&&typeof i=="object"&&r.push(i):(a.includes("animated")||a.includes("movable")||a.includes("triangle"))&&(Array.isArray(i)?s.push(...i):i&&typeof i=="object"&&s.push(i))}),e.shapes={static:r,animated:s}}!e.base&&t.base&&(e.base=t.base),!e.height&&t.height&&(e.height=t.height),!e.unit&&t.unit&&(e.unit=t.unit);const n=En(t.transform);return t.transform&&n==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:n,translation:t.transform.translation,distance:Ot(t.transform),direction:ys(t.transform)}),t.transform.translation&&(e.transform={type:"translation",translation:t.transform.translation},console.log("✅ Set converted.transform with distance:",Ot(t.transform)))):t.transform?console.log("⚠️ JSON has transform but not translation type:",En(t.transform)):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&t.boardConfig&&(e.boardConfig=t.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:En(e.transform),distance:Ot(e.transform),direction:ys(e.transform)}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),t}}function Ot(t){if(!t)return"N/A";const e=Array.isArray(t)?t[0]:t;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function ys(t){if(!t)return;const e=Array.isArray(t)?t[0]:t;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function En(t){return t&&(Array.isArray(t)?t[0]:t)?.type||"N/A"}function Qx(t,e,n){if(t?.solve?.content){const r=t.solve.content.map(s=>{if(s.type==="geometryTransform"){if(Jx(s))try{const i=Zx(s.config),a=$x(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",Ot(i.transform)),console.log("📐 JSON base:",i.base,"height:",i.height),{...s,metadata:{...s.metadata,config:i,source:"json",validationResult:a}};console.warn("❌ JSON-provided parallelogram config validation failed:",a.errors),console.log("📊 JSON config structure:",{hasShapes:!!i.shapes,hasTransform:!!i.transform,transformType:En(i.transform),distance:Ot(i.transform),strategy:i.strategy,theme:i.theme})}catch(i){console.warn("Failed to process JSON-provided parallelogram config:",i)}let o;try{const i=n?.base||9,a=n?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),o=el({base:i,height:a,unit:n?.baseUnit||n?.unit||"in",originX:n?.originX,originY:n?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",Ot(o.transform))}catch(i){console.warn("Failed to generate dynamic parallelogram config:",i),console.log("🔄 Using fallback dynamic config with base: 9, height: 6"),o=el({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",Ot(o.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:En(o.transform),direction:ys(o.transform),distance:Ot(o.transform)}),{...s,metadata:{...s.metadata,config:o,source:"generated"}}}return s});return{...t,solve:{...t.solve,content:r}}}return t}const e0="4.0.0",t0="1.0.0",n0="mp-10506-0002-0002-G01-0001",r0="锐角三角形面积练习",s0="通过双旋转策略练习锐角三角形面积公式 A=½bh",o0="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",i0=1,a0="g5",l0="三角形面积计算",c0=1050602,d0="锐角三角形的面积",u0=105060201,f0=1002,h0="已知锐角三角形的底和高,求三角形面积",g0="s-105-06-0002",m0=1002,p0=2,y0=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],b0={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},x0={question:"以下三角形面积是多少?",answerUnit:"cm²",shape:"acute_triangle",base:6,height:4,baseUnit:"cm",heightUnit:"cm",originX:2,originY:2,unit:"cm²",variables:{b:6,h:4,answer:12}},v0={acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_b"},{$ref:"point_c"}],withLabel:!0,label:{offset:[-15,-15],fontSize:16,color:"#000000",anchorX:"middle",anchorY:"bottom"}},left_triangle:{id:"left_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_d"},{$ref:"point_c"}]},right_triangle:{id:"right_triangle",type:"polygon",vertices:[{$ref:"point_b"},{$ref:"point_d"},{$ref:"point_c"}]},base_segment:{id:"base_segment",type:"segment",endpoints:[{$ref:"point_a"},{$ref:"point_b"}]},height_segment:{id:"height_segment",type:"segment",endpoints:[{$ref:"point_d"},{$ref:"point_c"}]},left_rotation_center:{id:"left_rotation_center",type:"point",position:{x:3.5,y:4}},right_rotation_center:{id:"right_rotation_center",type:"point",position:{x:6.5,y:4}},full_rectangle:{id:"full_rectangle",type:"polygon",vertices:[{x:2,y:2},{x:8,y:2},{x:8,y:6},{x:2,y:6}]},base_arrow:{id:"base_arrow",type:"segment",endpoints:[{x:2,y:1.5},{x:8,y:1.5}]},height_arrow:{id:"height_arrow",type:"segment",endpoints:[{x:5,y:2},{x:5,y:6}]},base_label_position:{id:"base_label_position",type:"point",position:{x:5,y:1.2}},height_label_position:{id:"height_label_position",type:"point",position:{x:5.5,y:4}},point_a:{id:"point_a",type:"point",position:{x:2,y:2},name:"A"},point_b:{id:"point_b",type:"point",position:{x:8,y:2},name:"B"},point_c:{id:"point_c",type:"point",position:{x:5,y:6},name:"C"},point_d:{id:"point_d",type:"point",position:{x:5,y:2},name:"D"}},w0={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},_0={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"以下三角形面积是多少?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},S0={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别锐角三角形的底和高",description:"确定锐角三角形的底边长度 b = 6 cm 和对应的高度 h = 4 cm。垂足将底边平分为两段。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base-label",type:"text",position:{x:5,y:1.4},content:"6 cm",styleRef:"label_error"},{id:"height-label",type:"text",position:{x:5.3,y:4},content:"4 cm",styleRef:"label_success"}]}},{id:"exp-step-2",type:"instructionalStep",title:"双旋转策略:分割为两个直角三角形",description:"沿高线将锐角三角形分割为两个直角三角形:左直角三角形和右直角三角形。每个直角三角形将独立旋转。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"point",geometryRef:"left_rotation_center",styleRef:"primary",size:4},{type:"point",geometryRef:"right_rotation_center",styleRef:"primary",size:4}]}},{id:"exp-step-3",type:"instructionalStep",title:"刚体旋转形成矩形",description:"每个直角三角形围绕其斜边中点旋转180度,形成对应的矩形。左直角三角形形成左矩形,右直角三角形形成右矩形。",chartConfig:{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}},{id:"exp-step-4",type:"instructionalStep",title:"组合形成完整矩形并推导面积公式",description:"两个小矩形组合形成完整的大矩形,其面积为 b × h = 6 × 4 = 24 cm²。锐角三角形面积是大矩形面积的一半,即 A = ½ × b × h = 12 cm²。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"full_rectangle",styleRef:"primary"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{type:"text",position:{x:5,y:1.2},content:"Base = 6 cm",style:{fontSize:"$fonts.label",color:"$colors.error",fontWeight:"bold",anchorX:"middle"}},{type:"text",position:{x:5.5,y:4},content:"Height = 4 cm",style:{fontSize:"$fonts.label",color:"$colors.success",fontWeight:"bold"}}]}}]},C0={value:12,unit:"cm²",type:"number",tolerance:.1,validation:{type:"exact",allowPartial:!1},explanation_text:"三角形面积 = ½ × 底 × 高 = ½ × 6cm × 4cm = 12cm²",solution_steps:["识别三角形的底和高","应用面积公式 A = ½ × b × h","代入数值:A = ½ × 6 × 4","计算:A = ½ × 24 = 12","添加单位:12 cm²"]},R0="2026-01-20T20:34:00Z",A0="2026-01-20T20:34:00Z",k0={double_rotation_proof:{id:"double_rotation_proof",description:"双旋转几何证明策略",base:6,height:4,unit:"cm",strategy:"double_rotation",shapes:{static:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary",appearanceRef:"always_visible"}],animated:[{id:"left_triangle",type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left",appearanceRef:"appear_at_90"},{id:"right_triangle",type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right",appearanceRef:"appear_at_90"}]},transform:{type:"composite",transforms:[{transformRef:"left_rotation"},{transformRef:"right_rotation"}],executionMode:"parallel"},boardRef:"default",sliderRef:"slider_horizontal"}},E0={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left_triangle"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right_triangle"}},N0={schema_version:e0,config_version:t0,math_prob_id:n0,title:r0,description:s0,objective:o0,difficulty:i0,grade_id:a0,unit_name:l0,unit_id:c0,lesson_name:d0,lesson_id:u0,module_id:f0,skill_description:h0,skill_item_id:g0,skill_id:m0,score:p0,knowledge_points:y0,metadata:b0,basic_info:x0,geometry_shapes:v0,layout:w0,scenes:_0,explanation:S0,answer_info:C0,created_at:R0,updated_at:A0,geometry_transform_configs:k0,transform_definitions:E0},T0="mp-10506-0001-0001-G01-0001",M0="平行四边形面积公式推导",$0="通过割补变换演示理解平行四边形面积公式 A=bh",j0="理解平行四边形面积公式 A=bh",O0=1,I0="g5",P0="多边形的面积",F0=1050601,D0="平行四边形的面积",L0=105060101,z0=1002,V0="已知平行四边形的底和高,求平行四边形面积",G0="s-105-06-0001",U0=1001,B0=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],H0={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},W0={question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",shape:"parallelogram",base:9,height:6,baseUnit:"in",heightUnit:"in",score:2,variables:{b:9,h:6,unit:"in"},context:{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},q0={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},Y0={question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}},{type:"graph",content:"parallelogram_static",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.8,strokeColor:"#2980b9",strokeWidth:2},{id:"height-dash",type:"line",start:{x:4,y:1},end:{x:4,y:7},strokeColor:"#64748b",strokeWidth:2,dash:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16},{id:"side-label",type:"text",position:{x:2.5,y:4},content:"9 in",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1},{type:"interactive",content:"answer_input",metadata:{componentType:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"square inches",submitButton:{label:"Submit",color:"#67b510"}}}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},remember:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}},{type:"text",content:"Area = base × height",style:{color:"#64748b",marginTop:"8px"}},{type:"formula",content:"A = bh",parts:["A = bh"],displayMode:!0,style:{color:"#64748b",marginTop:"4px"}}],layout:{type:"vertical",spacing:"15px",alignment:"center",cardStyle:{backgroundColor:"#F8FAFC",borderColor:"#E3F2FD",borderWidth:"2px"}}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"text",content:"This parallelogram has base b = 9 inches and height h = 6 inches.",style:{color:"#555",marginBottom:"15px"}},{type:"text",content:"Interactive Demo: Drag the slider to transform the parallelogram into a rectangle.",style:{color:"#555",fontStyle:"italic",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{type:"text",content:"Through dissection, the parallelogram transforms into a rectangle with the same area.",style:{color:"#555",marginTop:"15px",marginBottom:"15px"}},{type:"formula",content:"A = b \\times h",parts:["A = b \\times h","= 9 \\times 6","= 54"],displayMode:!0,style:{fontSize:"1.2rem",textAlign:"center",margin:"15px 0"}},{type:"text",content:"The area of the parallelogram is 54 square inches.",style:{fontWeight:"bold",color:"#4a90e2",marginTop:"10px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}}},K0={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。",chartConfig:{type:"graph",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。",chartConfig:{type:"geometryTransform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。",chartConfig:{type:"graph",shapes:[{id:"rectangle",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:10,y:7},{x:1,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:10.5,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}}],strategy:"visual_transformation",total_steps:3,estimated_time:120,hints:[{step:1,text:"注意平行四边形的高是从底边垂直向上的距离,不是斜边的长度"},{step:2,text:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},X0={value:54,unit:"square inches",type:"numeric",tolerance:0,format:{decimal_places:0,allow_fraction:!1,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!0},explanation_text:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。",solution_steps:[{step:1,action:"identify_dimensions",description:"底边 b = 9 英寸,高 h = 6 英寸"},{step:2,action:"apply_formula",description:"面积公式 A = b × h"},{step:3,action:"calculate",description:"A = 9 × 6 = 54"},{step:4,action:"add_unit",description:"54 平方英寸"}]},J0="2024-01-15T10:30:00Z",Z0="2024-01-15T10:30:00Z",Q0={math_prob_id:T0,title:M0,description:$0,objective:j0,difficulty:O0,grade_id:I0,unit_name:P0,unit_id:F0,lesson_name:D0,lesson_id:L0,module_id:z0,skill_description:V0,skill_item_id:G0,skill_id:U0,knowledge_points:B0,metadata:H0,basic_info:W0,layout:q0,scenes:Y0,explanation:K0,answer_info:X0,created_at:J0,updated_at:Z0},ev={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function tv(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
80
+ `)}`);return o}static validate(e,n){if(!this.canResolve(e))return!1;let r;const s=e.match(we.ANIMATION_REF);return s?r=s[1]:r=e,r in(n.animationConfigs||{})}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`动画引用解析失败: ${s}`,o)}return r}static extractAnimationRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.animationRef&&typeof s.animationRef=="string"&&n.push(s.animationRef),s.chartConfig?.animationRef&&typeof s.chartConfig.animationRef=="string"&&n.push(s.chartConfig.animationRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}function Q_(){return{type:he.ANIMATION_REF,canResolve:an.canResolve.bind(an),resolve:an.resolve.bind(an),validate:an.validate.bind(an)}}class zt{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,n){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!n,contextKeys:Object.keys(n||{}),animationDefinitionsKeys:n.animationDefinitions?Object.keys(n.animationDefinitions):[],animationConfigsKeys:n.animationConfigs?Object.keys(n.animationConfigs):[]}),!this.canResolve(e))throw new Ee(re.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const r=e.match(we.SLIDER_REF),s=r?r[1]:e;let o=n.animationDefinitions?.[s];return!o&&n.animationConfigs&&(o=n.animationConfigs[s]),!o&&cn?.animationDefinitions&&(o=cn.animationDefinitions[s]),!o&&cn?.animationConfigs&&(o=cn.animationConfigs[s]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:s,hasRawConfig:!!o,rawConfig:o,animationDefinitions:n.animationDefinitions,animationConfigs:n.animationConfigs,hasGlobalContext:!!cn}),o?this.validateAndTransformConfig(s,o):(console.warn(`⚠️ 滑块配置未找到: ${s},使用默认配置`),{...eS,id:s})}static validateAndTransformConfig(e,n){if(!n.slider)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:r}=n,s=["position","length","orientation","min","max","step"];for(const o of s)if(!(o in r))throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${o} 字段`);if(!Array.isArray(r.position)||r.position.length!==2)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(r.orientation!=="horizontal"&&r.orientation!=="vertical")throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(r.min>=r.max)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(r.step<=0)throw new Ee(re.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:r.position,length:r.length,orientation:r.orientation,min:r.min,max:r.max,step:r.step},progressIndicator:n.progressIndicator,duration:n.duration,easing:n.easing,description:n.description}}static validate(e,n){if(!this.canResolve(e))return!1;const r=e.match(we.SLIDER_REF),s=r?r[1]:e;return s in(n.animationDefinitions||{})||s in(n.animationConfigs||{}),!0}static batchResolve(e,n){const r={};for(const s of e)if(this.canResolve(s))try{r[s]=this.resolve(s,n)}catch(o){console.warn(`滑块引用解析失败: ${s}`,o)}return r}static extractSliderRefs(e){const n=[],r=s=>{if(!(!s||typeof s!="object")){s.sliderRef&&typeof s.sliderRef=="string"&&n.push(s.sliderRef),s.chartConfig?.sliderRef&&typeof s.chartConfig.sliderRef=="string"&&n.push(s.chartConfig.sliderRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(r):o&&typeof o=="object"&&r(o)}};return r(e),[...new Set(n)]}}const eS={id:"default_slider",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"默认滑块配置(引用未找到时使用)"};function tS(){return{type:he.SLIDER_REF,canResolve:zt.canResolve.bind(zt),resolve:zt.resolve.bind(zt),validate:zt.validate.bind(zt)}}class ln{static canResolve(e){return typeof e!="string"||e.length===0?!1:we.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,n,r){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const s=e.match(we.GEOMETRY_TRANSFORM_REF),o=s?s[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${o}`,{hasGeometryTransformConfigs:!!n.geometryTransformConfigs,configKeys:n.geometryTransformConfigs?Object.keys(n.geometryTransformConfigs):[]});const i=n.geometryTransformConfigs?.[o];if(!i)throw new Ee(re.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${o}`,{reference:e,configId:o,availableConfigs:n.geometryTransformConfigs?Object.keys(n.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=r?this.applyOverride(i,r):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,n){const r={...e};for(const[s,o]of Object.entries(n))o!==void 0&&(r[s]=o);return n.shapes&&(r.shapes={static:[...r.shapes?.static||[]],animated:[...r.shapes?.animated||[]]},n.shapes.static&&(r.shapes.static=n.shapes.static),n.shapes.animated&&(r.shapes.animated=n.shapes.animated)),n.transform&&(r.transform={...r.transform,...n.transform}),r}static validate(e,n){if(!this.canResolve(e))return!1;const r=e.match(we.GEOMETRY_TRANSFORM_REF),s=r?r[1]:e;return!!n.geometryTransformConfigs?.[s]}static batchResolve(e,n,r){const s={};for(const o of e)if(this.canResolve(o)&&this.validate(o,n))try{const i=r?.[o];s[o]=this.resolve(o,n,i)}catch(i){console.warn(`几何变换引用解析失败: ${o}`,i)}return s}static extractFromContentBlock(e){return!e||typeof e!="object"?null:e.geometryTransformRef&&typeof e.geometryTransformRef=="string"?e.geometryTransformRef:null}static extractFromContentBlocks(e){const n=[];for(const r of e){const s=this.extractFromContentBlock(r);s&&n.push(s)}return[...new Set(n)]}}function nS(){return{type:he.GEOMETRY_TRANSFORM_REF,canResolve:ln.canResolve.bind(ln),resolve:ln.resolve.bind(ln),validate:ln.validate.bind(ln)}}const Do={geometryRef:he.GEOMETRY_REF,styleRef:he.STYLE_REF,layoutRef:he.LAYOUT_REF,boardRef:he.BOARD_REF,animationRef:he.ANIMATION_REF,transformRef:he.TRANSFORM_REF,appearanceRef:he.STYLE_REF,geometryTransformRef:he.GEOMETRY_TRANSFORM_REF,sliderRef:he.SLIDER_REF,$ref:he.GEOMETRY_REF};class rS{static extractRefs(e){const n=[],r=new Set,s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o)){if(i in Do){if(typeof a=="string"){const l=Do[i],c=`${i}:${a}`;r.has(c)||(r.add(c),n.push({ref:a,type:l,path:i,value:a,fieldName:i,combined:c}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(c=>{const d=c;r.has(d)||(r.add(d),n.push({ref:c,type:he.DESIGN_TOKEN,path:"$ref",value:c,fieldName:"",combined:d}))});continue}if(Array.isArray(a)){a.forEach(l=>s(l));continue}typeof a=="object"&&s(a)}};return s(e),n}static extractDesignTokens(e){const n=[],r=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let s;for(;(s=r.exec(e))!==null;)n.push(s[0]);return n}static calculateStats(e){const n=this.extractRefs(e).map(o=>o.ref),r={},s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o))i in Do?r[i]=(r[i]||0)+1:typeof a=="object"&&s(a)};return s(e),{totalRefs:n.length,uniqueRefs:new Set(n).size,fieldCounts:r}}}class An{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(Y_()),this.register(K_()),this.register(X_()),this.register(J_()),this.register(Z_()),this.register(Q_()),this.register(tS()),this.register(nS())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(n=>n.type===e)}getResolverForRef(e){return this.resolvers.find(n=>n.canResolve(e))}resolve(e,n){if(typeof e!="string"){const s=this.getResolverByType(e.type);if(!s)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return s.resolve(e.value,n)}catch(o){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${o}`)}}const r=this.resolvers.filter(s=>s.canResolve(e));if(r.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const s of r)try{return s.resolve(e,n)}catch(o){console.debug(`解析器 ${s.type} 解析 ${e} 失败:`,o);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,n){const r={};for(const s of e)try{const o=this.resolve(s,n),i=typeof s=="string"?s:s.combined;r[i]=o}catch(o){const i=typeof s=="string"?s:s.combined;console.warn(`引用解析失败: ${i}`,o)}return r}extractAllRefsEnhanced(e){try{return rS.extractRefs(e)}catch(n){return console.warn("ReferenceExtractor 提取失败:",n),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(r=>r.combined)}extractAllRefsLegacy(e){const n=[],r=s=>{if(!(!s||typeof s!="object"))for(const[o,i]of Object.entries(s))if(o.endsWith("Ref")&&typeof i=="string")n.push(i);else if(typeof i=="string"&&i.includes("$")){const a=i.match(/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g);a&&n.push(...a)}else Array.isArray(i)?i.forEach(a=>r(a)):typeof i=="object"&&r(i)};return r(e),[...new Set(n)]}validate(e,n){const r=this.getResolverForRef(e);if(!r)return!1;if(r.validate)return r.validate(e,n);try{return r.resolve(e,n),!0}catch{return!1}}}function Tf(){return new An}class ls{static transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 GraphTransformer.transform START for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o,contextGeometryKeys:Object.keys(n.geometryPresets||{})}),console.error("🎯 GraphTransformer.transform called for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o}),e.shapes&&Array.isArray(e.shapes)&&console.warn(`📊 GraphTransformer contentBlock shapes (${e.shapes.length}):`,e.shapes.map(a=>({id:a.id,type:a.type,geometryRef:a.geometryRef,styleRef:a.styleRef})));const i={...e,type:$e.GRAPH};if(!s)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,n),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,l)=>(console.error(` 🎯 处理shape[${l}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,n,{strictMode:o})))),i.styleRef){try{const a=ze.resolve(i.styleRef,n);i.style=a}catch(a){if(o)throw a;console.warn(`图形样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}if(i.animationRef){console.warn(`🎬 GraphTransformer处理animationRef: ${i.animationRef}`);try{const a=i.animationRef.startsWith("animationRef:")?i.animationRef:`animationRef:${i.animationRef}`,l=an.resolve(a,n);console.warn(" 动画配置解析结果:",{animationId:l.id,transformCount:l.transforms.length,hasControl:!!l.control,controlConfig:l.control,hasVisualEffects:!!l.visualEffects,visualEffectsCount:l.visualEffects?.length||0}),i.animation=l,i.transformDefinitions&&(console.warn(" 清理旧的 transformDefinitions(被 animation 替代)"),delete i.transformDefinitions)}catch(a){if(o)throw a;console.warn(`❌ 动画配置解析失败: ${i.animationRef}`,a)}delete i.animationRef}else i.animation&&(console.warn("🎬 GraphTransformer检测到内联动画配置:",{animationId:i.animation.id,transformCount:i.animation.transforms?.length||0}),i.animation.transforms&&Array.isArray(i.animation.transforms)?console.warn(` 内联动画配置有效,transforms 数量: ${i.animation.transforms.length}`):(console.warn(" ⚠️ 内联动画配置格式无效,缺少 transforms 数组"),delete i.animation));return i}catch(a){if(o)throw a;return console.warn("图形转换失败:",a),i}}static transformShape(e,n,r={}){const{strictMode:s=!1}=r;console.error("🔄 GraphTransformer.transformShape START for shape:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:"geometryRef"in e,geometryRef:e.geometryRef,hasStyleRef:"styleRef"in e,styleRef:e.styleRef,allShapeKeys:Object.keys(e),contextGeometryKeys:Object.keys(n.geometryPresets||{})}),(e.id==="base_line"||e.id==="height_line")&&console.error(`🔍 特别处理 ${e.id}:`,{id:e.id,type:e.type,geometryRef:e.geometryRef,styleRef:e.styleRef,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints)});let o={...e};e.type==="point"&&console.warn(`📌 GraphTransformer processing point ${e.id}:`,{id:e.id,type:e.type,position:e.position,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),shapeKeys:Object.keys(e)});try{if(o.geometryRef){console.warn(`🔄 GraphTransformer processing geometryRef: ${o.geometryRef} for shape ${o.id}`,{shapeId:o.id,shapeType:o.type,geometryRef:o.geometryRef,contextHasGeometryPresets:!!n.geometryPresets,geometryPresetKeys:n.geometryPresets?Object.keys(n.geometryPresets):[]});try{const i=yt.resolve(o.geometryRef,n);console.warn(` Geometry resolved for ${o.geometryRef}:`,{type:i.type,hasVertices:"vertices"in i,vertices:i.vertices,hasPosition:"position"in i,position:i.position,hasEndpoints:"endpoints"in i,endpoints:i.endpoints,endpointsIsArray:Array.isArray(i.endpoints),geometryKeys:Object.keys(i)});const a=o.type,l=o.content,c={...o};Object.assign(o,i),o.id=e.id,a!==void 0&&(o.type=a),l!==void 0&&(o.content=l),console.warn(` After merge for ${o.id}:`,{type:o.type,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:"undefined",position:o.position,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),transformedShapeKeys:Object.keys(o)});const d=o.type;let f=!1;const g=n.geometryPresets[o.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:o.geometryRef,originalGeometryExists:!!g,originalGeometryType:g?.type,originalGeometryKeys:g?Object.keys(g):[],hasVertices:g&&"vertices"in g,verticesIsArray:g&&Array.isArray(g.vertices),verticesLength:g?.vertices?.length,contextGeometryPresetsKeys:Object.keys(n.geometryPresets||{})}),g&&g.vertices&&Array.isArray(g.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:g.vertices,hasWithLabel:"withLabel"in g,withLabel:g.withLabel,hasLabel:"label"in g,label:g.label}),o.verticesConfig||(o.verticesConfig={}),g.vertices.forEach((h,m)=>{if(console.warn(`🔍 DEBUG: 检查顶点${m}:`,{vertex:h,isObject:h&&typeof h=="object",hasDollarRef:h&&typeof h=="object"&&"$ref"in h,refName:h?.$ref}),h&&typeof h=="object"&&"$ref"in h){const p=h.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${p},检查context.geometryPresets`),n.geometryPresets&&n.geometryPresets[p]){const y=n.geometryPresets[p];console.warn(`🔍 DEBUG: 找到点定义 ${p}:`,y),y.name?(o.verticesConfig[m]||(o.verticesConfig[m]={}),o.verticesConfig[m].name=y.name,console.warn(`✅ 从原始几何定义提取顶点${m}名字: ${y.name}`)):console.warn(`⚠️ 点定义 ${p} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${p}`)}else console.warn(`⚠️ 顶点${m}不是$ref对象`)}),g.withLabel!==void 0&&(o.verticesConfig.withLabel=g.withLabel),g.label&&typeof g.label=="object"){const h=g.label;h.offset&&Array.isArray(h.offset)&&h.offset.length>=2&&(o.verticesConfig.offset=h.offset),h.fontSize!==void 0&&(o.verticesConfig.fontSize=h.fontSize),h.color&&(o.verticesConfig.color=h.color),h.anchorX&&(o.verticesConfig.anchorX=h.anchorX),h.anchorY&&(o.verticesConfig.anchorY=h.anchorY)}console.warn("✅ 构建的verticesConfig:",o.verticesConfig)}if(d==="segment"||d==="line"?f="endpoints"in o&&Array.isArray(o.endpoints):d==="point"?f="position"in o&&o.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?f="vertices"in o&&Array.isArray(o.vertices):f="vertices"in o&&Array.isArray(o.vertices)||"endpoints"in o&&Array.isArray(o.endpoints)||"position"in o&&o.position!==void 0,f||(console.error(`❌ ERROR: After geometryRef merge, shape ${o.id} (type: ${d}) has no valid geometry properties!`),console.error(" geometry keys:",Object.keys(i)),console.error(" geometry.type:",i.type),console.error(" transformedShape keys:",Object.keys(o))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const h=ze.resolve(i.styleRef,n);console.error(" 几何样式解析结果:",h),o.style=h}}catch(i){if(s)throw i;console.error(`❌ 图形几何解析失败: ${o.geometryRef}`,i),console.error(` shape id: ${o.id}, type: ${o.type}`),console.error(" context.geometryPresets keys:",n.geometryPresets?Object.keys(n.geometryPresets):"undefined")}delete o.geometryRef}if(o.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${o.styleRef}, shape id: ${o.id}`);try{const i=ze.resolve(o.styleRef,n);console.error(" 形状样式解析成功:",i);const{id:a,...l}=i;o={...o,...l,style:{...o.style,...i}}}catch(i){if(s)throw i;console.warn(`图形元素样式解析失败: ${o.styleRef}`,i),delete o.style}delete o.styleRef}if(Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(i=>this.transformTransform(i,n,{strictMode:s}))),o.label&&typeof o.label=="object"&&(o.label=this.transformLabel(o.label,n)),console.warn(`🔍 Checking segment conversion for ${o.id}:`,{type:o.type,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,shapeKeys:Object.keys(o)}),o=this.convertShapeCoordinates(o,n),o.type==="segment"&&Array.isArray(o.endpoints)&&o.endpoints.length>=2){console.warn(`🔄 Converting segment to line for ${o.id}:`,{originalType:o.type,endpoints:o.endpoints}),o.type="line";const i=this.resolvePointReference(o.endpoints[0],n),a=this.resolvePointReference(o.endpoints[1],n);Array.isArray(i)&&i.length>=2?o.start={x:i[0],y:i[1]}:i&&typeof i=="object"&&"x"in i&&"y"in i?o.start=i:o.start=o.endpoints[0],Array.isArray(a)&&a.length>=2?o.end={x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?o.end=a:o.end=o.endpoints[1],delete o.endpoints}return console.warn(`✅ GraphTransformer finished transforming shape ${o.id} (${o.type}):`,{id:o.id,type:o.type,hasVertices:"vertices"in o,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:0,hasVerticesConfig:"verticesConfig"in o,verticesConfig:o.verticesConfig,verticesConfigKeys:o.verticesConfig?Object.keys(o.verticesConfig):[],hasPosition:"position"in o,position:o.position,hasStart:"start"in o,start:o.start,hasEnd:"end"in o,end:o.end,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,hasGeometryRef:"geometryRef"in o,geometryRef:o.geometryRef,keys:Object.keys(o)}),o}catch(i){if(s)throw i;return console.warn("图形元素转换失败:",i),o}}static resolvePointReference(e,n){if(!e||typeof e!="object")return e;if("$ref"in e){const r=e.$ref;if(n&&n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}if("geometryRef"in e){const r=e.geometryRef;if(n&&n.geometryPresets&&n.geometryPresets[r]){const s=n.geometryPresets[r];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}return e}static convertShapeCoordinates(e,n){if(!e||typeof e!="object")return e;console.warn("🔄 GraphTransformer.convertShapeCoordinates START for shape:",{id:e.id,type:e.type,hasVertices:"vertices"in e,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e)});const r={...e};if(r.position){if(Array.isArray(r.position)&&r.position.length>=2)console.warn(`🔄 Converting position array to object for ${r.id}:`,{shapeId:r.id,positionArray:r.position,convertedTo:{x:r.position[0],y:r.position[1]}}),r.position={x:r.position[0],y:r.position[1]};else if(typeof r.position=="object"){const s=this.resolvePointReference(r.position,n);s&&typeof s=="object"&&(r.position=s)}}if(Array.isArray(r.vertices)){const s=r.verticesConfig?{...r.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!r.verticesConfig,existingKeys:r.verticesConfig?Object.keys(r.verticesConfig):[],verticesConfigKeys:Object.keys(s)}),r.vertices=r.vertices.map((o,i)=>{const a=this.resolvePointReference(o,n);let l=null;if(o&&typeof o=="object"&&"$ref"in o){const c=o.$ref;n&&n.geometryPresets&&n.geometryPresets[c]&&(l=n.geometryPresets[c],console.warn(`📌 Found point definition for ${c} at vertex ${i}:`,{hasWithLabel:"withLabel"in l,withLabel:l.withLabel,hasLabel:"label"in l,labelKeys:l.label?Object.keys(l.label):"none"}),l.name&&(s[i]||(s[i]={}),s[i].name=l.name))}return Array.isArray(a)&&a.length>=2?{x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?a:(o&&typeof o=="object"&&("$ref"in o||"geometryRef"in o),o)}),r.withLabel!==void 0||r.label){const o={withLabel:r.withLabel!==void 0?r.withLabel:!0};if(r.label&&typeof r.label=="object"){const a=r.label;a.offset&&Array.isArray(a.offset)&&a.offset.length>=2&&(o.offset=a.offset),a.fontSize!==void 0&&(o.fontSize=a.fontSize),a.color&&(o.color=a.color),a.anchorX&&(o.anchorX=a.anchorX),a.anchorY&&(o.anchorY=a.anchorY)}const i={...o};for(const a in s)isNaN(Number(a))||(i[a]||(i[a]={}),Object.assign(i[a],s[a]));r.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${r.id}:`,i)}else Object.keys(s).length>0&&(r.verticesConfig=s,console.warn(`✅ Added verticesConfig for polygon ${r.id}:`,s))}if(Array.isArray(r.endpoints)&&(r.endpoints=r.endpoints.map(s=>{const o=this.resolvePointReference(s,n);return Array.isArray(o)&&o.length>=2?{x:o[0],y:o[1]}:o&&typeof o=="object"&&"x"in o&&"y"in o?o:(s&&typeof s=="object"&&("$ref"in s||"geometryRef"in s),s)})),Array.isArray(r.center)&&r.center.length>=2)r.center={x:r.center[0],y:r.center[1]};else if(r.center&&typeof r.center=="object"){const s=this.resolvePointReference(r.center,n);s&&typeof s=="object"&&(r.center=s)}if(r.start){if(Array.isArray(r.start)&&r.start.length>=2)r.start={x:r.start[0],y:r.start[1]};else if(typeof r.start=="object"){const s=this.resolvePointReference(r.start,n);s&&typeof s=="object"&&(r.start=s)}}if(r.end){if(Array.isArray(r.end)&&r.end.length>=2)r.end={x:r.end[0],y:r.end[1]};else if(typeof r.end=="object"){const s=this.resolvePointReference(r.end,n);s&&typeof s=="object"&&(r.end=s)}}for(const[s,o]of Object.entries(r))Array.isArray(o)?r[s]=o.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,n):i):o&&typeof o=="object"&&(r[s]=this.convertShapeCoordinates(o,n));return r}static transformTransform(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.transformRef){try{const i=qe.resolve(o.transformRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformLabel(e,n){const r={...e};if(r.styleRef){try{const s=ze.resolve(r.styleRef,n);r.style=s}catch(s){console.warn(`标签样式解析失败: ${r.styleRef}`,s)}delete r.styleRef}return r}static resolveBoardConfig(e,n){if(n.boardDefinitions&&n.boardDefinitions[e])return n.boardDefinitions[e];const r={default:{originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1},extended:{originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1}};return r[e]||r.default}static validate(e){const n=[];return e?(e.type!==$e.GRAPH&&n.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&n.push("图形内容块 shapes 数组不能为空"):n.push("图形内容块缺少 shapes 数组"),n):(n.push("图形内容块不能为空"),n)}static batchTransform(e,n,r={}){return e.filter(s=>s.type===$e.GRAPH).map(s=>this.transform(s,n,r))}}function sS(){return{type:$e.GRAPH,transform:ls.transform.bind(ls),validate:ls.validate.bind(ls)}}class cs{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const n={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:n,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:n.static.length,animatedLength:n.animated.length}),n}static transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(s){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const d=ln.resolve(e.geometryTransformRef,n,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const f={type:$e.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",f.metadata.config),f.metadata.config&&typeof f.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),f.metadata.config=this.transformConfig(f.metadata.config,n,{strictMode:o})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",f),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",f.metadata.config),f}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:$e.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(d){if(o)throw d;console.error("❌ 几何变换引用解析失败:",d),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",n.geometryTransformConfigs)}}const i=e.base||e.config?.base||n.basicInfo?.base||0,a=e.height||e.config?.height||n.basicInfo?.height||0,l=e.unit||e.config?.unit||n.basicInfo?.baseUnit||"cm",c={...e,type:$e.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:l,...e.config||{},shapes:this.normalizeShapes(e.shapes||e.config?.shapes),transform:e.transform||e.config?.transform||{},animation:e.animation||e.config?.animation||{},boardConfig:e.boardConfig||e.config?.boardConfig||{}}}};if(console.error("🔍 GeometryTransformTransformer.transform: 转换后配置 =",{metadataConfig:c.metadata?.config,shapesAnimatedLength:c.metadata?.config?.shapes?.animated?.length,shapesStaticLength:c.metadata?.config?.shapes?.static?.length,base:c.metadata?.config?.base,height:c.metadata?.config?.height,unit:c.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete c.config,delete c.base,delete c.height,delete c.unit,delete c.shapes,delete c.transform,delete c.animation,delete c.boardConfig,!s)return c;try{if(c.geometryRef){try{const d=yt.resolve(c.geometryRef,n);if(c.metadata.config||(c.metadata.config={}),Object.assign(c.metadata.config,d),d.styleRef){const f=ze.resolve(d.styleRef,n);c.metadata.config.style=f}}catch(d){if(o)throw d;console.warn(`几何变换几何解析失败: ${c.geometryRef}`,d)}delete c.geometryRef}if(c.transformRef){try{const d=qe.resolve(c.transformRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.transform||(c.metadata.config.transform={}),Object.assign(c.metadata.config.transform,d)}catch(d){if(o)throw d;console.warn(`几何变换变换解析失败: ${c.transformRef}`,d)}delete c.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!c.metadata,hasConfig:!!c.metadata?.config,configType:c.metadata?.config?typeof c.metadata.config:"undefined",configIsObject:c.metadata?.config?typeof c.metadata.config=="object":!1,configKeys:c.metadata?.config?Object.keys(c.metadata.config):[]}),c.metadata?.config&&typeof c.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),c.metadata.config=this.transformConfig(c.metadata.config,n,{strictMode:o}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),c.styleRef){try{const d=ze.resolve(c.styleRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.style=d}catch(d){if(o)throw d;console.warn(`几何变换样式解析失败: ${c.styleRef}`,d)}delete c.styleRef}if(c.animationRef){try{const d=this.resolveAnimationConfig(c.animationRef,n,{strictMode:o});c.metadata.config||(c.metadata.config={}),c.metadata.config.animation={...d,...c.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层动画引用解析失败: ${c.animationRef}`,d)}delete c.animationRef}if(c.sliderRef){try{const d=zt.resolve(c.sliderRef,n);c.metadata.config||(c.metadata.config={}),c.metadata.config.animation={...d,...c.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层滑块引用解析失败: ${c.sliderRef}`,d)}delete c.sliderRef}if(c.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:c.boardRef,hasMetadataConfig:!!c.metadata?.config,currentBoardConfig:c.metadata?.config?.boardConfig});try{const d=this.resolveBoardConfig(c.boardRef,n,{strictMode:o});console.error("🔍 解析后的 boardConfig:",d),c.metadata.config||(c.metadata.config={}),c.metadata.config.boardConfig={...d,...c.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",c.metadata.config.boardConfig)}catch(d){if(o)throw d;console.warn(`顶层画板引用解析失败: ${c.boardRef}`,d)}delete c.boardRef}if(c.metadata?.config?.boardConfig&&typeof c.metadata.config.boardConfig=="object"){const d=c.metadata.config.boardConfig;(!d.boundingBox||!Array.isArray(d.boundingBox)||d.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),d.boundingBox=[0,7,10,0],d.originX=d.originX??2,d.originY=d.originY??2,d.keepAspectRatio=d.keepAspectRatio??!0,d.showGrid=d.showGrid??!1,d.showAxis=d.showAxis??!1,d.description=d.description||"默认画板配置")}return console.error("🔍 GeometryTransformTransformer.transform: 最终转换结果 =",{type:c.type,metadataConfig:c.metadata?.config,shapesAnimatedLength:c.metadata?.config?.shapes?.animated?.length,shapesStaticLength:c.metadata?.config?.shapes?.static?.length,base:c.metadata?.config?.base,height:c.metadata?.config?.height,unit:c.metadata?.config?.unit,hasTransform:!!c.metadata?.config?.transform,transform:c.metadata?.config?.transform,hasAnimation:!!c.metadata?.config?.animation,animation:c.metadata?.config?.animation,hasBoardConfig:!!c.metadata?.config?.boardConfig,boardConfig:c.metadata?.config?.boardConfig}),c}catch(d){if(o)throw d;return console.warn("几何变换转换失败:",d),c}}static transformConfig(e,n,r={}){const{strictMode:s=!1}=r,o={...e},i={};if(o.shapes&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 shapes"),console.error(" transformedConfig.shapes:",o.shapes),o.shapes.static&&(console.error(` 处理 static shapes (${o.shapes.static.length}):`),o.shapes.static=o.shapes.static.map((a,l)=>{console.error(` 处理 static shape[${l}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const c=this.transformShape(a,n,{strictMode:s});return a.geometryRef&&c.id&&(i[a.geometryRef]=c.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${c.id}" (转换后)`)),console.error(` 转换后的 static shape[${l}]:`,{id:c.id,type:c.type,hasGeometryRef:!!c.geometryRef,geometryRef:c.geometryRef,hasVertices:!!c.vertices,vertices:c.vertices}),c})),o.shapes.animated&&(console.error(` 处理 animated shapes (${o.shapes.animated.length}):`),o.shapes.animated=o.shapes.animated.map((a,l)=>{console.error(` 处理 animated shape[${l}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const c=this.transformShape(a,n,{strictMode:s});return a.geometryRef&&c.id&&(i[a.geometryRef]=c.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${c.id}" (转换后)`)),console.error(` 转换后的 animated shape[${l}]:`,{id:c.id,type:c.type,hasGeometryRef:!!c.geometryRef,geometryRef:c.geometryRef,hasVertices:!!c.vertices,vertices:c.vertices}),c}))),o.transform){if(o.transform.transformRef)try{const a=qe.resolve(o.transform.transformRef,n);o.transform={...a,...o.transform,transformRef:void 0},console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transform 对象中的 transformRef",{originalTransformRef:o.transform.transformRef,resolvedTransform:a,mergedTransform:o.transform})}catch(a){if(s)throw a;console.warn(`Transform ref解析失败: ${o.transform.transformRef}`,a)}o.transform=this.normalizeTransformConfig(o.transform,i),Array.isArray(o.transform.transforms)&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transforms 数组",{transformsLength:o.transform.transforms.length,transforms:o.transform.transforms}),o.transform.transforms=o.transform.transforms.map((a,l)=>{if(console.error(`🔍 处理 transform[${l}]:`,{type:typeof a,isString:typeof a=="string",isObject:typeof a=="object"&&a!==null,transformItem:a,hasTransformRef:a&&typeof a=="object"&&"transformRef"in a,transformRef:a&&typeof a=="object"?a.transformRef:void 0}),typeof a=="string"){if(console.error(`🔍 transform[${l}] 是字符串格式`),a.startsWith("transformRef:")){const c=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${c}`);try{const d=qe.resolve(c,n);console.error(`🔍 transform[${l}] 解析成功:`,d);const f=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${l}] 标准化后:`,f),f}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${c}`,d),a}}try{const c=qe.resolve(a,n);return this.normalizeTransformConfig(c,i)}catch(c){if(s)throw c;return console.warn(`Transform ref解析失败: ${a}`,c),a}}else if(a&&typeof a=="object"&&a.transformRef){const c=a.transformRef;console.error(`🔍 transform[${l}] 是对象格式,refName=${c}`);try{const d=qe.resolve(c,n);console.error(`🔍 transform[${l}] 解析成功:`,d);const f={...d,...a,transformRef:void 0};console.error(`🔍 transform[${l}] 合并后:`,f);const g=this.normalizeTransformConfig(f,i);return console.error(`🔍 transform[${l}] 标准化后:`,g),g}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${c}`,d),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${l}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${l}] 未处理,返回原始值:`,a),a}))}if(o.geometry&&typeof o.geometry=="object"&&(o.geometry=this.transformGeometry(o.geometry,n,{strictMode:s})),Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(a=>{if(a.transformRef)try{const l=qe.resolve(a.transformRef,n);return{...a,...l,transformRef:void 0}}catch(l){if(s)throw l;return console.warn(`Transformations解析失败: ${a.transformRef}`,l),a}return a})),o.style&&typeof o.style=="object"&&(o.style=this.transformStyle(o.style,n,{strictMode:s})),o.animationRef){try{const a=this.resolveAnimationConfig(o.animationRef,n,{strictMode:s});o.animation={...a,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`动画引用解析失败: ${o.animationRef}`,a)}delete o.animationRef}if(o.sliderRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 sliderRef",{sliderRef:o.sliderRef,hasAnimationDefinitions:!!n.animationDefinitions,animationDefinitionKeys:n.animationDefinitions?Object.keys(n.animationDefinitions):[]});try{const a={...cn,...n,animationDefinitions:n.animationDefinitions||cn.animationDefinitions},l=zt.resolve(o.sliderRef,a);o.animation={...l,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`滑块引用解析失败: ${o.sliderRef}`,a)}delete o.sliderRef}if(o.boardRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 config 中的 boardRef",{boardRef:o.boardRef,currentBoardConfig:o.boardConfig});try{const a=this.resolveBoardConfig(o.boardRef,n,{strictMode:s});console.error("🔍 解析后的 boardConfig (config):",a),o.boardConfig={...a,...o.boardConfig||{}},console.error("🔍 设置后的 transformedConfig.boardConfig:",o.boardConfig)}catch(a){if(s)throw a;console.warn(`画板引用解析失败: ${o.boardRef}`,a)}delete o.boardRef}return o}static normalizeTransformConfig(e,n){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:n?Object.keys(n):[],geometryRefToShapeId:n});const r={...e};switch(!r.type&&r.config&&r.config.type&&(r.type=r.config.type),r.type){case"rotation":if(r.config){if(r.rotation={...r.config},r.rotation.center&&typeof r.rotation.center=="object"){const s=r.rotation.center;"x"in s&&"y"in s&&(r.rotation.center=[s.x,s.y])}delete r.config}break;case"translation":r.config&&(r.translation={...r.config},delete r.config);break;case"scale":if(r.config){if(r.scale={...r.config},r.scale.center&&typeof r.scale.center=="object"){const s=r.scale.center;"x"in s&&"y"in s&&(r.scale.center=[s.x,s.y])}delete r.config}break;case"composite":r.config&&Array.isArray(r.config.transforms)&&(r.composite=r.config.transforms.map(s=>this.normalizeTransformConfig(s,n)),delete r.config);break;default:if(r.config){const{type:s,...o}=r.config;Object.assign(r,o),delete r.config}}if(r.targetGroup&&n){const s=r.targetGroup;let o;if(n[s])o=n[s],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:s,mapped:o,type:"exact"});else{const i=Object.keys(n).find(a=>{if(a.startsWith(s+"_")||a===s||a.includes(s))return!0;const l=a.split("_"),c=s.split("_");return l.some(d=>c.includes(d))});i&&(o=n[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:s,geometryRef:i,mapped:o,type:"heuristic"}))}o?r.targetGroup=o:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:s,geometryRefToShapeId:n,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!r.targetGroup&&(r.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:r,hasRotation:!!r.rotation,hasTranslation:!!r.translation,hasScale:!!r.scale,hasComposite:!!r.composite}),r}static transformShape(e,n,r={}){console.error("🔍 transformShape 被调用:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasStyleRef:!!e.styleRef,styleRef:e.styleRef,shapeKeys:Object.keys(e),contextHasGeometryPresets:!!n.geometryPresets,contextGeometryPresetKeys:n.geometryPresets?Object.keys(n.geometryPresets):[]});const{strictMode:s=!1}=r,o={...e};if(o.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",o.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",n.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",n.geometryPresets?Object.keys(n.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=yt.resolve(o.geometryRef,n);console.error("🔍 transformShape: geometry 解析结果:",i),Object.assign(o,i),console.error("🔍 transformShape: 合并后的 shape:",o),o.vertices&&Array.isArray(o.vertices)&&console.error("🔍 transformShape: 顶点数据:",{count:o.vertices.length,sample:o.vertices.slice(0,3).map((a,l)=>({index:l,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})}catch(i){if(console.error("🔍 transformShape: geometryRef 解析错误:",i),s)throw i;console.warn(`Shape geometryRef解析失败: ${o.geometryRef}`,i)}delete o.geometryRef,console.error("🔍 transformShape: 删除 geometryRef 后的 shape:",o)}if(o.styleRef){try{const i=ze.resolve(o.styleRef,n);o.style=i}catch(i){if(s)throw i;console.warn(`Shape styleRef解析失败: ${o.styleRef}`,i)}delete o.styleRef}if(o.metadata||(o.metadata={}),!o.metadata.id&&o.id&&(o.metadata.id=o.id),o.withLabel!==void 0&&(o.metadata.showLabel=o.withLabel,delete o.withLabel),o.label&&(typeof o.label=="object"?o.metadata.label=o.label.text||o.metadata.id||"":typeof o.label=="string"&&(o.metadata.label=o.label),delete o.label),o.metadata.showLabel&&!o.metadata.label&&o.metadata.id&&(o.metadata.label=o.metadata.id),o.metadata.id&&(o.metadata.rotationGroup=o.metadata.id),o.type==="point"&&o.position){console.error("🔍 transformShape: 转换point为circle:",{shapeId:o.metadata?.id,position:o.position,originalType:o.type});const i=o.position.x,a=o.position.y,l=.1;o.type="circle",o.vertices=[[i,a],[i+l,a]],delete o.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:o.type,vertices:o.vertices})}return o}static transformGeometry(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.geometryRef){try{const i=yt.resolve(o.geometryRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`几何对象解析失败: ${o.geometryRef}`,i)}delete o.geometryRef}return o}static transformTransform(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.transformRef){try{const i=qe.resolve(o.transformRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换对象解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformStyle(e,n,r={}){const{strictMode:s=!1}=r,o={...e};if(o.styleRef){try{const i=ze.resolve(o.styleRef,n);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`样式对象解析失败: ${o.styleRef}`,i)}delete o.styleRef}return o}static resolveAnimationConfig(e,n,r={}){const{strictMode:s=!1}=r;if(!e||typeof e!="string"){if(s)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const o=e.replace("animationRef:","");if(n.animationDefinitions&&n.animationDefinitions[o])return{...n.animationDefinitions[o]};if(s)throw new Error(`动画引用未找到: ${o}`);const i=this.getFallbackAnimationConfig(o);return console.warn(`动画引用未在上下文中找到,使用回退配置: ${o}`),i}catch(o){if(s)throw o;return console.warn(`动画配置解析失败: ${e}`,o),{}}}static resolveBoardConfig(e,n,r={}){const{strictMode:s=!1}=r;if(!e||typeof e!="string"){if(s)throw new Error(`无效的画板引用: ${e}`);return console.warn(`无效的画板引用: ${e}`),{}}try{const o=e.replace("boardRef:","");if(console.error("🔍 GeometryTransformTransformer.resolveBoardConfig:",{boardRef:e,refName:o,hasContextBoardDefinitions:!!n.boardDefinitions,contextBoardDefinitionKeys:n.boardDefinitions?Object.keys(n.boardDefinitions):[],hasRefInContext:n.boardDefinitions&&!!n.boardDefinitions[o]}),n.boardDefinitions&&n.boardDefinitions[o]){const a={...n.boardDefinitions[o]};return console.error("🔍 从上下文获取画板配置:",a),a}if(s)throw new Error(`画板引用未找到: ${o}`);const i=this.getFallbackBoardConfig(o);return console.warn(`画板引用未在上下文中找到,使用回退配置: ${o}`),console.error("🔍 使用回退画板配置:",i),i}catch(o){if(s)throw o;return console.warn(`画板配置解析失败: ${e}`,o),{}}}static getFallbackAnimationConfig(e){const n={slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}};return n[e]||n.slider_horizontal}static getFallbackBoardConfig(e){const n={default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}};return n[e]||n.default}static validate(e){const n=[];return e?(e.type!==$e.GEOMETRY_TRANSFORM&&n.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||n.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&n.push("几何变换内容块缺少 geometry 或 geometryRef"),n):(n.push("几何变换内容块不能为空"),n)}static batchTransform(e,n,r={}){return e.filter(s=>s.type===$e.GEOMETRY_TRANSFORM).map(s=>this.transform(s,n,r))}}function oS(){return{type:$e.GEOMETRY_TRANSFORM,transform:cs.transform.bind(cs),validate:cs.validate.bind(cs)}}class Bt{static transformText(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${s}`);const i={...e,type:$e.TEXT};if(!s)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,n,{strictMode:o})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,n,{strictMode:o})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=ze.resolve(i.styleRef,n);console.error(" StyleRefResolver解析结果:",a),i.style={...i.style,...a},console.error(" 合并后style:",i.style)}catch(a){if(o)throw a;console.warn(`文本样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("文本转换失败:",a),i}}static transformFormula(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r,i={...e,type:$e.FORMULA};if(!s)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,n,{strictMode:o})),i.styleRef){try{const a=ze.resolve(i.styleRef,n);i.style={...i.style,...a}}catch(a){if(o)throw a;console.warn(`公式样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("公式转换失败:",a),i}}static resolveTextContent(e,n,r={}){const{strictMode:s=!1}=r;if(console.error(`📝 TextTransformer.resolveTextContent START: text="${e}", hasDesignTokens=${e.includes("$")}`),!e.includes("$"))return console.error(` resolveTextContent END (no design tokens): "${e}"`),e;let o=e,i;const a=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;for(;(i=a.exec(e))!==null;){const l=i[0],c=i[1];console.error(` 发现设计令牌: ${l}, path=${c}`);try{const d=tt.resolve(l,n);console.error(` 解析结果: ${l} -> ${d}`),o=o.replace(l,String(d))}catch(d){if(s)throw d;console.warn(`文本中的设计令牌解析失败: ${l}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${o}"`),o}static resolveStyle(e,n,r={}){const{strictMode:s=!1}=r;try{return tt.replaceDesignTokenRefs(e,n,o=>{if(s)throw new Error(`设计令牌未找到: ${o}`);return console.warn(`设计令牌未找到: ${o}`),o})}catch(o){if(s)throw o;return console.warn("样式解析失败:",o),e}}static validateText(e){const n=[];return e?(e.type!==$e.TEXT&&n.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&n.push("文本内容块缺少 content 字段"),n):(n.push("文本内容块不能为空"),n)}static validateFormula(e){const n=[];return e?(e.type!==$e.FORMULA&&n.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&n.push("公式内容块缺少 content 字段"),n):(n.push("公式内容块不能为空"),n)}static batchTransformText(e,n,r={}){return e.filter(s=>s.type===$e.TEXT).map(s=>this.transformText(s,n,r))}static batchTransformFormula(e,n,r={}){return e.filter(s=>s.type===$e.FORMULA).map(s=>this.transformFormula(s,n,r))}}function iS(){return{type:$e.TEXT,transform:Bt.transformText.bind(Bt),validate:Bt.validateText.bind(Bt)}}function aS(){return{type:$e.FORMULA,transform:Bt.transformFormula.bind(Bt),validate:Bt.validateFormula.bind(Bt)}}class lS{type="hundredGrid";transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 HundredChartTransformer.transform START for content block:",{blockType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,enableReferenceResolution:s,strictMode:o});try{const i=e.geometryRef;if(!i)throw new kn(It.MISSING_REQUIRED_FIELD,"HundredGrid内容块缺少geometryRef字段");const a=this.extractShapeId(i),l=n.geometry_shapes?.[a]||n.geometryPresets?.[a];if(!l)throw new kn(It.GEOMETRY_REF_NOT_FOUND,`HundredGrid引用未找到: ${i} (解析后shapeId: ${a})`);if(l.type!=="hundredGrid")throw new kn(It.GEOMETRY_REF_NOT_FOUND,`引用${a}不是hundredGrid类型: ${l.type}`);const c=l.config||{},d=e.config||{},f=this.mergeConfigs(c,d),g=this.resolveStyle(l,n,f,s),h=this.mapToHundredChartProps(f,g),m={type:"hundredGrid",content:"",props:h,metadata:{shapeId:a,config:f,styleRef:l.styleRef}};return console.error("✅ HundredChartTransformer.transform SUCCESS:",{shapeId:a,propsKeys:Object.keys(h),hasHighlight:!!f.highlight?.numbers,highlightCount:f.highlight?.numbers?.length||0}),m}catch(i){if(console.error("❌ HundredChartTransformer.transform ERROR:",i),o)throw i;return e}}extractShapeId(e){return e.startsWith("geometryRef:")?e.replace("geometryRef:",""):e}mergeConfigs(e,n){const r={...e};return n.grid&&(r.grid={...e.grid,...n.grid}),n.highlight&&(r.highlight={...e.highlight,...n.highlight},n.highlight.numbers!==void 0&&(r.highlight.numbers=n.highlight.numbers)),n.interactive&&(r.interactive={...e.interactive,...n.interactive}),n.style&&(r.style={...e.style,...n.style}),r}resolveStyle(e,n,r,s){const o={};if(e.styleRef&&s)try{const i=e.styleRef.startsWith("styleRef:")?e.styleRef.replace("styleRef:",""):e.styleRef,a=n.stylePresets?.[i];a&&Object.entries(a).forEach(([l,c])=>{if(typeof c=="string"&&c.startsWith("$"))try{o[l]=tt.resolve(c,n)}catch(d){console.warn(`设计令牌解析失败: ${l}=${c}`,d),o[l]=c}else o[l]=c})}catch(i){console.warn(`样式引用解析失败: ${e.styleRef}`,i)}return r.style&&Object.entries(r.style).forEach(([i,a])=>{if(s&&typeof a=="string"&&a.startsWith("$"))try{o[i]=tt.resolve(a,n)}catch(l){console.warn(`设计令牌解析失败: ${i}=${a}`,l),o[i]=a}else o[i]=a}),o.baseColor||(o.baseColor="#f3f4f6"),o.selectedColor||(o.selectedColor="#3b82f6"),o.borderColor||(o.borderColor="#d1d5db"),o.textColor||(o.textColor="#333"),o.fontSize||(o.fontSize=14),o}mapToHundredChartProps(e,n){const r={};return r.rows=e.grid?.rows||10,r.cols=e.grid?.cols||10,r.cellSize=e.grid?.cellSize||36,r.mode=this.mapInteractiveMode(e.interactive?.mode),r.value=this.calculateValueFromHighlight(e.highlight?.numbers||[],r.rows,r.cols),r.fillColor=this.normalizeColor(n.selectedColor),r.baseColor=this.normalizeColor(n.baseColor),r.strokeColor=this.normalizeColor(n.borderColor),r.shadingDirection="ltr",r.hasShadow=!0,r.className="mathwiz-hundredgrid",r._config=e,r._style=n,r}mapInteractiveMode(e){return e==="readonly"?"readonly":"edit"}calculateValueFromHighlight(e,n=10,r=10){if(!e.length)return 0;const s=n*r;return e.length/s}normalizeColor(e){return typeof e!="string"?e:e.startsWith("#")?e.toLowerCase():e}validate(e){const n=[];return e.type||n.push("内容块缺少 type 字段"),e.type!=="hundredGrid"&&n.push(`内容块类型应为 hundredGrid,实际为 ${e.type}`),e.geometryRef||n.push("HundredGrid内容块缺少 geometryRef 字段"),n}}function cS(){return new lS}class dS{type="optionGroup";transform(e,n,r={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=r;console.error("🔄 OptionGroupTransformer.transform START for content block:",{blockType:e.type,hasOptionGroupRef:!!e.optionGroupRef,optionGroupRef:e.optionGroupRef,enableReferenceResolution:s,strictMode:o});try{const{optionGroupRef:i}=e;if(!i)throw new kn(It.MISSING_REQUIRED_FIELD,"OptionGroup 内容块缺少 optionGroupRef 字段");const a=n.optionGroups?.[i];if(!a)throw new kn(It.GEOMETRY_REF_NOT_FOUND,`OptionGroup 定义未找到: ${i}`);if(a.type!=="optionGroup")throw new kn(It.GEOMETRY_REF_NOT_FOUND,`引用 ${i} 不是 optionGroup 类型: ${a.type}`);const l=a.options.map(d=>({id:d.id,content:d.content,contentType:d.contentType||"text",graphConfig:d.graphConfig})),c={type:"optionGroup",content:"",options:l,correctAnswers:a.correctAnswers,answerType:a.answerType,layout:a.layout||"vertical",variant:a.variant||"default",mode:e.mode||"question",showUserAnswer:e.showUserAnswer||!1,metadata:{optionGroupId:i,definition:a}};return console.error("✅ OptionGroupTransformer.transform SUCCESS:",{optionGroupRef:i,optionsCount:l.length,answerType:a.answerType,correctAnswers:a.correctAnswers}),c}catch(i){if(console.error("❌ OptionGroupTransformer.transform ERROR:",i),o)throw i;return e}}validate(e){const n=[];return e.type||n.push("内容块缺少 type 字段"),e.type!=="optionGroup"&&n.push(`内容块类型应为 optionGroup,实际为 ${e.type}`),e.optionGroupRef||n.push("OptionGroup 内容块缺少 optionGroupRef 字段"),n}}function uS(){return new dS}class fS{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(sS()),this.register(oS()),this.register(iS()),this.register(aS()),this.register(cS()),this.register(uS())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,n,r={}){if(!e||!e.type)throw new Error("内容块缺少 type 字段");const s=this.getTransformer(e.type);return s?(console.error(`🔄 TransformerRegistry.transform: type="${e.type}", transformer.type="${s.type}", enableReferenceResolution=${r.enableReferenceResolution}`),s.transform(e,n,r)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,n,r={}){return e.map(s=>this.transform(s,n,r))}transformScene(e,n,r={}){const s=e.items||e.content;if(!e||!Array.isArray(s))return{items:[],layout:e?.layout};const o=this.batchTransform(s,n,r);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,n,r);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=bt.resolve(e.layout,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:o,layout:i}}resolveLayoutReferences(e,n,r){if(!e||!r.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return bt.resolve(e,n)}catch(s){if(r.strictMode)throw s;return console.warn(`布局引用解析失败: ${e}`,s),e}if(typeof e=="object"){if(e.layoutRef&&typeof e.layoutRef=="string")try{const o=`layoutRef:${e.layoutRef}`,i=bt.resolve(o,n),{layoutRef:a,...l}=e;return{...i,...l}}catch(o){if(r.strictMode)throw o;console.warn(`布局引用解析失败: ${e.layoutRef}`,o)}const s=Array.isArray(e)?[]:{};for(const[o,i]of Object.entries(e))if(typeof i=="string"&&i.startsWith("layoutRef:"))try{s[o]=bt.resolve(i,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),s[o]=i}else if(typeof i=="string"&&i.startsWith("$"))try{s[o]=tt.resolve(i,n)}catch(a){if(r.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${o}=${i}`,a),s[o]=i}else i&&typeof i=="object"?s[o]=this.resolveLayoutReferences(i,n,r):s[o]=i;return s}return e}transformScenes(e,n,r={}){const s={};for(const[o,i]of Object.entries(e))s[o]=this.transformScene(i,n,r);return s}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const n=this.getTransformer(e.type);return!n||!n.validate?[]:n.validate(e)}batchValidate(e){return e.map(n=>({block:n,errors:this.validate(n)}))}}function Mf(){return new fS}class hi{static validate(e,n={}){const{strictMode:r=!1,skipOptionalFields:s=!1}=n,o=[],i=[];return!e||typeof e!="object"?(o.push("输入数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i,{skipOptionalFields:s}),this.validateFieldTypes(e,o,i),this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswerInfo(e,o,i),r&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,n,r,s){const{skipOptionalFields:o}=s;for(const i of Fo.RAW_DATA)e[i]===void 0&&n.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Fo.BASIC_INFO)e.basic_info[i]===void 0&&n.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Fo.ANSWER_INFO)e.answer_info[i]===void 0&&n.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,n,r){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&n.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&n.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&n.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&n.push(`${a} 应为对象类型`)})}static validateScenes(e,n,r){if(!e.scenes||typeof e.scenes!="object"){n.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||n.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){n.push(`场景 ${o} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||n.push(`场景 ${o} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&n.push(`场景 ${o} 的 layout 应为对象类型`),_f.includes(o)||r.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,n,r){if(!e.basic_info||typeof e.basic_info!="object")return;const s=e.basic_info;["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&n.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&n.push(`basic_info.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&n.push("basic_info.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&n.push("basic_info.context 应为对象类型"),s.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(s.shape)&&r.push(`未知的形状类型: ${s.shape}`)}static validateAnswerInfo(e,n,r){if(!e.answer_info||typeof e.answer_info!="object")return;const s=e.answer_info;typeof s.value!="number"&&n.push("answer_info.value 应为数字类型"),typeof s.unit!="string"&&n.push("answer_info.unit 应为字符串类型"),typeof s.explanation_text!="string"&&n.push("answer_info.explanation_text 应为字符串类型"),s.value!==void 0&&(s.value<0&&r.push("answer_info.value 为负数,可能不正确"),s.value>1e4&&r.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,n,r){if(e.schema_version||r.push("建议添加 schema_version 字段"),e.config_version||r.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&r.push("knowledge_points 数组为空"),e.scenes)for(const[s,o]of Object.entries(e.scenes)){const i=o;i.content&&i.content.length===0&&r.push(`场景 ${s} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const n=["math_prob_id","title","basic_info","scenes","answer_info"];for(const r of n)if(e[r]===void 0)return!1;return!0}static validateAndClean(e,n={}){const{strictMode:r=!1,removeInvalidFields:s=!1}=n,o=this.validate(e,{strictMode:r});let i=e;return s&&!o.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(l=>{l in i&&delete i[l]})),{data:i,errors:o.errors,warnings:o.warnings}}}class gi{static validate(e,n={}){const{strictMode:r=!1,checkSceneContent:s=!0}=n,o=[],i=[];return!e||typeof e!="object"?(o.push("输出数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i),this.validateFieldTypes(e,o,i),s&&this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswer(e,o,i),this.validateExplanation(e,o,i),r&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,n,r){const s=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const o of s)e[o]===void 0&&n.push(`缺少必需字段: ${o}`)}static validateFieldTypes(e,n,r){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&n.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&n.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&n.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&n.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&n.push(`${i} 应为对象类型`)})}static validateScenes(e,n,r){if(!e.scenes||typeof e.scenes!="object"){n.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||n.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){n.push(`场景 ${o} 应为对象类型`);continue}const a=i,l=a.items||a.content;Array.isArray(l)?l.length===0&&r.push(`场景 ${o} 的内容数组为空`):n.push(`场景 ${o} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&n.push(`场景 ${o} 的 layout 应为对象类型`),_f.includes(o)||r.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,n,r){if(!e.basicInfo||typeof e.basicInfo!="object"){n.push("basicInfo 应为对象类型");return}const s=e.basicInfo;(s.question===void 0||typeof s.question!="string")&&n.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&n.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&n.push(`basicInfo.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&n.push("basicInfo.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&n.push("basicInfo.context 应为对象类型")}static validateAnswer(e,n,r){if(!e.answer||typeof e.answer!="object"){n.push("answer 应为对象类型");return}const s=e.answer;typeof s.value!="number"&&n.push("answer.value 应为数字类型"),typeof s.unit!="string"&&n.push("answer.unit 应为字符串类型"),typeof s.explanation!="string"&&n.push("answer.explanation 应为字符串类型"),s.value!==void 0&&(s.value<0&&r.push("answer.value 为负数,可能不正确"),s.value>1e4&&r.push("answer.value 过大,可能不正确"))}static validateExplanation(e,n,r){if(e.explanation===void 0){n.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){n.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&r.push("explanation 数组为空"),e.explanation.forEach((s,o)=>{(!s||typeof s!="object")&&n.push(`explanation[${o}] 应为对象类型`)})):e.explanation.steps===void 0?n.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||n.push("explanation.steps 应为数组类型")}static validateStrictMode(e,n,r){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||r.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&r.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&r.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&r.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const s=e.metadata;(!s.topic||typeof s.topic!="string")&&r.push("metadata.topic 应为字符串类型"),(!s.skill||typeof s.skill!="string")&&r.push("metadata.skill 应为字符串类型"),(!s.tags||!Array.isArray(s.tags))&&r.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const n=["id","title","basicInfo","scenes","answer"];for(const r of n)if(e[r]===void 0)return!1;return!(typeof e.title!="string"||e.basicInfo&&typeof e.basicInfo!="object"||e.scenes&&typeof e.scenes!="object"||e.answer&&typeof e.answer!="object")}static isValidMathPracticeProblemData(e){return this.validate(e,{strictMode:!1,checkSceneContent:!1}).isValid}}class yn{static validateInput(e,n={}){const{isValid:r,errors:s,warnings:o}=hi.validate(e,n);return{isValid:r,errors:s,warnings:o,timestamp:Date.now()}}static validateOutput(e,n={}){const{isValid:r,errors:s,warnings:o}=gi.validate(e,n);return{isValid:r,errors:s,warnings:o,timestamp:Date.now()}}static validateComplete(e,n,r={}){const{inputStrictMode:s=!1,outputStrictMode:o=!1}=r,i=this.validateInput(e,{strictMode:s}),a=this.validateOutput(n,{strictMode:o}),l=[...i.errors,...a.errors],c=[...i.warnings,...a.warnings],d={isValid:i.isValid&&a.isValid,errors:l,warnings:c};return{input:i,output:a,overall:d}}static quickValidateInput(e){return hi.quickValidate(e)}static quickValidateOutput(e){return gi.quickValidate(e)}static validateAndReport(e,n,r={}){const s=n==="input"?this.validateInput(e,r):this.validateOutput(e,r);console.group(`${n.toUpperCase()} 验证结果`),console.log(`有效性: ${s.isValid?"✅ 通过":"❌ 失败"}`),s.errors.length>0&&(console.group("❌ 错误:"),s.errors.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),s.warnings.length>0&&(console.group("⚠️ 警告:"),s.warnings.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),console.groupEnd()}}class mi{static extractAllReferences(e){const n=[],r=s=>{typeof s=="string"?n.push(s):Array.isArray(s)?s.forEach(r):s&&typeof s=="object"&&Object.values(s).forEach(r)};return r(e),[...new Set(n)]}static categorizeReferences(e,n){const r={[he.DESIGN_TOKEN]:[],[he.STYLE_REF]:[],[he.GEOMETRY_REF]:[],[he.TRANSFORM_REF]:[],[he.LAYOUT_REF]:[]},s=new An;for(const o of e){const i=s.getResolverForRef(o);i&&r[i.type].push(o)}return r}static batchResolveReferences(e,n,r={}){const{strictMode:s=!1,onMissing:o}=r,i=new An,a={};for(const l of e){const c=i.getResolverForRef(l);if(c)try{a[l]=c.resolve(l,n)}catch(d){if(s)throw d;console.warn(`引用解析失败: ${l}`,d),o&&(a[l]=o(l))}}return a}static replaceReferences(e,n,r={}){const{strictMode:s=!1,onMissing:o,maxDepth:i=10}=r,a=new An,l=new Set(["geometryRef","styleRef","transformRef","layoutRef","boardRef","animationRef","appearanceRef","position","vertices","endpoints","center","start","end","type","theme","strategy","content","description","title","question","answer","unit","id","name","label","config","metadata","layout","renderer","padding","component","inputType","placeholder","submitButton","targetGroup","direction","executionMode","transformSource","rotationGroup","isMovable","isStatic","shapes","animated","static","transform","chartConfig","steps","value","tolerance","validation","explanation_text","solution_steps","variables","originX","originY","areaUnit","baseUnit","heightUnit","answerUnit","base","height","displayMode","parts","fontSize","fontWeight","anchorX"]),c=(d,f=0,g)=>{if(f>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(g&&l.has(g))return console.warn(`🛡️ 跳过保留字段 "${g}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const m=a.getResolverForRef(d);if(m)try{return m.resolve(d,n)}catch(p){if(s)throw p;return console.warn(`引用解析失败: ${d}`,p),o?o(d):d}return d}else{if(Array.isArray(d))return d.map(h=>c(h,f+1,void 0));if(d&&typeof d=="object"){const h={};for(const[m,p]of Object.entries(d))h[m]=c(p,f+1,m);return h}}return d};return c(e)}static calculateReferenceStats(e,n){const r=new An,s={total:e.length,resolved:0,failed:0,byType:{}};Object.values(he).forEach(o=>{s.byType[o]={total:0,resolved:0,failed:0}}),console.log("🔍 calculateReferenceStats: 开始处理引用,总数=",e.length);for(const o of e){console.log("🔍 处理引用:",o);const i=r.getResolverForRef(o);if(i){const a=i.type;s.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const l=i.resolve(o,n);console.log(`🔍 引用解析成功: ${o} =>`,l),s.resolved++,s.byType[a].resolved++}catch(l){console.error(`🔍 引用解析失败: ${o}`,l),s.failed++,s.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${o}`)}return s}static checkReferenceExists(e,n){const s=new An().getResolverForRef(e);if(!s)return!1;if(s.validate)return s.validate(e,n);try{return s.resolve(e,n),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const n=e.match(/^(\w+):(\w+)$/);return n?[n[1],n[2]]:[e]}static createReference(e,n){switch(e){case he.DESIGN_TOKEN:return`$${n.join(".")}`;case he.STYLE_REF:return`styleRef:${n[0]}`;case he.GEOMETRY_REF:return`geometryRef:${n[0]}`;case he.TRANSFORM_REF:return`transformRef:${n[0]}`;case he.LAYOUT_REF:return`layoutRef:${n[0]}`;default:return n.join(":")}}static flattenNestedReferences(e){const n=[],r=(s,o=[])=>{if(typeof s=="string")n.push(`${o.join(".")}=${s}`);else if(Array.isArray(s))s.forEach((i,a)=>{r(i,[...o,`[${a}]`])});else if(s&&typeof s=="object")for(const[i,a]of Object.entries(s))r(a,[...o,i])};return r(e),n}}class jf{marks=new Map;stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0};memoryStart=0;constructor(){this.startMemoryTracking()}markStart(e){this.marks.set(e,{name:e,startTime:performance.now()})}markEnd(e){const n=this.marks.get(e);if(!n){console.warn(`性能标记未找到: ${e}`);return}const r=performance.now(),s=r-n.startTime;n.endTime=r,n.duration=s,this.updateStats(e,s)}updateStats(e,n){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=n;break;case"transformation":this.stats.transformationTime=n;break;case"validation":this.stats.validationTime=n;break;case"total":this.stats.totalTime=n;break}}startMemoryTracking(){typeof performance<"u"&&performance.memory&&(this.memoryStart=performance.memory.usedJSHeapSize)}endMemoryTracking(){if(typeof performance<"u"&&performance.memory){const e=performance.memory.usedJSHeapSize;this.stats.memoryUsage=e-this.memoryStart}}setReferenceCount(e){this.stats.referenceCount=e}getStats(){return this.endMemoryTracking(),{...this.stats}}getMarks(){return Array.from(this.marks.values())}checkPerformance(){const e=[];return this.stats.transformationTime>rn.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${rn.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>rn.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${rn.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>rn.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${rn.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>rn.MAX_REFERENCE_DEPTH*10&&e.push(`引用数量较多: ${this.stats.referenceCount} (可能影响性能)`),{passed:e.length===0,warnings:e}}reset(){this.marks.clear(),this.stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0},this.startMemoryTracking()}}class hS{static deepMerge(e,n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return Array.isArray(e)?e.map((s,o)=>o<n.length?this.deepMerge(s,n[o]):s):[...n];const r={...e};for(const[s,o]of Object.entries(n))o!==void 0&&(s in r&&typeof r[s]=="object"&&typeof o=="object"?r[s]=this.deepMerge(r[s],o):r[s]=o);return r}static deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n||typeof e!="object"||e===null||n===null||Array.isArray(e)!==Array.isArray(n))return!1;if(Array.isArray(e))return e.length!==n.length?!1:e.every((o,i)=>this.deepEqual(o,n[i]));const r=Object.keys(e),s=Object.keys(n);return r.length!==s.length?!1:r.every(o=>o in n?this.deepEqual(e[o],n[o]):!1)}static safeGet(e,n,r=void 0){const s=Array.isArray(n)?n:n.split(".");let o=e;for(const i of s){if(o==null||typeof o!="object")return r;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(o)){const l=parseInt(a[1],10);o=o[l]}else o=o[i]}return o!==void 0?o:r}static safeSet(e,n,r){const s=Array.isArray(n)?n:n.split("."),o=Array.isArray(e)?[...e]:{...e};let i=o;for(let c=0;c<s.length-1;c++){const d=s[c],f=d.match(/^\[(\d+)\]$/);if(f&&Array.isArray(i)){const g=parseInt(f[1],10);i[g]===void 0&&(i[g]={}),i=i[g]}else{if(i[d]===void 0){const h=s[c+1].match(/^\[(\d+)\]$/);i[d]=h?[]:{}}i=i[d]}}const a=s[s.length-1],l=a.match(/^\[(\d+)\]$/);if(l&&Array.isArray(i)){const c=parseInt(l[1],10);i[c]=r}else i[a]=r;return o}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,n){let r=0;return(...s)=>{const o=Date.now();o-r>=n&&(r=o,e(...s))}}static debounce(e,n){let r;return(...s)=>{clearTimeout(r),r=setTimeout(()=>e(...s),n)}}static formatBytes(e,n=2){if(e===0)return"0 Bytes";const r=1024,s=n<0?0:n,o=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,i)).toFixed(s))+" "+o[i]}static estimateObjectSize(e){const n=new Set,r=s=>n.has(s)?0:typeof s=="string"?s.length*2:typeof s=="number"?8:typeof s=="boolean"?4:s==null?0:Array.isArray(s)?(n.add(s),s.reduce((o,i)=>o+r(i),0)):typeof s=="object"?(n.add(s),Object.values(s).reduce((o,i)=>o+r(i),0)):0;return r(e)}}class gS{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...q_,...e},this.referenceContext=kf(),this.resolverRegistry=Tf(),this.transformerRegistry=Mf(),this.performanceMonitor=new jf}adapt(e){console.error("🔧 SyncAdapter.adapt called with inputData:",{math_prob_id:e?.math_prob_id,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{this.performanceMonitor.markStart("validation");const n=this.validateInput(e);if(!n.isValid&&this.config.strictMode)throw new Ee(re.INVALID_INPUT,yc[re.INVALID_INPUT],{errors:n.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const r=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let s=r;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),s=this.resolveReferences(r),this.performanceMonitor.markEnd("reference-resolution")),this.performanceMonitor.markStart("scene-transformation"),!this.referenceContext.basicInfo&&s.basicInfo&&(this.referenceContext.basicInfo=s.basicInfo);const o=this.transformScenes(s);this.performanceMonitor.markEnd("scene-transformation"),this.performanceMonitor.markStart("output-validation");const i=this.validateOutput(o);if(!i.isValid&&this.config.strictMode)throw new Ee(re.OUTPUT_VALIDATION_FAILED,yc[re.OUTPUT_VALIDATION_FAILED],{errors:i.errors});this.performanceMonitor.markEnd("output-validation"),this.performanceMonitor.markEnd("total"),console.error("🔧 adapt: transformedData before buildResult:",o),console.error("🔧 adapt: transformedData.basicInfo:",o.basicInfo),console.error("🔧 adapt: transformedData.basicInfo?.answerUnit:",o.basicInfo?.answerUnit);const a=this.buildResult(o,{inputValidation:n,outputValidation:i,inputWarnings:n.warnings,outputWarnings:i.warnings},e);return console.error("🔧 adapt: result.data.basicInfo:",a.data.basicInfo),console.error("🔧 adapt: result.data.basicInfo?.answerUnit:",a.data.basicInfo?.answerUnit),a}catch(n){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw n;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",n),this.createFallbackResult(e,n);throw n}}validateInput(e){return yn.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(console.error("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([n,r])=>{if(r&&typeof r=="object"){console.error(` 🔍 Processing geometry shape ${n}:`,{id:r.id,type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),shapeKeys:Object.keys(r)});const s=this.convertGeometryShapeCoordinates(r);console.error(` 📍 ${n}:`,{type:r.type,position:r.position,vertices:r.vertices}),this.referenceContext.geometryPresets[n]=s}}),console.error("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):console.error("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&Object.entries(e.transform_definitions).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertTransformDefinitionCoordinates(r);this.referenceContext.transformDefinitions[n]=s}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(n=>{n&&n.content&&Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="graph"&&r.shapes&&this.extractPointCoordinatesFromShapes(r.shapes)})})}extractGeometryTransformConfigsFromInput(e){if(!e){console.error("⚠️ extractGeometryTransformConfigsFromInput: inputData is null or undefined");return}this.referenceContext.geometryTransformConfigs||(this.referenceContext.geometryTransformConfigs={}),e.geometry_transform_configs&&typeof e.geometry_transform_configs=="object"?(console.error("📦 Extracting geometry_transform_configs:",Object.keys(e.geometry_transform_configs)),Object.entries(e.geometry_transform_configs).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing geometry transform config ${n}:`,{id:r.id,strategy:r.strategy,hasBase:"base"in r,hasHeight:"height"in r,hasShapes:"shapes"in r,hasTransform:"transform"in r}),this.referenceContext.geometryTransformConfigs[n]=r)}),console.error("✅ geometryTransformConfigs after extraction:",Object.keys(this.referenceContext.geometryTransformConfigs))):console.error("⚠️ No geometry_transform_configs found in input data")}extractAnimationConfigsFromInput(e){if(!e){console.error("⚠️ extractAnimationConfigsFromInput: inputData is null or undefined");return}this.referenceContext.animationConfigs||(this.referenceContext.animationConfigs={}),e.animation_configs&&typeof e.animation_configs=="object"?(console.error("📦 Extracting animation_configs:",Object.keys(e.animation_configs)),Object.entries(e.animation_configs).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing animation config ${n}:`,{id:r.id,description:r.description,hasTransforms:"transforms"in r,hasVisualEffects:"visualEffects"in r}),this.referenceContext.animationConfigs[n]=r)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}extractOptionGroupsFromInput(e){if(!e){console.error("⚠️ extractOptionGroupsFromInput: inputData is null or undefined");return}this.referenceContext.optionGroups||(this.referenceContext.optionGroups={}),e.option_groups&&typeof e.option_groups=="object"?(console.error("📦 Extracting option_groups:",Object.keys(e.option_groups)),Object.entries(e.option_groups).forEach(([n,r])=>{r&&typeof r=="object"&&(console.error(` 🔍 Processing option group ${n}:`,{id:r.id,type:r.type,answerType:r.answerType,optionsCount:r.options?.length||0}),this.referenceContext.optionGroups[n]=r)}),console.error("✅ optionGroups after extraction:",Object.keys(this.referenceContext.optionGroups))):console.error("⚠️ No option_groups found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;if(console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0}),e.type==="hundredGrid")return console.error(`✅ hundredGrid类型跳过坐标转换: ${e.id}`),e;const n={...e};n.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line"),Array.isArray(n.position)&&n.position.length>=2&&(n.position={x:n.position[0],y:n.position[1]}),Array.isArray(n.vertices)&&(n.vertices=n.vertices.map(r=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:r)),Array.isArray(n.endpoints)?(console.error(`🔄 Processing endpoints for shape ${n.id||"unknown"}:`,{endpointsLength:n.endpoints.length,firstEndpoint:n.endpoints[0],firstEndpointType:typeof n.endpoints[0],firstEndpointIsArray:Array.isArray(n.endpoints[0])}),n.endpoints=n.endpoints.map((r,s)=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:(console.error(` Endpoint ${s} is not array:`,r),r)),n.type==="segment"&&Array.isArray(n.endpoints)&&n.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line",n.start=n.endpoints[0],n.end=n.endpoints[1],delete n.endpoints)):"endpoints"in n&&console.error(`⚠️ Shape ${n.id||"unknown"} has endpoints but not array:`,{endpoints:n.endpoints,endpointsType:typeof n.endpoints});for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?n[r]=s:n[r]=this.convertGeometryShapeCoordinates(s));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),endpointsLength:n.endpoints?n.endpoints.length:0,keys:Object.keys(n)}),n}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const n={...e};if(n.config&&n.config.center){const r=n.config.center;r&&typeof r=="object"&&"x"in r&&"y"in r&&(n.config.center=[r.x,r.y])}for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(n[r]=this.convertTransformDefinitionCoordinates(s));return n}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(n=>{if(n&&n.type==="point"&&n.position&&Array.isArray(n.position)&&n.position.length>=2){const r=n.id||`point_${n.position[0]}_${n.position[1]}`;this.referenceContext.geometryPresets[r]={type:"point",position:{x:n.position[0],y:n.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e),this.extractOptionGroupsFromInput(e);const n={id:e.math_prob_id||hS.generateId("triangle"),title:e.title,grade:this.parseGrade(e.grade_id),unit:e.unit_name,lesson:e.lesson_name,skill:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points||[],difficulty:e.difficulty||1,metadata:this.transformMetadata(e),description:e.description,scenes:this.transformScenesStructure(e.scenes),answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info)};["unit_id","lesson_id","module_id","skill_item_id","skill_id","created_at","updated_at","layout"].forEach(o=>{e[o]!==void 0&&(n[o]=e[o])}),console.error("🔧 transformBaseData: inputData.basic_info =",e.basic_info);const s=this.transformBasicInfo(e.basic_info);return console.error("🔧 transformBaseData: basicInfo after transform =",s),console.error("🔧 transformBaseData: basicInfo.answerUnit =",s?.answerUnit),this.referenceContext.basicInfo=s,n.basicInfo=s,console.error("🔧 transformBaseData: transformed.basicInfo set =",n.basicInfo),n.explanation=this.transformExplanation(e.explanation),n}parseGrade(e){const n=e.match(/g(\d+)/);return n?parseInt(n[1],10):5}transformMetadata(e){return e.metadata&&typeof e.metadata=="object"?e.metadata:{topic:e.unit_name||"三角形面积计算",skill:e.skill_description||"三角形面积求解技能",tags:e.knowledge_points||["三角形面积公式"]}}transformBasicInfo(e){if(console.error("🔄 transformBasicInfo called with:",e),!e||typeof e!="object")return console.error("⚠️ transformBasicInfo: basicInfo is empty, returning default"),{question:""};const n={...e};return console.error("🔄 transformBasicInfo: transformed copy:",n),n.question===void 0&&n.content!==void 0&&(n.question=n.content),n.question===void 0&&(n.question=""),console.error("🔄 transformBasicInfo: returning:",n),n}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const n={};return["question","solve","review"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];n[o]={...i,items:a},i.content!==void 0&&delete n[o].content}else n[o]={items:[]}}),["remember","explanation","success"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];n[o]={...i,items:a},i.content!==void 0&&delete n[o].content}}),n}transformExplanation(e){if(console.error("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&e.steps&&Array.isArray(e.steps),stepsCount:e&&e.steps?e.steps.length:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){console.error(`🔄 transformExplanation: processing ${e.steps.length} steps`);const n=e.steps.map((r,s)=>(console.error(` Step ${s}: hasChartConfig=${!!r.chartConfig}`),this.transformExplanationStep(r)));return{...e,steps:n}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const n=e.chartConfig,r=n.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${r}`),console.error(" chartConfig keys:",Object.keys(n)),r!=="graph"&&r!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${r},跳过转换`),e;try{const s={type:r,...n};console.error(" contentBlock keys:",Object.keys(s)),r==="graph"&&s.shapes&&(console.error(" shapes count:",s.shapes.length),s.shapes.length>0&&console.error(" first shape:",s.shapes[0])),console.error("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.error("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]);const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});console.error(" transformedBlock keys:",Object.keys(o)),r==="graph"&&o.shapes&&console.error(" transformed shapes count:",o.shapes.length);let i;if(r==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,console.error(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.error(` geometryTransform preserved: step.title=${e.title}`),console.error(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.error(" geometryTransform preserved: config=",i.metadata?.config);else if(r==="graph"&&o.boardConfig){const{boardConfig:a,...l}=o;i={...l,...a},console.error(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}resolveReferences(e){const n=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(n.length),this.resolverRegistry.batchResolve(n,this.referenceContext),mi.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:r=>(console.warn(`引用未找到: ${r}`),r)})}transformScenes(e){const n={...e};return n.scenes&&typeof n.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),n.scenes=this.transformerRegistry.transformScenes(n.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),n}validateOutput(e){return yn.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,n,r){const s=this.performanceMonitor.getStats(),o=this.performanceMonitor.checkPerformance(),i=[...n.inputValidation.warnings.map(d=>({code:re.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...n.outputValidation.warnings.map(d=>({code:re.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...o.warnings.map(d=>({code:re.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=r||e,l=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],c=mi.calculateReferenceStats(l,this.referenceContext);return{data:e,warnings:i,performance:s,referenceStats:{total:c.total,resolved:c.resolved,failed:c.failed,byType:c.byType}}}createFallbackResult(e,n){const r={...xs,id:e?.math_prob_id||xs.id,title:e?.title||xs.title},s={code:re.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${n.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:r,warnings:[s],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class Or{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...W_,...e},this.referenceContext=kf(),this.resolverRegistry=Tf(),this.transformerRegistry=Mf(),this.performanceMonitor=new jf,this.syncAdapter=new gS(e)}adapt(e){this.config.enableLogging&&console.log("🔧 GeometryAdapter.adapt called with inputData (delegating to SyncAdapterCore):",{math_prob_id:e?.math_prob_id,schema_version:e?.schema_version,shape:e?.basic_info?.shape,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{const n=e,r=this.syncAdapter.adapt(n);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:r.data.id,hasBasicInfo:!!r.data.basicInfo,warningCount:r.warnings.length,referenceStats:r.referenceStats}),r}catch(n){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw n;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",n),this.createFallbackResult(e,n);throw n}}_validateInput(e){return yn.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){this.config.enableLogging&&console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(this.config.enableLogging&&console.log("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertGeometryShapeCoordinates(r);this.referenceContext.geometryPresets[n]=s}}),this.config.enableLogging&&console.log("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):this.config.enableLogging&&console.log("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&(this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),Object.entries(e.transform_definitions).forEach(([n,r])=>{if(r&&typeof r=="object"){const s=this.convertTransformDefinitionCoordinates(r);this.referenceContext.transformDefinitions[n]=s}}))}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}transformExplanation(e){if(this.config.enableLogging&&console.log("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&!Array.isArray(e)&&e.steps&&Array.isArray(e.steps),stepsCount:e?Array.isArray(e)?e.length:e.steps?e.steps.length:0:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){this.config.enableLogging&&console.log(`🔄 transformExplanation: processing ${e.steps.length} steps`);const n=e.steps.map((r,s)=>(this.config.enableLogging&&console.log(` Step ${s}: hasChartConfig=${!!r.chartConfig}`),this.transformExplanationStep(r)));return{...e,steps:n}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const n=e.chartConfig,r=n.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${r}`),console.log(" chartConfig keys:",Object.keys(n))),r!=="graph"&&r!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${r},跳过转换`),e;try{const s={...n,type:r};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(s)),r==="graph"&&s.shapes&&(console.log(" shapes count:",s.shapes.length),s.shapes.length>0&&console.log(" first shape:",s.shapes[0]))),this.config.enableLogging&&(console.log("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.log("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]));const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});this.config.enableLogging&&(console.log(" transformedBlock keys:",Object.keys(o)),r==="graph"&&o.shapes&&console.log(" transformed shapes count:",o.shapes.length));let i;if(r==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,this.config.enableLogging&&(console.log(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.log(` geometryTransform preserved: step.title=${e.title}`),console.log(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.log(" geometryTransform preserved: config=",i.metadata?.config));else if(r==="graph"&&o.boardConfig){const{boardConfig:a,...l}=o;i={...l,...a},this.config.enableLogging&&console.log(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(this.config.enableLogging&&console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;this.config.enableLogging&&console.log("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const n={...e};n.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line"),Array.isArray(n.position)&&n.position.length>=2&&(n.position={x:n.position[0],y:n.position[1]}),Array.isArray(n.vertices)&&(n.vertices=n.vertices.map(r=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:r)),Array.isArray(n.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${n.id||"unknown"}:`,{endpointsLength:n.endpoints.length,firstEndpoint:n.endpoints[0],firstEndpointType:typeof n.endpoints[0],firstEndpointIsArray:Array.isArray(n.endpoints[0])}),n.endpoints=n.endpoints.map((r,s)=>Array.isArray(r)&&r.length>=2?{x:r[0],y:r[1]}:(this.config.enableLogging&&console.log(` Endpoint ${s} is not array:`,r),r)),n.type==="line"&&Array.isArray(n.endpoints)&&n.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${n.id||"unknown"}`),n.type="line",n.start=n.endpoints[0],n.end=n.endpoints[1],delete n.endpoints)):"endpoints"in n&&this.config.enableLogging&&console.log(`⚠️ Shape ${n.id||"unknown"} has endpoints but not array:`,{endpoints:n.endpoints,endpointsType:typeof n.endpoints});for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?n[r]=s:n[r]=this.convertGeometryShapeCoordinates(s));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),endpointsLength:n.endpoints?n.endpoints.length:0,keys:Object.keys(n)}),n}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const n={...e};if(n.config&&n.config.center){const r=n.config.center;r&&typeof r=="object"&&"x"in r&&"y"in r&&(n.config.center=[r.x,r.y])}for(const[r,s]of Object.entries(n))Array.isArray(s)?n[r]=s.map(o=>typeof o=="object"&&o!==null?"id"in o&&"type"in o&&"config"in o?this.convertTransformDefinitionCoordinates(o):this.deepClone(o):o):s&&typeof s=="object"&&("id"in s&&"type"in s&&"config"in s?n[r]=this.convertTransformDefinitionCoordinates(s):n[r]=this.deepClone(s));return n}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.deepClone(r));const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=this.deepClone(e[r]));return n}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const n={id:e.math_prob_id,title:e.title,grade:parseInt(e.grade_id.replace("g",""))||5,unit:e.unit_name,lesson:e.lesson_name,skillDescription:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points,difficulty:e.difficulty,description:e.description,metadata:e.metadata,basicInfo:{question:e.basic_info.question,answerUnit:e.basic_info.answerUnit||e.basic_info.areaUnit,shape:e.basic_info.shape,base:e.basic_info.base,height:e.basic_info.height,baseUnit:e.basic_info.baseUnit,heightUnit:e.basic_info.heightUnit,topBase:e.basic_info.topBase,topBaseUnit:e.basic_info.topBaseUnit,length:e.basic_info.length,width:e.basic_info.width,lengthUnit:e.basic_info.lengthUnit,widthUnit:e.basic_info.widthUnit,side:e.basic_info.side,sideUnit:e.basic_info.sideUnit,variables:e.basic_info.variables,score:e.basic_info.score,context:e.basic_info.context},rawGeometryShapes:e.geometry_shapes,rawTransformDefinitions:e.transform_definitions,rawGeometryTransformConfigs:e.geometry_transform_configs,rawAnimationConfigs:e.animation_configs,rawScenes:e.scenes,rawExplanation:e.explanation,rawAnswerInfo:e.answer_info,answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info),explanation:this.transformExplanation(e.explanation),unitId:e.unit_id,lessonId:e.lesson_id,moduleId:e.module_id,skillItemId:e.skill_item_id,skillId:e.skill_id,createdAt:e.created_at,updatedAt:e.updated_at,layout:e.layout};return this.referenceContext.basicInfo=n.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),n}_resolveReferences(e){const n=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(n.length),this.resolverRegistry.batchResolve(n,this.referenceContext),mi.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:r=>(this.config.enableLogging&&console.warn(`引用未找到: ${r}`),r)})}_transformScenes(e){const n={...e};return n.scenes&&typeof n.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),n.scenes=this.transformerRegistry.transformScenes(n.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),n}_validateOutput(e){return yn.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,n,r){const s=this.performanceMonitor.getStats(),o=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(n.inputWarnings||[]).map(a=>({code:It.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(n.outputWarnings||[]).map(a=>({code:It.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?s:void 0,referenceStats:o}}createFallbackResult(e,n){return{data:{...xs,id:e?.math_prob_id||"geometry-fallback",title:e?.title||"几何问题(回退)",basicInfo:{question:e?.basic_info?.question||"计算下面几何图形的面积:",answerUnit:e?.basic_info?.answerUnit||"cm²",shape:e?.basic_info?.shape||"triangle",base:e?.basic_info?.base||6,height:e?.basic_info?.height||4,baseUnit:e?.basic_info?.baseUnit||"cm",heightUnit:e?.basic_info?.heightUnit||"cm"}},warnings:[{code:It.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${n instanceof Error?n.message:n}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new Or(e)}}function _n(t,e){return new Or(e).adapt(t)}async function ca(t,e){return Promise.resolve(_n(t,e))}function $f(t,e){const n=typeof t=="function"?t():t;return _n(n,e)}async function Of(t,e){const n=typeof t=="function"?await t():t instanceof Promise?await t:t;return _n(n,e)}function If(t){return new Or(t)}function Pf(t){const e=new Or(t);return{adapt:n=>Promise.resolve(e.adapt(n))}}function mS(t,e="input"){return e==="input"?yn.validateInput(t):yn.validateOutput(t)}function pS(t,e,n=100){const r=[];for(let l=0;l<n;l++){const c=performance.now();t.adapt(e);const d=performance.now();r.push(d-c)}const s=r.reduce((l,c)=>l+c,0)/n,o=Math.min(...r),i=Math.max(...r),a=process.memoryUsage?.().heapUsed||0;return{averageTime:s,minTime:o,maxTime:i,memoryUsage:a}}const yS={adapt:(t,e)=>_n(t,e),adaptAsync:(t,e)=>ca(t,e),create:t=>If(t)},bS="4.0.0",Ff="4.0.0";function xS(t="4.0.0"){return Ff>=t}function Df(t){return t?.schema_version==="4.0.0"||t?.schema_version?.startsWith("4.")}function vS(t){return Df(t)&&(t.geometry_shapes||t.transform_definitions||t.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(t.basic_info.shape))}class Lo extends Error{constructor(e,n,r,s){super(`Failed to generate config for ${n}: ${e}`),this.shapeType=n,this.options=r,this.innerError=s,this.name="ConfigGenerationError"}}function wS(t){const e=[],n=[];if(t.shapes||e.push(J("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),t.transform||e.push(J("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),t.strategy||e.push(J("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:xc(e),timestamp:new Date().toISOString()};t.shapes&&e.push(..._S(t.shapes));let r=!1;if(t.shapes?.animated){for(const s of t.shapes.animated)if(s.transform){r=!0;break}}return t.transform?e.push(...SS(t.transform)):r||e.push(J("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...CS(t)),e.push(...RS(t)),e.push(...AS(t)),e.length>0&&n.push(...xc(e)),{isValid:e.length===0,errors:e,fixes:n,timestamp:new Date().toISOString()}}function Lf(t){if(!t||typeof t!="object"||!t.type||typeof t.type!="string"||!["rotation","translation","scale","composite"].includes(t.type))return!1;switch(t.type){case"rotation":if(!t.config||typeof t.config!="object")return!1;const n=t.config.center;if(n!=="auto"&&(!Array.isArray(n)||n.length!==2)||typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number"||t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical")return!1;break;case"translation":if(!t.config||typeof t.config!="object")return!1;const r=t.config.direction;if(Array.isArray(r)){if(r.length!==2||typeof r[0]!="number"||typeof r[1]!="number")return!1}else if(typeof r=="string"){if(r!=="horizontal"&&r!=="vertical")return!1}else return!1;if(typeof t.config.distance!="number"||t.config.distance<=0)return!1;break;case"scale":if(!t.config||typeof t.config!="object")return!1;const s=t.config.center;if(s!=="centroid"&&(!Array.isArray(s)||s.length!==2)||typeof t.config.startScale!="number"||typeof t.config.endScale!="number"||typeof t.config.uniform!="boolean")return!1;break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))return!1;for(const o of t.transforms)if(!Lf(o))return!1;if(t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel")return!1;break}return!0}function zf(t,e){const n=[];if(!t||typeof t!="object")return n.push(J("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,t,{type:"rotation"})),n;(!t.type||typeof t.type!="string")&&n.push(J("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,t.type,"rotation"));const r=["rotation","translation","scale","composite"];switch(t.type&&!r.includes(t.type)&&n.push(J("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${t.type}`,`${e}.type`,t.type,"rotation")),t.type){case"rotation":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,t.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const s=t.config.center;s!=="auto"&&(!Array.isArray(s)||s.length!==2)&&n.push(J("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,t.config.center,[0,0])),(typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,t.config,{startAngle:0,endAngle:Math.PI})),t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical"&&n.push(J("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,t.config.direction,"clockwise"))}break;case"translation":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,t.config,{direction:"horizontal",distance:1}));else{const s=t.config.direction;Array.isArray(s)?s.length!==2?n.push(J("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,s,[1,0])):(typeof s[0]!="number"||typeof s[1]!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,s,[1,0])):typeof s=="string"?s!=="horizontal"&&s!=="vertical"&&n.push(J("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,s,"horizontal")):n.push(J("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,s,"horizontal")),(typeof t.config.distance!="number"||t.config.distance<=0)&&n.push(J("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,t.config.distance,1))}break;case"scale":if(!t.config||typeof t.config!="object")n.push(J("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,t.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const s=t.config.center;s!=="centroid"&&(!Array.isArray(s)||s.length!==2)&&n.push(J("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,t.config.center,"centroid")),(typeof t.config.startScale!="number"||typeof t.config.endScale!="number")&&n.push(J("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,t.config,{startScale:1,endScale:2})),typeof t.config.uniform!="boolean"&&n.push(J("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,t.config.uniform,!0))}break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))n.push(J("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,t.transforms,[]));else for(let s=0;s<t.transforms.length;s++){const o=zf(t.transforms[s],`${e}.transforms[${s}]`);n.push(...o)}t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel"&&n.push(J("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,t.executionMode,"sequential"));break}return n}function J(t,e,n,r,s){let o=s;if(s===void 0)switch(t){case"INVALID_TRIANGLE_TYPE":o="right_triangle";break;case"INVALID_BASE_VALUE":case"INVALID_HEIGHT_VALUE":o=1;break;case"INVALID_ORIGIN":o=0;break;case"MISSING_SHAPES":o={static:[],animated:[]};break;case"MISSING_TRANSFORM":o={type:"rotation"};break;case"STRATEGY_MISMATCH":o="single_rotation";break;case"UNIT_MISMATCH":o="in";break;default:o=void 0}return{code:t,message:e,path:n,value:r,suggestedValue:o}}function _S(t){const e=[];if(!t||typeof t!="object")return e.push(J("MISSING_SHAPES","形状定义无效或缺失","$.shapes",t)),e;if(!Array.isArray(t.static))e.push(J("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",t.static));else for(let n=0;n<t.static.length;n++){const r=t.static[n],s=bc(r,`$.shapes.static[${n}]`);e.push(...s)}if(!Array.isArray(t.animated))e.push(J("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",t.animated));else for(let n=0;n<t.animated.length;n++){const r=t.animated[n],s=bc(r,`$.shapes.animated[${n}]`);e.push(...s)}return e}function bc(t,e){const n=[];if(!t||typeof t!="object")return n.push(J("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,t)),n;if((!t.type||typeof t.type!="string")&&n.push(J("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,t.type)),!Array.isArray(t.vertices))n.push(J("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,t.vertices));else if(t.vertices.length===0)n.push(J("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,t.vertices));else for(let r=0;r<t.vertices.length;r++){const s=t.vertices[r];!Array.isArray(s)||s.length!==2?n.push(J("INVALID_SHAPE_VERTICES",`顶点 ${r} 必须是包含两个数字的数组`,`${e}.vertices[${r}]`,s)):(typeof s[0]!="number"||typeof s[1]!="number")&&n.push(J("INVALID_SHAPE_VERTICES",`顶点 ${r} 必须包含数字`,`${e}.vertices[${r}]`,s))}if(t.transform!==void 0){const r=zf(t.transform,`${e}.transform`);n.push(...r)}return n}function SS(t){const e=[];if(!t)return e.push(J("MISSING_TRANSFORM","变换配置缺失","$.transform",t)),e;const n=Array.isArray(t),r=n?t:[t],s="$.transform";for(let o=0;o<r.length;o++){const i=r[o],a=n?`${s}[${o}]`:s;Lf(i)||e.push(J("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function CS(t){const e=[];if(!t.strategy)return e;const{strategy:n}=t;let r=0;if(t.transform&&(Array.isArray(t.transform)?r+=t.transform.length:typeof t.transform=="object"&&(t.transform&&typeof t.transform=="object"&&"transforms"in t.transform?r+=t.transform.transforms.length:r+=1)),t.shapes?.animated)for(const o of t.shapes.animated)o.transform&&(r+=1);return n.includes("single")&&r!==1&&e.push(J("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${r} 个`,"$.strategy",n,r===0?"single_rotation":"double_rotation")),n.includes("double")&&r!==2&&e.push(J("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${r} 个`,"$.strategy",n,r===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(n)||e.push(J("STRATEGY_MISMATCH",`无效的策略名称: ${n}`,"$.strategy",n,"single_rotation")),e}function RS(t){const e=[];if(t.unit&&typeof t.unit!="string"&&e.push(J("UNIT_MISMATCH","单位必须是字符串","$.unit",t.unit,"in")),t.baseUnit&&typeof t.baseUnit!="string"&&e.push(J("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",t.baseUnit,t.unit||"in")),t.heightUnit&&typeof t.heightUnit!="string"&&e.push(J("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",t.heightUnit,t.unit||"in")),t.unit&&t.baseUnit&&t.baseUnit!==t.unit&&e.push(J("UNIT_MISMATCH",`底边单位 (${t.baseUnit}) 与主单位 (${t.unit}) 不一致`,"$.baseUnit",t.baseUnit,t.unit)),t.unit&&t.heightUnit&&t.heightUnit!==t.unit&&e.push(J("UNIT_MISMATCH",`高度单位 (${t.heightUnit}) 与主单位 (${t.unit}) 不一致`,"$.heightUnit",t.heightUnit,t.unit)),t.unit&&t.boardConfig&&t.boardConfig.boundingBox){const[n,r,s,o]=t.boardConfig.boundingBox,i=s-n,a=r-o,l=t.unit==="cm"?50:20;(i>l*5||a>l*5)&&e.push(J("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${t.unit})不匹配`,"$.boardConfig.boundingBox",t.boardConfig.boundingBox,void 0))}return e}function AS(t){const e=[];if(t.shapes&&t.boardConfig&&t.boardConfig.boundingBox){const n=t.boardConfig.boundingBox,[r,s,o,i]=n,a=[...t.shapes.static||[],...t.shapes.animated||[]];for(let l=0;l<a.length;l++){const c=a[l];if(c&&c.vertices)for(let d=0;d<c.vertices.length;d++){const f=c.vertices[d];if(Array.isArray(f)&&f.length===2){const[g,h]=f;(g<r||g>o||h<i||h>s)&&e.push(J("GEOMETRY_INCONSISTENCY",`形状 ${l} 的顶点 ${d} (${g}, ${h}) 超出画板边界`,`$.shapes.${l<(t.shapes.static?.length||0)?"static":"animated"}[${l}].vertices[${d}]`,f,[Math.max(r,Math.min(g,o)),Math.max(i,Math.min(h,s))]))}}}}if(t.metadata&&t.metadata.base&&t.metadata.height){const n=.5*t.metadata.base*t.metadata.height;if(t.shapes?.static?.[0]?.vertices){const r=t.shapes.static[0].vertices;if(r.length===3){const[s,o]=r[0],[i,a]=r[1],[l,c]=r[2],d=.5*Math.abs((i-s)*(c-o)-(l-s)*(a-o));Math.abs(d-n)>.01&&e.push(J("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${n.toFixed(2)}) 不一致`,"$.metadata",{base:t.metadata.base,height:t.metadata.height,calculatedArea:d,expectedArea:n}))}}}return e}function xc(t){const e=[];for(const n of t)switch(n.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:n.path,value:n.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${n.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:n.path,value:n.suggestedValue||1,description:`将底边长度修复为: ${n.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:n.path,value:n.suggestedValue||1,description:`将高度修复为: ${n.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:n.path,value:n.suggestedValue||0,description:`将原点坐标修复为: ${n.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:n.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:n.suggestedValue!==void 0&&e.push({action:"replace",path:n.path,value:n.suggestedValue,description:`修复 ${n.code} 错误`,isSafe:!1})}return e}function vc(t){if(!NS(t))throw new Lo("Invalid parallelogram config options","parallelogram",t);const{base:e,height:n,unit:r="in",layoutDensity:s="compact",theme:o="light"}=t,i=t.originX??0,a=t.originY??0,l=t.skew??e/3;try{const c=ES(e,n,l,i,a,o),d=kS(e),f=TS(s),g=MS(e,n,l,i,a);return{ui:{layoutDensity:s},base:e,height:n,unit:r,shapes:c,transform:d,animation:f,boardConfig:g,strategy:"cut_and_paste",theme:o,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:n,unit:r,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(c){if(c instanceof Lo)throw c;const d=c instanceof Error?c.message:String(c);throw new Lo(d,"parallelogram",t,c instanceof Error?c:void 0)}}function NS(t){if(!t||typeof t!="object")return!1;const e=["base","height"];for(const n of e)if(!(n in t))return!1;return!(typeof t.base!="number"||t.base<=0||typeof t.height!="number"||t.height<=0||t.skew!==void 0&&(typeof t.skew!="number"||t.skew<0)||t.originX!==void 0&&(typeof t.originX!="number"||!isFinite(t.originX))||t.originY!==void 0&&(typeof t.originY!="number"||!isFinite(t.originY)))}function ES(t,e,n,r,s,o){const a=o==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},l=[[r+n,s],[r+t,s],[r+t+n,s+e],[r+n,s+e]],c=[[r,s],[r+n,s],[r+n,s+e]];return{static:[{type:"trapezoid",vertices:l,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:c,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function kS(t){return{type:"translation",config:{direction:[1,0],distance:t}}}function TS(t){return{slider:{position:t==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function MS(t,e,n,r,s){const o=Math.min(r,r+n,r+t,r+t+n),i=Math.max(r,r+n,r+t,r+t+n),a=Math.min(s,s+e),l=Math.max(s,s+e),c=3;return{boundingBox:[o-c,l+c,i+c,a-c],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function jS(t){return{id:t.id||t.math_prob_id,title:t.title||"",grade:t.grade||5,unit:t.unit||t.unit_name||"",lesson:t.lesson||t.lesson_name||"",skill:t.skill||t.skill_description||"",objective:t.objective||"",knowledgePoints:Array.isArray(t.knowledge_points)?t.knowledge_points:Array.isArray(t.knowledgePoints)?t.knowledgePoints:[],difficulty:t.difficulty||1,description:t.description||"",metadata:t.metadata||{topic:"",skill:"",tags:[]},math_prob_id:t.math_prob_id,grade_id:t.grade_id,unit_id:t.unit_id,lesson_id:t.lesson_id,module_id:t.module_id,skill_item_id:t.skill_item_id,skill_id:t.skill_id,created_at:t.created_at,updated_at:t.updated_at,layout:t.layout||{type:"card",padding:"20px",theme:"light"}}}function $S(t){const e=t||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function OS(t,e,n){return{value:t,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:n}}function IS(t){return t?{value:t.value,unit:t.unit,explanation:t.explanation_text||t.explanation||"正确答案"}:null}function PS(t){return t.answer?t.answer:t.answer_info?IS(t.answer_info):null}function FS(){return{question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}},review:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}}]}}}function DS(){return{steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。"},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。"},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。"}],strategy:"visual_transformation",total_steps:3,estimated_time:120}}function LS(t){return Array.isArray(t)||t&&t.steps?t:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Vf(t){const e=jS(t),n=$S(t.basic_info||t.basicInfo),r=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"];return{...e,id:e.id||"parallelogram-area-001",title:e.title||"平行四边形面积公式推导",grade:e.grade||5,unit:e.unit||"多边形的面积",lesson:e.lesson||"平行四边形的面积",skill:e.skill||"已知平行四边形的底和高,求平行四边形面积",objective:e.objective||"理解平行四边形面积公式 A=bh",knowledgePoints:e.knowledgePoints?.length?e.knowledgePoints:r,difficulty:e.difficulty||1,description:e.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:e.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...n,question:n.question||"计算下面平行四边形的面积:",answerUnit:n.answerUnit||"平方英寸",shape:n.shape||"parallelogram",base:n.base||9,height:n.height||6,baseUnit:n.baseUnit||"in",heightUnit:n.heightUnit||"in",variables:n.variables||{b:9,h:6,unit:"in"},context:n.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:GS(t.scenes||FS(),"parallelogram",n),explanation:LS(t.explanation||DS()),answer:PS(t)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:t.answer_info||OS(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:t.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function zS(t){return t?.config&&typeof t.config=="object"}function VS(t){if(t.shapes?.static&&t.shapes?.animated)return console.log("🔍 JSON config already in system format"),t;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!t.transform,type:En(t.transform),distance:Ot(t.transform),direction:vs(t.transform)});try{const e={...t};if(t.shapes&&typeof t.shapes=="object"){const r=[],s=[];if(t.shapes.trapezoid){const o=t.shapes.trapezoid;Array.isArray(o)?r.push(...o.map(i=>({...i,metadata:{...i.metadata,isStatic:!0}}))):typeof o=="object"&&r.push({...o,metadata:{...o.metadata,isStatic:!0}})}if(t.shapes.triangle){const o=t.shapes.triangle;Array.isArray(o)?s.push(...o.map(i=>({...i,metadata:{...i.metadata,isMovable:!0}}))):typeof o=="object"&&s.push({...o,metadata:{...o.metadata,isMovable:!0}})}(r.length===0||s.length===0)&&Object.entries(t.shapes).forEach(([o,i])=>{const a=o.toLowerCase();a.includes("static")||a.includes("original")||a.includes("trapezoid")?Array.isArray(i)?r.push(...i):i&&typeof i=="object"&&r.push(i):(a.includes("animated")||a.includes("movable")||a.includes("triangle"))&&(Array.isArray(i)?s.push(...i):i&&typeof i=="object"&&s.push(i))}),e.shapes={static:r,animated:s}}!e.base&&t.base&&(e.base=t.base),!e.height&&t.height&&(e.height=t.height),!e.unit&&t.unit&&(e.unit=t.unit);const n=En(t.transform);return t.transform&&n==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:n,translation:t.transform.translation,distance:Ot(t.transform),direction:vs(t.transform)}),t.transform.translation&&(e.transform={type:"translation",translation:t.transform.translation},console.log("✅ Set converted.transform with distance:",Ot(t.transform)))):t.transform?console.log("⚠️ JSON has transform but not translation type:",En(t.transform)):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&t.boardConfig&&(e.boardConfig=t.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:En(e.transform),distance:Ot(e.transform),direction:vs(e.transform)}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),t}}function Ot(t){if(!t)return"N/A";const e=Array.isArray(t)?t[0]:t;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function vs(t){if(!t)return;const e=Array.isArray(t)?t[0]:t;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function En(t){return t&&(Array.isArray(t)?t[0]:t)?.type||"N/A"}function GS(t,e,n){if(t?.solve?.content){const r=t.solve.content.map(s=>{if(s.type==="geometryTransform"){if(zS(s))try{const i=VS(s.config),a=wS(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",Ot(i.transform)),console.log("📐 JSON base:",i.base,"height:",i.height),{...s,metadata:{...s.metadata,config:i,source:"json",validationResult:a}};console.warn("❌ JSON-provided parallelogram config validation failed:",a.errors),console.log("📊 JSON config structure:",{hasShapes:!!i.shapes,hasTransform:!!i.transform,transformType:En(i.transform),distance:Ot(i.transform),strategy:i.strategy,theme:i.theme})}catch(i){console.warn("Failed to process JSON-provided parallelogram config:",i)}let o;try{const i=n?.base||9,a=n?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),o=vc({base:i,height:a,unit:n?.baseUnit||n?.unit||"in",originX:n?.originX,originY:n?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",Ot(o.transform))}catch(i){console.warn("Failed to generate dynamic parallelogram config:",i),console.log("🔄 Using fallback dynamic config with base: 9, height: 6"),o=vc({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",Ot(o.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:En(o.transform),direction:vs(o.transform),distance:Ot(o.transform)}),{...s,metadata:{...s.metadata,config:o,source:"generated"}}}return s});return{...t,solve:{...t.solve,content:r}}}return t}const US="4.0.0",BS="1.0.0",HS="mp-10506-0002-0002-G01-0001",WS="锐角三角形面积练习",qS="通过双旋转策略练习锐角三角形面积公式 A=½bh",YS="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",KS=1,XS="g5",JS="三角形面积计算",ZS=1050602,QS="锐角三角形的面积",eC=105060201,tC=1002,nC="已知锐角三角形的底和高,求三角形面积",rC="s-105-06-0002",sC=1002,oC=2,iC=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],aC={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},lC={question:"以下三角形面积是多少?",answerUnit:"cm²",shape:"acute_triangle",base:6,height:4,baseUnit:"cm",heightUnit:"cm",originX:2,originY:2,unit:"cm²",variables:{b:6,h:4,answer:12}},cC={acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_b"},{$ref:"point_c"}],withLabel:!0,label:{offset:[-15,-15],fontSize:16,color:"#000000",anchorX:"middle",anchorY:"bottom"}},left_triangle:{id:"left_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_d"},{$ref:"point_c"}]},right_triangle:{id:"right_triangle",type:"polygon",vertices:[{$ref:"point_b"},{$ref:"point_d"},{$ref:"point_c"}]},base_segment:{id:"base_segment",type:"segment",endpoints:[{$ref:"point_a"},{$ref:"point_b"}]},height_segment:{id:"height_segment",type:"segment",endpoints:[{$ref:"point_d"},{$ref:"point_c"}]},left_rotation_center:{id:"left_rotation_center",type:"point",position:{x:3.5,y:4}},right_rotation_center:{id:"right_rotation_center",type:"point",position:{x:6.5,y:4}},full_rectangle:{id:"full_rectangle",type:"polygon",vertices:[{x:2,y:2},{x:8,y:2},{x:8,y:6},{x:2,y:6}]},base_arrow:{id:"base_arrow",type:"segment",endpoints:[{x:2,y:1.5},{x:8,y:1.5}]},height_arrow:{id:"height_arrow",type:"segment",endpoints:[{x:5,y:2},{x:5,y:6}]},base_label_position:{id:"base_label_position",type:"point",position:{x:5,y:1.2}},height_label_position:{id:"height_label_position",type:"point",position:{x:5.5,y:4}},point_a:{id:"point_a",type:"point",position:{x:2,y:2},name:"A"},point_b:{id:"point_b",type:"point",position:{x:8,y:2},name:"B"},point_c:{id:"point_c",type:"point",position:{x:5,y:6},name:"C"},point_d:{id:"point_d",type:"point",position:{x:5,y:2},name:"D"}},dC={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},uC={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"以下三角形面积是多少?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},fC={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别锐角三角形的底和高",description:"确定锐角三角形的底边长度 b = 6 cm 和对应的高度 h = 4 cm。垂足将底边平分为两段。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base-label",type:"text",position:{x:5,y:1.4},content:"6 cm",styleRef:"label_error"},{id:"height-label",type:"text",position:{x:5.3,y:4},content:"4 cm",styleRef:"label_success"}]}},{id:"exp-step-2",type:"instructionalStep",title:"双旋转策略:分割为两个直角三角形",description:"沿高线将锐角三角形分割为两个直角三角形:左直角三角形和右直角三角形。每个直角三角形将独立旋转。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"point",geometryRef:"left_rotation_center",styleRef:"primary",size:4},{type:"point",geometryRef:"right_rotation_center",styleRef:"primary",size:4}]}},{id:"exp-step-3",type:"instructionalStep",title:"刚体旋转形成矩形",description:"每个直角三角形围绕其斜边中点旋转180度,形成对应的矩形。左直角三角形形成左矩形,右直角三角形形成右矩形。",chartConfig:{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}},{id:"exp-step-4",type:"instructionalStep",title:"组合形成完整矩形并推导面积公式",description:"两个小矩形组合形成完整的大矩形,其面积为 b × h = 6 × 4 = 24 cm²。锐角三角形面积是大矩形面积的一半,即 A = ½ × b × h = 12 cm²。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"full_rectangle",styleRef:"primary"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{type:"text",position:{x:5,y:1.2},content:"Base = 6 cm",style:{fontSize:"$fonts.label",color:"$colors.error",fontWeight:"bold",anchorX:"middle"}},{type:"text",position:{x:5.5,y:4},content:"Height = 4 cm",style:{fontSize:"$fonts.label",color:"$colors.success",fontWeight:"bold"}}]}}]},hC={value:12,unit:"cm²",type:"number",tolerance:.1,validation:{type:"exact",allowPartial:!1},explanation_text:"三角形面积 = ½ × 底 × 高 = ½ × 6cm × 4cm = 12cm²",solution_steps:["识别三角形的底和高","应用面积公式 A = ½ × b × h","代入数值:A = ½ × 6 × 4","计算:A = ½ × 24 = 12","添加单位:12 cm²"]},gC="2026-01-20T20:34:00Z",mC="2026-01-20T20:34:00Z",pC={double_rotation_proof:{id:"double_rotation_proof",description:"双旋转几何证明策略",base:6,height:4,unit:"cm",strategy:"double_rotation",shapes:{static:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary",appearanceRef:"always_visible"}],animated:[{id:"left_triangle",type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left",appearanceRef:"appear_at_90"},{id:"right_triangle",type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right",appearanceRef:"appear_at_90"}]},transform:{type:"composite",transforms:[{transformRef:"left_rotation"},{transformRef:"right_rotation"}],executionMode:"parallel"},boardRef:"default",sliderRef:"slider_horizontal"}},yC={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left_triangle"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right_triangle"}},bC={schema_version:US,config_version:BS,math_prob_id:HS,title:WS,description:qS,objective:YS,difficulty:KS,grade_id:XS,unit_name:JS,unit_id:ZS,lesson_name:QS,lesson_id:eC,module_id:tC,skill_description:nC,skill_item_id:rC,skill_id:sC,score:oC,knowledge_points:iC,metadata:aC,basic_info:lC,geometry_shapes:cC,layout:dC,scenes:uC,explanation:fC,answer_info:hC,created_at:gC,updated_at:mC,geometry_transform_configs:pC,transform_definitions:yC},xC="mp-10506-0001-0001-G01-0001",vC="平行四边形面积公式推导",wC="通过割补变换演示理解平行四边形面积公式 A=bh",_C="理解平行四边形面积公式 A=bh",SC=1,CC="g5",RC="多边形的面积",AC=1050601,NC="平行四边形的面积",EC=105060101,kC=1002,TC="已知平行四边形的底和高,求平行四边形面积",MC="s-105-06-0001",jC=1001,$C=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],OC={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},IC={question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",shape:"parallelogram",base:9,height:6,baseUnit:"in",heightUnit:"in",score:2,variables:{b:9,h:6,unit:"in"},context:{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},PC={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},FC={question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}},{type:"graph",content:"parallelogram_static",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.8,strokeColor:"#2980b9",strokeWidth:2},{id:"height-dash",type:"line",start:{x:4,y:1},end:{x:4,y:7},strokeColor:"#64748b",strokeWidth:2,dash:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16},{id:"side-label",type:"text",position:{x:2.5,y:4},content:"9 in",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1},{type:"interactive",content:"answer_input",metadata:{componentType:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"square inches",submitButton:{label:"Submit",color:"#67b510"}}}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},remember:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}},{type:"text",content:"Area = base × height",style:{color:"#64748b",marginTop:"8px"}},{type:"formula",content:"A = bh",parts:["A = bh"],displayMode:!0,style:{color:"#64748b",marginTop:"4px"}}],layout:{type:"vertical",spacing:"15px",alignment:"center",cardStyle:{backgroundColor:"#F8FAFC",borderColor:"#E3F2FD",borderWidth:"2px"}}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"text",content:"This parallelogram has base b = 9 inches and height h = 6 inches.",style:{color:"#555",marginBottom:"15px"}},{type:"text",content:"Interactive Demo: Drag the slider to transform the parallelogram into a rectangle.",style:{color:"#555",fontStyle:"italic",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{type:"text",content:"Through dissection, the parallelogram transforms into a rectangle with the same area.",style:{color:"#555",marginTop:"15px",marginBottom:"15px"}},{type:"formula",content:"A = b \\times h",parts:["A = b \\times h","= 9 \\times 6","= 54"],displayMode:!0,style:{fontSize:"1.2rem",textAlign:"center",margin:"15px 0"}},{type:"text",content:"The area of the parallelogram is 54 square inches.",style:{fontWeight:"bold",color:"#4a90e2",marginTop:"10px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}}},DC={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。",chartConfig:{type:"graph",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。",chartConfig:{type:"geometryTransform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。",chartConfig:{type:"graph",shapes:[{id:"rectangle",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:10,y:7},{x:1,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:10.5,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}}],strategy:"visual_transformation",total_steps:3,estimated_time:120,hints:[{step:1,text:"注意平行四边形的高是从底边垂直向上的距离,不是斜边的长度"},{step:2,text:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},LC={value:54,unit:"square inches",type:"numeric",tolerance:0,format:{decimal_places:0,allow_fraction:!1,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!0},explanation_text:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。",solution_steps:[{step:1,action:"identify_dimensions",description:"底边 b = 9 英寸,高 h = 6 英寸"},{step:2,action:"apply_formula",description:"面积公式 A = b × h"},{step:3,action:"calculate",description:"A = 9 × 6 = 54"},{step:4,action:"add_unit",description:"54 平方英寸"}]},zC="2024-01-15T10:30:00Z",VC="2024-01-15T10:30:00Z",GC={math_prob_id:xC,title:vC,description:wC,objective:_C,difficulty:SC,grade_id:CC,unit_name:RC,unit_id:AC,lesson_name:NC,lesson_id:EC,module_id:kC,skill_description:TC,skill_item_id:MC,skill_id:jC,knowledge_points:$C,metadata:OC,basic_info:IC,layout:PC,scenes:FC,explanation:DC,answer_info:LC,created_at:zC,updated_at:VC},UC={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function BC(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
48
81
  函数 loadAcuteTriangleV2Data() 已弃用。
49
82
  组件库不再包含数据加载逻辑。
50
83
 
@@ -57,7 +90,7 @@ ${i.errors?.join(`
57
90
  ${new Error().stack?.split(`
58
91
  `).slice(2,6).join(`
59
92
  `)||"无法获取调用栈"}
60
- `);const t=wn(N0,ev);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",t.data.id),t.data}async function nv(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
93
+ `);const t=_n(bC,UC);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",t.data.id),t.data}async function HC(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
61
94
  函数 loadTriangleProblemData() 已弃用。
62
95
  组件库不再包含数据加载逻辑。
63
96
 
@@ -70,7 +103,7 @@ ${new Error().stack?.split(`
70
103
  ${new Error().stack?.split(`
71
104
  `).slice(2,6).join(`
72
105
  `)||"无法获取调用栈"}
73
- `),tv()}async function rv(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
106
+ `),BC()}async function WC(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
74
107
  函数 loadParallelogramProblemData() 已弃用。
75
108
  组件库不再包含数据加载逻辑。
76
109
 
@@ -83,7 +116,7 @@ ${new Error().stack?.split(`
83
116
  ${new Error().stack?.split(`
84
117
  `).slice(2,6).join(`
85
118
  `)||"无法获取调用栈"}
86
- `);try{const t=zu(Q0);return console.log("平行四边形数据加载成功 (传统适配器):",t.id),t}catch(t){return console.error("传统适配器失败:",t),sv()}}function sv(){return zu({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const ov=({className:t="",problemData:e})=>{const n=qs(),r=Ys(),s=Ks(),o=Xs(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=Js(),[d,f]=x.useState(!0),[g,h]=x.useState(null),[m,p]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){f(!1),h(null),p(null);return}(async()=>{try{f(!0),h(null);const v=await rv();p(v)}catch(v){const S=v instanceof Error?v.message:"数据加载失败";h(S),console.error("页面数据加载失败:",v)}finally{f(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&c(b)},[b,c]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):g?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:g}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(xn,{problemData:b,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(Un,{problemData:b,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(vn,{problemData:b,onNextQuestion:l})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},iv=({className:t="",problemData:e})=>{const n=qs(),r=Ys(),s=Ks(),o=Xs(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=Js(),[d,f]=x.useState(!0),[g,h]=x.useState(null),[m,p]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){f(!1),h(null),p(null);return}(async()=>{try{f(!0),h(null);const v=await nv();p(v)}catch(v){const S=v instanceof Error?v.message:"数据加载失败";h(S),console.error("页面数据加载失败:",v)}finally{f(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&c(b)},[b,c]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):g?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:g}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(xn,{problemData:b,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(Un,{problemData:b,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(vn,{problemData:b,onNextQuestion:l})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Vu=x.createContext(void 0),av=()=>{const t=x.useContext(Vu);if(!t)throw new Error("useMathCardContext must be used within a MathCard component");return t},Gu=(t,e,n)=>t.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,n.join(", ")),lv=t=>t.type==="formula"?x.createElement(Gn,{key:t.content,parts:[t.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):t.type==="image"?x.createElement("img",{src:t.content,alt:"content",className:"image",key:t.content}):x.createElement("span",{key:t.content},t.content),Xi=t=>t.map((e,n)=>x.createElement("div",{className:"content-block",key:n},lv(e))),cv=t=>{const e=[];let n=0;const r=/\$\$?[^$]+\$\$?/g;let s;for(;(s=r.exec(t))!==null;){const o=s.index,i=s.index+s[0].length;if(o>n){const c=t.substring(n,o);c.trim()&&e.push({type:"text",content:c})}const l=s[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:l}),n=i}if(n<t.length){const o=t.substring(n);o.trim()&&e.push({type:"text",content:o})}return e},dv=(t,e,n)=>{const r=Gu(t,e,n),s=cv(r);return Xi(s)},uv=t=>{const{type:e,content:n,style:r={}}=t,s={marginBottom:"8px",lineHeight:"1.6",...r};switch(e){case"instruction":return x.createElement("div",{key:t.id,style:{...s,fontWeight:"bold",color:"#4a6cf7"}},n);case"formula":const o=n.includes("\\\\")||n.includes("\\downarrow")||n.includes("\\quad");return x.createElement(Gn,{key:t.id,parts:[n],children:null,displayMode:o,fontSize:"1.1em",color:"#333333"});case"conclusion":return x.createElement("div",{key:t.id,style:{...s,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},n);case"image":return x.createElement("div",{key:t.id,style:s},x.createElement("img",{src:n,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return x.createElement("div",{key:t.id,style:s},x.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},n));default:return x.createElement("div",{key:t.id,style:s},n)}},fv=(t,e,n)=>{const{type:r,content:s,style:o={}}=t,i={marginBottom:"8px",lineHeight:"1.6",...o};switch(r){case"instruction":return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},s);case"formula":const a=s.includes("\\\\")||s.includes("\\downarrow")||s.includes("\\quad");return x.createElement(Gn,{key:t.id,parts:[s],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const l=Gu(s,n,e);return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},l);default:return x.createElement("div",{key:t.id,style:i},s)}},hv=t=>t.map(uv),gv=(t,e,n)=>t.map(r=>fv(r,e,n)),Uu=({scene:t,position:e="header",size:n="medium",color:r,bgColor:s,hidden:o=!1})=>{if(o)return null;const i={question:"题目作答",solve:"官方解析",review:"用户复习"},a=()=>{const l={display:"flex",alignItems:"center",justifyContent:"center",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px"},c={question:"#f97316",solve:"#4a6cf7",review:"#4ade80"};return l.background=s||c[t],l.color=r||"#ffffff",e==="header"?l.borderBottom="1px solid #e0e0e0":e==="sidebar"&&(l.borderRight="1px solid #e0e0e0",l.writingMode="vertical-rl",l.textOrientation="mixed"),Object.assign(l,{small:{fontSize:"12px",padding:"8px 12px"},medium:{fontSize:"14px",padding:"12px 16px"},large:{fontSize:"16px",padding:"16px 20px"}}[n]),l};return u.jsx("div",{style:a(),children:i[t]})},Bu=({question:t})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return u.jsx("div",{style:e,children:Xi(t)})},Hu=({problemType:t,options:e,value:n=[],onChange:r,placeholder:s="请输入答案"})=>{const o={padding:"20px",borderTop:"1px solid #e0e0e0"},i={width:"100%",padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",fontSize:"14px"},a={display:"grid",gap:"12px"},l=f=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:f?"#f97316":"transparent",color:f?"#ffffff":"inherit",borderColor:f?"#f97316":"#e0e0e0"}),c=f=>{if(r)if(t==="multiple-choice"){const g=n.includes(f)?n.filter(h=>h!==f):[...n,f];r(g)}else r([f])},d=f=>{r&&r([f.target.value])};return t==="multiple-choice"&&e?u.jsx("div",{style:o,children:u.jsx("div",{style:a,children:e.map(f=>u.jsx("div",{style:l(n.includes(f.id)),onClick:()=>c(f.id),children:Xi(f.content)},f.id))})}):u.jsx("div",{style:o,children:u.jsx("input",{type:"text",style:i,placeholder:s,value:n[0]||"",onChange:d})})},bs=({onClick:t,children:e,disabled:n=!1,loading:r=!1})=>{const s={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.6:1};return u.jsx("button",{style:s,onClick:t,disabled:n||r,children:r?"提交中...":e})},Wu=({steps:t,title:e="解题步骤"})=>{const n={padding:"20px",borderTop:"1px solid #e0e0e0"},r={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4a6cf7"},s={display:"flex",flexDirection:"column",gap:"12px"},o={padding:"12px",borderLeft:"3px solid #4a6cf7",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return u.jsxs("div",{style:n,children:[u.jsx("div",{style:r,children:e}),u.jsx("div",{style:s,children:hv(t).map((i,a)=>u.jsx("div",{style:o,children:i},t[a].id))})]})},qu=({reviewContent:t,userAnswer:e,correctAnswer:n})=>{const r={padding:"20px",borderTop:"1px solid #e0e0e0"},s={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4ade80"},o={lineHeight:"1.6"},i={padding:"12px",background:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:"4px",marginBottom:"16px"},a={display:"flex",flexDirection:"column",gap:"12px"},l={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return u.jsxs("div",{style:r,children:[u.jsx("div",{style:s,children:"复习内容"}),u.jsxs("div",{style:o,children:[t.reviewTemplate&&u.jsx("div",{style:i,children:dv(t.reviewTemplate,n,e)}),t.reviewExplanation&&u.jsx("div",{style:a,children:gv(t.reviewExplanation,e,n).map((c,d)=>u.jsx("div",{style:l,children:c},t.reviewExplanation[d].id))})]})]})},Yu=({type:t="skeleton"})=>{const e={padding:"20px"},n={height:"16px",background:"linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",backgroundSize:"200% 100%",animation:"loading 1.5s infinite",borderRadius:"4px",marginBottom:"12px"},r={display:"flex",justifyContent:"center",alignItems:"center",padding:"24px"},s={width:"40px",height:"40px",border:"4px solid #f0f0f0",borderTop:"4px solid #f97316",borderRadius:"50%",animation:"spin 1s linear infinite"};return t==="spinner"?u.jsx("div",{style:r,children:u.jsx("div",{style:s})}):u.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[u.jsx("div",{style:{...n,width:"80%"}}),u.jsx("div",{style:{...n,width:"60%"}}),u.jsx("div",{style:{...n,width:"70%"}})]})},Ns=({error:t,onRetry:e})=>{const n={padding:"24px",textAlign:"center",color:"#ef4444"},r={marginBottom:"16px",fontSize:"16px"},s={padding:"12px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},o=typeof t=="string"?t:t.message;return u.jsxs("div",{style:n,children:[u.jsx("div",{style:r,children:o}),e&&u.jsx("button",{style:s,onClick:()=>e(t),children:"重试"})]})},mv=({orientation:t="horizontal",size:e="medium"})=>{const n={background:"#e0e0e0"},r={small:"12px",medium:"16px",large:"20px"};return t==="horizontal"?(n.height="1px",n.width="100%",n.margin=`${r[e]} 0`):(n.width="1px",n.height="100%",n.margin=`0 ${r[e]}`),u.jsx("div",{style:n})},pv=({onSubmit:t,onNext:e,onRetry:n,onAnswerChange:r,value:s})=>{const{problemData:o,scene:i,submissionResult:a,config:l}=av();if(!o)return u.jsx(Ns,{error:"No problem data provided"});const c=()=>{t&&t()},d=()=>{e&&e(o.problemId)},f=()=>{n&&n(o.problemId)},g=p=>{r&&r(p,o.problemType)},h={background:l?.theme==="dark"?"#1a1a1a":"#ffffff",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",fontFamily:"'Arial', sans-serif",fontSize:"14px",overflow:"hidden",color:l?.theme==="dark"?"#ffffff":"#333333",width:"100%",maxWidth:"800px"},m={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return u.jsxs("div",{style:h,"data-testid":"math-card","data-theme":l?.theme,children:[l?.showBanner!==!1&&u.jsx(Uu,{scene:i,position:l?.bannerPosition,size:l?.bannerSize,color:l?.bannerCustomStyle?.color,bgColor:l?.bannerCustomStyle?.bgColor}),u.jsx(Bu,{question:o.question,problemType:o.problemType}),i==="question"&&u.jsxs(u.Fragment,{children:[u.jsx(Hu,{problemType:o.problemType,options:o.answer.options,value:s,onChange:g,placeholder:l?.inputPlaceholder}),u.jsx("div",{style:m,children:u.jsx(bs,{onClick:c,disabled:!t,children:l?.submitButtonText||"提交答案"})})]}),i==="solve"&&o.explanation&&u.jsx(Wu,{steps:o.explanation,title:"官方解析"}),i==="review"&&a&&o.reviewContent&&u.jsx(qu,{reviewContent:o.reviewContent,userAnswer:a.userAnswer,correctAnswer:o.answer.correctAnswer}),(i==="solve"||i==="review")&&u.jsxs("div",{style:m,children:[e&&u.jsx(bs,{onClick:d,children:l?.nextButtonText||"下一题"}),n&&u.jsx(bs,{onClick:f,children:l?.retryButtonText||"重新作答"})]})]})},Rt=({problemData:t,scene:e,submissionResult:n,loading:r,error:s,config:o,children:i,onSubmit:a,onNext:l,onRetry:c,onErrorRetry:d,onAnswerChange:f,onHintToggle:g,value:h})=>{if(r)return u.jsx(Yu,{type:"skeleton"});if(s)return u.jsx(Ns,{error:s,onRetry:d});if(!t)return u.jsx(Ns,{error:"No problem data provided"});const m={problemData:t,scene:e,submissionResult:n,config:o,value:h};return u.jsx(Vu.Provider,{value:m,children:i||u.jsx(pv,{onSubmit:a,onNext:l,onRetry:c,onAnswerChange:f,onHintToggle:g,value:h})})};Rt.Banner=Uu;Rt.Question=Bu;Rt.AnswerInput=Hu;Rt.SubmitButton=bs;Rt.Explanation=Wu;Rt.ReviewContent=qu;Rt.LoadingState=Yu;Rt.ErrorState=Ns;Rt.Divider=mv;function yv(t){if(t.sheet)return t.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===t)return document.styleSheets[e]}function bv(t){var e=document.createElement("style");return e.setAttribute("data-emotion",t.key),t.nonce!==void 0&&e.setAttribute("nonce",t.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var xv=(function(){function t(n){var r=this;this._insertTag=function(s){var o;r.tags.length===0?r.insertionPoint?o=r.insertionPoint.nextSibling:r.prepend?o=r.container.firstChild:o=r.before:o=r.tags[r.tags.length-1].nextSibling,r.container.insertBefore(s,o),r.tags.push(s)},this.isSpeedy=n.speedy===void 0?!0:n.speedy,this.tags=[],this.ctr=0,this.nonce=n.nonce,this.key=n.key,this.container=n.container,this.prepend=n.prepend,this.insertionPoint=n.insertionPoint,this.before=null}var e=t.prototype;return e.hydrate=function(r){r.forEach(this._insertTag)},e.insert=function(r){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(bv(this));var s=this.tags[this.tags.length-1];if(this.isSpeedy){var o=yv(s);try{o.insertRule(r,o.cssRules.length)}catch{}}else s.appendChild(document.createTextNode(r));this.ctr++},e.flush=function(){this.tags.forEach(function(r){var s;return(s=r.parentNode)==null?void 0:s.removeChild(r)}),this.tags=[],this.ctr=0},t})(),Le="-ms-",Ts="-moz-",le="-webkit-",Ku="comm",Ji="rule",Zi="decl",vv="@import",Xu="@keyframes",wv="@layer",_v=Math.abs,Zs=String.fromCharCode,Sv=Object.assign;function Cv(t,e){return Ie(t,0)^45?(((e<<2^Ie(t,0))<<2^Ie(t,1))<<2^Ie(t,2))<<2^Ie(t,3):0}function Ju(t){return t.trim()}function Rv(t,e){return(t=e.exec(t))?t[0]:t}function ce(t,e,n){return t.replace(e,n)}function ai(t,e){return t.indexOf(e)}function Ie(t,e){return t.charCodeAt(e)|0}function pr(t,e,n){return t.slice(e,n)}function xt(t){return t.length}function Qi(t){return t.length}function Xr(t,e){return e.push(t),t}function Av(t,e){return t.map(e).join("")}var Qs=1,On=1,Zu=0,Je=0,Ne=0,Bn="";function eo(t,e,n,r,s,o,i){return{value:t,root:e,parent:n,type:r,props:s,children:o,line:Qs,column:On,length:i,return:""}}function Jn(t,e){return Sv(eo("",null,null,"",null,null,0),t,{length:-t.length},e)}function kv(){return Ne}function Ev(){return Ne=Je>0?Ie(Bn,--Je):0,On--,Ne===10&&(On=1,Qs--),Ne}function nt(){return Ne=Je<Zu?Ie(Bn,Je++):0,On++,Ne===10&&(On=1,Qs++),Ne}function St(){return Ie(Bn,Je)}function xs(){return Je}function jr(t,e){return pr(Bn,t,e)}function yr(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function Qu(t){return Qs=On=1,Zu=xt(Bn=t),Je=0,[]}function ef(t){return Bn="",t}function vs(t){return Ju(jr(Je-1,li(t===91?t+2:t===40?t+1:t)))}function Nv(t){for(;(Ne=St())&&Ne<33;)nt();return yr(t)>2||yr(Ne)>3?"":" "}function Tv(t,e){for(;--e&&nt()&&!(Ne<48||Ne>102||Ne>57&&Ne<65||Ne>70&&Ne<97););return jr(t,xs()+(e<6&&St()==32&&nt()==32))}function li(t){for(;nt();)switch(Ne){case t:return Je;case 34:case 39:t!==34&&t!==39&&li(Ne);break;case 40:t===41&&li(t);break;case 92:nt();break}return Je}function Mv(t,e){for(;nt()&&t+Ne!==57;)if(t+Ne===84&&St()===47)break;return"/*"+jr(e,Je-1)+"*"+Zs(t===47?t:nt())}function $v(t){for(;!yr(St());)nt();return jr(t,Je)}function jv(t){return ef(ws("",null,null,null,[""],t=Qu(t),0,[0],t))}function ws(t,e,n,r,s,o,i,a,l){for(var c=0,d=0,f=i,g=0,h=0,m=0,p=1,y=1,b=1,w=0,v="",S=s,_=o,A=r,C=v;y;)switch(m=w,w=nt()){case 40:if(m!=108&&Ie(C,f-1)==58){ai(C+=ce(vs(w),"&","&\f"),"&\f")!=-1&&(b=-1);break}case 34:case 39:case 91:C+=vs(w);break;case 9:case 10:case 13:case 32:C+=Nv(m);break;case 92:C+=Tv(xs()-1,7);continue;case 47:switch(St()){case 42:case 47:Xr(Ov(Mv(nt(),xs()),e,n),l);break;default:C+="/"}break;case 123*p:a[c++]=xt(C)*b;case 125*p:case 59:case 0:switch(w){case 0:case 125:y=0;case 59+d:b==-1&&(C=ce(C,/\f/g,"")),h>0&&xt(C)-f&&Xr(h>32?nl(C+";",r,n,f-1):nl(ce(C," ","")+";",r,n,f-2),l);break;case 59:C+=";";default:if(Xr(A=tl(C,e,n,c,d,s,a,v,S=[],_=[],f),o),w===123)if(d===0)ws(C,e,A,A,S,o,f,a,_);else switch(g===99&&Ie(C,3)===110?100:g){case 100:case 108:case 109:case 115:ws(t,A,A,r&&Xr(tl(t,A,A,0,0,s,a,v,s,S=[],f),_),s,_,f,a,r?S:_);break;default:ws(C,A,A,A,[""],_,0,a,_)}}c=d=h=0,p=b=1,v=C="",f=i;break;case 58:f=1+xt(C),h=m;default:if(p<1){if(w==123)--p;else if(w==125&&p++==0&&Ev()==125)continue}switch(C+=Zs(w),w*p){case 38:b=d>0?1:(C+="\f",-1);break;case 44:a[c++]=(xt(C)-1)*b,b=1;break;case 64:St()===45&&(C+=vs(nt())),g=St(),d=f=xt(v=C+=$v(xs())),w++;break;case 45:m===45&&xt(C)==2&&(p=0)}}return o}function tl(t,e,n,r,s,o,i,a,l,c,d){for(var f=s-1,g=s===0?o:[""],h=Qi(g),m=0,p=0,y=0;m<r;++m)for(var b=0,w=pr(t,f+1,f=_v(p=i[m])),v=t;b<h;++b)(v=Ju(p>0?g[b]+" "+w:ce(w,/&\f/g,g[b])))&&(l[y++]=v);return eo(t,e,n,s===0?Ji:a,l,c,d)}function Ov(t,e,n){return eo(t,e,n,Ku,Zs(kv()),pr(t,2,-2),0)}function nl(t,e,n,r){return eo(t,e,n,Zi,pr(t,0,r),pr(t,r+1,-1),r)}function Tn(t,e){for(var n="",r=Qi(t),s=0;s<r;s++)n+=e(t[s],s,t,e)||"";return n}function Iv(t,e,n,r){switch(t.type){case wv:if(t.children.length)break;case vv:case Zi:return t.return=t.return||t.value;case Ku:return"";case Xu:return t.return=t.value+"{"+Tn(t.children,r)+"}";case Ji:t.value=t.props.join(",")}return xt(n=Tn(t.children,r))?t.return=t.value+"{"+n+"}":""}function Pv(t){var e=Qi(t);return function(n,r,s,o){for(var i="",a=0;a<e;a++)i+=t[a](n,r,s,o)||"";return i}}function Fv(t){return function(e){e.root||(e=e.return)&&t(e)}}function Dv(t){var e=Object.create(null);return function(n){return e[n]===void 0&&(e[n]=t(n)),e[n]}}var Lv=function(e,n,r){for(var s=0,o=0;s=o,o=St(),s===38&&o===12&&(n[r]=1),!yr(o);)nt();return jr(e,Je)},zv=function(e,n){var r=-1,s=44;do switch(yr(s)){case 0:s===38&&St()===12&&(n[r]=1),e[r]+=Lv(Je-1,n,r);break;case 2:e[r]+=vs(s);break;case 4:if(s===44){e[++r]=St()===58?"&\f":"",n[r]=e[r].length;break}default:e[r]+=Zs(s)}while(s=nt());return e},Vv=function(e,n){return ef(zv(Qu(e),n))},rl=new WeakMap,Gv=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var n=e.value,r=e.parent,s=e.column===r.column&&e.line===r.line;r.type!=="rule";)if(r=r.parent,!r)return;if(!(e.props.length===1&&n.charCodeAt(0)!==58&&!rl.get(r))&&!s){rl.set(e,!0);for(var o=[],i=Vv(n,o),a=r.props,l=0,c=0;l<i.length;l++)for(var d=0;d<a.length;d++,c++)e.props[c]=o[l]?i[l].replace(/&\f/g,a[d]):a[d]+" "+i[l]}}},Uv=function(e){if(e.type==="decl"){var n=e.value;n.charCodeAt(0)===108&&n.charCodeAt(2)===98&&(e.return="",e.value="")}};function tf(t,e){switch(Cv(t,e)){case 5103:return le+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return le+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return le+t+Ts+t+Le+t+t;case 6828:case 4268:return le+t+Le+t+t;case 6165:return le+t+Le+"flex-"+t+t;case 5187:return le+t+ce(t,/(\w+).+(:[^]+)/,le+"box-$1$2"+Le+"flex-$1$2")+t;case 5443:return le+t+Le+"flex-item-"+ce(t,/flex-|-self/,"")+t;case 4675:return le+t+Le+"flex-line-pack"+ce(t,/align-content|flex-|-self/,"")+t;case 5548:return le+t+Le+ce(t,"shrink","negative")+t;case 5292:return le+t+Le+ce(t,"basis","preferred-size")+t;case 6060:return le+"box-"+ce(t,"-grow","")+le+t+Le+ce(t,"grow","positive")+t;case 4554:return le+ce(t,/([^-])(transform)/g,"$1"+le+"$2")+t;case 6187:return ce(ce(ce(t,/(zoom-|grab)/,le+"$1"),/(image-set)/,le+"$1"),t,"")+t;case 5495:case 3959:return ce(t,/(image-set\([^]*)/,le+"$1$`$1");case 4968:return ce(ce(t,/(.+:)(flex-)?(.*)/,le+"box-pack:$3"+Le+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+le+t+t;case 4095:case 3583:case 4068:case 2532:return ce(t,/(.+)-inline(.+)/,le+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(xt(t)-1-e>6)switch(Ie(t,e+1)){case 109:if(Ie(t,e+4)!==45)break;case 102:return ce(t,/(.+:)(.+)-([^]+)/,"$1"+le+"$2-$3$1"+Ts+(Ie(t,e+3)==108?"$3":"$2-$3"))+t;case 115:return~ai(t,"stretch")?tf(ce(t,"stretch","fill-available"),e)+t:t}break;case 4949:if(Ie(t,e+1)!==115)break;case 6444:switch(Ie(t,xt(t)-3-(~ai(t,"!important")&&10))){case 107:return ce(t,":",":"+le)+t;case 101:return ce(t,/(.+:)([^;!]+)(;|!.+)?/,"$1"+le+(Ie(t,14)===45?"inline-":"")+"box$3$1"+le+"$2$3$1"+Le+"$2box$3")+t}break;case 5936:switch(Ie(t,e+11)){case 114:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"lr")+t}return le+t+Le+t+t}return t}var Bv=function(e,n,r,s){if(e.length>-1&&!e.return)switch(e.type){case Zi:e.return=tf(e.value,e.length);break;case Xu:return Tn([Jn(e,{value:ce(e.value,"@","@"+le)})],s);case Ji:if(e.length)return Av(e.props,function(o){switch(Rv(o,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Tn([Jn(e,{props:[ce(o,/:(read-\w+)/,":"+Ts+"$1")]})],s);case"::placeholder":return Tn([Jn(e,{props:[ce(o,/:(plac\w+)/,":"+le+"input-$1")]}),Jn(e,{props:[ce(o,/:(plac\w+)/,":"+Ts+"$1")]}),Jn(e,{props:[ce(o,/:(plac\w+)/,Le+"input-$1")]})],s)}return""})}},Hv=[Bv],Wv=function(e){var n=e.key;if(n==="css"){var r=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(r,function(p){var y=p.getAttribute("data-emotion");y.indexOf(" ")!==-1&&(document.head.appendChild(p),p.setAttribute("data-s",""))})}var s=e.stylisPlugins||Hv,o={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+n+' "]'),function(p){for(var y=p.getAttribute("data-emotion").split(" "),b=1;b<y.length;b++)o[y[b]]=!0;a.push(p)});var l,c=[Gv,Uv];{var d,f=[Iv,Fv(function(p){d.insert(p)})],g=Pv(c.concat(s,f)),h=function(y){return Tn(jv(y),g)};l=function(y,b,w,v){d=w,h(y?y+"{"+b.styles+"}":b.styles),v&&(m.inserted[b.name]=!0)}}var m={key:n,sheet:new xv({key:n,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:o,registered:{},insert:l};return m.sheet.hydrate(a),m},Jr={exports:{}},ue={};var sl;function qv(){if(sl)return ue;sl=1;var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,n=t?Symbol.for("react.portal"):60106,r=t?Symbol.for("react.fragment"):60107,s=t?Symbol.for("react.strict_mode"):60108,o=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,l=t?Symbol.for("react.async_mode"):60111,c=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,f=t?Symbol.for("react.suspense"):60113,g=t?Symbol.for("react.suspense_list"):60120,h=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,p=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,w=t?Symbol.for("react.scope"):60119;function v(_){if(typeof _=="object"&&_!==null){var A=_.$$typeof;switch(A){case e:switch(_=_.type,_){case l:case c:case r:case o:case s:case f:return _;default:switch(_=_&&_.$$typeof,_){case a:case d:case m:case h:case i:return _;default:return A}}case n:return A}}}function S(_){return v(_)===c}return ue.AsyncMode=l,ue.ConcurrentMode=c,ue.ContextConsumer=a,ue.ContextProvider=i,ue.Element=e,ue.ForwardRef=d,ue.Fragment=r,ue.Lazy=m,ue.Memo=h,ue.Portal=n,ue.Profiler=o,ue.StrictMode=s,ue.Suspense=f,ue.isAsyncMode=function(_){return S(_)||v(_)===l},ue.isConcurrentMode=S,ue.isContextConsumer=function(_){return v(_)===a},ue.isContextProvider=function(_){return v(_)===i},ue.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},ue.isForwardRef=function(_){return v(_)===d},ue.isFragment=function(_){return v(_)===r},ue.isLazy=function(_){return v(_)===m},ue.isMemo=function(_){return v(_)===h},ue.isPortal=function(_){return v(_)===n},ue.isProfiler=function(_){return v(_)===o},ue.isStrictMode=function(_){return v(_)===s},ue.isSuspense=function(_){return v(_)===f},ue.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===r||_===c||_===o||_===s||_===f||_===g||typeof _=="object"&&_!==null&&(_.$$typeof===m||_.$$typeof===h||_.$$typeof===i||_.$$typeof===a||_.$$typeof===d||_.$$typeof===y||_.$$typeof===b||_.$$typeof===w||_.$$typeof===p)},ue.typeOf=v,ue}var fe={};var ol;function Yv(){return ol||(ol=1,process.env.NODE_ENV!=="production"&&(function(){var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,n=t?Symbol.for("react.portal"):60106,r=t?Symbol.for("react.fragment"):60107,s=t?Symbol.for("react.strict_mode"):60108,o=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,l=t?Symbol.for("react.async_mode"):60111,c=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,f=t?Symbol.for("react.suspense"):60113,g=t?Symbol.for("react.suspense_list"):60120,h=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,p=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,w=t?Symbol.for("react.scope"):60119;function v(N){return typeof N=="string"||typeof N=="function"||N===r||N===c||N===o||N===s||N===f||N===g||typeof N=="object"&&N!==null&&(N.$$typeof===m||N.$$typeof===h||N.$$typeof===i||N.$$typeof===a||N.$$typeof===d||N.$$typeof===y||N.$$typeof===b||N.$$typeof===w||N.$$typeof===p)}function S(N){if(typeof N=="object"&&N!==null){var de=N.$$typeof;switch(de){case e:var ye=N.type;switch(ye){case l:case c:case r:case o:case s:case f:return ye;default:var W=ye&&ye.$$typeof;switch(W){case a:case d:case m:case h:case i:return W;default:return de}}case n:return de}}}var _=l,A=c,C=a,R=i,k=e,M=d,F=r,D=m,P=h,j=n,O=o,T=s,B=f,$=!1;function Q(N){return $||($=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),oe(N)||S(N)===l}function oe(N){return S(N)===c}function se(N){return S(N)===a}function ee(N){return S(N)===i}function L(N){return typeof N=="object"&&N!==null&&N.$$typeof===e}function X(N){return S(N)===d}function ae(N){return S(N)===r}function ve(N){return S(N)===m}function me(N){return S(N)===h}function Ft(N){return S(N)===n}function At(N){return S(N)===o}function z(N){return S(N)===s}function I(N){return S(N)===f}fe.AsyncMode=_,fe.ConcurrentMode=A,fe.ContextConsumer=C,fe.ContextProvider=R,fe.Element=k,fe.ForwardRef=M,fe.Fragment=F,fe.Lazy=D,fe.Memo=P,fe.Portal=j,fe.Profiler=O,fe.StrictMode=T,fe.Suspense=B,fe.isAsyncMode=Q,fe.isConcurrentMode=oe,fe.isContextConsumer=se,fe.isContextProvider=ee,fe.isElement=L,fe.isForwardRef=X,fe.isFragment=ae,fe.isLazy=ve,fe.isMemo=me,fe.isPortal=Ft,fe.isProfiler=At,fe.isStrictMode=z,fe.isSuspense=I,fe.isValidElementType=v,fe.typeOf=S})()),fe}var il;function Kv(){return il||(il=1,process.env.NODE_ENV==="production"?Jr.exports=qv():Jr.exports=Yv()),Jr.exports}var ko,al;function Xv(){if(al)return ko;al=1;var t=Kv(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},r={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},o={};o[t.ForwardRef]=r,o[t.Memo]=s;function i(m){return t.isMemo(m)?s:o[m.$$typeof]||e}var a=Object.defineProperty,l=Object.getOwnPropertyNames,c=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,f=Object.getPrototypeOf,g=Object.prototype;function h(m,p,y){if(typeof p!="string"){if(g){var b=f(p);b&&b!==g&&h(m,b,y)}var w=l(p);c&&(w=w.concat(c(p)));for(var v=i(m),S=i(p),_=0;_<w.length;++_){var A=w[_];if(!n[A]&&!(y&&y[A])&&!(S&&S[A])&&!(v&&v[A])){var C=d(p,A);try{a(m,A,C)}catch{}}}}return m}return ko=h,ko}Xv();var Jv=!0;function Zv(t,e,n){var r="";return n.split(" ").forEach(function(s){t[s]!==void 0?e.push(t[s]+";"):s&&(r+=s+" ")}),r}var nf=function(e,n,r){var s=e.key+"-"+n.name;(r===!1||Jv===!1)&&e.registered[s]===void 0&&(e.registered[s]=n.styles)},Qv=function(e,n,r){nf(e,n,r);var s=e.key+"-"+n.name;if(e.inserted[n.name]===void 0){var o=n;do e.insert(n===o?"."+s:"",o,e.sheet,!0),o=o.next;while(o!==void 0)}};function ew(t){for(var e=0,n,r=0,s=t.length;s>=4;++r,s-=4)n=t.charCodeAt(r)&255|(t.charCodeAt(++r)&255)<<8|(t.charCodeAt(++r)&255)<<16|(t.charCodeAt(++r)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,e=(n&65535)*1540483477+((n>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(s){case 3:e^=(t.charCodeAt(r+2)&255)<<16;case 2:e^=(t.charCodeAt(r+1)&255)<<8;case 1:e^=t.charCodeAt(r)&255,e=(e&65535)*1540483477+((e>>>16)*59797<<16)}return e^=e>>>13,e=(e&65535)*1540483477+((e>>>16)*59797<<16),((e^e>>>15)>>>0).toString(36)}var tw={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},nw=/[A-Z]|^ms/g,rw=/_EMO_([^_]+?)_([^]*?)_EMO_/g,rf=function(e){return e.charCodeAt(1)===45},ll=function(e){return e!=null&&typeof e!="boolean"},Eo=Dv(function(t){return rf(t)?t:t.replace(nw,"-$&").toLowerCase()}),cl=function(e,n){switch(e){case"animation":case"animationName":if(typeof n=="string")return n.replace(rw,function(r,s,o){return vt={name:s,styles:o,next:vt},s})}return tw[e]!==1&&!rf(e)&&typeof n=="number"&&n!==0?n+"px":n};function br(t,e,n){if(n==null)return"";var r=n;if(r.__emotion_styles!==void 0)return r;switch(typeof n){case"boolean":return"";case"object":{var s=n;if(s.anim===1)return vt={name:s.name,styles:s.styles,next:vt},s.name;var o=n;if(o.styles!==void 0){var i=o.next;if(i!==void 0)for(;i!==void 0;)vt={name:i.name,styles:i.styles,next:vt},i=i.next;var a=o.styles+";";return a}return sw(t,e,n)}case"function":{if(t!==void 0){var l=vt,c=n(t);return vt=l,br(t,e,c)}break}}var d=n;return d}function sw(t,e,n){var r="";if(Array.isArray(n))for(var s=0;s<n.length;s++)r+=br(t,e,n[s])+";";else for(var o in n){var i=n[o];if(typeof i!="object"){var a=i;ll(a)&&(r+=Eo(o)+":"+cl(o,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var l=0;l<i.length;l++)ll(i[l])&&(r+=Eo(o)+":"+cl(o,i[l])+";");else{var c=br(t,e,i);switch(o){case"animation":case"animationName":{r+=Eo(o)+":"+c+";";break}default:r+=o+"{"+c+"}"}}}return r}var dl=/label:\s*([^\s;{]+)\s*(;|$)/g,vt;function sf(t,e,n){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null&&t[0].styles!==void 0)return t[0];var r=!0,s="";vt=void 0;var o=t[0];if(o==null||o.raw===void 0)r=!1,s+=br(n,e,o);else{var i=o;s+=i[0]}for(var a=1;a<t.length;a++)if(s+=br(n,e,t[a]),r){var l=o;s+=l[a]}dl.lastIndex=0;for(var c="",d;(d=dl.exec(s))!==null;)c+="-"+d[1];var f=ew(s)+c;return{name:f,styles:s,next:vt}}var ow=function(e){return e()},iw=et.useInsertionEffect?et.useInsertionEffect:!1,aw=iw||ow,of=et.createContext(typeof HTMLElement<"u"?Wv({key:"css"}):null);of.Provider;var lw=function(e){return x.forwardRef(function(n,r){var s=x.useContext(of);return e(n,s,r)})},cw=et.createContext({}),ea={}.hasOwnProperty,ci="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",dw=function(e,n){var r={};for(var s in n)ea.call(n,s)&&(r[s]=n[s]);return r[ci]=e,r},uw=function(e){var n=e.cache,r=e.serialized,s=e.isStringTag;return nf(n,r,s),aw(function(){return Qv(n,r,s)}),null},fw=lw(function(t,e,n){var r=t.css;typeof r=="string"&&e.registered[r]!==void 0&&(r=e.registered[r]);var s=t[ci],o=[r],i="";typeof t.className=="string"?i=Zv(e.registered,o,t.className):t.className!=null&&(i=t.className+" ");var a=sf(o,void 0,et.useContext(cw));i+=e.key+"-"+a.name;var l={};for(var c in t)ea.call(t,c)&&c!=="css"&&c!==ci&&(l[c]=t[c]);return l.className=i,n&&(l.ref=n),et.createElement(et.Fragment,null,et.createElement(uw,{cache:e,serialized:a,isStringTag:typeof s=="string"}),et.createElement(s,l))}),hw=fw,ul=function(e,n){var r=arguments;if(n==null||!ea.call(n,"css"))return et.createElement.apply(void 0,r);var s=r.length,o=new Array(s);o[0]=hw,o[1]=dw(e,n);for(var i=2;i<s;i++)o[i]=r[i];return et.createElement.apply(null,o)};(function(t){var e;e||(e=t.JSX||(t.JSX={}))})(ul||(ul={}));function _e(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return sf(e)}const V={colors:{text:{light:"#ffffff"},background:{card:"#ffffff",feedbackCorrect:"#f0fdf4",feedbackIncorrect:"#fef2f2"},border:{default:"#e0e0e0"},scene:{solve:"#4a6cf7",review:"#4ade80",question:"#f97316"}},typography:{fontFamily:"'Arial', sans-serif",fontSizeBase:"14px",fontSizeLarge:"16px",fontSizeSmall:"12px"},spacing:{sm:"12px",md:"16px",lg:"20px",xl:"24px"},borderRadius:{card:"8px",button:"6px",input:"4px"},shadows:{card:"0 2px 8px rgba(0,0,0,0.1)"}};_e`
119
+ `);try{const t=Vf(GC);return console.log("平行四边形数据加载成功 (传统适配器):",t.id),t}catch(t){return console.error("传统适配器失败:",t),qC()}}function qC(){return Vf({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const YC=({className:t="",problemData:e})=>{const n=Qs(),r=eo(),s=to(),o=no(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=ro(),[d,f]=x.useState(!0),[g,h]=x.useState(null),[m,p]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){f(!1),h(null),p(null);return}(async()=>{try{f(!0),h(null);const v=await WC();p(v)}catch(v){const S=v instanceof Error?v.message:"数据加载失败";h(S),console.error("页面数据加载失败:",v)}finally{f(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&c(b)},[b,c]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):g?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:g}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(vn,{problemData:b,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(Bn,{problemData:b,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(wn,{problemData:b,onNextQuestion:l})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},KC=({className:t="",problemData:e})=>{const n=Qs(),r=eo(),s=to(),o=no(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=ro(),[d,f]=x.useState(!0),[g,h]=x.useState(null),[m,p]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){f(!1),h(null),p(null);return}(async()=>{try{f(!0),h(null);const v=await HC();p(v)}catch(v){const S=v instanceof Error?v.message:"数据加载失败";h(S),console.error("页面数据加载失败:",v)}finally{f(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&c(b)},[b,c]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):g?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:g}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(vn,{problemData:b,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(Bn,{problemData:b,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(wn,{problemData:b,onNextQuestion:l})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Gf=x.createContext(void 0),XC=()=>{const t=x.useContext(Gf);if(!t)throw new Error("useMathCardContext must be used within a MathCard component");return t},Uf=(t,e,n)=>t.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,n.join(", ")),JC=t=>t.type==="formula"?x.createElement(Gn,{key:t.content,parts:[t.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):t.type==="image"?x.createElement("img",{src:t.content,alt:"content",className:"image",key:t.content}):x.createElement("span",{key:t.content},t.content),da=t=>t.map((e,n)=>x.createElement("div",{className:"content-block",key:n},JC(e))),ZC=t=>{const e=[];let n=0;const r=/\$\$?[^$]+\$\$?/g;let s;for(;(s=r.exec(t))!==null;){const o=s.index,i=s.index+s[0].length;if(o>n){const c=t.substring(n,o);c.trim()&&e.push({type:"text",content:c})}const l=s[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:l}),n=i}if(n<t.length){const o=t.substring(n);o.trim()&&e.push({type:"text",content:o})}return e},QC=(t,e,n)=>{const r=Uf(t,e,n),s=ZC(r);return da(s)},eR=t=>{const{type:e,content:n,style:r={}}=t,s={marginBottom:"8px",lineHeight:"1.6",...r};switch(e){case"instruction":return x.createElement("div",{key:t.id,style:{...s,fontWeight:"bold",color:"#4a6cf7"}},n);case"formula":const o=n.includes("\\\\")||n.includes("\\downarrow")||n.includes("\\quad");return x.createElement(Gn,{key:t.id,parts:[n],children:null,displayMode:o,fontSize:"1.1em",color:"#333333"});case"conclusion":return x.createElement("div",{key:t.id,style:{...s,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},n);case"image":return x.createElement("div",{key:t.id,style:s},x.createElement("img",{src:n,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return x.createElement("div",{key:t.id,style:s},x.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},n));default:return x.createElement("div",{key:t.id,style:s},n)}},tR=(t,e,n)=>{const{type:r,content:s,style:o={}}=t,i={marginBottom:"8px",lineHeight:"1.6",...o};switch(r){case"instruction":return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},s);case"formula":const a=s.includes("\\\\")||s.includes("\\downarrow")||s.includes("\\quad");return x.createElement(Gn,{key:t.id,parts:[s],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const l=Uf(s,n,e);return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},l);default:return x.createElement("div",{key:t.id,style:i},s)}},nR=t=>t.map(eR),rR=(t,e,n)=>t.map(r=>tR(r,e,n)),Bf=({scene:t,position:e="header",size:n="medium",color:r,bgColor:s,hidden:o=!1})=>{if(o)return null;const i={question:"题目作答",solve:"官方解析",review:"用户复习"},a=()=>{const l={display:"flex",alignItems:"center",justifyContent:"center",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px"},c={question:"#f97316",solve:"#4a6cf7",review:"#4ade80"};return l.background=s||c[t],l.color=r||"#ffffff",e==="header"?l.borderBottom="1px solid #e0e0e0":e==="sidebar"&&(l.borderRight="1px solid #e0e0e0",l.writingMode="vertical-rl",l.textOrientation="mixed"),Object.assign(l,{small:{fontSize:"12px",padding:"8px 12px"},medium:{fontSize:"14px",padding:"12px 16px"},large:{fontSize:"16px",padding:"16px 20px"}}[n]),l};return u.jsx("div",{style:a(),children:i[t]})},Hf=({question:t})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return u.jsx("div",{style:e,children:da(t)})},Wf=({problemType:t,options:e,value:n=[],onChange:r,placeholder:s="请输入答案"})=>{const o={padding:"20px",borderTop:"1px solid #e0e0e0"},i={width:"100%",padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",fontSize:"14px"},a={display:"grid",gap:"12px"},l=f=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:f?"#f97316":"transparent",color:f?"#ffffff":"inherit",borderColor:f?"#f97316":"#e0e0e0"}),c=f=>{if(r)if(t==="multiple-choice"){const g=n.includes(f)?n.filter(h=>h!==f):[...n,f];r(g)}else r([f])},d=f=>{r&&r([f.target.value])};return t==="multiple-choice"&&e?u.jsx("div",{style:o,children:u.jsx("div",{style:a,children:e.map(f=>u.jsx("div",{style:l(n.includes(f.id)),onClick:()=>c(f.id),children:da(f.content)},f.id))})}):u.jsx("div",{style:o,children:u.jsx("input",{type:"text",style:i,placeholder:s,value:n[0]||"",onChange:d})})},ws=({onClick:t,children:e,disabled:n=!1,loading:r=!1})=>{const s={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.6:1};return u.jsx("button",{style:s,onClick:t,disabled:n||r,children:r?"提交中...":e})},qf=({steps:t,title:e="解题步骤"})=>{const n={padding:"20px",borderTop:"1px solid #e0e0e0"},r={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4a6cf7"},s={display:"flex",flexDirection:"column",gap:"12px"},o={padding:"12px",borderLeft:"3px solid #4a6cf7",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return u.jsxs("div",{style:n,children:[u.jsx("div",{style:r,children:e}),u.jsx("div",{style:s,children:nR(t).map((i,a)=>u.jsx("div",{style:o,children:i},t[a].id))})]})},Yf=({reviewContent:t,userAnswer:e,correctAnswer:n})=>{const r={padding:"20px",borderTop:"1px solid #e0e0e0"},s={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4ade80"},o={lineHeight:"1.6"},i={padding:"12px",background:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:"4px",marginBottom:"16px"},a={display:"flex",flexDirection:"column",gap:"12px"},l={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return u.jsxs("div",{style:r,children:[u.jsx("div",{style:s,children:"复习内容"}),u.jsxs("div",{style:o,children:[t.reviewTemplate&&u.jsx("div",{style:i,children:QC(t.reviewTemplate,n,e)}),t.reviewExplanation&&u.jsx("div",{style:a,children:rR(t.reviewExplanation,e,n).map((c,d)=>u.jsx("div",{style:l,children:c},t.reviewExplanation[d].id))})]})]})},Kf=({type:t="skeleton"})=>{const e={padding:"20px"},n={height:"16px",background:"linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",backgroundSize:"200% 100%",animation:"loading 1.5s infinite",borderRadius:"4px",marginBottom:"12px"},r={display:"flex",justifyContent:"center",alignItems:"center",padding:"24px"},s={width:"40px",height:"40px",border:"4px solid #f0f0f0",borderTop:"4px solid #f97316",borderRadius:"50%",animation:"spin 1s linear infinite"};return t==="spinner"?u.jsx("div",{style:r,children:u.jsx("div",{style:s})}):u.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[u.jsx("div",{style:{...n,width:"80%"}}),u.jsx("div",{style:{...n,width:"60%"}}),u.jsx("div",{style:{...n,width:"70%"}})]})},Ps=({error:t,onRetry:e})=>{const n={padding:"24px",textAlign:"center",color:"#ef4444"},r={marginBottom:"16px",fontSize:"16px"},s={padding:"12px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},o=typeof t=="string"?t:t.message;return u.jsxs("div",{style:n,children:[u.jsx("div",{style:r,children:o}),e&&u.jsx("button",{style:s,onClick:()=>e(t),children:"重试"})]})},sR=({orientation:t="horizontal",size:e="medium"})=>{const n={background:"#e0e0e0"},r={small:"12px",medium:"16px",large:"20px"};return t==="horizontal"?(n.height="1px",n.width="100%",n.margin=`${r[e]} 0`):(n.width="1px",n.height="100%",n.margin=`0 ${r[e]}`),u.jsx("div",{style:n})},oR=({onSubmit:t,onNext:e,onRetry:n,onAnswerChange:r,value:s})=>{const{problemData:o,scene:i,submissionResult:a,config:l}=XC();if(!o)return u.jsx(Ps,{error:"No problem data provided"});const c=()=>{t&&t()},d=()=>{e&&e(o.problemId)},f=()=>{n&&n(o.problemId)},g=p=>{r&&r(p,o.problemType)},h={background:l?.theme==="dark"?"#1a1a1a":"#ffffff",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",fontFamily:"'Arial', sans-serif",fontSize:"14px",overflow:"hidden",color:l?.theme==="dark"?"#ffffff":"#333333",width:"100%",maxWidth:"800px"},m={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return u.jsxs("div",{style:h,"data-testid":"math-card","data-theme":l?.theme,children:[l?.showBanner!==!1&&u.jsx(Bf,{scene:i,position:l?.bannerPosition,size:l?.bannerSize,color:l?.bannerCustomStyle?.color,bgColor:l?.bannerCustomStyle?.bgColor}),u.jsx(Hf,{question:o.question,problemType:o.problemType}),i==="question"&&u.jsxs(u.Fragment,{children:[u.jsx(Wf,{problemType:o.problemType,options:o.answer.options,value:s,onChange:g,placeholder:l?.inputPlaceholder}),u.jsx("div",{style:m,children:u.jsx(ws,{onClick:c,disabled:!t,children:l?.submitButtonText||"提交答案"})})]}),i==="solve"&&o.explanation&&u.jsx(qf,{steps:o.explanation,title:"官方解析"}),i==="review"&&a&&o.reviewContent&&u.jsx(Yf,{reviewContent:o.reviewContent,userAnswer:a.userAnswer,correctAnswer:o.answer.correctAnswer}),(i==="solve"||i==="review")&&u.jsxs("div",{style:m,children:[e&&u.jsx(ws,{onClick:d,children:l?.nextButtonText||"下一题"}),n&&u.jsx(ws,{onClick:f,children:l?.retryButtonText||"重新作答"})]})]})},Rt=({problemData:t,scene:e,submissionResult:n,loading:r,error:s,config:o,children:i,onSubmit:a,onNext:l,onRetry:c,onErrorRetry:d,onAnswerChange:f,onHintToggle:g,value:h})=>{if(r)return u.jsx(Kf,{type:"skeleton"});if(s)return u.jsx(Ps,{error:s,onRetry:d});if(!t)return u.jsx(Ps,{error:"No problem data provided"});const m={problemData:t,scene:e,submissionResult:n,config:o,value:h};return u.jsx(Gf.Provider,{value:m,children:i||u.jsx(oR,{onSubmit:a,onNext:l,onRetry:c,onAnswerChange:f,onHintToggle:g,value:h})})};Rt.Banner=Bf;Rt.Question=Hf;Rt.AnswerInput=Wf;Rt.SubmitButton=ws;Rt.Explanation=qf;Rt.ReviewContent=Yf;Rt.LoadingState=Kf;Rt.ErrorState=Ps;Rt.Divider=sR;function iR(t){if(t.sheet)return t.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===t)return document.styleSheets[e]}function aR(t){var e=document.createElement("style");return e.setAttribute("data-emotion",t.key),t.nonce!==void 0&&e.setAttribute("nonce",t.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var lR=(function(){function t(n){var r=this;this._insertTag=function(s){var o;r.tags.length===0?r.insertionPoint?o=r.insertionPoint.nextSibling:r.prepend?o=r.container.firstChild:o=r.before:o=r.tags[r.tags.length-1].nextSibling,r.container.insertBefore(s,o),r.tags.push(s)},this.isSpeedy=n.speedy===void 0?!0:n.speedy,this.tags=[],this.ctr=0,this.nonce=n.nonce,this.key=n.key,this.container=n.container,this.prepend=n.prepend,this.insertionPoint=n.insertionPoint,this.before=null}var e=t.prototype;return e.hydrate=function(r){r.forEach(this._insertTag)},e.insert=function(r){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(aR(this));var s=this.tags[this.tags.length-1];if(this.isSpeedy){var o=iR(s);try{o.insertRule(r,o.cssRules.length)}catch{}}else s.appendChild(document.createTextNode(r));this.ctr++},e.flush=function(){this.tags.forEach(function(r){var s;return(s=r.parentNode)==null?void 0:s.removeChild(r)}),this.tags=[],this.ctr=0},t})(),Le="-ms-",Fs="-moz-",le="-webkit-",Xf="comm",ua="rule",fa="decl",cR="@import",Jf="@keyframes",dR="@layer",uR=Math.abs,so=String.fromCharCode,fR=Object.assign;function hR(t,e){return Ie(t,0)^45?(((e<<2^Ie(t,0))<<2^Ie(t,1))<<2^Ie(t,2))<<2^Ie(t,3):0}function Zf(t){return t.trim()}function gR(t,e){return(t=e.exec(t))?t[0]:t}function ce(t,e,n){return t.replace(e,n)}function pi(t,e){return t.indexOf(e)}function Ie(t,e){return t.charCodeAt(e)|0}function wr(t,e,n){return t.slice(e,n)}function xt(t){return t.length}function ha(t){return t.length}function ds(t,e){return e.push(t),t}function mR(t,e){return t.map(e).join("")}var oo=1,Fn=1,Qf=0,Je=0,ke=0,Hn="";function io(t,e,n,r,s,o,i){return{value:t,root:e,parent:n,type:r,props:s,children:o,line:oo,column:Fn,length:i,return:""}}function nr(t,e){return fR(io("",null,null,"",null,null,0),t,{length:-t.length},e)}function pR(){return ke}function yR(){return ke=Je>0?Ie(Hn,--Je):0,Fn--,ke===10&&(Fn=1,oo--),ke}function nt(){return ke=Je<Qf?Ie(Hn,Je++):0,Fn++,ke===10&&(Fn=1,oo++),ke}function Ct(){return Ie(Hn,Je)}function _s(){return Je}function Ir(t,e){return wr(Hn,t,e)}function _r(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function eh(t){return oo=Fn=1,Qf=xt(Hn=t),Je=0,[]}function th(t){return Hn="",t}function Ss(t){return Zf(Ir(Je-1,yi(t===91?t+2:t===40?t+1:t)))}function bR(t){for(;(ke=Ct())&&ke<33;)nt();return _r(t)>2||_r(ke)>3?"":" "}function xR(t,e){for(;--e&&nt()&&!(ke<48||ke>102||ke>57&&ke<65||ke>70&&ke<97););return Ir(t,_s()+(e<6&&Ct()==32&&nt()==32))}function yi(t){for(;nt();)switch(ke){case t:return Je;case 34:case 39:t!==34&&t!==39&&yi(ke);break;case 40:t===41&&yi(t);break;case 92:nt();break}return Je}function vR(t,e){for(;nt()&&t+ke!==57;)if(t+ke===84&&Ct()===47)break;return"/*"+Ir(e,Je-1)+"*"+so(t===47?t:nt())}function wR(t){for(;!_r(Ct());)nt();return Ir(t,Je)}function _R(t){return th(Cs("",null,null,null,[""],t=eh(t),0,[0],t))}function Cs(t,e,n,r,s,o,i,a,l){for(var c=0,d=0,f=i,g=0,h=0,m=0,p=1,y=1,b=1,w=0,v="",S=s,_=o,A=r,C=v;y;)switch(m=w,w=nt()){case 40:if(m!=108&&Ie(C,f-1)==58){pi(C+=ce(Ss(w),"&","&\f"),"&\f")!=-1&&(b=-1);break}case 34:case 39:case 91:C+=Ss(w);break;case 9:case 10:case 13:case 32:C+=bR(m);break;case 92:C+=xR(_s()-1,7);continue;case 47:switch(Ct()){case 42:case 47:ds(SR(vR(nt(),_s()),e,n),l);break;default:C+="/"}break;case 123*p:a[c++]=xt(C)*b;case 125*p:case 59:case 0:switch(w){case 0:case 125:y=0;case 59+d:b==-1&&(C=ce(C,/\f/g,"")),h>0&&xt(C)-f&&ds(h>32?_c(C+";",r,n,f-1):_c(ce(C," ","")+";",r,n,f-2),l);break;case 59:C+=";";default:if(ds(A=wc(C,e,n,c,d,s,a,v,S=[],_=[],f),o),w===123)if(d===0)Cs(C,e,A,A,S,o,f,a,_);else switch(g===99&&Ie(C,3)===110?100:g){case 100:case 108:case 109:case 115:Cs(t,A,A,r&&ds(wc(t,A,A,0,0,s,a,v,s,S=[],f),_),s,_,f,a,r?S:_);break;default:Cs(C,A,A,A,[""],_,0,a,_)}}c=d=h=0,p=b=1,v=C="",f=i;break;case 58:f=1+xt(C),h=m;default:if(p<1){if(w==123)--p;else if(w==125&&p++==0&&yR()==125)continue}switch(C+=so(w),w*p){case 38:b=d>0?1:(C+="\f",-1);break;case 44:a[c++]=(xt(C)-1)*b,b=1;break;case 64:Ct()===45&&(C+=Ss(nt())),g=Ct(),d=f=xt(v=C+=wR(_s())),w++;break;case 45:m===45&&xt(C)==2&&(p=0)}}return o}function wc(t,e,n,r,s,o,i,a,l,c,d){for(var f=s-1,g=s===0?o:[""],h=ha(g),m=0,p=0,y=0;m<r;++m)for(var b=0,w=wr(t,f+1,f=uR(p=i[m])),v=t;b<h;++b)(v=Zf(p>0?g[b]+" "+w:ce(w,/&\f/g,g[b])))&&(l[y++]=v);return io(t,e,n,s===0?ua:a,l,c,d)}function SR(t,e,n){return io(t,e,n,Xf,so(pR()),wr(t,2,-2),0)}function _c(t,e,n,r){return io(t,e,n,fa,wr(t,0,r),wr(t,r+1,-1),r)}function Tn(t,e){for(var n="",r=ha(t),s=0;s<r;s++)n+=e(t[s],s,t,e)||"";return n}function CR(t,e,n,r){switch(t.type){case dR:if(t.children.length)break;case cR:case fa:return t.return=t.return||t.value;case Xf:return"";case Jf:return t.return=t.value+"{"+Tn(t.children,r)+"}";case ua:t.value=t.props.join(",")}return xt(n=Tn(t.children,r))?t.return=t.value+"{"+n+"}":""}function RR(t){var e=ha(t);return function(n,r,s,o){for(var i="",a=0;a<e;a++)i+=t[a](n,r,s,o)||"";return i}}function AR(t){return function(e){e.root||(e=e.return)&&t(e)}}function NR(t){var e=Object.create(null);return function(n){return e[n]===void 0&&(e[n]=t(n)),e[n]}}var ER=function(e,n,r){for(var s=0,o=0;s=o,o=Ct(),s===38&&o===12&&(n[r]=1),!_r(o);)nt();return Ir(e,Je)},kR=function(e,n){var r=-1,s=44;do switch(_r(s)){case 0:s===38&&Ct()===12&&(n[r]=1),e[r]+=ER(Je-1,n,r);break;case 2:e[r]+=Ss(s);break;case 4:if(s===44){e[++r]=Ct()===58?"&\f":"",n[r]=e[r].length;break}default:e[r]+=so(s)}while(s=nt());return e},TR=function(e,n){return th(kR(eh(e),n))},Sc=new WeakMap,MR=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var n=e.value,r=e.parent,s=e.column===r.column&&e.line===r.line;r.type!=="rule";)if(r=r.parent,!r)return;if(!(e.props.length===1&&n.charCodeAt(0)!==58&&!Sc.get(r))&&!s){Sc.set(e,!0);for(var o=[],i=TR(n,o),a=r.props,l=0,c=0;l<i.length;l++)for(var d=0;d<a.length;d++,c++)e.props[c]=o[l]?i[l].replace(/&\f/g,a[d]):a[d]+" "+i[l]}}},jR=function(e){if(e.type==="decl"){var n=e.value;n.charCodeAt(0)===108&&n.charCodeAt(2)===98&&(e.return="",e.value="")}};function nh(t,e){switch(hR(t,e)){case 5103:return le+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return le+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return le+t+Fs+t+Le+t+t;case 6828:case 4268:return le+t+Le+t+t;case 6165:return le+t+Le+"flex-"+t+t;case 5187:return le+t+ce(t,/(\w+).+(:[^]+)/,le+"box-$1$2"+Le+"flex-$1$2")+t;case 5443:return le+t+Le+"flex-item-"+ce(t,/flex-|-self/,"")+t;case 4675:return le+t+Le+"flex-line-pack"+ce(t,/align-content|flex-|-self/,"")+t;case 5548:return le+t+Le+ce(t,"shrink","negative")+t;case 5292:return le+t+Le+ce(t,"basis","preferred-size")+t;case 6060:return le+"box-"+ce(t,"-grow","")+le+t+Le+ce(t,"grow","positive")+t;case 4554:return le+ce(t,/([^-])(transform)/g,"$1"+le+"$2")+t;case 6187:return ce(ce(ce(t,/(zoom-|grab)/,le+"$1"),/(image-set)/,le+"$1"),t,"")+t;case 5495:case 3959:return ce(t,/(image-set\([^]*)/,le+"$1$`$1");case 4968:return ce(ce(t,/(.+:)(flex-)?(.*)/,le+"box-pack:$3"+Le+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+le+t+t;case 4095:case 3583:case 4068:case 2532:return ce(t,/(.+)-inline(.+)/,le+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(xt(t)-1-e>6)switch(Ie(t,e+1)){case 109:if(Ie(t,e+4)!==45)break;case 102:return ce(t,/(.+:)(.+)-([^]+)/,"$1"+le+"$2-$3$1"+Fs+(Ie(t,e+3)==108?"$3":"$2-$3"))+t;case 115:return~pi(t,"stretch")?nh(ce(t,"stretch","fill-available"),e)+t:t}break;case 4949:if(Ie(t,e+1)!==115)break;case 6444:switch(Ie(t,xt(t)-3-(~pi(t,"!important")&&10))){case 107:return ce(t,":",":"+le)+t;case 101:return ce(t,/(.+:)([^;!]+)(;|!.+)?/,"$1"+le+(Ie(t,14)===45?"inline-":"")+"box$3$1"+le+"$2$3$1"+Le+"$2box$3")+t}break;case 5936:switch(Ie(t,e+11)){case 114:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return le+t+Le+ce(t,/[svh]\w+-[tblr]{2}/,"lr")+t}return le+t+Le+t+t}return t}var $R=function(e,n,r,s){if(e.length>-1&&!e.return)switch(e.type){case fa:e.return=nh(e.value,e.length);break;case Jf:return Tn([nr(e,{value:ce(e.value,"@","@"+le)})],s);case ua:if(e.length)return mR(e.props,function(o){switch(gR(o,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Tn([nr(e,{props:[ce(o,/:(read-\w+)/,":"+Fs+"$1")]})],s);case"::placeholder":return Tn([nr(e,{props:[ce(o,/:(plac\w+)/,":"+le+"input-$1")]}),nr(e,{props:[ce(o,/:(plac\w+)/,":"+Fs+"$1")]}),nr(e,{props:[ce(o,/:(plac\w+)/,Le+"input-$1")]})],s)}return""})}},OR=[$R],IR=function(e){var n=e.key;if(n==="css"){var r=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(r,function(p){var y=p.getAttribute("data-emotion");y.indexOf(" ")!==-1&&(document.head.appendChild(p),p.setAttribute("data-s",""))})}var s=e.stylisPlugins||OR,o={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+n+' "]'),function(p){for(var y=p.getAttribute("data-emotion").split(" "),b=1;b<y.length;b++)o[y[b]]=!0;a.push(p)});var l,c=[MR,jR];{var d,f=[CR,AR(function(p){d.insert(p)})],g=RR(c.concat(s,f)),h=function(y){return Tn(_R(y),g)};l=function(y,b,w,v){d=w,h(y?y+"{"+b.styles+"}":b.styles),v&&(m.inserted[b.name]=!0)}}var m={key:n,sheet:new lR({key:n,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:o,registered:{},insert:l};return m.sheet.hydrate(a),m},us={exports:{}},ue={};var Cc;function PR(){if(Cc)return ue;Cc=1;var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,n=t?Symbol.for("react.portal"):60106,r=t?Symbol.for("react.fragment"):60107,s=t?Symbol.for("react.strict_mode"):60108,o=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,l=t?Symbol.for("react.async_mode"):60111,c=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,f=t?Symbol.for("react.suspense"):60113,g=t?Symbol.for("react.suspense_list"):60120,h=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,p=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,w=t?Symbol.for("react.scope"):60119;function v(_){if(typeof _=="object"&&_!==null){var A=_.$$typeof;switch(A){case e:switch(_=_.type,_){case l:case c:case r:case o:case s:case f:return _;default:switch(_=_&&_.$$typeof,_){case a:case d:case m:case h:case i:return _;default:return A}}case n:return A}}}function S(_){return v(_)===c}return ue.AsyncMode=l,ue.ConcurrentMode=c,ue.ContextConsumer=a,ue.ContextProvider=i,ue.Element=e,ue.ForwardRef=d,ue.Fragment=r,ue.Lazy=m,ue.Memo=h,ue.Portal=n,ue.Profiler=o,ue.StrictMode=s,ue.Suspense=f,ue.isAsyncMode=function(_){return S(_)||v(_)===l},ue.isConcurrentMode=S,ue.isContextConsumer=function(_){return v(_)===a},ue.isContextProvider=function(_){return v(_)===i},ue.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},ue.isForwardRef=function(_){return v(_)===d},ue.isFragment=function(_){return v(_)===r},ue.isLazy=function(_){return v(_)===m},ue.isMemo=function(_){return v(_)===h},ue.isPortal=function(_){return v(_)===n},ue.isProfiler=function(_){return v(_)===o},ue.isStrictMode=function(_){return v(_)===s},ue.isSuspense=function(_){return v(_)===f},ue.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===r||_===c||_===o||_===s||_===f||_===g||typeof _=="object"&&_!==null&&(_.$$typeof===m||_.$$typeof===h||_.$$typeof===i||_.$$typeof===a||_.$$typeof===d||_.$$typeof===y||_.$$typeof===b||_.$$typeof===w||_.$$typeof===p)},ue.typeOf=v,ue}var fe={};var Rc;function FR(){return Rc||(Rc=1,process.env.NODE_ENV!=="production"&&(function(){var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,n=t?Symbol.for("react.portal"):60106,r=t?Symbol.for("react.fragment"):60107,s=t?Symbol.for("react.strict_mode"):60108,o=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,l=t?Symbol.for("react.async_mode"):60111,c=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,f=t?Symbol.for("react.suspense"):60113,g=t?Symbol.for("react.suspense_list"):60120,h=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,p=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,w=t?Symbol.for("react.scope"):60119;function v(k){return typeof k=="string"||typeof k=="function"||k===r||k===c||k===o||k===s||k===f||k===g||typeof k=="object"&&k!==null&&(k.$$typeof===m||k.$$typeof===h||k.$$typeof===i||k.$$typeof===a||k.$$typeof===d||k.$$typeof===y||k.$$typeof===b||k.$$typeof===w||k.$$typeof===p)}function S(k){if(typeof k=="object"&&k!==null){var de=k.$$typeof;switch(de){case e:var ye=k.type;switch(ye){case l:case c:case r:case o:case s:case f:return ye;default:var W=ye&&ye.$$typeof;switch(W){case a:case d:case m:case h:case i:return W;default:return de}}case n:return de}}}var _=l,A=c,C=a,R=i,N=e,M=d,F=r,D=m,P=h,$=n,O=o,T=s,B=f,j=!1;function Q(k){return j||(j=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),oe(k)||S(k)===l}function oe(k){return S(k)===c}function se(k){return S(k)===a}function ee(k){return S(k)===i}function L(k){return typeof k=="object"&&k!==null&&k.$$typeof===e}function X(k){return S(k)===d}function ae(k){return S(k)===r}function ve(k){return S(k)===m}function me(k){return S(k)===h}function Ft(k){return S(k)===n}function At(k){return S(k)===o}function z(k){return S(k)===s}function I(k){return S(k)===f}fe.AsyncMode=_,fe.ConcurrentMode=A,fe.ContextConsumer=C,fe.ContextProvider=R,fe.Element=N,fe.ForwardRef=M,fe.Fragment=F,fe.Lazy=D,fe.Memo=P,fe.Portal=$,fe.Profiler=O,fe.StrictMode=T,fe.Suspense=B,fe.isAsyncMode=Q,fe.isConcurrentMode=oe,fe.isContextConsumer=se,fe.isContextProvider=ee,fe.isElement=L,fe.isForwardRef=X,fe.isFragment=ae,fe.isLazy=ve,fe.isMemo=me,fe.isPortal=Ft,fe.isProfiler=At,fe.isStrictMode=z,fe.isSuspense=I,fe.isValidElementType=v,fe.typeOf=S})()),fe}var Ac;function DR(){return Ac||(Ac=1,process.env.NODE_ENV==="production"?us.exports=PR():us.exports=FR()),us.exports}var zo,Nc;function LR(){if(Nc)return zo;Nc=1;var t=DR(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},r={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},o={};o[t.ForwardRef]=r,o[t.Memo]=s;function i(m){return t.isMemo(m)?s:o[m.$$typeof]||e}var a=Object.defineProperty,l=Object.getOwnPropertyNames,c=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,f=Object.getPrototypeOf,g=Object.prototype;function h(m,p,y){if(typeof p!="string"){if(g){var b=f(p);b&&b!==g&&h(m,b,y)}var w=l(p);c&&(w=w.concat(c(p)));for(var v=i(m),S=i(p),_=0;_<w.length;++_){var A=w[_];if(!n[A]&&!(y&&y[A])&&!(S&&S[A])&&!(v&&v[A])){var C=d(p,A);try{a(m,A,C)}catch{}}}}return m}return zo=h,zo}LR();var zR=!0;function VR(t,e,n){var r="";return n.split(" ").forEach(function(s){t[s]!==void 0?e.push(t[s]+";"):s&&(r+=s+" ")}),r}var rh=function(e,n,r){var s=e.key+"-"+n.name;(r===!1||zR===!1)&&e.registered[s]===void 0&&(e.registered[s]=n.styles)},GR=function(e,n,r){rh(e,n,r);var s=e.key+"-"+n.name;if(e.inserted[n.name]===void 0){var o=n;do e.insert(n===o?"."+s:"",o,e.sheet,!0),o=o.next;while(o!==void 0)}};function UR(t){for(var e=0,n,r=0,s=t.length;s>=4;++r,s-=4)n=t.charCodeAt(r)&255|(t.charCodeAt(++r)&255)<<8|(t.charCodeAt(++r)&255)<<16|(t.charCodeAt(++r)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,e=(n&65535)*1540483477+((n>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(s){case 3:e^=(t.charCodeAt(r+2)&255)<<16;case 2:e^=(t.charCodeAt(r+1)&255)<<8;case 1:e^=t.charCodeAt(r)&255,e=(e&65535)*1540483477+((e>>>16)*59797<<16)}return e^=e>>>13,e=(e&65535)*1540483477+((e>>>16)*59797<<16),((e^e>>>15)>>>0).toString(36)}var BR={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},HR=/[A-Z]|^ms/g,WR=/_EMO_([^_]+?)_([^]*?)_EMO_/g,sh=function(e){return e.charCodeAt(1)===45},Ec=function(e){return e!=null&&typeof e!="boolean"},Vo=NR(function(t){return sh(t)?t:t.replace(HR,"-$&").toLowerCase()}),kc=function(e,n){switch(e){case"animation":case"animationName":if(typeof n=="string")return n.replace(WR,function(r,s,o){return vt={name:s,styles:o,next:vt},s})}return BR[e]!==1&&!sh(e)&&typeof n=="number"&&n!==0?n+"px":n};function Sr(t,e,n){if(n==null)return"";var r=n;if(r.__emotion_styles!==void 0)return r;switch(typeof n){case"boolean":return"";case"object":{var s=n;if(s.anim===1)return vt={name:s.name,styles:s.styles,next:vt},s.name;var o=n;if(o.styles!==void 0){var i=o.next;if(i!==void 0)for(;i!==void 0;)vt={name:i.name,styles:i.styles,next:vt},i=i.next;var a=o.styles+";";return a}return qR(t,e,n)}case"function":{if(t!==void 0){var l=vt,c=n(t);return vt=l,Sr(t,e,c)}break}}var d=n;return d}function qR(t,e,n){var r="";if(Array.isArray(n))for(var s=0;s<n.length;s++)r+=Sr(t,e,n[s])+";";else for(var o in n){var i=n[o];if(typeof i!="object"){var a=i;Ec(a)&&(r+=Vo(o)+":"+kc(o,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var l=0;l<i.length;l++)Ec(i[l])&&(r+=Vo(o)+":"+kc(o,i[l])+";");else{var c=Sr(t,e,i);switch(o){case"animation":case"animationName":{r+=Vo(o)+":"+c+";";break}default:r+=o+"{"+c+"}"}}}return r}var Tc=/label:\s*([^\s;{]+)\s*(;|$)/g,vt;function oh(t,e,n){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null&&t[0].styles!==void 0)return t[0];var r=!0,s="";vt=void 0;var o=t[0];if(o==null||o.raw===void 0)r=!1,s+=Sr(n,e,o);else{var i=o;s+=i[0]}for(var a=1;a<t.length;a++)if(s+=Sr(n,e,t[a]),r){var l=o;s+=l[a]}Tc.lastIndex=0;for(var c="",d;(d=Tc.exec(s))!==null;)c+="-"+d[1];var f=UR(s)+c;return{name:f,styles:s,next:vt}}var YR=function(e){return e()},KR=et.useInsertionEffect?et.useInsertionEffect:!1,XR=KR||YR,ih=et.createContext(typeof HTMLElement<"u"?IR({key:"css"}):null);ih.Provider;var JR=function(e){return x.forwardRef(function(n,r){var s=x.useContext(ih);return e(n,s,r)})},ZR=et.createContext({}),ga={}.hasOwnProperty,bi="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",QR=function(e,n){var r={};for(var s in n)ga.call(n,s)&&(r[s]=n[s]);return r[bi]=e,r},eA=function(e){var n=e.cache,r=e.serialized,s=e.isStringTag;return rh(n,r,s),XR(function(){return GR(n,r,s)}),null},tA=JR(function(t,e,n){var r=t.css;typeof r=="string"&&e.registered[r]!==void 0&&(r=e.registered[r]);var s=t[bi],o=[r],i="";typeof t.className=="string"?i=VR(e.registered,o,t.className):t.className!=null&&(i=t.className+" ");var a=oh(o,void 0,et.useContext(ZR));i+=e.key+"-"+a.name;var l={};for(var c in t)ga.call(t,c)&&c!=="css"&&c!==bi&&(l[c]=t[c]);return l.className=i,n&&(l.ref=n),et.createElement(et.Fragment,null,et.createElement(eA,{cache:e,serialized:a,isStringTag:typeof s=="string"}),et.createElement(s,l))}),nA=tA,Mc=function(e,n){var r=arguments;if(n==null||!ga.call(n,"css"))return et.createElement.apply(void 0,r);var s=r.length,o=new Array(s);o[0]=nA,o[1]=QR(e,n);for(var i=2;i<s;i++)o[i]=r[i];return et.createElement.apply(null,o)};(function(t){var e;e||(e=t.JSX||(t.JSX={}))})(Mc||(Mc={}));function _e(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return oh(e)}const V={colors:{text:{light:"#ffffff"},background:{card:"#ffffff",feedbackCorrect:"#f0fdf4",feedbackIncorrect:"#fef2f2"},border:{default:"#e0e0e0"},scene:{solve:"#4a6cf7",review:"#4ade80",question:"#f97316"}},typography:{fontFamily:"'Arial', sans-serif",fontSizeBase:"14px",fontSizeLarge:"16px",fontSizeSmall:"12px"},spacing:{sm:"12px",md:"16px",lg:"20px",xl:"24px"},borderRadius:{card:"8px",button:"6px",input:"4px"},shadows:{card:"0 2px 8px rgba(0,0,0,0.1)"}};_e`
87
120
  background: ${V.colors.background.card};
88
121
  border-radius: ${V.borderRadius.card};
89
122
  box-shadow: ${V.shadows.card};
@@ -279,41 +312,8 @@ ${new Error().stack?.split(`
279
312
  &[data-size="large"] {
280
313
  margin: 0 ${V.spacing.lg};
281
314
  }
282
- `;const gw="/api/v1/content",mw="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",pw=10,Lt="question",Ce=Dn.create()(Th.devtools((t,e)=>({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:"question",userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1,loadQuestions:async(n,r)=>{t({loading:!0,sessionId:n});try{const{gradeLevel:s,unitId:o,lessonId:i,count:a=pw}=r,l=`${gw}/grades/${s}/units/${o}/lessons/${i}/sessions/${n}/questions`,c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${mw}`},body:JSON.stringify({count:a})});if(!c.ok)throw new Error(`Failed to load questions: ${c.status} ${c.statusText}`);const f=(await c.json()).questions||[],g={};f.forEach(h=>{h.geometryShapes&&Array.isArray(h.geometryShapes)&&(g[h.problemId]=h.geometryShapes)}),t({problems:f,totalProblems:f.length,currentProblemIndex:0,currentScene:Lt,geometryShapes:g,loading:!1,error:null,startTime:Date.now()})}catch(s){const o=s instanceof Error?s.message:"Unknown error occurred";throw t({error:o,loading:!1}),s}},goToNextProblem:()=>{const{currentProblemIndex:n,problems:r,currentScene:s}=e();if(s!==Lt){console.warn("Cannot navigate during review/solve scene");return}n<r.length-1?t({currentProblemIndex:n+1,currentScene:Lt}):t({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:n,currentScene:r}=e();r===Lt&&n>0&&t({currentProblemIndex:n-1,currentScene:Lt})},goToProblem:n=>{const{problems:r,currentScene:s}=e();s===Lt&&(n<0||n>=r.length||t({currentProblemIndex:n,currentScene:Lt}))},switchScene:n=>{t({currentScene:n})},submitAnswer:async(n,r)=>{const{problems:s,currentProblemIndex:o}=e(),i=s[o];t({loading:!0});try{const a=i?.answer.correctAnswer||[],l=r.length>0&&r[0]===a[0],c={userAnswer:r,isCorrect:l,feedback:l?"🎉 Great job! Your answer is correct!":"❌ Sorry, that's not correct."};t(d=>({userAnswers:{...d.userAnswers,[n]:r},submissionResults:{...d.submissionResults,[n]:c},loading:!1,currentScene:l?"review":"solve"}))}catch(a){t({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(n,r)=>{t(s=>({userAnswers:{...s.userAnswers,[n]:r}}))},updateShape:(n,r,s)=>{t(o=>{const a=(o.geometryShapes[n]||[]).map(l=>l.id===r&&l.type==="point"?{...l,position:s}:l);return{geometryShapes:{...o.geometryShapes,[n]:a}}})},selectShape:(n,r)=>{t({selectedShapeId:r})},setGeometryMode:(n,r)=>{t({geometryMode:r})},startTimer:()=>{t({startTime:Date.now()})},stopTimer:()=>{const{startTime:n}=e();if(n){const r=Math.floor((Date.now()-n)/1e3);t(s=>({timeSpent:s.timeSpent+r,startTime:null}))}},reset:()=>{t({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:Lt,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:n,currentProblemIndex:r}=e();return n[r]||null},getProgress:()=>{const{currentProblemIndex:n,totalProblems:r}=e();return{current:n+1,total:r,percentage:r>0?(n+1)/r*100:0}},getSessionResults:()=>{const{sessionId:n,problems:r,submissionResults:s,timeSpent:o}=e(),i=r.map(l=>({problemId:l.problemId,userAnswer:s[l.problemId]?.userAnswer||[],isCorrect:s[l.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(l=>l.isCorrect).length;return{sessionId:n||"",totalProblems:r.length,correctAnswers:a,accuracy:r.length>0?a/r.length:0,timeSpent:o,averageTime:r.length>0?o/r.length:0,answers:i}}}),{name:"MathSessionStore"})),af=(t,e,n,r,s,o,i)=>{const a=x.useMemo(()=>n==="question",[n]),l=x.useMemo(()=>t<e.length-1,[t,e.length]),c=x.useMemo(()=>t>0,[t]),d=x.useMemo(()=>!r||!s?!1:r.problemType?.includes("geometry")||o&&o[s]&&o[s].length>0?!0:i?.enableMathGraph!==void 0?i.enableMathGraph:!1,[r,s,o,i?.enableMathGraph]);return{canNavigate:a,canGoNext:l,canGoPrevious:c,shouldRenderMathGraph:d}},lf=(t,e,n,r,s)=>{const o=Ce(d=>d.selectShape),i=Ce(d=>d.setGeometryMode),a=x.useMemo(()=>!e||!r?[]:r[e]||[],[r,e]);x.useEffect(()=>{if(!e||!n)return;let d="view";switch(t){case"question":d="edit";break;case"solve":case"review":d="view";break;default:d="view"}s!==d&&i(e,d)},[t,e,s,i,n]);const l=x.useCallback(d=>{e&&Ce.setState(f=>({geometryShapes:{...f.geometryShapes,[e]:d}}))},[e]),c=x.useCallback(d=>{if(e){const f=d.length>0?d[0]:null;o(e,f)}},[e,o]);return{currentGeometryShapes:a,geometryMode:s,handleShapeChange:l,handleSelectionChange:c}},cf=(t,e,n)=>{const r=Ce(h=>h.updateUserAnswer),s=Ce(h=>h.submitAnswer),o=Ce(h=>h.goToNextProblem),i=Ce(h=>h.goToPreviousProblem),a=Ce(h=>h.goToProblem),l=x.useCallback(h=>{t&&r(t,h)},[t,r]),c=x.useCallback(()=>{t&&n[t]&&s(t,n[t])},[t,n,s]),d=x.useCallback(h=>{o(),h?.(t,e+1)},[o,t,e]),f=x.useCallback(h=>{i(),h?.(t,e-1)},[i,t,e]),g=x.useCallback((h,m)=>{a(h-1),m?.(t,h-1)},[a,t]);return{handleAnswerChange:l,handleSubmit:c,handleNext:d,handlePrevious:f,handlePagination:g}},df=({config:t={},onSessionComplete:e,onSessionExit:n,onProblemChange:r,className:s="",style:o})=>{const i=Ce(T=>T.problems),a=Ce(T=>T.currentProblemIndex),l=Ce(T=>T.currentScene),c=Ce(T=>T.loading),d=Ce(T=>T.error),f=Ce(T=>T.sessionComplete),g=Ce(T=>T.submissionResults),h=Ce(T=>T.userAnswers),m=Ce(T=>T.geometryShapes),p=Ce(T=>T.geometryMode),y=Ce(T=>T.getSessionResults),b=x.useMemo(()=>i[a]??null,[i,a]),w=x.useMemo(()=>b?.problemId??"",[b]),{canNavigate:v,canGoNext:S,canGoPrevious:_,shouldRenderMathGraph:A}=af(a,i,l,b,w,m,t),{currentGeometryShapes:C,handleShapeChange:R,handleSelectionChange:k}=lf(l,w,A,m,p),{handleAnswerChange:M,handleSubmit:F,handleNext:D,handlePrevious:P,handlePagination:j}=cf(w,a,h);x.useEffect(()=>{if(f&&typeof y=="function"){const T=y();e?.(T)}},[f,y,e]);const O=T=>typeof T=="string"?T:T instanceof Error?T.message:String(T);return c&&i.length===0?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:u.jsxs("div",{className:"text-center",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),u.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):d&&d!==null?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:u.jsxs("div",{className:"text-center text-red-600",children:[u.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),u.jsx("p",{children:O(d)})]})}):b?u.jsxs("div",{className:`flex flex-col max-w-4xl mx-auto p-6 ${s}`,style:o,"data-testid":"math-session-container",role:"region","aria-label":"数学练习会话",children:[u.jsx("div",{className:"mb-6",children:u.jsx(H.Pagination,{total:i.length,page:a+1,onChange:T=>j(T,r),isDisabled:!v,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),u.jsx(Rt,{problemData:b,scene:l,submissionResult:g[w],loading:c,error:d?O(d):void 0,value:h[w],onAnswerChange:M,onSubmit:F,onNext:()=>D(r),config:{theme:t.theme??"light",submitButtonText:"提交答案",nextButtonText:l==="solve"?"Got it!":"下一题",showHints:t.enableHints}}),A&&u.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:u.jsx(Nr,{shapes:C,mode:p,onShapeChange:R,onSelectionChange:k,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),t.showProgress&&u.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[u.jsx("button",{onClick:()=>P(r),disabled:!_,className:"px-4 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"上一题"}),u.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),u.jsx("button",{onClick:()=>D(r),disabled:!S||!v,className:"px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"下一题"})]}),n&&u.jsx("div",{className:"mt-4 flex justify-center",children:u.jsx("button",{onClick:n,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:u.jsx("p",{className:"text-gray-600",children:"No problems available"})})},yw=({sessionId:t,gradeId:e,unitId:n,lessonId:r,userId:s,config:o={},className:i="",onSessionComplete:a,onSessionExit:l})=>{const[c,d]=x.useState({loading:!1,error:null,initialized:!1}),[f,g]=x.useState(0),[h,m]=x.useState(""),p=x.useRef(null),y=x.useRef(null),b=x.useRef(null),w=Ce(R=>R.loadQuestions),v=Ce(R=>R.reset);x.useEffect(()=>{const R=async()=>{try{d(k=>({...k,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:t,gradeId:e,unitId:n,lessonId:r,userId:s}),await w(t,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:n,lessonId:r,count:o.questionCount||10}),d(k=>({...k,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch(k){const M=k instanceof Error?k.message:"Failed to initialize session";d(F=>({...F,loading:!1,error:M,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",k)}};t&&e&&n&&r&&!c.initialized&&R()},[t,e,n,r,w,o.questionCount,c.initialized,f]),x.useEffect(()=>{c.loading&&!c.initialized?m("正在加载数学练习内容,请稍候..."):c.error?m(`加载失败:${c.error},请点击重试按钮重新加载`):c.initialized&&m("数学练习内容已加载完成,可以开始练习")},[c.loading,c.error,c.initialized]),x.useEffect(()=>{c.initialized&&p.current&&p.current.focus()},[c.initialized]),x.useEffect(()=>{c.error&&b.current&&b.current.focus()},[c.error]),x.useEffect(()=>{c.loading&&y.current&&y.current.focus()},[c.loading]),x.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),v()},[v]);const S=x.useCallback(R=>{console.log("🎉 MathSessionPage: 会话完成",R),a?.(R)},[a]),_=x.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),l?.()},[l]),A=x.useCallback((R,k)=>{console.log(`📝 MathSessionPage: 切换到题目 ${k+1}`,R)},[]),C=x.useCallback(R=>{R.key==="Escape"&&(R.preventDefault(),_()),R.key==="Enter"&&c.error&&R.target===b.current&&(R.preventDefault(),d({loading:!1,error:null,initialized:!1}),g(k=>k+1))},[_,c.error]);return c.loading&&!c.initialized?u.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:C,tabIndex:-1,ref:y,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:h}),u.jsx("div",{className:"page-loading-container",children:u.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[u.jsx("div",{className:"spinner","aria-hidden":"true"}),u.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):c.error?u.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:C,tabIndex:-1,ref:b,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:h}),u.jsxs("div",{className:"error-container",children:[u.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),u.jsx("h3",{className:"error-title",children:"加载失败"}),u.jsx("p",{className:"error-message",children:c.error}),u.jsx(Pt,{onClick:()=>{d({loading:!1,error:null,initialized:!1}),g(R=>R+1)},intent:"retry",useNewClassName:!0,className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):u.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:C,children:[u.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:h}),o.layout?.showHeader&&u.jsx("header",{className:"page-header",role:"banner",children:u.jsxs("div",{className:"header-content",children:[u.jsx("h1",{className:"page-title",children:"数学练习"}),u.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[u.jsxs("span",{className:"session-id",children:["会话: ",t]}),u.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),u.jsx("main",{className:"page-main",ref:p,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:u.jsx(df,{config:{showProgress:o.showProgress??!0,enableHints:o.enableHints??!1,autoAdvance:o.autoAdvance??!1,theme:o.theme??"light"},onSessionComplete:S,onSessionExit:_,onProblemChange:A})}),o.layout?.showFooter&&u.jsx("footer",{className:"page-footer",role:"contentinfo",children:u.jsx("div",{className:"footer-content",children:u.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},bw=x.memo(yw),xw=({problemData:t,userAnswer:e,onNextQuestion:n})=>u.jsxs("div",{children:[u.jsxs("div",{className:"decimal-error-banner",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),u.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",u.jsx("strong",{children:t.answer.value})]})]}),u.jsx("button",{onClick:n,className:"decimal-understand-button",children:"明白了"})]}),u.jsxs("div",{className:"decimal-content-area",children:[u.jsx(qi,{problemData:t,userAnswer:e}),u.jsx(Yi,{problemData:t})]}),u.jsx("div",{className:"decimal-bottom-area",children:u.jsx("button",{onClick:n,className:"decimal-bottom-button",children:"明白了"})})]}),vw="rectangle-area-003",ww="矩形面积计算问题",_w=5,Sw="几何与测量",Cw="计算矩形的面积,理解面积公式 A = l × w 的应用",Rw={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},Aw=[{type:"text",content:"What is the area of this rectangle?"}],kw={question:{content:[{type:"text",content:"What is the area of this rectangle?",style:{fontSize:"1.5rem",color:"#1e293b"}},{type:"graph",content:"矩形图形",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2,name:"矩形"},{id:"lengthLabel",type:"text",position:{x:4.5,y:0},content:"7 yd",color:"#475569",fontSize:16},{id:"widthLabel",type:"text",position:{x:9,y:3.5},content:"5 yd",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}]},solve:{content:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"1. 观察矩形:长度是 7 码,宽度是 5 码",style:{marginTop:"8px"}},{type:"formula",content:"A = l × w",parts:["A = l \\times w"]},{type:"formula",content:"= 7 × 5",parts:["= 7 \\times 5"]},{type:"formula",content:"= 35",parts:["= 35"]},{type:"text",content:"长度和宽度以码为单位,所以面积以平方码为单位",style:{marginTop:"8px"}},{type:"text",content:"最终答案:矩形的面积是 35 平方码",style:{marginTop:"8px",fontWeight:"bold"}}]},review:{content:[{type:"text",content:"核心概念回顾:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"矩形面积公式:A = l × w",style:{marginTop:"8px"}},{type:"text",content:"其中 l 是长度,w 是宽度",style:{color:"#64748b"}}]}},Ew=[{id:"exp-step-1",type:"instructionalStep",content:{title:"步骤1:识别矩形的尺寸",description:"观察图形,确定矩形的长度和宽度,并理解尺寸的单位。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"lengthLabel",type:"text",position:{x:4.5,y:0},content:"长度:7 码",color:"#475569",fontSize:14},{id:"widthLabel",type:"text",position:{x:9,y:3.5},content:"宽度:5 码",color:"#475569",fontSize:14}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-2",type:"instructionalStep",content:{title:"步骤2:回忆矩形面积公式",description:"复习矩形面积的基本公式:面积 = 长度 × 宽度。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"formulaLabel",type:"text",position:{x:5,y:7},content:"面积公式:A = l × w",color:"#10B981",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-3",type:"instructionalStep",content:{title:"步骤3:代入数值计算",description:"将已知的长度和宽度代入公式进行计算。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"calculationLabel",type:"text",position:{x:5,y:7},content:"A = 7 × 5 = 35",color:"#F59E0B",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-4",type:"instructionalStep",content:{title:"步骤4:确定面积单位",description:"根据长度和宽度的单位确定面积的单位。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"unitLabel",type:"text",position:{x:5,y:7},content:"长度:码,宽度:码 → 面积:平方码",color:"#8B5CF6",fontSize:14},{id:"finalAnswer",type:"text",position:{x:5,y:7.5},content:"最终答案:35 平方码",color:"#10B981",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}}],Nw={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},Tw={type:"card",padding:"20px"},Mw={id:vw,title:ww,grade:_w,unit:Sw,description:Cw,basicInfo:Rw,content:Aw,scenes:kw,explanation:Ew,answer:Nw,layout:Tw},$w=({className:t=""})=>{const e=Ui(),n=Bi(),r=Hi(),{updateUserAnswer:s,submitAnswer:o,nextQuestion:i}=Wi(),a=c=>{if(!c)return c;const d=JSON.parse(JSON.stringify(c));return d.lesson||(d.lesson="面积计算"),d.skill||(d.skill="面积公式应用"),d.objective||(d.objective="掌握面积计算方法"),(!d.knowledgePoints||!Array.isArray(d.knowledgePoints))&&(d.knowledgePoints=["面积公式","几何变换"]),d.difficulty||(d.difficulty=2),d.metadata||(d.metadata={topic:"几何",skill:"面积计算",tags:["面积","公式"]}),["question","solve","review","remember"].forEach(g=>{if(d.scenes?.[g]){const h=d.scenes[g];!h.items&&h.content&&(h.items=h.content),Array.isArray(h.items)||(h.items=[])}}),d},l=x.useMemo(()=>a(Mw),[]);return u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[l.grade,"年级 - ",l.unit]})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&u.jsx(xn,{problemData:l,userAnswer:n,showAnswerForm:r,onAnswerSubmit:o,onAnswerChange:s}),e==="explanation"&&u.jsx(Un,{problemData:l,userAnswer:n,onNextQuestion:i}),e==="success"&&u.jsx(vn,{problemData:l,onNextQuestion:i})]})]})},Hn=Dn.create(t=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{t({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{const n=typeof e=="string"?e:JSON.stringify(e);t({userAnswer:n,validationError:null})},submitAnswer:e=>{const n=Hn.getState();if(!n.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}const r=n.problemData.answer.value.toString(),s=typeof e=="string"?e:JSON.stringify(e),o=s.trim(),i=r.trim();let a=!1;(o===i||o===".12"&&i==="0.12"||o==="0,12"&&i==="0.12")&&(a=!0),t({userAnswer:s,isCorrect:a,showAnswerForm:!1,validationError:null,currentScene:a?"success":"explanation"})},updateChoiceAnswer:e=>{t({userAnswer:e,validationError:null})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),uf=()=>Hn(t=>t.currentScene),ff=()=>Hn(t=>t.userAnswer),hf=()=>Hn(t=>t.showAnswerForm),jw=()=>Hn(t=>t.validationError),gf=()=>Hn(bn.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),Ow={id:"decimal-grid-problem-001",title:"百格图识别小数",grade:4,unit:"小数的认识",lesson:"小数认识",skill:"百格图识别小数",objective:"理解百分位和小数的关系",knowledgePoints:["小数表示","百分位概念","百格图模型"],difficulty:1,metadata:{topic:"小数",skill:"小数识别",tags:["百格图","百分位","小数表示"]},description:"通过百格图模型理解百分位和小数的关系。",basicInfo:{question:"What decimal number does the model represent?",answerUnit:""},scenes:{question:{content:[{type:"text",content:"What decimal number does the model represent?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold"}},{type:"text",content:"The large square represents 1 whole.",style:{fontSize:"1rem",color:"#475569",marginTop:"4px"}},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}],items:[{type:"text",content:"What decimal number does the model represent?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold"}},{type:"text",content:"The large square represents 1 whole.",style:{fontSize:"1rem",color:"#475569",marginTop:"4px"}},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}]},solve:{content:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:'1. 在模型中, 100个小方格中有12个被涂色。这代表 12/100 或者"一百分之十二"。'},{type:"text",content:'2. 你可以使用数位表将"一百分之十二"写作小数。'},{type:"placeValueChart",content:"",props:{headers:["ones (个位)","tenths (十分位)","hundredths (百分位)"],values:["0","1","2"],colors:{headerBg:"#f1f5f9",valueBg:"#ffffff",borderColor:"#e2e8f0"}}},{type:"text",content:"所以, 这个模型代表的小数是 <strong>0.12</strong>。",style:{marginTop:"1rem"}}],items:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:'1. 在模型中, 100个小方格中有12个被涂色。这代表 12/100 或者"一百分之十二"。'},{type:"text",content:'2. 你可以使用数位表将"一百分之十二"写作小数。'},{type:"placeValueChart",content:"",props:{headers:["ones (个位)","tenths (十分位)","hundredths (百分位)"],values:["0","1","2"],colors:{headerBg:"#f1f5f9",valueBg:"#ffffff",borderColor:"#e2e8f0"}}},{type:"text",content:"所以, 这个模型代表的小数是 <strong>0.12</strong>。",style:{marginTop:"1rem"}}]},review:{content:[{type:"text",content:"回顾问题:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:`What decimal number does the model represent?
315
+ `;const rA="/api/v1/content",sA="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",oA=10,Lt="question",Ce=Dn.create()(Dh.devtools((t,e)=>({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:"question",userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1,loadQuestions:async(n,r)=>{t({loading:!0,sessionId:n});try{const{gradeLevel:s,unitId:o,lessonId:i,count:a=oA}=r,l=`${rA}/grades/${s}/units/${o}/lessons/${i}/sessions/${n}/questions`,c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${sA}`},body:JSON.stringify({count:a})});if(!c.ok)throw new Error(`Failed to load questions: ${c.status} ${c.statusText}`);const f=(await c.json()).questions||[],g={};f.forEach(h=>{h.geometryShapes&&Array.isArray(h.geometryShapes)&&(g[h.problemId]=h.geometryShapes)}),t({problems:f,totalProblems:f.length,currentProblemIndex:0,currentScene:Lt,geometryShapes:g,loading:!1,error:null,startTime:Date.now()})}catch(s){const o=s instanceof Error?s.message:"Unknown error occurred";throw t({error:o,loading:!1}),s}},goToNextProblem:()=>{const{currentProblemIndex:n,problems:r,currentScene:s}=e();if(s!==Lt){console.warn("Cannot navigate during review/solve scene");return}n<r.length-1?t({currentProblemIndex:n+1,currentScene:Lt}):t({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:n,currentScene:r}=e();r===Lt&&n>0&&t({currentProblemIndex:n-1,currentScene:Lt})},goToProblem:n=>{const{problems:r,currentScene:s}=e();s===Lt&&(n<0||n>=r.length||t({currentProblemIndex:n,currentScene:Lt}))},switchScene:n=>{t({currentScene:n})},submitAnswer:async(n,r)=>{const{problems:s,currentProblemIndex:o}=e(),i=s[o];t({loading:!0});try{const a=i?.answer.correctAnswer||[],l=r.length>0&&r[0]===a[0],c={userAnswer:r,isCorrect:l,feedback:l?"🎉 Great job! Your answer is correct!":"❌ Sorry, that's not correct."};t(d=>({userAnswers:{...d.userAnswers,[n]:r},submissionResults:{...d.submissionResults,[n]:c},loading:!1,currentScene:l?"review":"solve"}))}catch(a){t({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(n,r)=>{t(s=>({userAnswers:{...s.userAnswers,[n]:r}}))},updateShape:(n,r,s)=>{t(o=>{const a=(o.geometryShapes[n]||[]).map(l=>l.id===r&&l.type==="point"?{...l,position:s}:l);return{geometryShapes:{...o.geometryShapes,[n]:a}}})},selectShape:(n,r)=>{t({selectedShapeId:r})},setGeometryMode:(n,r)=>{t({geometryMode:r})},startTimer:()=>{t({startTime:Date.now()})},stopTimer:()=>{const{startTime:n}=e();if(n){const r=Math.floor((Date.now()-n)/1e3);t(s=>({timeSpent:s.timeSpent+r,startTime:null}))}},reset:()=>{t({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:Lt,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:n,currentProblemIndex:r}=e();return n[r]||null},getProgress:()=>{const{currentProblemIndex:n,totalProblems:r}=e();return{current:n+1,total:r,percentage:r>0?(n+1)/r*100:0}},getSessionResults:()=>{const{sessionId:n,problems:r,submissionResults:s,timeSpent:o}=e(),i=r.map(l=>({problemId:l.problemId,userAnswer:s[l.problemId]?.userAnswer||[],isCorrect:s[l.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(l=>l.isCorrect).length;return{sessionId:n||"",totalProblems:r.length,correctAnswers:a,accuracy:r.length>0?a/r.length:0,timeSpent:o,averageTime:r.length>0?o/r.length:0,answers:i}}}),{name:"MathSessionStore"})),ah=(t,e,n,r,s,o,i)=>{const a=x.useMemo(()=>n==="question",[n]),l=x.useMemo(()=>t<e.length-1,[t,e.length]),c=x.useMemo(()=>t>0,[t]),d=x.useMemo(()=>!r||!s?!1:r.problemType?.includes("geometry")||o&&o[s]&&o[s].length>0?!0:i?.enableMathGraph!==void 0?i.enableMathGraph:!1,[r,s,o,i?.enableMathGraph]);return{canNavigate:a,canGoNext:l,canGoPrevious:c,shouldRenderMathGraph:d}},lh=(t,e,n,r,s)=>{const o=Ce(d=>d.selectShape),i=Ce(d=>d.setGeometryMode),a=x.useMemo(()=>!e||!r?[]:r[e]||[],[r,e]);x.useEffect(()=>{if(!e||!n)return;let d="view";switch(t){case"question":d="edit";break;case"solve":case"review":d="view";break;default:d="view"}s!==d&&i(e,d)},[t,e,s,i,n]);const l=x.useCallback(d=>{e&&Ce.setState(f=>({geometryShapes:{...f.geometryShapes,[e]:d}}))},[e]),c=x.useCallback(d=>{if(e){const f=d.length>0?d[0]:null;o(e,f)}},[e,o]);return{currentGeometryShapes:a,geometryMode:s,handleShapeChange:l,handleSelectionChange:c}},ch=(t,e,n)=>{const r=Ce(h=>h.updateUserAnswer),s=Ce(h=>h.submitAnswer),o=Ce(h=>h.goToNextProblem),i=Ce(h=>h.goToPreviousProblem),a=Ce(h=>h.goToProblem),l=x.useCallback(h=>{t&&r(t,h)},[t,r]),c=x.useCallback(()=>{t&&n[t]&&s(t,n[t])},[t,n,s]),d=x.useCallback(h=>{o(),h?.(t,e+1)},[o,t,e]),f=x.useCallback(h=>{i(),h?.(t,e-1)},[i,t,e]),g=x.useCallback((h,m)=>{a(h-1),m?.(t,h-1)},[a,t]);return{handleAnswerChange:l,handleSubmit:c,handleNext:d,handlePrevious:f,handlePagination:g}},dh=({config:t={},onSessionComplete:e,onSessionExit:n,onProblemChange:r,className:s="",style:o})=>{const i=Ce(T=>T.problems),a=Ce(T=>T.currentProblemIndex),l=Ce(T=>T.currentScene),c=Ce(T=>T.loading),d=Ce(T=>T.error),f=Ce(T=>T.sessionComplete),g=Ce(T=>T.submissionResults),h=Ce(T=>T.userAnswers),m=Ce(T=>T.geometryShapes),p=Ce(T=>T.geometryMode),y=Ce(T=>T.getSessionResults),b=x.useMemo(()=>i[a]??null,[i,a]),w=x.useMemo(()=>b?.problemId??"",[b]),{canNavigate:v,canGoNext:S,canGoPrevious:_,shouldRenderMathGraph:A}=ah(a,i,l,b,w,m,t),{currentGeometryShapes:C,handleShapeChange:R,handleSelectionChange:N}=lh(l,w,A,m,p),{handleAnswerChange:M,handleSubmit:F,handleNext:D,handlePrevious:P,handlePagination:$}=ch(w,a,h);x.useEffect(()=>{if(f&&typeof y=="function"){const T=y();e?.(T)}},[f,y,e]);const O=T=>typeof T=="string"?T:T instanceof Error?T.message:String(T);return c&&i.length===0?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:u.jsxs("div",{className:"text-center",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),u.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):d&&d!==null?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:u.jsxs("div",{className:"text-center text-red-600",children:[u.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),u.jsx("p",{children:O(d)})]})}):b?u.jsxs("div",{className:`flex flex-col max-w-4xl mx-auto p-6 ${s}`,style:o,"data-testid":"math-session-container",role:"region","aria-label":"数学练习会话",children:[u.jsx("div",{className:"mb-6",children:u.jsx(H.Pagination,{total:i.length,page:a+1,onChange:T=>$(T,r),isDisabled:!v,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),u.jsx(Rt,{problemData:b,scene:l,submissionResult:g[w],loading:c,error:d?O(d):void 0,value:h[w],onAnswerChange:M,onSubmit:F,onNext:()=>D(r),config:{theme:t.theme??"light",submitButtonText:"提交答案",nextButtonText:l==="solve"?"Got it!":"下一题",showHints:t.enableHints}}),A&&u.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:u.jsx(kr,{shapes:C,mode:p,onShapeChange:R,onSelectionChange:N,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),t.showProgress&&u.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[u.jsx("button",{onClick:()=>P(r),disabled:!_,className:"px-4 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"上一题"}),u.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),u.jsx("button",{onClick:()=>D(r),disabled:!S||!v,className:"px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"下一题"})]}),n&&u.jsx("div",{className:"mt-4 flex justify-center",children:u.jsx("button",{onClick:n,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:u.jsx("p",{className:"text-gray-600",children:"No problems available"})})},iA=({sessionId:t,gradeId:e,unitId:n,lessonId:r,userId:s,config:o={},className:i="",onSessionComplete:a,onSessionExit:l})=>{const[c,d]=x.useState({loading:!1,error:null,initialized:!1}),[f,g]=x.useState(0),[h,m]=x.useState(""),p=x.useRef(null),y=x.useRef(null),b=x.useRef(null),w=Ce(R=>R.loadQuestions),v=Ce(R=>R.reset);x.useEffect(()=>{const R=async()=>{try{d(N=>({...N,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:t,gradeId:e,unitId:n,lessonId:r,userId:s}),await w(t,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:n,lessonId:r,count:o.questionCount||10}),d(N=>({...N,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch(N){const M=N instanceof Error?N.message:"Failed to initialize session";d(F=>({...F,loading:!1,error:M,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",N)}};t&&e&&n&&r&&!c.initialized&&R()},[t,e,n,r,w,o.questionCount,c.initialized,f]),x.useEffect(()=>{c.loading&&!c.initialized?m("正在加载数学练习内容,请稍候..."):c.error?m(`加载失败:${c.error},请点击重试按钮重新加载`):c.initialized&&m("数学练习内容已加载完成,可以开始练习")},[c.loading,c.error,c.initialized]),x.useEffect(()=>{c.initialized&&p.current&&p.current.focus()},[c.initialized]),x.useEffect(()=>{c.error&&b.current&&b.current.focus()},[c.error]),x.useEffect(()=>{c.loading&&y.current&&y.current.focus()},[c.loading]),x.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),v()},[v]);const S=x.useCallback(R=>{console.log("🎉 MathSessionPage: 会话完成",R),a?.(R)},[a]),_=x.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),l?.()},[l]),A=x.useCallback((R,N)=>{console.log(`📝 MathSessionPage: 切换到题目 ${N+1}`,R)},[]),C=x.useCallback(R=>{R.key==="Escape"&&(R.preventDefault(),_()),R.key==="Enter"&&c.error&&R.target===b.current&&(R.preventDefault(),d({loading:!1,error:null,initialized:!1}),g(N=>N+1))},[_,c.error]);return c.loading&&!c.initialized?u.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:C,tabIndex:-1,ref:y,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:h}),u.jsx("div",{className:"page-loading-container",children:u.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[u.jsx("div",{className:"spinner","aria-hidden":"true"}),u.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):c.error?u.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:C,tabIndex:-1,ref:b,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:h}),u.jsxs("div",{className:"error-container",children:[u.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),u.jsx("h3",{className:"error-title",children:"加载失败"}),u.jsx("p",{className:"error-message",children:c.error}),u.jsx(Pt,{onClick:()=>{d({loading:!1,error:null,initialized:!1}),g(R=>R+1)},intent:"retry",useNewClassName:!0,className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):u.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:C,children:[u.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:h}),o.layout?.showHeader&&u.jsx("header",{className:"page-header",role:"banner",children:u.jsxs("div",{className:"header-content",children:[u.jsx("h1",{className:"page-title",children:"数学练习"}),u.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[u.jsxs("span",{className:"session-id",children:["会话: ",t]}),u.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),u.jsx("main",{className:"page-main",ref:p,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:u.jsx(dh,{config:{showProgress:o.showProgress??!0,enableHints:o.enableHints??!1,autoAdvance:o.autoAdvance??!1,theme:o.theme??"light"},onSessionComplete:S,onSessionExit:_,onProblemChange:A})}),o.layout?.showFooter&&u.jsx("footer",{className:"page-footer",role:"contentinfo",children:u.jsx("div",{className:"footer-content",children:u.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},aA=x.memo(iA),lA=({problemData:t,userAnswer:e,onNextQuestion:n})=>u.jsxs("div",{children:[u.jsxs("div",{className:"decimal-error-banner",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),u.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",u.jsx("strong",{children:t.answer.value})]})]}),u.jsx("button",{onClick:n,className:"decimal-understand-button",children:"明白了"})]}),u.jsxs("div",{className:"decimal-content-area",children:[u.jsx(aa,{problemData:t,userAnswer:e}),u.jsx(la,{problemData:t})]}),u.jsx("div",{className:"decimal-bottom-area",children:u.jsx("button",{onClick:n,className:"decimal-bottom-button",children:"明白了"})})]}),cA="rectangle-area-003",dA="矩形面积计算问题",uA=5,fA="几何与测量",hA="计算矩形的面积,理解面积公式 A = l × w 的应用",gA={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},mA=[{type:"text",content:"What is the area of this rectangle?"}],pA={question:{content:[{type:"text",content:"What is the area of this rectangle?",style:{fontSize:"1.5rem",color:"#1e293b"}},{type:"graph",content:"矩形图形",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2,name:"矩形"},{id:"lengthLabel",type:"text",position:{x:4.5,y:0},content:"7 yd",color:"#475569",fontSize:16},{id:"widthLabel",type:"text",position:{x:9,y:3.5},content:"5 yd",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}]},solve:{content:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"1. 观察矩形:长度是 7 码,宽度是 5 码",style:{marginTop:"8px"}},{type:"formula",content:"A = l × w",parts:["A = l \\times w"]},{type:"formula",content:"= 7 × 5",parts:["= 7 \\times 5"]},{type:"formula",content:"= 35",parts:["= 35"]},{type:"text",content:"长度和宽度以码为单位,所以面积以平方码为单位",style:{marginTop:"8px"}},{type:"text",content:"最终答案:矩形的面积是 35 平方码",style:{marginTop:"8px",fontWeight:"bold"}}]},review:{content:[{type:"text",content:"核心概念回顾:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"矩形面积公式:A = l × w",style:{marginTop:"8px"}},{type:"text",content:"其中 l 是长度,w 是宽度",style:{color:"#64748b"}}]}},yA=[{id:"exp-step-1",type:"instructionalStep",content:{title:"步骤1:识别矩形的尺寸",description:"观察图形,确定矩形的长度和宽度,并理解尺寸的单位。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"lengthLabel",type:"text",position:{x:4.5,y:0},content:"长度:7 码",color:"#475569",fontSize:14},{id:"widthLabel",type:"text",position:{x:9,y:3.5},content:"宽度:5 码",color:"#475569",fontSize:14}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-2",type:"instructionalStep",content:{title:"步骤2:回忆矩形面积公式",description:"复习矩形面积的基本公式:面积 = 长度 × 宽度。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"formulaLabel",type:"text",position:{x:5,y:7},content:"面积公式:A = l × w",color:"#10B981",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-3",type:"instructionalStep",content:{title:"步骤3:代入数值计算",description:"将已知的长度和宽度代入公式进行计算。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"calculationLabel",type:"text",position:{x:5,y:7},content:"A = 7 × 5 = 35",color:"#F59E0B",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}},{id:"exp-step-4",type:"instructionalStep",content:{title:"步骤4:确定面积单位",description:"根据长度和宽度的单位确定面积的单位。",chartConfig:{type:"graph",shapes:[{id:"pointA",type:"point",position:{x:1,y:1},name:"A",size:4,strokeColor:"#3B82F6"},{id:"pointB",type:"point",position:{x:8,y:1},name:"B",size:4,strokeColor:"#3B82F6"},{id:"pointC",type:"point",position:{x:8,y:6},name:"C",size:4,strokeColor:"#3B82F6"},{id:"pointD",type:"point",position:{x:1,y:6},name:"D",size:4,strokeColor:"#3B82F6"},{id:"rectangle",type:"polygon",vertices:[{$ref:"pointA"},{$ref:"pointB"},{$ref:"pointC"},{$ref:"pointD"}],strokeColor:"#0ea5e9",fillColor:"#7dd3fc",fillOpacity:.3,strokeWidth:2},{id:"unitLabel",type:"text",position:{x:5,y:7},content:"长度:码,宽度:码 → 面积:平方码",color:"#8B5CF6",fontSize:14},{id:"finalAnswer",type:"text",position:{x:5,y:7.5},content:"最终答案:35 平方码",color:"#10B981",fontSize:16,fontWeight:"bold"}],boundingBox:[0,8,10,0],showGrid:!1,showAxis:!1}}}],bA={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},xA={type:"card",padding:"20px"},vA={id:cA,title:dA,grade:uA,unit:fA,description:hA,basicInfo:gA,content:mA,scenes:pA,explanation:yA,answer:bA,layout:xA},wA=({className:t=""})=>{const e=ra(),n=sa(),r=oa(),{updateUserAnswer:s,submitAnswer:o,nextQuestion:i}=ia(),a=c=>{if(!c)return c;const d=JSON.parse(JSON.stringify(c));return d.lesson||(d.lesson="面积计算"),d.skill||(d.skill="面积公式应用"),d.objective||(d.objective="掌握面积计算方法"),(!d.knowledgePoints||!Array.isArray(d.knowledgePoints))&&(d.knowledgePoints=["面积公式","几何变换"]),d.difficulty||(d.difficulty=2),d.metadata||(d.metadata={topic:"几何",skill:"面积计算",tags:["面积","公式"]}),["question","solve","review","remember"].forEach(g=>{if(d.scenes?.[g]){const h=d.scenes[g];!h.items&&h.content&&(h.items=h.content),Array.isArray(h.items)||(h.items=[])}}),d},l=x.useMemo(()=>a(vA),[]);return u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[l.grade,"年级 - ",l.unit]})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&u.jsx(vn,{problemData:l,userAnswer:n,showAnswerForm:r,onAnswerSubmit:o,onAnswerChange:s}),e==="explanation"&&u.jsx(Bn,{problemData:l,userAnswer:n,onNextQuestion:i}),e==="success"&&u.jsx(wn,{problemData:l,onNextQuestion:i})]})]})},Wn=Dn.create(t=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{t({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{const n=typeof e=="string"?e:JSON.stringify(e);t({userAnswer:n,validationError:null})},submitAnswer:e=>{const n=Wn.getState();if(!n.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}const r=n.problemData.answer.value.toString(),s=typeof e=="string"?e:JSON.stringify(e),o=s.trim(),i=r.trim();let a=!1;(o===i||o===".12"&&i==="0.12"||o==="0,12"&&i==="0.12")&&(a=!0),t({userAnswer:s,isCorrect:a,showAnswerForm:!1,validationError:null,currentScene:a?"success":"explanation"})},updateChoiceAnswer:e=>{t({userAnswer:e,validationError:null})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),uh=()=>Wn(t=>t.currentScene),fh=()=>Wn(t=>t.userAnswer),hh=()=>Wn(t=>t.showAnswerForm),_A=()=>Wn(t=>t.validationError),gh=()=>Wn(bn.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),SA={id:"decimal-grid-problem-001",title:"百格图识别小数",grade:4,unit:"小数的认识",lesson:"小数认识",skill:"百格图识别小数",objective:"理解百分位和小数的关系",knowledgePoints:["小数表示","百分位概念","百格图模型"],difficulty:1,metadata:{topic:"小数",skill:"小数识别",tags:["百格图","百分位","小数表示"]},description:"通过百格图模型理解百分位和小数的关系。",basicInfo:{question:"What decimal number does the model represent?",answerUnit:""},scenes:{question:{content:[{type:"text",content:"What decimal number does the model represent?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold"}},{type:"text",content:"The large square represents 1 whole.",style:{fontSize:"1rem",color:"#475569",marginTop:"4px"}},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}],items:[{type:"text",content:"What decimal number does the model represent?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold"}},{type:"text",content:"The large square represents 1 whole.",style:{fontSize:"1rem",color:"#475569",marginTop:"4px"}},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}]},solve:{content:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:'1. 在模型中, 100个小方格中有12个被涂色。这代表 12/100 或者"一百分之十二"。'},{type:"text",content:'2. 你可以使用数位表将"一百分之十二"写作小数。'},{type:"placeValueChart",content:"",props:{headers:["ones (个位)","tenths (十分位)","hundredths (百分位)"],values:["0","1","2"],colors:{headerBg:"#f1f5f9",valueBg:"#ffffff",borderColor:"#e2e8f0"}}},{type:"text",content:"所以, 这个模型代表的小数是 <strong>0.12</strong>。",style:{marginTop:"1rem"}}],items:[{type:"text",content:"解题步骤:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:'1. 在模型中, 100个小方格中有12个被涂色。这代表 12/100 或者"一百分之十二"。'},{type:"text",content:'2. 你可以使用数位表将"一百分之十二"写作小数。'},{type:"placeValueChart",content:"",props:{headers:["ones (个位)","tenths (十分位)","hundredths (百分位)"],values:["0","1","2"],colors:{headerBg:"#f1f5f9",valueBg:"#ffffff",borderColor:"#e2e8f0"}}},{type:"text",content:"所以, 这个模型代表的小数是 <strong>0.12</strong>。",style:{marginTop:"1rem"}}]},review:{content:[{type:"text",content:"回顾问题:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:`What decimal number does the model represent?
283
316
  The large square represents 1 whole.`},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}],items:[{type:"text",content:"回顾问题:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:`What decimal number does the model represent?
284
- The large square represents 1 whole.`},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}]}},explanation:[],answer:{value:.12,unit:"",explanation:"模型中100个方格有12个被涂色,代表12/100,即0.12。"}},Iw=({className:t="",problemData:e})=>{const n=uf(),r=ff(),s=hf(),o=jw(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=gf(),d=x.useMemo(()=>e||Ow,[e]);return x.useEffect(()=>{c(d)},[d,c]),u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[d.grade,"年级 - ",d.unit]}),u.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(xn,{problemData:d,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(xw,{problemData:d,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(vn,{problemData:d,onNextQuestion:l})]}),u.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[n==="question"&&"请识别百格图代表的小数",n==="explanation"&&"查看详细解释",n==="success"&&"恭喜!答案正确"]})]})},at=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),Pw=()=>{const t={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},n={x:.9,y:.75,name:"C"},r={...at(t,e,1/3),name:"D"},s={...at(t,n,1/3),name:"E"},o={...at(t,e,2/3),name:"M"},i={...at(t,n,2/3),name:"N"},a={...at(e,n,1/3),name:"P"},l={...at(e,n,2/3),name:"Q"},c={...at(r,s,1/3),name:"U"},d={...at(r,s,2/3),name:"S"},f={...at(o,i,1/3),name:"K"},g={...at(o,i,2/3),name:"L"};return{A:t,B:e,C:n,D:r,E:s,M:o,N:i,P:a,Q:l,U:c,S:d,K:f,L:g}},Fw=(t,e,n)=>{const r={};for(const[s,o]of Object.entries(t))r[s]={...o,x:o.x*e,y:o.y*n};return r},Dw=(t,e)=>{const[n,r,s]=e,{x:o,y:i}=t,a=(r.y-s.y)*(n.x-s.x)+(s.x-r.x)*(n.y-s.y);if(Math.abs(a)<1e-4)return!1;const l=((r.y-s.y)*(o-s.x)+(s.x-r.x)*(i-s.y))/a,c=((s.y-n.y)*(o-s.x)+(n.x-s.x)*(i-s.y))/a,d=1-l-c;return l>=-.001&&c>=-.001&&d>=-.001},Lw=(t,e)=>{if(!t||!e||t.length!==3||e.length!==3)return!1;const n=t.map(s=>s.name).sort(),r=e.map(s=>s.name).sort();return n.every((s,o)=>s===r[o])},zw=(t,e)=>{if(!t||!e||t.length!==e.length)return!1;const n=t.map(s=>s.name).sort(),r=e.map(s=>s.name).sort();return n.join("")===r.join("")},Vw=()=>[{from:"A",to:"B"},{from:"A",to:"C"},{from:"B",to:"C"},{from:"D",to:"E"},{from:"M",to:"N"},{from:"P",to:"Q"},{from:"A",to:"D"},{from:"A",to:"E"},{from:"A",to:"M"},{from:"A",to:"N"},{from:"A",to:"P"},{from:"A",to:"Q"},{from:"D",to:"U"},{from:"U",to:"S"},{from:"S",to:"E"},{from:"M",to:"K"},{from:"K",to:"L"},{from:"L",to:"N"},{from:"B",to:"P"},{from:"P",to:"Q"},{from:"Q",to:"C"}],Gw=()=>[{id:"gem_1",vertices:["A","B","P"],points:10,category:"basic"},{id:"gem_2",vertices:["A","P","Q"],points:10,category:"basic"},{id:"gem_3",vertices:["A","Q","C"],points:10,category:"basic"},{id:"gem_4",vertices:["A","B","Q"],points:15,category:"medium"},{id:"gem_5",vertices:["A","P","C"],points:15,category:"medium"},{id:"gem_6",vertices:["A","B","C"],points:20,category:"large"},{id:"gem_7",vertices:["A","D","U"],points:12,category:"ade_small"},{id:"gem_8",vertices:["A","U","S"],points:12,category:"ade_small"},{id:"gem_9",vertices:["A","S","E"],points:12,category:"ade_small"},{id:"gem_10",vertices:["A","D","S"],points:18,category:"ade_medium"},{id:"gem_11",vertices:["A","U","E"],points:18,category:"ade_medium"},{id:"gem_12",vertices:["A","D","E"],points:25,category:"ade_large"},{id:"gem_13",vertices:["A","M","K"],points:14,category:"amn_small"},{id:"gem_14",vertices:["A","K","L"],points:14,category:"amn_small"},{id:"gem_15",vertices:["A","L","N"],points:14,category:"amn_small"},{id:"gem_16",vertices:["A","M","L"],points:20,category:"amn_medium"},{id:"gem_17",vertices:["A","K","N"],points:20,category:"amn_medium"},{id:"gem_18",vertices:["A","M","N"],points:30,category:"amn_large"}],Uw={TOTAL_GEMS:18,CANVAS_RATIO:4/3,DEFAULT_VIEWBOX:{width:700,height:600},POINT_RADIUS:{default:6,selected:9},TOLERANCE:.001,MIN_TRIANGLE_AREA:.001,COORDINATE_PRECISION:1e-4,BARYCENTRIC_TOLERANCE:-.001},mf=(t=Tr.id)=>{const e=Re.units.map((s,o)=>{const i=Math.min(100,Math.max(0,o*15+Math.random()*20)),a=Math.floor(s.lessons.length*i/100),l=s.lessons.map((c,d)=>{const f=Math.min(100,Math.max(0,i-d*10+Math.random()*30));return{lessonId:c.id,status:f>=100?"completed":f>0?"in-progress":"not-started",progressPercentage:Math.round(f),lastAccessed:f>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:f>0?Math.floor(Math.random()*120+10):void 0,score:f>=100?Math.floor(Math.random()*21+80):void 0,attempts:f>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:s.id,userId:t,totalLessons:s.lessons.length,completedLessons:a,progressPercentage:Math.round(i),status:i>=100?"completed":i>0?"in-progress":"not-started",lastAccessed:i>0?new Date(Date.now()-Math.random()*14*24*60*60*1e3).toISOString():void 0,lessons:l}}),n=e.reduce((s,o)=>s+o.progressPercentage,0)/e.length,r=e.filter(s=>s.status==="completed").length;return{courseId:Re.id,userId:t,totalUnits:e.length,completedUnits:r,progressPercentage:Math.round(n),status:n>=100?"completed":n>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},pf=mf(),ta=(t,e)=>t===Tr.id&&e===Re.id?pf:null,yf=(t,e,n)=>{const r=ta(t,e);return r&&r.units.find(s=>s.unitId===n)||null},Bw=(t,e,n,r)=>{const s=yf(t,e,n);return s&&s.lessons.find(o=>o.lessonId===r)||null},Hw=(t,e,n,r,s)=>(console.log("Updating lesson progress:",{userId:t,courseId:e,unitId:n,lessonId:r,progress:s}),!0),na=(t,e)=>{const n=ta(t,e);if(!n)return null;const r=Re.units.map((s,o)=>{const i=n.units.find(a=>a.unitId===s.id);return{unitId:s.id,title:s.title,description:s.description,moduleCategory:s.moduleCategory,estimatedDuration:s.estimatedDuration,totalLessons:s.lessons.length,completedLessons:i?.completedLessons||0,progressPercentage:i?.progressPercentage||0,status:i?.status||"not-started",lastAccessed:i?.lastAccessed,isActive:o===0,route:`/math/grade-${Re.level}/unit/${s.id}`}});return{userId:t,courseId:Re.id,courseTitle:Re.title,courseLevel:Re.level,totalUnits:r.length,completedUnits:r.filter(s=>s.status==="completed").length,overallProgress:n.progressPercentage,status:n.status,lastAccessed:n.lastAccessed,units:r}},Ww=(t,e,n)=>{const r=na(t,e);return r&&r.units.find(s=>s.unitId===n)||null},qw=(t,e,n,r)=>(console.log("Updating unit active status:",{userId:t,courseId:e,unitId:n,isActive:r}),!0),Yw=na(Tr.id,Re.id),Kw={userId:Tr.id,courseId:Re.id,courseTitle:Re.title,courseLevel:Re.level,totalUnits:Re.units.length,completedUnits:3,overallProgress:45,status:"in-progress",lastAccessed:"2024-01-15T10:30:00Z",units:[{unitId:"unit_1",title:"小数乘法",description:"学习小数乘法的计算方法及应用",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:10,completedLessons:8,progressPercentage:80,status:"completed",lastAccessed:"2024-01-10T14:20:00Z",isActive:!1,route:"/math/grade-5/unit/unit_1",icon:"🔢"},{unitId:"unit_2",title:"小数除法",description:"学习小数除法的计算方法及应用",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:12,completedLessons:6,progressPercentage:50,status:"in-progress",lastAccessed:"2024-01-15T10:30:00Z",isActive:!0,route:"/math/grade-5/unit/unit_2",icon:"➗"},{unitId:"unit_3",title:"简易方程",description:"学习用字母表示数和解简易方程",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"4周",totalLessons:14,completedLessons:2,progressPercentage:14,status:"in-progress",lastAccessed:"2024-01-12T16:45:00Z",isActive:!1,route:"/math/grade-5/unit/unit_3",icon:"📝"},{unitId:"unit_4",title:"多边形的面积",description:"学习平行四边形、三角形、梯形和组合图形的面积计算",moduleCategory:"Graphics and Geometry",estimatedDuration:"3周",totalLessons:12,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_4",icon:"📐"},{unitId:"unit_5",title:"因数与倍数",description:"学习因数、倍数、质数、合数等概念",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:10,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_5",icon:"🔢"},{unitId:"unit_6",title:"长方体和正方体",description:"学习长方体和正方体的特征、表面积和体积计算",moduleCategory:"Graphics and Geometry",estimatedDuration:"4周",totalLessons:14,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_6",icon:"📦"},{unitId:"unit_7",title:"分数的意义和性质",description:"学习分数的意义、性质和约分、通分等方法",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"4周",totalLessons:16,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_7",icon:"½"},{unitId:"unit_8",title:"分数的加法和减法",description:"学习同分母分数、异分母分数的加法和减法",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:12,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_8",icon:"➕"},{unitId:"unit_9",title:"折线统计图",description:"学习单式折线统计图和复式折线统计图的认识和制作",moduleCategory:"Probability and Statistics",estimatedDuration:"2周",totalLessons:6,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_9",icon:"📊"}]},di={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Xw={HINT:"hint",EXPLANATION:"explanation",SOLUTION:"solution",FOLLOW_UP:"follow_up",GENERAL:"general"},Jw={PENDING:"pending",UPLOADING:"uploading",SUCCESS:"success",ERROR:"error"},ra="你好!我是你的数学学习助手。你可以问我任何数学问题,或者上传题目图片让我帮你解答。",bf="输入消息...",xf=4,vf=[{id:"1",label:"怎么解",message:"这道题怎么解?",icon:"HelpCircle"},{id:"2",label:"检查答案",message:"请检查我的答案",icon:"CheckCircle"},{id:"3",label:"类似题目",message:"给我一道类似的题目",icon:"Copy"},{id:"4",label:"知识点",message:"这道题涉及哪些知识点?",icon:"BookOpen"}],Zw={inputValue:"",isInputFocused:!1,pendingImages:[],isContextBarCollapsed:!1,isHistoryOpen:!1,abortController:null},wf=()=>Dn.create((t,e)=>({...Zw,setInputValue:n=>{t({inputValue:n})},setInputFocused:n=>{t({isInputFocused:n})},clearInput:()=>{t({inputValue:"",pendingImages:[]})},addPendingImage:n=>{const{pendingImages:r}=e();if(r.length>=4){console.warn("[AICopilot] 最多只能添加4张图片");return}t({pendingImages:[...r,n]})},removePendingImage:n=>{const{pendingImages:r}=e();t({pendingImages:r.filter(s=>s.id!==n)})},clearPendingImages:()=>{t({pendingImages:[]})},updateImageStatus:(n,r)=>{const{pendingImages:s}=e();t({pendingImages:s.map(o=>o.id===n?{...o,status:r}:o)})},toggleContextBar:()=>{const{isContextBarCollapsed:n}=e();t({isContextBarCollapsed:!n})},collapseContextBar:()=>{t({isContextBarCollapsed:!0})},expandContextBar:()=>{t({isContextBarCollapsed:!1})},setHistoryOpen:n=>{t({isHistoryOpen:n})},toggleHistory:()=>{const{isHistoryOpen:n}=e();t({isHistoryOpen:!n})},setAbortController:n=>{t({abortController:n})}})),Or=wf(),_f=()=>Or(bn.useShallow(t=>({inputValue:t.inputValue,isInputFocused:t.isInputFocused,setInputValue:t.setInputValue,setInputFocused:t.setInputFocused,clearInput:t.clearInput}))),Sf=()=>Or(bn.useShallow(t=>({pendingImages:t.pendingImages,addPendingImage:t.addPendingImage,removePendingImage:t.removePendingImage,clearPendingImages:t.clearPendingImages,updateImageStatus:t.updateImageStatus}))),Cf=()=>Or(bn.useShallow(t=>({isContextBarCollapsed:t.isContextBarCollapsed,isHistoryOpen:t.isHistoryOpen,toggleContextBar:t.toggleContextBar,collapseContextBar:t.collapseContextBar,expandContextBar:t.expandContextBar,setHistoryOpen:t.setHistoryOpen,toggleHistory:t.toggleHistory}))),Qw=()=>Or(bn.useShallow(t=>({abortController:t.abortController,setAbortController:t.setAbortController}))),e_=t=>{try{return new Date(t).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}catch{return"未知时间"}},Rf=x.memo(({message:t,showProblemTag:e=!1,className:n=""})=>{const r=t.role===di.USER,s=t.role===di.ASSISTANT,o=r?"mathwiz-chat-message--user flex-row-reverse":"mathwiz-chat-message--assistant flex-row",i=r?"mathwiz-chat-bubble--user bg-primary-100 text-primary-900":"mathwiz-chat-bubble--assistant bg-default-100 text-default-900",a=r?"用户消息":s?"AI助手消息":"系统消息",l=r?"你":"AI助手",c=r?"primary":"success";return u.jsxs("article",{className:`mathwiz-chat-message flex gap-3 p-4 ${o} ${n}`,"aria-label":a,"data-message-id":t.messageId,"data-role":t.role,children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx(H.Avatar,{size:"sm",color:c,className:"mathwiz-chat-avatar","aria-label":l,children:r?"U":"AI"})}),u.jsxs("div",{className:`flex-1 ${r?"text-right":"text-left"}`,children:[u.jsxs("div",{className:`flex items-center gap-2 mb-1 ${r?"justify-end":"justify-start"}`,children:[u.jsx("span",{className:"text-sm font-medium text-default-700",children:l}),u.jsx("span",{className:"text-xs text-default-400",children:e_(t.timestamp)})]}),e&&t.referencedProblemTitle&&u.jsx("div",{className:`mb-2 ${r?"text-right":"text-left"}`,children:u.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs rounded-full bg-default-200 text-default-600",children:["关联题目: ",t.referencedProblemTitle]})}),u.jsx("div",{className:`inline-block max-w-[80%] px-4 py-2 rounded-2xl text-left ${i}`,children:u.jsx("p",{className:"whitespace-pre-wrap break-words",children:t.content})}),t.images&&t.images.length>0&&u.jsx("div",{className:`flex gap-2 mt-2 flex-wrap ${r?"justify-end":"justify-start"}`,children:t.images.map((d,f)=>u.jsx("div",{className:"mathwiz-chat-image-preview relative w-20 h-20 rounded-lg overflow-hidden border border-default-200",children:u.jsx("img",{src:d.url,alt:`上传图片 ${f+1}`,className:"w-full h-full object-cover",loading:"lazy"})},d.id))})]})]})});Rf.displayName="ChatMessage";const t_=()=>u.jsxs("div",{className:"mathwiz-typing-indicator flex items-center gap-1 px-2 py-3","data-testid":"typing-indicator",children:[u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"0ms"}}),u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"150ms"}}),u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"300ms"}})]}),Af=x.memo(({content:t,className:e=""})=>{const n=t&&t.trim().length>0;return u.jsxs("article",{className:`mathwiz-stream-message flex gap-3 p-4 ${e}`,"aria-label":"AI正在输入","aria-live":"polite","aria-busy":"true",children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx(H.Avatar,{size:"sm",color:"success",className:"mathwiz-chat-avatar","aria-label":"AI助手",children:"AI"})}),u.jsxs("div",{className:"flex-1",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-sm font-medium text-default-700",children:"AI助手"}),u.jsx("span",{className:"text-xs text-default-400",children:"正在输入..."})]}),u.jsx("div",{className:"inline-block max-w-[80%] px-4 py-2 rounded-2xl bg-default-100 text-default-900",children:n?u.jsx("p",{className:"whitespace-pre-wrap break-words",children:t}):u.jsx(t_,{})}),!n&&u.jsxs("div",{className:"mt-2 space-y-2 max-w-[60%]",children:[u.jsx(H.Skeleton,{className:"h-3 w-full rounded-lg"}),u.jsx(H.Skeleton,{className:"h-3 w-3/4 rounded-lg"})]})]})]})});Af.displayName="StreamMessage";const kf=x.memo(({welcomeMessage:t=ra})=>u.jsxs("div",{className:"mathwiz-empty-state flex flex-col items-center justify-center h-full p-8 text-center",children:[u.jsx("div",{className:"w-16 h-16 mb-4 rounded-full bg-primary-100 flex items-center justify-center","data-testid":"empty-state-icon",children:u.jsx(Z.Bot,{size:32,className:"text-primary-600"})}),u.jsx("h3",{className:"text-lg font-semibold text-default-900 mb-2",children:"AI 数学助手"}),u.jsx("p",{className:"text-sm text-default-600 max-w-md",children:t}),u.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-default-400",children:[u.jsx(Z.MessageSquare,{size:14}),u.jsx("span",{children:"开始你的数学学习之旅"})]})]}));kf.displayName="EmptyState";const Ef=x.memo(({messages:t,isStreaming:e=!1,streamingContent:n="",welcomeMessage:r,className:s=""})=>{const o=t.length>0,i=x.useRef(null);return x.useEffect(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[t,n]),u.jsx(H.ScrollShadow,{hideScrollBar:!0,className:`mathwiz-chat-container flex-1 overflow-y-auto ${s}`,role:"log","aria-label":"消息列表","aria-live":"polite",children:o?u.jsxs("div",{className:"pb-4",children:[t.map((a,l)=>{const c=a.role==="user"&&!!a.referencedProblemTitle&&t.findIndex(d=>d.referencedProblemId===a.referencedProblemId)===l;return u.jsx(Rf,{message:a,showProblemTag:c},a.messageId)}),e&&u.jsx(Af,{content:n}),u.jsx("div",{ref:i})]}):u.jsx(kf,{welcomeMessage:r})})});Ef.displayName="ChatContainer";const Nf=x.memo(({value:t,onChange:e,onSend:n,onAbort:r,isStreaming:s=!1,pendingImages:o,onImageAdd:i,onImageRemove:a,onImageUpload:l,placeholder:c="输入消息...",maxImages:d=4,disabled:f=!1,className:g=""})=>{const h=x.useRef(null),m=t.trim().length>0||o.length>0,p=o.length>=d,y=x.useCallback(async v=>{const S=v.target.files?.[0];if(S){if(l)try{const _=await l(S);i(_)}catch(_){console.error("图片上传失败:",_)}else{const _=URL.createObjectURL(S);i({id:`local_${Date.now()}`,url:_,file:S,status:"pending"})}h.current&&(h.current.value="")}},[i,l]),b=x.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),m&&!f&&!s&&n())},[m,f,s,n]),w=x.useCallback(()=>{s&&r?r():m&&!f&&n()},[s,m,f,r,n]);return u.jsxs("div",{className:`mathwiz-chat-input bg-background border-t border-default-200 ${g}`,children:[o.length>0&&u.jsx("div",{className:"flex gap-2 p-3 overflow-x-auto",children:o.map((v,S)=>u.jsxs("div",{className:"mathwiz-pending-image relative flex-shrink-0 w-16 h-16 rounded-lg overflow-hidden border border-default-200",children:[u.jsx("img",{src:v.url,alt:`待发送图片 ${S+1}`,className:"w-full h-full object-cover"}),u.jsx("button",{onClick:()=>a(v.id),className:"absolute top-0.5 right-0.5 p-0.5 bg-default-900/50 hover:bg-default-900/70 rounded-full text-white transition-colors","aria-label":"移除图片",children:u.jsx(Z.X,{size:12})})]},v.id))}),u.jsxs("div",{className:"flex items-end gap-2 p-3",children:[u.jsx(H.Tooltip,{content:p?`最多${d}张图片`:"上传图片",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",isDisabled:p||f||s,onPress:()=>h.current?.click(),"aria-label":"上传图片",children:u.jsx(Z.ImagePlus,{size:20})})}),u.jsx("input",{ref:h,type:"file",accept:"image/*",className:"hidden",onChange:y,"aria-hidden":"true"}),u.jsx(H.Textarea,{value:t,onChange:v=>e(v.target.value),onKeyDown:b,placeholder:c,minRows:1,maxRows:4,isDisabled:f,className:"flex-1",classNames:{input:"min-h-[40px] py-2"}}),s?u.jsx(H.Button,{isIconOnly:!0,color:"danger",variant:"solid",size:"sm",onPress:w,"aria-label":"停止生成",children:u.jsx(Z.Square,{size:18,fill:"currentColor"})}):u.jsx(H.Button,{isIconOnly:!0,color:"primary",variant:"solid",size:"sm",isDisabled:!m||f,onPress:w,"aria-label":"发送消息",children:u.jsx(Z.Send,{size:18})})]})]})});Nf.displayName="ChatInput";const n_=t=>{const e={size:16,className:"mr-1"};switch(t.icon){case"HelpCircle":return u.jsx(Z.HelpCircle,{...e});case"CheckCircle":return u.jsx(Z.CheckCircle,{...e});case"Copy":return u.jsx(Z.Copy,{...e});case"BookOpen":return u.jsx(Z.BookOpen,{...e});default:return u.jsx(Z.Sparkles,{...e})}},Tf=x.memo(({actions:t,onActionClick:e,className:n=""})=>!t||t.length===0?null:u.jsx(H.ScrollShadow,{orientation:"horizontal",hideScrollBar:!0,className:`mathwiz-quick-actions w-full ${n}`,role:"region","aria-label":"快捷操作",children:u.jsx("div",{className:"flex gap-2 px-4 py-2",children:t.map(r=>u.jsx(H.Button,{variant:"flat",size:"sm",className:"mathwiz-quick-action-btn flex-shrink-0",startContent:n_(r),onPress:()=>e(r),"aria-label":r.label,children:r.label},r.id))})}));Tf.displayName="QuickActions";const Mf=x.memo(({difficulty:t})=>{const e=Array.from({length:5},(n,r)=>r<t);return u.jsx("div",{className:"flex gap-0.5","aria-label":`难度等级: ${t}/5`,children:e.map((n,r)=>u.jsx(Z.Star,{size:14,"data-testid":"difficulty-star",className:n?"text-warning fill-warning":"text-default-300"},r))})});Mf.displayName="DifficultyStars";const $f=x.memo(({problemContext:t,isCollapsed:e,onToggle:n,onChangeProblem:r,className:s=""})=>{const{title:o,difficulty:i,knowledgePoints:a}=t;return u.jsx(H.Card,{className:`mathwiz-context-bar mx-4 mb-4 ${s}`,role:"region","aria-label":"当前题目上下文",children:u.jsxs(H.CardBody,{className:"p-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Z.BookOpen,{size:18,className:"text-primary"}),u.jsx("h3",{className:"font-medium text-default-900",children:o})]}),u.jsxs("div",{className:"flex items-center gap-1",children:[r&&u.jsx(H.Tooltip,{content:"更换题目",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:r,"aria-label":"更换题目",children:u.jsx(Z.RefreshCw,{size:16})})}),u.jsx(H.Tooltip,{content:e?"展开":"折叠",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:n,"aria-label":e?"展开":"折叠",children:e?u.jsx(Z.ChevronDown,{size:16}):u.jsx(Z.ChevronUp,{size:16})})})]})]}),!e&&u.jsxs("div",{className:"mt-3 pt-3 border-t border-default-200",children:[u.jsx("div",{className:"flex items-center gap-4",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-xs text-default-500",children:"难度:"}),u.jsx(Mf,{difficulty:i})]})}),a.length>0&&u.jsxs("div",{className:"mt-2 flex items-center gap-2 flex-wrap",children:[u.jsx("span",{className:"text-xs text-default-500",children:"知识点:"}),a.map(l=>u.jsx(H.Chip,{size:"sm",variant:"flat",color:"primary",children:l.name},l.id))]})]})]})})});$f.displayName="CollapsibleContextBar";const jf=x.memo(({onLoadHistory:t,onNewSession:e})=>u.jsxs(H.Navbar,{className:"mathwiz-copilot-header border-b border-default-200",shouldHideOnScroll:!1,children:[u.jsx(H.NavbarContent,{justify:"start",children:u.jsx(H.NavbarItem,{children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Z.MessageSquare,{className:"text-primary",size:24}),u.jsx("span",{className:"font-bold text-lg",children:"AI 数学助手"})]})})}),u.jsxs(H.NavbarContent,{justify:"end",children:[e&&u.jsx(H.NavbarItem,{children:u.jsx(H.Tooltip,{content:"新建会话",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:e,"aria-label":"新建会话",children:u.jsx(Z.Plus,{size:20})})})}),t&&u.jsx(H.NavbarItem,{children:u.jsx(H.Tooltip,{content:"历史记录",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:t,"aria-label":"历史记录",children:u.jsx(Z.History,{size:20})})})})]})]}));jf.displayName="Header";const Of=x.memo(({messages:t,problemContext:e,isStreaming:n=!1,streamingContent:r="",onSendMessage:s,onAbortStreaming:o,onLoadHistory:i,onNewSession:a,onChangeProblem:l,onImageUpload:c,quickActions:d=vf,welcomeMessage:f=ra,placeholder:g=bf,maxImages:h=xf,className:m=""})=>{const{inputValue:p,setInputValue:y,clearInput:b}=_f(),{pendingImages:w,addPendingImage:v,removePendingImage:S}=Sf(),{isContextBarCollapsed:_,toggleContextBar:A}=Cf(),C=x.useCallback(()=>{!p.trim()&&w.length===0||(s(p,{problemId:e?.problemId,images:w.length>0?w:void 0}),b())},[p,w,e?.problemId,s,b]),R=x.useCallback(k=>{s(k.message,{problemId:e?.problemId})},[s,e?.problemId]);return u.jsxs("div",{className:`mathwiz-copilot flex flex-col h-full bg-background ${m}`,role:"main","aria-label":"AI数学助手",children:[u.jsx(jf,{onLoadHistory:i,onNewSession:a}),e&&u.jsx($f,{problemContext:e,isCollapsed:_,onToggle:A,onChangeProblem:l}),u.jsx(Ef,{messages:t,isStreaming:n,streamingContent:r,welcomeMessage:f}),u.jsx(Tf,{actions:d,onActionClick:R}),u.jsx(Nf,{value:p,onChange:y,onSend:C,onAbort:o,isStreaming:n,pendingImages:w,onImageAdd:v,onImageRemove:S,onImageUpload:c,placeholder:g,maxImages:h})]})});Of.displayName="AICopilot";const r_={CORRECT:"correct",INCORRECT:"incorrect",IDLE:"idle"},s_={LABEL:"label",INPUT:"input",RESULT:"result",PLACEHOLDER:"placeholder"},o_=({className:t="",problemData:e,children:n})=>{const r=qs(),s=Ys(),o=Ks(),i=Xs(),{updateUserAnswer:a,submitAnswer:l,nextQuestion:c,setProblemData:d}=Js();x.useEffect(()=>{e&&d(e)},[e,d]);const g=(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"text-cyan-600",label:"三角形面积"};case"parallelogram":return{titleColor:"text-blue-600",label:"平行四边形面积"};case"trapezoid":return{titleColor:"text-green-600",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"text-purple-600",label:"年龄问题"}:{titleColor:"text-slate-600",label:"数学问题"}}})();return u.jsxs("div",{className:`bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center p-4 font-sans ${t}`,children:[u.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[u.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${g.titleColor}`,children:e?.title||"数学问题练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),u.jsx("div",{className:"mt-4 md:mt-0",children:u.jsx("span",{className:"inline-block px-3 py-1 text-sm font-medium rounded-full bg-white border border-slate-200 text-slate-700",children:g.label})})]}),e?.description&&u.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),u.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm",children:e?u.jsxs(u.Fragment,{children:[r==="question"&&u.jsx(xn,{problemData:e,userAnswer:s,showAnswerForm:o,onAnswerSubmit:l,onAnswerChange:a,validationError:i}),r==="explanation"&&u.jsx(Un,{problemData:e,userAnswer:s,onNextQuestion:c}),r==="success"&&u.jsx(vn,{problemData:e,onNextQuestion:c})]}):u.jsxs("div",{className:"p-8 text-center",children:[u.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),u.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),u.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),u.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:u.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[u.jsx("div",{className:"mb-4 md:mb-0",children:u.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),u.jsx("div",{children:u.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),n&&u.jsx("div",{className:"w-full max-w-4xl mt-8",children:n})]})},i_=()=>u.jsxs("div",{className:"ixl-dashboard-panels",children:[u.jsxs("div",{className:"ixl-dashboard-card ixl-questions-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Questions",u.jsx("br",{}),"answered"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-time-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Time",u.jsx("br",{}),"elapsed"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsxs("div",{className:"ixl-time-display",children:[u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"hr"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"min"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"06"}),u.jsx("div",{className:"ixl-time-label",children:"sec"})]})]})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-score-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["SmartScore",u.jsx("span",{className:"ixl-score-subtitle",children:"out of 100"}),u.jsx("span",{className:"ixl-help-icon",title:"What is this?",children:"?"})]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsx("p",{className:"ixl-dashboard-note",children:"*在实际业务项目中集成StatBlock组件显示实时数据"})]}),a_=()=>u.jsxs("div",{className:"ixl-scaffolding-links",children:[u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),u.jsx("span",{children:"Learn with an example"})]}),u.jsx("span",{className:"ixl-scaffolding-separator",children:"or"}),u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"currentColor",viewBox:"0 0 20 20",children:u.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"})}),u.jsx("span",{children:"Watch a video"})]})]}),l_=()=>{const t=[{icon:"💎",title:"Understanding area of a triangle",isPurple:!1},{icon:"💎",title:"Multiply two decimals: products up to hundredths",isPurple:!1},{icon:"💎",title:"Division with decimal divisors",isPurple:!1},{icon:"📚",title:"Lesson: Area of triangles",isPurple:!0}];return u.jsx("div",{className:"ixl-work-it-out-grid",children:t.map((e,n)=>u.jsxs("a",{href:"#",className:`ixl-work-it-out-card ${e.isPurple?"ixl-work-it-out-card-purple":""}`,children:[u.jsx("span",{className:`ixl-work-it-out-icon ${e.isPurple?"ixl-work-it-out-icon-purple":""}`,children:e.icon}),u.jsx("span",{className:"ixl-work-it-out-text",children:e.title})]},n))})},c_=({className:t="",problemData:e,children:n})=>{const r=qs(),s=Ys(),o=Ks(),i=Xs(),{updateUserAnswer:a,submitAnswer:l,nextQuestion:c,setProblemData:d}=Js();return x.useEffect(()=>{e&&d(e)},[e,d]),(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"ixl-title-color-triangle",label:"三角形面积"};case"parallelogram":return{titleColor:"ixl-title-color-parallelogram",label:"平行四边形面积"};case"trapezoid":return{titleColor:"ixl-title-color-trapezoid",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"ixl-title-color-age",label:"年龄问题"}:{titleColor:"ixl-title-color-default",label:"数学问题"}}})(),u.jsxs("div",{className:`ixl-immersive-container ${t}`,children:[u.jsx("div",{className:"ixl-top-nav",children:u.jsxs("div",{className:"ixl-breadcrumb",children:[u.jsx("span",{className:"ixl-breadcrumb-item",children:"Sixth grade"}),u.jsx("span",{className:"ixl-breadcrumb-separator",children:"›"}),u.jsx("span",{className:"ixl-breadcrumb-item",children:"GG.6 Area of triangles"}),u.jsx("span",{className:"ixl-breadcrumb-tag",children:"C8S"})]})}),u.jsxs("main",{className:"ixl-main-layout",children:[u.jsxs("div",{className:"ixl-content-area",children:[u.jsxs("div",{className:"ixl-main-card",children:[u.jsx(a_,{}),u.jsxs("div",{className:"ixl-status-banner",children:[u.jsx("strong",{children:"Parent results not recorded."})," Continue practicing or ",u.jsx("a",{href:"#",className:"ixl-status-link",children:"switch user"}),"."]}),u.jsx("div",{className:"ixl-question-display",children:e?u.jsxs(u.Fragment,{children:[r==="question"&&u.jsx(xn,{problemData:e,userAnswer:s,showAnswerForm:o,onAnswerSubmit:l,onAnswerChange:a,validationError:i}),r==="explanation"&&u.jsx(Un,{problemData:e,userAnswer:s,onNextQuestion:c}),r==="success"&&u.jsx(vn,{problemData:e,onNextQuestion:c})]}):u.jsxs("div",{className:"ixl-no-data-message",children:[u.jsx("div",{className:"ixl-no-data-icon",children:"⚠️"}),u.jsx("h3",{className:"ixl-no-data-title",children:"缺少问题数据"}),u.jsx("p",{className:"ixl-no-data-desc",children:"请提供有效的problemData prop"})]})})]}),u.jsxs("div",{className:"ixl-review-area",children:[u.jsxs("div",{className:"ixl-review-header",children:[u.jsx("h3",{className:"ixl-review-title",children:"Work it out"}),u.jsx("p",{className:"ixl-review-subtitle",children:"Not feeling ready yet? These can help:"})]}),u.jsx(l_,{})]})]}),u.jsx("aside",{className:"ixl-dashboard-area",children:u.jsx(i_,{})})]}),n&&u.jsx("div",{className:"ixl-children-area",children:n})]})},d_={brand:"primary",growth:"success",motivation:"warning",neutral:"default"},fl={sm:"text-[10px] px-2 py-0.5",md:"text-xs px-3 py-1"},u_={brand:{solid:"bg-brand-600 text-white",outline:"bg-brand-100 border-brand-500 text-brand-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},growth:{solid:"bg-growth-500 text-white",outline:"bg-growth-50 border-growth-500 text-growth-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},motivation:{solid:"bg-motivation-500 text-white",outline:"bg-motivation-50 border-motivation-500 text-motivation-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},neutral:{solid:"bg-gray-500 text-white",outline:"bg-gray-100 border-gray-500 text-gray-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"}},f_=({variant:t="solid",color:e="brand",size:n="md",icon:r,children:s,className:o,"aria-label":i})=>{const a="inline-flex items-center gap-1.5 font-bold uppercase tracking-wider rounded-full";if(t==="glass"){const d=[a,fl[n],u_[e].glass,o].join(" ");return u.jsxs("span",{className:d,"aria-label":i,children:[r&&u.jsx("i",{className:r,"aria-hidden":"true"}),s]})}const l=t==="outline"?"flat":"solid",c=d_[e];return u.jsxs(H.Badge,{variant:l,color:c,className:`${a} ${fl[n]} ${o||""}`,"aria-label":i,children:[r&&u.jsx("i",{className:r,"aria-hidden":"true"}),s]})},h_={streak:{emoji:"🔥",bgColor:"bg-orange-50",textColor:"text-orange-600"},coin:{emoji:"💰",bgColor:"bg-yellow-50",textColor:"text-yellow-600"},gem:{emoji:"💎",bgColor:"bg-blue-50",textColor:"text-blue-600"},star:{emoji:"⭐",bgColor:"bg-purple-50",textColor:"text-purple-600"}},g_={sm:{text:"text-sm",padding:"px-2 py-1",gap:"gap-1"},md:{text:"text-base",padding:"px-3 py-1.5",gap:"gap-1.5"}};function m_(t){return typeof t=="string"?t:t.toLocaleString("en-US")}const ui=({type:t,value:e,label:n,size:r="md",isAnimated:s=!1,onClick:o})=>{const i=h_[t],a=g_[r],l=f=>{o&&(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),o())},c=["inline-flex","items-center","rounded-full","font-medium","transition-all","duration-200",a.padding,a.gap,a.text,i.bgColor,i.textColor,s?"animate-bounce":"",o?"cursor-pointer hover:opacity-80":""].join(" "),d=u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"select-none",role:"img","aria-label":t,children:i.emoji}),u.jsx("span",{className:"font-semibold",children:m_(e)}),n&&u.jsx("span",{className:"text-gray-500 text-xs",children:n})]});return o?u.jsx("button",{type:"button",className:c,onClick:o,onKeyDown:l,tabIndex:0,role:"button",children:d}):u.jsx("span",{className:c,children:d})},sa={sm:{segmentWidth:16,barHeight:24,fontSize:16,operatorWidth:24,gap:2},md:{segmentWidth:20,barHeight:32,fontSize:24,operatorWidth:32,gap:2}},If={add:"+",subtract:"-",multiply:"×",divide:"÷"},fi={filled:"#10B981",empty:"#E5E7EB",operator:"#9CA3AF"};function hl(t,e){const n=sa[e];return t*n.segmentWidth+(t-1)*n.gap}function gl(t,e,n,r){const s=sa[r],o=[];for(let i=0;i<e;i++){const a=n+i*(s.segmentWidth+s.gap),l=i<t;o.push(u.jsx("rect",{x:a,y:0,width:s.segmentWidth,height:s.barHeight,rx:3,fill:l?fi.filled:fi.empty,className:`math-visualizer__segment ${l?"math-visualizer__segment--filled":"math-visualizer__segment--empty"}`},`segment-${i}`))}return o}const p_=({data:t,size:e})=>{const n=t,{fraction1:r,fraction2:s,operation:o}=n,i=sa[e],a=!!s&&!!o,l=hl(r.denominator,e),c=a?hl(s.denominator,e):0,d=a?i.operatorWidth:0,f=a?l+d+c:l,g=i.barHeight,h=l+d/2,m=l+d;return u.jsxs("svg",{width:f,height:g,viewBox:`0 0 ${f} ${g}`,className:"math-visualizer__svg",children:[u.jsx("g",{className:"math-visualizer__bar",children:gl(r.numerator,r.denominator,0,e)}),a&&u.jsx("text",{x:h,y:g/2,dy:"0.35em",textAnchor:"middle",fill:fi.operator,fontSize:i.fontSize,fontWeight:"bold",className:"math-visualizer__operator",children:If[o]||o}),a&&s&&u.jsx("g",{className:"math-visualizer__bar",transform:`translate(${m}, 0)`,children:gl(s.numerator,s.denominator,0,e)})]})},y_=({data:t,size:e})=>{const n=t,r=e==="sm"?"math-visualizer__formula--sm":"math-visualizer__formula--md";return u.jsx("div",{className:`math-visualizer__formula ${r}`,children:u.jsx("code",{className:"math-visualizer__formula-text",children:n.formula})})};function b_(t,e){if(t==="formula")return`Mathematical formula: ${e.formula}`;const n=e,{fraction1:r,fraction2:s,operation:o}=n;let i=`Fraction visualization: ${r.numerator} out of ${r.denominator} parts filled`;if(s&&o){const a=If[o]||o;i+=` ${a} ${s.numerator} out of ${s.denominator} parts filled`}return i}const x_=({type:t,data:e,size:n="md",className:r="","aria-label":s})=>{const o="math-visualizer",i=`${o}--${n}`,a=`${o} ${i} ${r}`.trim(),l=s||b_(t,e);return u.jsx("div",{className:a,role:"img","aria-label":l,children:t==="visual"?u.jsx(p_,{data:e,size:n}):u.jsx(y_,{data:e,size:n})})},v_="#3B82F6",ml=15.9155,w_=1e3,No=60;function Pf({value:t,size:e="sm",color:n=v_,titleEn:r,subTitleZh:s,maxLabel:o,centerContent:i,isAnimated:a=!0,className:l=""}){const c=x.useMemo(()=>t<0?0:t>100?100:t,[t]),[d,f]=x.useState(a?0:c),g=x.useMemo(()=>e==="lg"?{containerClass:"w-32 h-32",strokeWidth:3,valueTextClass:"text-3xl font-bold",percentTextClass:"text-sm",maxLabelClass:"text-xs text-gray-500 mt-0.5"}:{containerClass:"w-16 h-16",strokeWidth:4,valueTextClass:"text-sm font-bold",percentTextClass:"text-xs",maxLabelClass:"hidden"},[e]);x.useEffect(()=>{if(!a){f(c);return}f(0);const m=c/No,p=w_/No;let y=0;const b=setInterval(()=>{y++,y>=No?(f(c),clearInterval(b)):f(Math.round(m*y))},p);return()=>clearInterval(b)},[c,a]);const h=`${d}, 100`;return u.jsxs("div",{className:`radial-progress-wrapper flex flex-col items-center ${l}`,children:[u.jsxs("div",{className:`radial-progress-container relative ${g.containerClass}`,children:[u.jsxs("svg",{viewBox:"0 0 36 36",className:"w-full h-full block",style:{transform:"rotate(-90deg)"},children:[u.jsx("circle",{className:"radial-progress-bg text-gray-100",cx:"18",cy:"18",r:ml,fill:"none",stroke:"currentColor",strokeWidth:g.strokeWidth}),u.jsx("circle",{className:"radial-progress-bar",cx:"18",cy:"18",r:ml,fill:"none",stroke:n,strokeWidth:g.strokeWidth,strokeLinecap:"round",strokeDasharray:h,style:{transition:"stroke-dasharray 0.3s ease-out"}})]}),u.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:i||u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"flex items-baseline",children:[u.jsx("span",{className:g.valueTextClass,style:{color:n},children:d}),u.jsx("span",{className:`${g.percentTextClass} text-gray-400 ml-0.5`,children:"%"})]}),e==="lg"&&o&&u.jsx("span",{className:g.maxLabelClass,children:o})]})})]}),(r||s)&&u.jsxs("div",{className:"mt-2 text-center",children:[r&&u.jsx("div",{className:"text-sm font-semibold text-gray-800",children:r}),s&&u.jsx("div",{className:"text-xs text-gray-500",children:s})]})]})}const Ff=({tabs:t,activeId:e,onChange:n,size:r="lg",className:s="",isDisabled:o=!1,isFullWidth:i=!1,"aria-label":a})=>{const l=d=>{d!==e&&n(String(d))},c=d=>{if(o)return;const f=t.filter(h=>!h.isDisabled),g=f.findIndex(h=>h.id===e);switch(d.key){case"ArrowRight":{d.preventDefault();const h=(g+1)%f.length;n(f[h].id);break}case"ArrowLeft":{d.preventDefault();const h=g<=0?f.length-1:g-1;n(f[h].id);break}case"Home":{d.preventDefault(),f.length>0&&n(f[0].id);break}case"End":{d.preventDefault(),f.length>0&&n(f[f.length-1].id);break}}};return u.jsx(H.Tabs,{selectedKey:e,onSelectionChange:l,isDisabled:o,fullWidth:i,"aria-label":a,onKeyDown:c,variant:"bordered",color:"primary",radius:"full",children:t.map(d=>u.jsx(H.Tab,{title:u.jsx("span",{className:"text-sm font-medium",children:d.label}),isDisabled:d.isDisabled||o},d.id))})},__=()=>u.jsx("svg",{"data-testid":"checkmark-icon",className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})}),Df=({isCompleted:t,titleEn:e,titleZh:n,onToggle:r,isDisabled:s=!1,className:o=""})=>{const i=()=>{t||s||r?.(!0)},a=t?"bg-gray-50":"bg-white",l=t?"text-sm font-medium line-through text-gray-400 leading-loose":"text-sm font-medium text-gray-900 leading-loose",c=t?"text-xs text-gray-400 leading-loose":"text-xs text-gray-500 leading-loose",d=t?"w-5 h-5 rounded-full bg-brand-500 flex items-center justify-center":"w-5 h-5 rounded-full border-2 border-gray-300 hover:border-brand-500 flex items-center justify-center";return u.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-lg transition-colors ${a} ${o}`,"data-testid":"task-checkbox",children:[u.jsx("button",{type:"button",role:"button","aria-label":`${e} - ${n}`,"aria-pressed":t,disabled:s||t,onClick:i,className:"flex-shrink-0 mt-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2 rounded-full disabled:cursor-not-allowed",children:u.jsx("div",{"data-testid":"task-checkbox-icon",className:d,children:t&&u.jsx(__,{})})}),u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("span",{className:l,children:e}),u.jsx("span",{className:c,children:n})]})]})},S_=()=>u.jsx("div",{className:"flex items-center justify-center w-full h-full",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("div",{className:"flex gap-0.5",children:[u.jsx("div",{className:"w-4 h-6 bg-green-500 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"})]}),u.jsx("span",{className:"font-bold text-gray-400 mx-1",children:"+"}),u.jsxs("div",{className:"flex gap-0.5",children:[u.jsx("div",{className:"w-4 h-6 bg-green-500 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"}),u.jsx("div",{className:"w-4 h-6 bg-gray-200 rounded-sm"})]})]})});function C_({courseCategory:t,lessonTitleEn:e,lessonTitleZh:n,visualNode:r,onAction:s,className:o=""}){const i=()=>{s?.()},a=()=>{s?.()},l=d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),s?.())},c=`Continue lesson: ${e} - ${n}`;return u.jsx("div",{"data-testid":"action-hero-card",role:s?"button":void 0,tabIndex:s?0:void 0,"aria-label":s?c:void 0,onClick:i,onKeyDown:l,className:`
285
- bg-white rounded-2xl p-6
286
- border border-gray-200
287
- shadow-sm
288
- hover:-translate-y-[3px] hover:shadow-lg hover:border-blue-100
289
- transition-all duration-200 ease-out
290
- cursor-pointer
291
- h-full min-h-[240px]
292
- ${o}
293
- `.trim(),children:u.jsxs("div",{className:"flex flex-col md:flex-row gap-8 flex-1 h-full",children:[u.jsxs("div",{className:"flex-1 min-w-0 flex flex-col",children:[u.jsxs("div",{className:"inline-flex items-center gap-2 bg-blue-500 text-white px-4 py-1.5 rounded-full text-sm font-bold shadow-sm mb-3 w-fit group-hover:bg-blue-600 transition-colors",children:[u.jsx("span",{children:"1-Click Continue"}),u.jsx("span",{className:"font-normal opacity-80 border-l border-white/30 pl-2 ml-1",children:"一键继续"})]}),u.jsx("p",{className:"text-gray-500 text-sm font-semibold tracking-wide mb-2",children:t}),u.jsx("h2",{className:"text-gray-900 text-2xl font-bold leading-loose tracking-wide mb-4",children:e}),u.jsx("p",{className:"text-gray-500 text-lg leading-loose tracking-wide",children:n})]}),u.jsxs("div",{"data-testid":"visual-container",className:"w-full md:w-[44%] md:max-w-[240px] shrink-0 bg-gray-50 rounded-2xl p-4 border border-gray-100 flex flex-col items-center justify-between gap-4",children:[u.jsx("div",{className:"flex-1 flex items-center justify-center w-full min-h-[80px]",children:r||u.jsx(S_,{})}),u.jsxs(H.Button,{color:"primary",variant:"solid",radius:"full",fullWidth:!0,onPress:a,className:"font-medium bg-blue-600 hover:bg-blue-500",children:["Try this ",">"]})]})]})})}function Ir(t){return t+.5|0}const Ut=(t,e,n)=>Math.max(Math.min(t,n),e);function ar(t){return Ut(Ir(t*2.55),0,255)}function Ht(t){return Ut(Ir(t*255),0,255)}function jt(t){return Ut(Ir(t/2.55)/100,0,1)}function pl(t){return Ut(Ir(t*100),0,100)}const ot={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},hi=[..."0123456789ABCDEF"],R_=t=>hi[t&15],A_=t=>hi[(t&240)>>4]+hi[t&15],Zr=t=>(t&240)>>4===(t&15),k_=t=>Zr(t.r)&&Zr(t.g)&&Zr(t.b)&&Zr(t.a);function E_(t){var e=t.length,n;return t[0]==="#"&&(e===4||e===5?n={r:255&ot[t[1]]*17,g:255&ot[t[2]]*17,b:255&ot[t[3]]*17,a:e===5?ot[t[4]]*17:255}:(e===7||e===9)&&(n={r:ot[t[1]]<<4|ot[t[2]],g:ot[t[3]]<<4|ot[t[4]],b:ot[t[5]]<<4|ot[t[6]],a:e===9?ot[t[7]]<<4|ot[t[8]]:255})),n}const N_=(t,e)=>t<255?e(t):"";function T_(t){var e=k_(t)?R_:A_;return t?"#"+e(t.r)+e(t.g)+e(t.b)+N_(t.a,e):void 0}const M_=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lf(t,e,n){const r=e*Math.min(n,1-n),s=(o,i=(o+t/30)%12)=>n-r*Math.max(Math.min(i-3,9-i,1),-1);return[s(0),s(8),s(4)]}function $_(t,e,n){const r=(s,o=(s+t/60)%6)=>n-n*e*Math.max(Math.min(o,4-o,1),0);return[r(5),r(3),r(1)]}function j_(t,e,n){const r=Lf(t,1,.5);let s;for(e+n>1&&(s=1/(e+n),e*=s,n*=s),s=0;s<3;s++)r[s]*=1-e-n,r[s]+=e;return r}function O_(t,e,n,r,s){return t===s?(e-n)/r+(e<n?6:0):e===s?(n-t)/r+2:(t-e)/r+4}function oa(t){const n=t.r/255,r=t.g/255,s=t.b/255,o=Math.max(n,r,s),i=Math.min(n,r,s),a=(o+i)/2;let l,c,d;return o!==i&&(d=o-i,c=a>.5?d/(2-o-i):d/(o+i),l=O_(n,r,s,d,o),l=l*60+.5),[l|0,c||0,a]}function ia(t,e,n,r){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,n,r)).map(Ht)}function aa(t,e,n){return ia(Lf,t,e,n)}function I_(t,e,n){return ia(j_,t,e,n)}function P_(t,e,n){return ia($_,t,e,n)}function zf(t){return(t%360+360)%360}function F_(t){const e=M_.exec(t);let n=255,r;if(!e)return;e[5]!==r&&(n=e[6]?ar(+e[5]):Ht(+e[5]));const s=zf(+e[2]),o=+e[3]/100,i=+e[4]/100;return e[1]==="hwb"?r=I_(s,o,i):e[1]==="hsv"?r=P_(s,o,i):r=aa(s,o,i),{r:r[0],g:r[1],b:r[2],a:n}}function D_(t,e){var n=oa(t);n[0]=zf(n[0]+e),n=aa(n),t.r=n[0],t.g=n[1],t.b=n[2]}function L_(t){if(!t)return;const e=oa(t),n=e[0],r=pl(e[1]),s=pl(e[2]);return t.a<255?`hsla(${n}, ${r}%, ${s}%, ${jt(t.a)})`:`hsl(${n}, ${r}%, ${s}%)`}const yl={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},bl={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};function z_(){const t={},e=Object.keys(bl),n=Object.keys(yl);let r,s,o,i,a;for(r=0;r<e.length;r++){for(i=a=e[r],s=0;s<n.length;s++)o=n[s],a=a.replace(o,yl[o]);o=parseInt(bl[i],16),t[a]=[o>>16&255,o>>8&255,o&255]}return t}let Qr;function V_(t){Qr||(Qr=z_(),Qr.transparent=[0,0,0,0]);const e=Qr[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:e.length===4?e[3]:255}}const G_=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;function U_(t){const e=G_.exec(t);let n=255,r,s,o;if(e){if(e[7]!==r){const i=+e[7];n=e[8]?ar(i):Ut(i*255,0,255)}return r=+e[1],s=+e[3],o=+e[5],r=255&(e[2]?ar(r):Ut(r,0,255)),s=255&(e[4]?ar(s):Ut(s,0,255)),o=255&(e[6]?ar(o):Ut(o,0,255)),{r,g:s,b:o,a:n}}}function B_(t){return t&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${jt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`)}const To=t=>t<=.0031308?t*12.92:Math.pow(t,1/2.4)*1.055-.055,Cn=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function H_(t,e,n){const r=Cn(jt(t.r)),s=Cn(jt(t.g)),o=Cn(jt(t.b));return{r:Ht(To(r+n*(Cn(jt(e.r))-r))),g:Ht(To(s+n*(Cn(jt(e.g))-s))),b:Ht(To(o+n*(Cn(jt(e.b))-o))),a:t.a+n*(e.a-t.a)}}function es(t,e,n){if(t){let r=oa(t);r[e]=Math.max(0,Math.min(r[e]+r[e]*n,e===0?360:1)),r=aa(r),t.r=r[0],t.g=r[1],t.b=r[2]}}function Vf(t,e){return t&&Object.assign(e||{},t)}function xl(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Ht(t[3]))):(e=Vf(t,{r:0,g:0,b:0,a:1}),e.a=Ht(e.a)),e}function W_(t){return t.charAt(0)==="r"?U_(t):F_(t)}class xr{constructor(e){if(e instanceof xr)return e;const n=typeof e;let r;n==="object"?r=xl(e):n==="string"&&(r=E_(e)||V_(e)||W_(e)),this._rgb=r,this._valid=!!r}get valid(){return this._valid}get rgb(){var e=Vf(this._rgb);return e&&(e.a=jt(e.a)),e}set rgb(e){this._rgb=xl(e)}rgbString(){return this._valid?B_(this._rgb):void 0}hexString(){return this._valid?T_(this._rgb):void 0}hslString(){return this._valid?L_(this._rgb):void 0}mix(e,n){if(e){const r=this.rgb,s=e.rgb;let o;const i=n===o?.5:n,a=2*i-1,l=r.a-s.a,c=((a*l===-1?a:(a+l)/(1+a*l))+1)/2;o=1-c,r.r=255&c*r.r+o*s.r+.5,r.g=255&c*r.g+o*s.g+.5,r.b=255&c*r.b+o*s.b+.5,r.a=i*r.a+(1-i)*s.a,this.rgb=r}return this}interpolate(e,n){return e&&(this._rgb=H_(this._rgb,e._rgb,n)),this}clone(){return new xr(this.rgb)}alpha(e){return this._rgb.a=Ht(e),this}clearer(e){const n=this._rgb;return n.a*=1-e,this}greyscale(){const e=this._rgb,n=Ir(e.r*.3+e.g*.59+e.b*.11);return e.r=e.g=e.b=n,this}opaquer(e){const n=this._rgb;return n.a*=1+e,this}negate(){const e=this._rgb;return e.r=255-e.r,e.g=255-e.g,e.b=255-e.b,this}lighten(e){return es(this._rgb,2,e),this}darken(e){return es(this._rgb,2,-e),this}saturate(e){return es(this._rgb,1,e),this}desaturate(e){return es(this._rgb,1,-e),this}rotate(e){return D_(this._rgb,e),this}}function Et(){}const q_=(()=>{let t=0;return()=>t++})();function xe(t){return t==null}function Oe(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return e.slice(0,7)==="[object"&&e.slice(-6)==="Array]"}function ie(t){return t!==null&&Object.prototype.toString.call(t)==="[object Object]"}function Ue(t){return(typeof t=="number"||t instanceof Number)&&isFinite(+t)}function ht(t,e){return Ue(t)?t:e}function pe(t,e){return typeof t>"u"?e:t}const Y_=(t,e)=>typeof t=="string"&&t.endsWith("%")?parseFloat(t)/100*e:+t;function ke(t,e,n){if(t&&typeof t.call=="function")return t.apply(n,e)}function ge(t,e,n,r){let s,o,i;if(Oe(t))for(o=t.length,s=0;s<o;s++)e.call(n,t[s],s);else if(ie(t))for(i=Object.keys(t),o=i.length,s=0;s<o;s++)e.call(n,t[i[s]],i[s])}function Ms(t,e){let n,r,s,o;if(!t||!e||t.length!==e.length)return!1;for(n=0,r=t.length;n<r;++n)if(s=t[n],o=e[n],s.datasetIndex!==o.datasetIndex||s.index!==o.index)return!1;return!0}function $s(t){if(Oe(t))return t.map($s);if(ie(t)){const e=Object.create(null),n=Object.keys(t),r=n.length;let s=0;for(;s<r;++s)e[n[s]]=$s(t[n[s]]);return e}return t}function Gf(t){return["__proto__","prototype","constructor"].indexOf(t)===-1}function K_(t,e,n,r){if(!Gf(t))return;const s=e[t],o=n[t];ie(s)&&ie(o)?vr(s,o,r):e[t]=$s(o)}function vr(t,e,n){const r=Oe(e)?e:[e],s=r.length;if(!ie(t))return t;n=n||{};const o=n.merger||K_;let i;for(let a=0;a<s;++a){if(i=r[a],!ie(i))continue;const l=Object.keys(i);for(let c=0,d=l.length;c<d;++c)o(l[c],t,i,n)}return t}function ur(t,e){return vr(t,e,{merger:X_})}function X_(t,e,n){if(!Gf(t))return;const r=e[t],s=n[t];ie(r)&&ie(s)?ur(r,s):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=$s(s))}const vl={"":t=>t,x:t=>t.x,y:t=>t.y};function J_(t){const e=t.split("."),n=[];let r="";for(const s of e)r+=s,r.endsWith("\\")?r=r.slice(0,-1)+".":(n.push(r),r="");return n}function Z_(t){const e=J_(t);return n=>{for(const r of e){if(r==="")break;n=n&&n[r]}return n}}function js(t,e){return(vl[e]||(vl[e]=Z_(e)))(t)}function la(t){return t.charAt(0).toUpperCase()+t.slice(1)}const Os=t=>typeof t<"u",qt=t=>typeof t=="function",wl=(t,e)=>{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0};function Q_(t){return t.type==="mouseup"||t.type==="click"||t.type==="contextmenu"}const Ge=Math.PI,Ct=2*Ge,eS=Ct+Ge,Is=Number.POSITIVE_INFINITY,tS=Ge/180,lt=Ge/2,tn=Ge/4,_l=Ge*2/3,Uf=Math.log10,In=Math.sign;function fr(t,e,n){return Math.abs(t-e)<n}function Sl(t){const e=Math.round(t);t=fr(t,e,t/1e3)?e:t;const n=Math.pow(10,Math.floor(Uf(t))),r=t/n;return(r<=1?1:r<=2?2:r<=5?5:10)*n}function nS(t){const e=[],n=Math.sqrt(t);let r;for(r=1;r<n;r++)t%r===0&&(e.push(r),e.push(t/r));return n===(n|0)&&e.push(n),e.sort((s,o)=>s-o).pop(),e}function rS(t){return typeof t=="symbol"||typeof t=="object"&&t!==null&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}function wr(t){return!rS(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function sS(t,e){const n=Math.round(t);return n-e<=t&&n+e>=t}function oS(t,e,n){let r,s,o;for(r=0,s=t.length;r<s;r++)o=t[r][n],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function un(t){return t*(Ge/180)}function iS(t){return t*(180/Ge)}function Cl(t){if(!Ue(t))return;let e=1,n=0;for(;Math.round(t*e)/e!==t;)e*=10,n++;return n}function aS(t,e){const n=e.x-t.x,r=e.y-t.y,s=Math.sqrt(n*n+r*r);let o=Math.atan2(r,n);return o<-.5*Ge&&(o+=Ct),{angle:o,distance:s}}function gi(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function lS(t,e){return(t-e+eS)%Ct-Ge}function pt(t){return(t%Ct+Ct)%Ct}function Bf(t,e,n,r){const s=pt(t),o=pt(e),i=pt(n),a=pt(o-s),l=pt(i-s),c=pt(s-o),d=pt(s-i);return s===o||s===i||r&&o===i||a>l&&c<d}function it(t,e,n){return Math.max(e,Math.min(n,t))}function cS(t){return it(t,-32768,32767)}function Hf(t,e,n,r=1e-6){return t>=Math.min(e,n)-r&&t<=Math.max(e,n)+r}function ca(t,e,n){n=n||(i=>t[i]<e);let r=t.length-1,s=0,o;for(;r-s>1;)o=s+r>>1,n(o)?s=o:r=o;return{lo:s,hi:r}}const fn=(t,e,n,r)=>ca(t,n,r?s=>{const o=t[s][e];return o<n||o===n&&t[s+1][e]===n}:s=>t[s][e]<n),dS=(t,e,n)=>ca(t,n,r=>t[r][e]>=n);function uS(t,e,n){let r=0,s=t.length;for(;r<s&&t[r]<e;)r++;for(;s>r&&t[s-1]>n;)s--;return r>0||s<t.length?t.slice(r,s):t}const Wf=["push","pop","shift","splice","unshift"];function fS(t,e){if(t._chartjs){t._chartjs.listeners.push(e);return}Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),Wf.forEach(n=>{const r="_onData"+la(n),s=t[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!1,value(...o){const i=s.apply(this,o);return t._chartjs.listeners.forEach(a=>{typeof a[r]=="function"&&a[r](...o)}),i}})})}function Rl(t,e){const n=t._chartjs;if(!n)return;const r=n.listeners,s=r.indexOf(e);s!==-1&&r.splice(s,1),!(r.length>0)&&(Wf.forEach(o=>{delete t[o]}),delete t._chartjs)}function hS(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const qf=(function(){return typeof window>"u"?function(t){return t()}:window.requestAnimationFrame})();function Yf(t,e){let n=[],r=!1;return function(...s){n=s,r||(r=!0,qf.call(window,()=>{r=!1,t.apply(e,n)}))}}function gS(t,e){let n;return function(...r){return e?(clearTimeout(n),n=setTimeout(t,e,r)):t.apply(this,r),e}}const mS=t=>t==="start"?"left":t==="end"?"right":"center",Al=(t,e,n)=>t==="start"?e:t==="end"?n:(e+n)/2;function pS(t,e,n){const r=e.length;let s=0,o=r;if(t._sorted){const{iScale:i,vScale:a,_parsed:l}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=i.axis,{min:f,max:g,minDefined:h,maxDefined:m}=i.getUserBounds();if(h){if(s=Math.min(fn(l,d,f).lo,n?r:fn(e,d,i.getPixelForValue(f)).lo),c){const p=l.slice(0,s+1).reverse().findIndex(y=>!xe(y[a.axis]));s-=Math.max(0,p)}s=it(s,0,r-1)}if(m){let p=Math.max(fn(l,i.axis,g,!0).hi+1,n?0:fn(e,d,i.getPixelForValue(g),!0).hi+1);if(c){const y=l.slice(p-1).findIndex(b=>!xe(b[a.axis]));p+=Math.max(0,y)}o=it(p,s,r)-s}else o=r-s}return{start:s,count:o}}function yS(t){const{xScale:e,yScale:n,_scaleRanges:r}=t,s={xmin:e.min,xmax:e.max,ymin:n.min,ymax:n.max};if(!r)return t._scaleRanges=s,!0;const o=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==n.min||r.ymax!==n.max;return Object.assign(r,s),o}const ts=t=>t===0||t===1,kl=(t,e,n)=>-(Math.pow(2,10*(t-=1))*Math.sin((t-e)*Ct/n)),El=(t,e,n)=>Math.pow(2,-10*t)*Math.sin((t-e)*Ct/n)+1,hr={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>-Math.cos(t*lt)+1,easeOutSine:t=>Math.sin(t*lt),easeInOutSine:t=>-.5*(Math.cos(Ge*t)-1),easeInExpo:t=>t===0?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>t===1?1:-Math.pow(2,-10*t)+1,easeInOutExpo:t=>ts(t)?t:t<.5?.5*Math.pow(2,10*(t*2-1)):.5*(-Math.pow(2,-10*(t*2-1))+2),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ts(t)?t:kl(t,.075,.3),easeOutElastic:t=>ts(t)?t:El(t,.075,.3),easeInOutElastic(t){return ts(t)?t:t<.5?.5*kl(t*2,.1125,.45):.5+.5*El(t*2-1,.1125,.45)},easeInBack(t){return t*t*((1.70158+1)*t-1.70158)},easeOutBack(t){return(t-=1)*t*((1.70158+1)*t+1.70158)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?.5*(t*t*(((e*=1.525)+1)*t-e)):.5*((t-=2)*t*(((e*=1.525)+1)*t+e)+2)},easeInBounce:t=>1-hr.easeOutBounce(1-t),easeOutBounce(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:t=>t<.5?hr.easeInBounce(t*2)*.5:hr.easeOutBounce(t*2-1)*.5+.5};function da(t){if(t&&typeof t=="object"){const e=t.toString();return e==="[object CanvasPattern]"||e==="[object CanvasGradient]"}return!1}function Nl(t){return da(t)?t:new xr(t)}function Mo(t){return da(t)?t:new xr(t).saturate(.5).darken(.1).hexString()}const bS=["x","y","borderWidth","radius","tension"],xS=["color","borderColor","backgroundColor"];function vS(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:e=>e!=="onProgress"&&e!=="onComplete"&&e!=="fn"}),t.set("animations",{colors:{type:"color",properties:xS},numbers:{type:"number",properties:bS}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:e=>e|0}}}})}function wS(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}const Tl=new Map;function _S(t,e){e=e||{};const n=t+JSON.stringify(e);let r=Tl.get(n);return r||(r=new Intl.NumberFormat(t,e),Tl.set(n,r)),r}function Kf(t,e,n){return _S(e,n).format(t)}const SS={values(t){return Oe(t)?t:""+t},numeric(t,e,n){if(t===0)return"0";const r=this.chart.options.locale;let s,o=t;if(n.length>1){const c=Math.max(Math.abs(n[0].value),Math.abs(n[n.length-1].value));(c<1e-4||c>1e15)&&(s="scientific"),o=CS(t,n)}const i=Uf(Math.abs(o)),a=isNaN(i)?1:Math.max(Math.min(-1*Math.floor(i),20),0),l={notation:s,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(l,this.options.ticks.format),Kf(t,r,l)}};function CS(t,e){let n=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(n)>=1&&t!==Math.floor(t)&&(n=t-Math.floor(t)),n}var Xf={formatters:SS};function RS(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(e,n)=>n.lineWidth,tickColor:(e,n)=>n.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:Xf.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:e=>!e.startsWith("before")&&!e.startsWith("after")&&e!=="callback"&&e!=="parser",_indexable:e=>e!=="borderDash"&&e!=="tickBorderDash"&&e!=="dash"}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:e=>e!=="backdropPadding"&&e!=="callback",_indexable:e=>e!=="backdropPadding"})}const yn=Object.create(null),mi=Object.create(null);function gr(t,e){if(!e)return t;const n=e.split(".");for(let r=0,s=n.length;r<s;++r){const o=n[r];t=t[o]||(t[o]=Object.create(null))}return t}function $o(t,e,n){return typeof e=="string"?vr(gr(t,e),n):vr(gr(t,""),e)}class AS{constructor(e,n){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=r=>r.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(r,s)=>Mo(s.backgroundColor),this.hoverBorderColor=(r,s)=>Mo(s.borderColor),this.hoverColor=(r,s)=>Mo(s.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(e),this.apply(n)}set(e,n){return $o(this,e,n)}get(e){return gr(this,e)}describe(e,n){return $o(mi,e,n)}override(e,n){return $o(yn,e,n)}route(e,n,r,s){const o=gr(this,e),i=gr(this,r),a="_"+n;Object.defineProperties(o,{[a]:{value:o[n],writable:!0},[n]:{enumerable:!0,get(){const l=this[a],c=i[s];return ie(l)?Object.assign({},c,l):pe(l,c)},set(l){this[a]=l}}})}apply(e){e.forEach(n=>n(this))}}var Te=new AS({_scriptable:t=>!t.startsWith("on"),_indexable:t=>t!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[vS,wS,RS]);function kS(t){return!t||xe(t.size)||xe(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ml(t,e,n,r,s){let o=e[s];return o||(o=e[s]=t.measureText(s).width,n.push(s)),o>r&&(r=o),r}function nn(t,e,n){const r=t.currentDevicePixelRatio,s=n!==0?Math.max(n/2,.5):0;return Math.round((e-s)*r)/r+s}function $l(t,e){!e&&!t||(e=e||t.getContext("2d"),e.save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function pi(t,e,n,r){ES(t,e,n,r)}function ES(t,e,n,r,s){let o,i,a,l,c,d,f,g;const h=e.pointStyle,m=e.rotation,p=e.radius;let y=(m||0)*tS;if(h&&typeof h=="object"&&(o=h.toString(),o==="[object HTMLImageElement]"||o==="[object HTMLCanvasElement]")){t.save(),t.translate(n,r),t.rotate(y),t.drawImage(h,-h.width/2,-h.height/2,h.width,h.height),t.restore();return}if(!(isNaN(p)||p<=0)){switch(t.beginPath(),h){default:t.arc(n,r,p,0,Ct),t.closePath();break;case"triangle":d=p,t.moveTo(n+Math.sin(y)*d,r-Math.cos(y)*p),y+=_l,t.lineTo(n+Math.sin(y)*d,r-Math.cos(y)*p),y+=_l,t.lineTo(n+Math.sin(y)*d,r-Math.cos(y)*p),t.closePath();break;case"rectRounded":c=p*.516,l=p-c,i=Math.cos(y+tn)*l,f=Math.cos(y+tn)*l,a=Math.sin(y+tn)*l,g=Math.sin(y+tn)*l,t.arc(n-f,r-a,c,y-Ge,y-lt),t.arc(n+g,r-i,c,y-lt,y),t.arc(n+f,r+a,c,y,y+lt),t.arc(n-g,r+i,c,y+lt,y+Ge),t.closePath();break;case"rect":if(!m){l=Math.SQRT1_2*p,d=l,t.rect(n-d,r-l,2*d,2*l);break}y+=tn;case"rectRot":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+g,r-i),t.lineTo(n+f,r+a),t.lineTo(n-g,r+i),t.closePath();break;case"crossRot":y+=tn;case"cross":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i);break;case"star":f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i),y+=tn,f=Math.cos(y)*p,i=Math.cos(y)*p,a=Math.sin(y)*p,g=Math.sin(y)*p,t.moveTo(n-f,r-a),t.lineTo(n+f,r+a),t.moveTo(n+g,r-i),t.lineTo(n-g,r+i);break;case"line":i=Math.cos(y)*p,a=Math.sin(y)*p,t.moveTo(n-i,r-a),t.lineTo(n+i,r+a);break;case"dash":t.moveTo(n,r),t.lineTo(n+Math.cos(y)*p,r+Math.sin(y)*p);break;case!1:t.closePath();break}t.fill(),e.borderWidth>0&&t.stroke()}}function _r(t,e,n){return n=n||.5,!e||t&&t.x>e.left-n&&t.x<e.right+n&&t.y>e.top-n&&t.y<e.bottom+n}function ua(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function fa(t){t.restore()}function NS(t,e,n,r,s){if(!e)return t.lineTo(n.x,n.y);if(s==="middle"){const o=(e.x+n.x)/2;t.lineTo(o,e.y),t.lineTo(o,n.y)}else s==="after"!=!!r?t.lineTo(e.x,n.y):t.lineTo(n.x,e.y);t.lineTo(n.x,n.y)}function TS(t,e,n,r){if(!e)return t.lineTo(n.x,n.y);t.bezierCurveTo(r?e.cp1x:e.cp2x,r?e.cp1y:e.cp2y,r?n.cp2x:n.cp1x,r?n.cp2y:n.cp1y,n.x,n.y)}function MS(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),xe(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}function $S(t,e,n,r,s){if(s.strikethrough||s.underline){const o=t.measureText(r),i=e-o.actualBoundingBoxLeft,a=e+o.actualBoundingBoxRight,l=n-o.actualBoundingBoxAscent,c=n+o.actualBoundingBoxDescent,d=s.strikethrough?(l+c)/2:c;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=s.decorationWidth||2,t.moveTo(i,d),t.lineTo(a,d),t.stroke()}}function jS(t,e){const n=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=n}function jl(t,e,n,r,s,o={}){const i=Oe(e)?e:[e],a=o.strokeWidth>0&&o.strokeColor!=="";let l,c;for(t.save(),t.font=s.string,MS(t,o),l=0;l<i.length;++l)c=i[l],o.backdrop&&jS(t,o.backdrop),a&&(o.strokeColor&&(t.strokeStyle=o.strokeColor),xe(o.strokeWidth)||(t.lineWidth=o.strokeWidth),t.strokeText(c,n,r,o.maxWidth)),t.fillText(c,n,r,o.maxWidth),$S(t,n,r,c,o),r+=Number(s.lineHeight);t.restore()}function Ol(t,e){const{x:n,y:r,w:s,h:o,radius:i}=e;t.arc(n+i.topLeft,r+i.topLeft,i.topLeft,1.5*Ge,Ge,!0),t.lineTo(n,r+o-i.bottomLeft),t.arc(n+i.bottomLeft,r+o-i.bottomLeft,i.bottomLeft,Ge,lt,!0),t.lineTo(n+s-i.bottomRight,r+o),t.arc(n+s-i.bottomRight,r+o-i.bottomRight,i.bottomRight,lt,0,!0),t.lineTo(n+s,r+i.topRight),t.arc(n+s-i.topRight,r+i.topRight,i.topRight,0,-lt,!0),t.lineTo(n+i.topLeft,r)}const OS=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,IS=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function PS(t,e){const n=(""+t).match(OS);if(!n||n[1]==="normal")return e*1.2;switch(t=+n[2],n[3]){case"px":return t;case"%":t/=100;break}return e*t}const FS=t=>+t||0;function Jf(t,e){const n={},r=ie(e),s=r?Object.keys(e):e,o=ie(t)?r?i=>pe(t[i],t[e[i]]):i=>t[i]:()=>t;for(const i of s)n[i]=FS(o(i));return n}function DS(t){return Jf(t,{top:"y",right:"x",bottom:"y",left:"x"})}function _s(t){return Jf(t,["topLeft","topRight","bottomLeft","bottomRight"])}function Yt(t){const e=DS(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function _t(t,e){t=t||{},e=e||Te.font;let n=pe(t.size,e.size);typeof n=="string"&&(n=parseInt(n,10));let r=pe(t.style,e.style);r&&!(""+r).match(IS)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const s={family:pe(t.family,e.family),lineHeight:PS(pe(t.lineHeight,e.lineHeight),n),size:n,style:r,weight:pe(t.weight,e.weight),string:""};return s.string=kS(s),s}function ns(t,e,n,r){let s,o,i;for(s=0,o=t.length;s<o;++s)if(i=t[s],i!==void 0&&i!==void 0)return i}function LS(t,e,n){const{min:r,max:s}=t,o=Y_(e,(s-r)/2),i=(a,l)=>n&&a===0?0:a+l;return{min:i(r,-Math.abs(o)),max:i(s,o)}}function _n(t,e){return Object.assign(Object.create(t),e)}function ha(t,e=[""],n,r,s=()=>t[0]){const o=n||t;typeof r>"u"&&(r=th("_fallback",t));const i={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:r,_getTarget:s,override:a=>ha([a,...t],e,o,r)};return new Proxy(i,{deleteProperty(a,l){return delete a[l],delete a._keys,delete t[0][l],!0},get(a,l){return Qf(a,l,()=>qS(l,e,t,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(t[0])},has(a,l){return Pl(a).includes(l)},ownKeys(a){return Pl(a)},set(a,l,c){const d=a._storage||(a._storage=s());return a[l]=d[l]=c,delete a._keys,!0}})}function Pn(t,e,n,r){const s={_cacheable:!1,_proxy:t,_context:e,_subProxy:n,_stack:new Set,_descriptors:Zf(t,r),setContext:o=>Pn(t,o,n,r),override:o=>Pn(t.override(o),e,n,r)};return new Proxy(s,{deleteProperty(o,i){return delete o[i],delete t[i],!0},get(o,i,a){return Qf(o,i,()=>VS(o,i,a))},getOwnPropertyDescriptor(o,i){return o._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i)},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(o,i){return Reflect.has(t,i)},ownKeys(){return Reflect.ownKeys(t)},set(o,i,a){return t[i]=a,delete o[i],!0}})}function Zf(t,e={scriptable:!0,indexable:!0}){const{_scriptable:n=e.scriptable,_indexable:r=e.indexable,_allKeys:s=e.allKeys}=t;return{allKeys:s,scriptable:n,indexable:r,isScriptable:qt(n)?n:()=>n,isIndexable:qt(r)?r:()=>r}}const zS=(t,e)=>t?t+la(e):e,ga=(t,e)=>ie(e)&&t!=="adapters"&&(Object.getPrototypeOf(e)===null||e.constructor===Object);function Qf(t,e,n){if(Object.prototype.hasOwnProperty.call(t,e)||e==="constructor")return t[e];const r=n();return t[e]=r,r}function VS(t,e,n){const{_proxy:r,_context:s,_subProxy:o,_descriptors:i}=t;let a=r[e];return qt(a)&&i.isScriptable(e)&&(a=GS(e,a,t,n)),Oe(a)&&a.length&&(a=US(e,a,t,i.isIndexable)),ga(e,a)&&(a=Pn(a,s,o&&o[e],i)),a}function GS(t,e,n,r){const{_proxy:s,_context:o,_subProxy:i,_stack:a}=n;if(a.has(t))throw new Error("Recursion detected: "+Array.from(a).join("->")+"->"+t);a.add(t);let l=e(o,i||r);return a.delete(t),ga(t,l)&&(l=ma(s._scopes,s,t,l)),l}function US(t,e,n,r){const{_proxy:s,_context:o,_subProxy:i,_descriptors:a}=n;if(typeof o.index<"u"&&r(t))return e[o.index%e.length];if(ie(e[0])){const l=e,c=s._scopes.filter(d=>d!==l);e=[];for(const d of l){const f=ma(c,s,t,d);e.push(Pn(f,o,i&&i[t],a))}}return e}function eh(t,e,n){return qt(t)?t(e,n):t}const BS=(t,e)=>t===!0?e:typeof t=="string"?js(e,t):void 0;function HS(t,e,n,r,s){for(const o of e){const i=BS(n,o);if(i){t.add(i);const a=eh(i._fallback,n,s);if(typeof a<"u"&&a!==n&&a!==r)return a}else if(i===!1&&typeof r<"u"&&n!==r)return null}return!1}function ma(t,e,n,r){const s=e._rootScopes,o=eh(e._fallback,n,r),i=[...t,...s],a=new Set;a.add(r);let l=Il(a,i,n,o||n,r);return l===null||typeof o<"u"&&o!==n&&(l=Il(a,i,o,l,r),l===null)?!1:ha(Array.from(a),[""],s,o,()=>WS(e,n,r))}function Il(t,e,n,r,s){for(;n;)n=HS(t,e,n,r,s);return n}function WS(t,e,n){const r=t._getTarget();e in r||(r[e]={});const s=r[e];return Oe(s)&&ie(n)?n:s||{}}function qS(t,e,n,r){let s;for(const o of e)if(s=th(zS(o,t),n),typeof s<"u")return ga(t,s)?ma(n,r,t,s):s}function th(t,e){for(const n of e){if(!n)continue;const r=n[t];if(typeof r<"u")return r}}function Pl(t){let e=t._keys;return e||(e=t._keys=YS(t._scopes)),e}function YS(t){const e=new Set;for(const n of t)for(const r of Object.keys(n).filter(s=>!s.startsWith("_")))e.add(r);return Array.from(e)}const KS=Number.EPSILON||1e-14,Fn=(t,e)=>e<t.length&&!t[e].skip&&t[e],nh=t=>t==="x"?"y":"x";function XS(t,e,n,r){const s=t.skip?e:t,o=e,i=n.skip?e:n,a=gi(o,s),l=gi(i,o);let c=a/(a+l),d=l/(a+l);c=isNaN(c)?0:c,d=isNaN(d)?0:d;const f=r*c,g=r*d;return{previous:{x:o.x-f*(i.x-s.x),y:o.y-f*(i.y-s.y)},next:{x:o.x+g*(i.x-s.x),y:o.y+g*(i.y-s.y)}}}function JS(t,e,n){const r=t.length;let s,o,i,a,l,c=Fn(t,0);for(let d=0;d<r-1;++d)if(l=c,c=Fn(t,d+1),!(!l||!c)){if(fr(e[d],0,KS)){n[d]=n[d+1]=0;continue}s=n[d]/e[d],o=n[d+1]/e[d],a=Math.pow(s,2)+Math.pow(o,2),!(a<=9)&&(i=3/Math.sqrt(a),n[d]=s*i*e[d],n[d+1]=o*i*e[d])}}function ZS(t,e,n="x"){const r=nh(n),s=t.length;let o,i,a,l=Fn(t,0);for(let c=0;c<s;++c){if(i=a,a=l,l=Fn(t,c+1),!a)continue;const d=a[n],f=a[r];i&&(o=(d-i[n])/3,a[`cp1${n}`]=d-o,a[`cp1${r}`]=f-o*e[c]),l&&(o=(l[n]-d)/3,a[`cp2${n}`]=d+o,a[`cp2${r}`]=f+o*e[c])}}function QS(t,e="x"){const n=nh(e),r=t.length,s=Array(r).fill(0),o=Array(r);let i,a,l,c=Fn(t,0);for(i=0;i<r;++i)if(a=l,l=c,c=Fn(t,i+1),!!l){if(c){const d=c[e]-l[e];s[i]=d!==0?(c[n]-l[n])/d:0}o[i]=a?c?In(s[i-1])!==In(s[i])?0:(s[i-1]+s[i])/2:s[i-1]:s[i]}JS(t,s,o),ZS(t,o,e)}function rs(t,e,n){return Math.max(Math.min(t,n),e)}function eC(t,e){let n,r,s,o,i,a=_r(t[0],e);for(n=0,r=t.length;n<r;++n)i=o,o=a,a=n<r-1&&_r(t[n+1],e),o&&(s=t[n],i&&(s.cp1x=rs(s.cp1x,e.left,e.right),s.cp1y=rs(s.cp1y,e.top,e.bottom)),a&&(s.cp2x=rs(s.cp2x,e.left,e.right),s.cp2y=rs(s.cp2y,e.top,e.bottom)))}function tC(t,e,n,r,s){let o,i,a,l;if(e.spanGaps&&(t=t.filter(c=>!c.skip)),e.cubicInterpolationMode==="monotone")QS(t,s);else{let c=r?t[t.length-1]:t[0];for(o=0,i=t.length;o<i;++o)a=t[o],l=XS(c,a,t[Math.min(o+1,i-(r?0:1))%i],e.tension),a.cp1x=l.previous.x,a.cp1y=l.previous.y,a.cp2x=l.next.x,a.cp2y=l.next.y,c=a}e.capBezierPoints&&eC(t,n)}function pa(){return typeof window<"u"&&typeof document<"u"}function ya(t){let e=t.parentNode;return e&&e.toString()==="[object ShadowRoot]"&&(e=e.host),e}function Ps(t,e,n){let r;return typeof t=="string"?(r=parseInt(t,10),t.indexOf("%")!==-1&&(r=r/100*e.parentNode[n])):r=t,r}const to=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function nC(t,e){return to(t).getPropertyValue(e)}const rC=["top","right","bottom","left"];function gn(t,e,n){const r={};n=n?"-"+n:"";for(let s=0;s<4;s++){const o=rC[s];r[o]=parseFloat(t[e+"-"+o+n])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}const sC=(t,e,n)=>(t>0||e>0)&&(!n||!n.shadowRoot);function oC(t,e){const n=t.touches,r=n&&n.length?n[0]:t,{offsetX:s,offsetY:o}=r;let i=!1,a,l;if(sC(s,o,t.target))a=s,l=o;else{const c=e.getBoundingClientRect();a=r.clientX-c.left,l=r.clientY-c.top,i=!0}return{x:a,y:l,box:i}}function an(t,e){if("native"in t)return t;const{canvas:n,currentDevicePixelRatio:r}=e,s=to(n),o=s.boxSizing==="border-box",i=gn(s,"padding"),a=gn(s,"border","width"),{x:l,y:c,box:d}=oC(t,n),f=i.left+(d&&a.left),g=i.top+(d&&a.top);let{width:h,height:m}=e;return o&&(h-=i.width+a.width,m-=i.height+a.height),{x:Math.round((l-f)/h*n.width/r),y:Math.round((c-g)/m*n.height/r)}}function iC(t,e,n){let r,s;if(e===void 0||n===void 0){const o=t&&ya(t);if(!o)e=t.clientWidth,n=t.clientHeight;else{const i=o.getBoundingClientRect(),a=to(o),l=gn(a,"border","width"),c=gn(a,"padding");e=i.width-c.width-l.width,n=i.height-c.height-l.height,r=Ps(a.maxWidth,o,"clientWidth"),s=Ps(a.maxHeight,o,"clientHeight")}}return{width:e,height:n,maxWidth:r||Is,maxHeight:s||Is}}const Bt=t=>Math.round(t*10)/10;function aC(t,e,n,r){const s=to(t),o=gn(s,"margin"),i=Ps(s.maxWidth,t,"clientWidth")||Is,a=Ps(s.maxHeight,t,"clientHeight")||Is,l=iC(t,e,n);let{width:c,height:d}=l;if(s.boxSizing==="content-box"){const g=gn(s,"border","width"),h=gn(s,"padding");c-=h.width+g.width,d-=h.height+g.height}return c=Math.max(0,c-o.width),d=Math.max(0,r?c/r:d-o.height),c=Bt(Math.min(c,i,l.maxWidth)),d=Bt(Math.min(d,a,l.maxHeight)),c&&!d&&(d=Bt(c/2)),(e!==void 0||n!==void 0)&&r&&l.height&&d>l.height&&(d=l.height,c=Bt(Math.floor(d*r))),{width:c,height:d}}function Fl(t,e,n){const r=e||1,s=Bt(t.height*r),o=Bt(t.width*r);t.height=Bt(t.height),t.width=Bt(t.width);const i=t.canvas;return i.style&&(n||!i.style.height&&!i.style.width)&&(i.style.height=`${t.height}px`,i.style.width=`${t.width}px`),t.currentDevicePixelRatio!==r||i.height!==s||i.width!==o?(t.currentDevicePixelRatio=r,i.height=s,i.width=o,t.ctx.setTransform(r,0,0,r,0,0),!0):!1}const lC=(function(){let t=!1;try{const e={get passive(){return t=!0,!1}};pa()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch{}return t})();function Dl(t,e){const n=nC(t,e),r=n&&n.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function ln(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:t.y+n*(e.y-t.y)}}function cC(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:r==="middle"?n<.5?t.y:e.y:r==="after"?n<1?t.y:e.y:n>0?e.y:t.y}}function dC(t,e,n,r){const s={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},i=ln(t,s,n),a=ln(s,o,n),l=ln(o,e,n),c=ln(i,a,n),d=ln(a,l,n);return ln(c,d,n)}const uC=function(t,e){return{x(n){return t+t+e-n},setWidth(n){e=n},textAlign(n){return n==="center"?n:n==="right"?"left":"right"},xPlus(n,r){return n-r},leftForLtr(n,r){return n-r}}},fC=function(){return{x(t){return t},setWidth(t){},textAlign(t){return t},xPlus(t,e){return t+e},leftForLtr(t,e){return t}}};function jo(t,e,n){return t?uC(e,n):fC()}function hC(t,e){let n,r;(e==="ltr"||e==="rtl")&&(n=t.canvas.style,r=[n.getPropertyValue("direction"),n.getPropertyPriority("direction")],n.setProperty("direction",e,"important"),t.prevTextDirection=r)}function gC(t,e){e!==void 0&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function rh(t){return t==="angle"?{between:Bf,compare:lS,normalize:pt}:{between:Hf,compare:(e,n)=>e-n,normalize:e=>e}}function Ll({start:t,end:e,count:n,loop:r,style:s}){return{start:t%n,end:e%n,loop:r&&(e-t+1)%n===0,style:s}}function mC(t,e,n){const{property:r,start:s,end:o}=n,{between:i,normalize:a}=rh(r),l=e.length;let{start:c,end:d,loop:f}=t,g,h;if(f){for(c+=l,d+=l,g=0,h=l;g<h&&i(a(e[c%l][r]),s,o);++g)c--,d--;c%=l,d%=l}return d<c&&(d+=l),{start:c,end:d,loop:f,style:t.style}}function sh(t,e,n){if(!n)return[t];const{property:r,start:s,end:o}=n,i=e.length,{compare:a,between:l,normalize:c}=rh(r),{start:d,end:f,loop:g,style:h}=mC(t,e,n),m=[];let p=!1,y=null,b,w,v;const S=()=>l(s,v,b)&&a(s,v)!==0,_=()=>a(o,b)===0||l(o,v,b),A=()=>p||S(),C=()=>!p||_();for(let R=d,k=d;R<=f;++R)w=e[R%i],!w.skip&&(b=c(w[r]),b!==v&&(p=l(b,s,o),y===null&&A()&&(y=a(b,s)===0?R:k),y!==null&&C()&&(m.push(Ll({start:y,end:R,loop:g,count:i,style:h})),y=null),k=R,v=b));return y!==null&&m.push(Ll({start:y,end:f,loop:g,count:i,style:h})),m}function oh(t,e){const n=[],r=t.segments;for(let s=0;s<r.length;s++){const o=sh(r[s],t.points,e);o.length&&n.push(...o)}return n}function pC(t,e,n,r){let s=0,o=e-1;if(n&&!r)for(;s<e&&!t[s].skip;)s++;for(;s<e&&t[s].skip;)s++;for(s%=e,n&&(o+=s);o>s&&t[o%e].skip;)o--;return o%=e,{start:s,end:o}}function yC(t,e,n,r){const s=t.length,o=[];let i=e,a=t[e],l;for(l=e+1;l<=n;++l){const c=t[l%s];c.skip||c.stop?a.skip||(r=!1,o.push({start:e%s,end:(l-1)%s,loop:r}),e=i=c.stop?l:null):(i=l,a.skip&&(e=l)),a=c}return i!==null&&o.push({start:e%s,end:i%s,loop:r}),o}function bC(t,e){const n=t.points,r=t.options.spanGaps,s=n.length;if(!s)return[];const o=!!t._loop,{start:i,end:a}=pC(n,s,o,r);if(r===!0)return zl(t,[{start:i,end:a,loop:o}],n,e);const l=a<i?a+s:a,c=!!t._fullLoop&&i===0&&a===s-1;return zl(t,yC(n,i,l,c),n,e)}function zl(t,e,n,r){return!r||!r.setContext||!n?e:xC(t,e,n,r)}function xC(t,e,n,r){const s=t._chart.getContext(),o=Vl(t.options),{_datasetIndex:i,options:{spanGaps:a}}=t,l=n.length,c=[];let d=o,f=e[0].start,g=f;function h(m,p,y,b){const w=a?-1:1;if(m!==p){for(m+=l;n[m%l].skip;)m-=w;for(;n[p%l].skip;)p+=w;m%l!==p%l&&(c.push({start:m%l,end:p%l,loop:y,style:b}),d=b,f=p%l)}}for(const m of e){f=a?f:m.start;let p=n[f%l],y;for(g=f+1;g<=m.end;g++){const b=n[g%l];y=Vl(r.setContext(_n(s,{type:"segment",p0:p,p1:b,p0DataIndex:(g-1)%l,p1DataIndex:g%l,datasetIndex:i}))),vC(y,d)&&h(f,g-1,m.loop,d),p=b,d=y}f<g-1&&h(f,g-1,m.loop,d)}return c}function Vl(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function vC(t,e){if(!e)return!1;const n=[],r=function(s,o){return da(o)?(n.includes(o)||n.push(o),n.indexOf(o)):o};return JSON.stringify(t,r)!==JSON.stringify(e,r)}function ss(t,e,n){return t.options.clip?t[n]:e[n]}function wC(t,e){const{xScale:n,yScale:r}=t;return n&&r?{left:ss(n,e,"left"),right:ss(n,e,"right"),top:ss(r,e,"top"),bottom:ss(r,e,"bottom")}:e}function ih(t,e){const n=e._clip;if(n.disabled)return!1;const r=wC(e,t.chartArea);return{left:n.left===!1?0:r.left-(n.left===!0?0:n.left),right:n.right===!1?t.width:r.right+(n.right===!0?0:n.right),top:n.top===!1?0:r.top-(n.top===!0?0:n.top),bottom:n.bottom===!1?t.height:r.bottom+(n.bottom===!0?0:n.bottom)}}class _C{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(e,n,r,s){const o=n.listeners[s],i=n.duration;o.forEach(a=>a({chart:e,initial:n.initial,numSteps:i,currentStep:Math.min(r-n.start,i)}))}_refresh(){this._request||(this._running=!0,this._request=qf.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let n=0;this._charts.forEach((r,s)=>{if(!r.running||!r.items.length)return;const o=r.items;let i=o.length-1,a=!1,l;for(;i>=0;--i)l=o[i],l._active?(l._total>r.duration&&(r.duration=l._total),l.tick(e),a=!0):(o[i]=o[o.length-1],o.pop());a&&(s.draw(),this._notify(s,r,e,"progress")),o.length||(r.running=!1,this._notify(s,r,e,"complete"),r.initial=!1),n+=o.length}),this._lastDate=e,n===0&&(this._running=!1)}_getAnims(e){const n=this._charts;let r=n.get(e);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},n.set(e,r)),r}listen(e,n,r){this._getAnims(e).listeners[n].push(r)}add(e,n){!n||!n.length||this._getAnims(e).items.push(...n)}has(e){return this._getAnims(e).items.length>0}start(e){const n=this._charts.get(e);n&&(n.running=!0,n.start=Date.now(),n.duration=n.items.reduce((r,s)=>Math.max(r,s._duration),0),this._refresh())}running(e){if(!this._running)return!1;const n=this._charts.get(e);return!(!n||!n.running||!n.items.length)}stop(e){const n=this._charts.get(e);if(!n||!n.items.length)return;const r=n.items;let s=r.length-1;for(;s>=0;--s)r[s].cancel();n.items=[],this._notify(e,n,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var Nt=new _C;const Gl="transparent",SC={boolean(t,e,n){return n>.5?e:t},color(t,e,n){const r=Nl(t||Gl),s=r.valid&&Nl(e||Gl);return s&&s.valid?s.mix(r,n).hexString():e},number(t,e,n){return t+(e-t)*n}};class CC{constructor(e,n,r,s){const o=n[r];s=ns([e.to,s,o,e.from]);const i=ns([e.from,o,s]);this._active=!0,this._fn=e.fn||SC[e.type||typeof i],this._easing=hr[e.easing]||hr.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=n,this._prop=r,this._from=i,this._to=s,this._promises=void 0}active(){return this._active}update(e,n,r){if(this._active){this._notify(!1);const s=this._target[this._prop],o=r-this._start,i=this._duration-o;this._start=r,this._duration=Math.floor(Math.max(i,e.duration)),this._total+=o,this._loop=!!e.loop,this._to=ns([e.to,n,s,e.from]),this._from=ns([e.from,s,n])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const n=e-this._start,r=this._duration,s=this._prop,o=this._from,i=this._loop,a=this._to;let l;if(this._active=o!==a&&(i||n<r),!this._active){this._target[s]=a,this._notify(!0);return}if(n<0){this._target[s]=o;return}l=n/r%2,l=i&&l>1?2-l:l,l=this._easing(Math.min(1,Math.max(0,l))),this._target[s]=this._fn(o,a,l)}wait(){const e=this._promises||(this._promises=[]);return new Promise((n,r)=>{e.push({res:n,rej:r})})}_notify(e){const n=e?"res":"rej",r=this._promises||[];for(let s=0;s<r.length;s++)r[s][n]()}}class ah{constructor(e,n){this._chart=e,this._properties=new Map,this.configure(n)}configure(e){if(!ie(e))return;const n=Object.keys(Te.animation),r=this._properties;Object.getOwnPropertyNames(e).forEach(s=>{const o=e[s];if(!ie(o))return;const i={};for(const a of n)i[a]=o[a];(Oe(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(e,n){const r=n.options,s=AC(e,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&RC(e.options.$animations,r).then(()=>{e.options=r},()=>{}),o}_createAnimations(e,n){const r=this._properties,s=[],o=e.$animations||(e.$animations={}),i=Object.keys(n),a=Date.now();let l;for(l=i.length-1;l>=0;--l){const c=i[l];if(c.charAt(0)==="$")continue;if(c==="options"){s.push(...this._animateOptions(e,n));continue}const d=n[c];let f=o[c];const g=r.get(c);if(f)if(g&&f.active()){f.update(g,d,a);continue}else f.cancel();if(!g||!g.duration){e[c]=d;continue}o[c]=f=new CC(g,e,c,d),s.push(f)}return s}update(e,n){if(this._properties.size===0){Object.assign(e,n);return}const r=this._createAnimations(e,n);if(r.length)return Nt.add(this._chart,r),!0}}function RC(t,e){const n=[],r=Object.keys(e);for(let s=0;s<r.length;s++){const o=t[r[s]];o&&o.active()&&n.push(o.wait())}return Promise.all(n)}function AC(t,e){if(!e)return;let n=t.options;if(!n){t.options=e;return}return n.$shared&&(t.options=n=Object.assign({},n,{$shared:!1,$animations:{}})),n}function Ul(t,e){const n=t&&t.options||{},r=n.reverse,s=n.min===void 0?e:0,o=n.max===void 0?e:0;return{start:r?o:s,end:r?s:o}}function kC(t,e,n){if(n===!1)return!1;const r=Ul(t,n),s=Ul(e,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function EC(t){let e,n,r,s;return ie(t)?(e=t.top,n=t.right,r=t.bottom,s=t.left):e=n=r=s=t,{top:e,right:n,bottom:r,left:s,disabled:t===!1}}function lh(t,e){const n=[],r=t._getSortedDatasetMetas(e);let s,o;for(s=0,o=r.length;s<o;++s)n.push(r[s].index);return n}function Bl(t,e,n,r={}){const s=t.keys,o=r.mode==="single";let i,a,l,c;if(e===null)return;let d=!1;for(i=0,a=s.length;i<a;++i){if(l=+s[i],l===n){if(d=!0,r.all)continue;break}c=t.values[l],Ue(c)&&(o||e===0||In(e)===In(c))&&(e+=c)}return!d&&!r.all?0:e}function NC(t,e){const{iScale:n,vScale:r}=e,s=n.axis==="x"?"x":"y",o=r.axis==="x"?"x":"y",i=Object.keys(t),a=new Array(i.length);let l,c,d;for(l=0,c=i.length;l<c;++l)d=i[l],a[l]={[s]:d,[o]:t[d]};return a}function Oo(t,e){const n=t&&t.options.stacked;return n||n===void 0&&e.stack!==void 0}function TC(t,e,n){return`${t.id}.${e.id}.${n.stack||n.type}`}function MC(t){const{min:e,max:n,minDefined:r,maxDefined:s}=t.getUserBounds();return{min:r?e:Number.NEGATIVE_INFINITY,max:s?n:Number.POSITIVE_INFINITY}}function $C(t,e,n){const r=t[e]||(t[e]={});return r[n]||(r[n]={})}function Hl(t,e,n,r){for(const s of e.getMatchingVisibleMetas(r).reverse()){const o=t[s.index];if(n&&o>0||!n&&o<0)return s.index}return null}function Wl(t,e){const{chart:n,_cachedMeta:r}=t,s=n._stacks||(n._stacks={}),{iScale:o,vScale:i,index:a}=r,l=o.axis,c=i.axis,d=TC(o,i,r),f=e.length;let g;for(let h=0;h<f;++h){const m=e[h],{[l]:p,[c]:y}=m,b=m._stacks||(m._stacks={});g=b[c]=$C(s,d,p),g[a]=y,g._top=Hl(g,i,!0,r.type),g._bottom=Hl(g,i,!1,r.type);const w=g._visualValues||(g._visualValues={});w[a]=y}}function Io(t,e){const n=t.scales;return Object.keys(n).filter(r=>n[r].axis===e).shift()}function jC(t,e){return _n(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function OC(t,e,n){return _n(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:n,index:e,mode:"default",type:"data"})}function Zn(t,e){const n=t.controller.index,r=t.vScale&&t.vScale.axis;if(r){e=e||t._parsed;for(const s of e){const o=s._stacks;if(!o||o[r]===void 0||o[r][n]===void 0)return;delete o[r][n],o[r]._visualValues!==void 0&&o[r]._visualValues[n]!==void 0&&delete o[r]._visualValues[n]}}}const Po=t=>t==="reset"||t==="none",ql=(t,e)=>e?t:Object.assign({},t),IC=(t,e,n)=>t&&!e.hidden&&e._stacked&&{keys:lh(n,!0),values:null};class ch{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(e,n){this.chart=e,this._ctx=e.ctx,this.index=n,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=Oo(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&Zn(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(f,g,h,m)=>f==="x"?g:f==="r"?m:h,o=n.xAxisID=pe(r.xAxisID,Io(e,"x")),i=n.yAxisID=pe(r.yAxisID,Io(e,"y")),a=n.rAxisID=pe(r.rAxisID,Io(e,"r")),l=n.indexAxis,c=n.iAxisID=s(l,o,i,a),d=n.vAxisID=s(l,i,o,a);n.xScale=this.getScaleForId(o),n.yScale=this.getScaleForId(i),n.rScale=this.getScaleForId(a),n.iScale=this.getScaleForId(c),n.vScale=this.getScaleForId(d)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const n=this._cachedMeta;return e===n.iScale?n.vScale:n.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&Rl(this._data,this),e._stacked&&Zn(e)}_dataCheck(){const e=this.getDataset(),n=e.data||(e.data=[]),r=this._data;if(ie(n)){const s=this._cachedMeta;this._data=NC(n,s)}else if(r!==n){if(r){Rl(r,this);const s=this._cachedMeta;Zn(s),s._parsed=[]}n&&Object.isExtensible(n)&&fS(n,this),this._syncList=[],this._data=n}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const n=this._cachedMeta,r=this.getDataset();let s=!1;this._dataCheck();const o=n._stacked;n._stacked=Oo(n.vScale,n),n.stack!==r.stack&&(s=!0,Zn(n),n.stack=r.stack),this._resyncElements(e),(s||o!==n._stacked)&&(Wl(this,n._parsed),n._stacked=Oo(n.vScale,n))}configure(){const e=this.chart.config,n=e.datasetScopeKeys(this._type),r=e.getOptionScopes(this.getDataset(),n,!0);this.options=e.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,n){const{_cachedMeta:r,_data:s}=this,{iScale:o,_stacked:i}=r,a=o.axis;let l=e===0&&n===s.length?!0:r._sorted,c=e>0&&r._parsed[e-1],d,f,g;if(this._parsing===!1)r._parsed=s,r._sorted=!0,g=s;else{Oe(s[e])?g=this.parseArrayData(r,s,e,n):ie(s[e])?g=this.parseObjectData(r,s,e,n):g=this.parsePrimitiveData(r,s,e,n);const h=()=>f[a]===null||c&&f[a]<c[a];for(d=0;d<n;++d)r._parsed[d+e]=f=g[d],l&&(h()&&(l=!1),c=f);r._sorted=l}i&&Wl(this,g)}parsePrimitiveData(e,n,r,s){const{iScale:o,vScale:i}=e,a=o.axis,l=i.axis,c=o.getLabels(),d=o===i,f=new Array(s);let g,h,m;for(g=0,h=s;g<h;++g)m=g+r,f[g]={[a]:d||o.parse(c[m],m),[l]:i.parse(n[m],m)};return f}parseArrayData(e,n,r,s){const{xScale:o,yScale:i}=e,a=new Array(s);let l,c,d,f;for(l=0,c=s;l<c;++l)d=l+r,f=n[d],a[l]={x:o.parse(f[0],d),y:i.parse(f[1],d)};return a}parseObjectData(e,n,r,s){const{xScale:o,yScale:i}=e,{xAxisKey:a="x",yAxisKey:l="y"}=this._parsing,c=new Array(s);let d,f,g,h;for(d=0,f=s;d<f;++d)g=d+r,h=n[g],c[d]={x:o.parse(js(h,a),g),y:i.parse(js(h,l),g)};return c}getParsed(e){return this._cachedMeta._parsed[e]}getDataElement(e){return this._cachedMeta.data[e]}applyStack(e,n,r){const s=this.chart,o=this._cachedMeta,i=n[e.axis],a={keys:lh(s,!0),values:n._stacks[e.axis]._visualValues};return Bl(a,i,o.index,{mode:r})}updateRangeFromParsed(e,n,r,s){const o=r[n.axis];let i=o===null?NaN:o;const a=s&&r._stacks[n.axis];s&&a&&(s.values=a,i=Bl(s,o,this._cachedMeta.index)),e.min=Math.min(e.min,i),e.max=Math.max(e.max,i)}getMinMax(e,n){const r=this._cachedMeta,s=r._parsed,o=r._sorted&&e===r.iScale,i=s.length,a=this._getOtherScale(e),l=IC(n,r,this.chart),c={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=MC(a);let g,h;function m(){h=s[g];const p=h[a.axis];return!Ue(h[e.axis])||d>p||f<p}for(g=0;g<i&&!(!m()&&(this.updateRangeFromParsed(c,e,h,l),o));++g);if(o){for(g=i-1;g>=0;--g)if(!m()){this.updateRangeFromParsed(c,e,h,l);break}}return c}getAllParsedValues(e){const n=this._cachedMeta._parsed,r=[];let s,o,i;for(s=0,o=n.length;s<o;++s)i=n[s][e.axis],Ue(i)&&r.push(i);return r}getMaxOverflow(){return!1}getLabelAndValue(e){const n=this._cachedMeta,r=n.iScale,s=n.vScale,o=this.getParsed(e);return{label:r?""+r.getLabelForValue(o[r.axis]):"",value:s?""+s.getLabelForValue(o[s.axis]):""}}_update(e){const n=this._cachedMeta;this.update(e||"default"),n._clip=EC(pe(this.options.clip,kC(n.xScale,n.yScale,this.getMaxOverflow())))}update(e){}draw(){const e=this._ctx,n=this.chart,r=this._cachedMeta,s=r.data||[],o=n.chartArea,i=[],a=this._drawStart||0,l=this._drawCount||s.length-a,c=this.options.drawActiveElementsOnTop;let d;for(r.dataset&&r.dataset.draw(e,o,a,l),d=a;d<a+l;++d){const f=s[d];f.hidden||(f.active&&c?i.push(f):f.draw(e,o))}for(d=0;d<i.length;++d)i[d].draw(e,o)}getStyle(e,n){const r=n?"active":"default";return e===void 0&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(r):this.resolveDataElementOptions(e||0,r)}getContext(e,n,r){const s=this.getDataset();let o;if(e>=0&&e<this._cachedMeta.data.length){const i=this._cachedMeta.data[e];o=i.$context||(i.$context=OC(this.getContext(),e,i)),o.parsed=this.getParsed(e),o.raw=s.data[e],o.index=o.dataIndex=e}else o=this.$context||(this.$context=jC(this.chart.getContext(),this.index)),o.dataset=s,o.index=o.datasetIndex=this.index;return o.active=!!n,o.mode=r,o}resolveDatasetElementOptions(e){return this._resolveElementOptions(this.datasetElementType.id,e)}resolveDataElementOptions(e,n){return this._resolveElementOptions(this.dataElementType.id,n,e)}_resolveElementOptions(e,n="default",r){const s=n==="active",o=this._cachedDataOpts,i=e+"-"+n,a=o[i],l=this.enableOptionSharing&&Os(r);if(a)return ql(a,l);const c=this.chart.config,d=c.datasetElementScopeKeys(this._type,e),f=s?[`${e}Hover`,"hover",e,""]:[e,""],g=c.getOptionScopes(this.getDataset(),d),h=Object.keys(Te.elements[e]),m=()=>this.getContext(r,s,n),p=c.resolveNamedOptions(g,h,m,f);return p.$shared&&(p.$shared=l,o[i]=Object.freeze(ql(p,l))),p}_resolveAnimations(e,n,r){const s=this.chart,o=this._cachedDataOpts,i=`animation-${n}`,a=o[i];if(a)return a;let l;if(s.options.animation!==!1){const d=this.chart.config,f=d.datasetAnimationScopeKeys(this._type,n),g=d.getOptionScopes(this.getDataset(),f);l=d.createResolver(g,this.getContext(e,r,n))}const c=new ah(s,l&&l.animations);return l&&l._cacheable&&(o[i]=Object.freeze(c)),c}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,n){return!n||Po(e)||this.chart._animationsDisabled}_getSharedOptions(e,n){const r=this.resolveDataElementOptions(e,n),s=this._sharedOptions,o=this.getSharedOptions(r),i=this.includeOptions(n,o)||o!==s;return this.updateSharedOptions(o,n,r),{sharedOptions:o,includeOptions:i}}updateElement(e,n,r,s){Po(s)?Object.assign(e,r):this._resolveAnimations(n,s).update(e,r)}updateSharedOptions(e,n,r){e&&!Po(n)&&this._resolveAnimations(void 0,n).update(e,r)}_setStyle(e,n,r,s){e.active=s;const o=this.getStyle(n,s);this._resolveAnimations(n,r,s).update(e,{options:!s&&this.getSharedOptions(o)||o})}removeHoverStyle(e,n,r){this._setStyle(e,r,"active",!1)}setHoverStyle(e,n,r){this._setStyle(e,r,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const n=this._data,r=this._cachedMeta.data;for(const[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];const s=r.length,o=n.length,i=Math.min(o,s);i&&this.parse(0,i),o>s?this._insertElements(s,o-s,e):o<s&&this._removeElements(o,s-o)}_insertElements(e,n,r=!0){const s=this._cachedMeta,o=s.data,i=e+n;let a;const l=c=>{for(c.length+=n,a=c.length-1;a>=i;a--)c[a]=c[a-n]};for(l(o),a=e;a<i;++a)o[a]=new this.dataElementType;this._parsing&&l(s._parsed),this.parse(e,n),r&&this.updateElements(o,e,n,"reset")}updateElements(e,n,r,s){}_removeElements(e,n){const r=this._cachedMeta;if(this._parsing){const s=r._parsed.splice(e,n);r._stacked&&Zn(r,s)}r.data.splice(e,n)}_sync(e){if(this._parsing)this._syncList.push(e);else{const[n,r,s]=e;this[n](r,s)}this.chart._dataChanges.push([this.index,...e])}_onDataPush(){const e=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-e,e])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(e,n){n&&this._sync(["_removeElements",e,n]);const r=arguments.length-2;r&&this._sync(["_insertElements",e,r])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}class PC extends ch{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(e){const n=this._cachedMeta,{dataset:r,data:s=[],_dataset:o}=n,i=this.chart._animationsDisabled;let{start:a,count:l}=pS(n,s,i);this._drawStart=a,this._drawCount=l,yS(n)&&(a=0,l=s.length),r._chart=this.chart,r._datasetIndex=this.index,r._decimated=!!o._decimated,r.points=s;const c=this.resolveDatasetElementOptions(e);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(r,void 0,{animated:!i,options:c},e),this.updateElements(s,a,l,e)}updateElements(e,n,r,s){const o=s==="reset",{iScale:i,vScale:a,_stacked:l,_dataset:c}=this._cachedMeta,{sharedOptions:d,includeOptions:f}=this._getSharedOptions(n,s),g=i.axis,h=a.axis,{spanGaps:m,segment:p}=this.options,y=wr(m)?m:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||s==="none",w=n+r,v=e.length;let S=n>0&&this.getParsed(n-1);for(let _=0;_<v;++_){const A=e[_],C=b?A:{};if(_<n||_>=w){C.skip=!0;continue}const R=this.getParsed(_),k=xe(R[h]),M=C[g]=i.getPixelForValue(R[g],_),F=C[h]=o||k?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,R,l):R[h],_);C.skip=isNaN(M)||isNaN(F)||k,C.stop=_>0&&Math.abs(R[g]-S[g])>y,p&&(C.parsed=R,C.raw=c.data[_]),f&&(C.options=d||this.resolveDataElementOptions(_,A.active?"active":s)),b||this.updateElement(A,_,C,s),S=R}}getMaxOverflow(){const e=this._cachedMeta,n=e.dataset,r=n.options&&n.options.borderWidth||0,s=e.data||[];if(!s.length)return r;const o=s[0].size(this.resolveDataElementOptions(0)),i=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(r,o,i)/2}draw(){const e=this._cachedMeta;e.dataset.updateControlPoints(this.chart.chartArea,e.iScale.axis),super.draw()}}function rn(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class ba{static override(e){Object.assign(ba.prototype,e)}options;constructor(e){this.options=e||{}}init(){}formats(){return rn()}parse(){return rn()}format(){return rn()}add(){return rn()}diff(){return rn()}startOf(){return rn()}endOf(){return rn()}}var FC={_date:ba};function DC(t,e,n,r){const{controller:s,data:o,_sorted:i}=t,a=s._cachedMeta.iScale,l=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(a&&e===a.axis&&e!=="r"&&i&&o.length){const c=a._reversePixels?dS:fn;if(r){if(s._sharedOptions){const d=o[0],f=typeof d.getRange=="function"&&d.getRange(e);if(f){const g=c(o,e,n-f),h=c(o,e,n+f);return{lo:g.lo,hi:h.hi}}}}else{const d=c(o,e,n);if(l){const{vScale:f}=s._cachedMeta,{_parsed:g}=t,h=g.slice(0,d.lo+1).reverse().findIndex(p=>!xe(p[f.axis]));d.lo-=Math.max(0,h);const m=g.slice(d.hi).findIndex(p=>!xe(p[f.axis]));d.hi+=Math.max(0,m)}return d}}return{lo:0,hi:o.length-1}}function no(t,e,n,r,s){const o=t.getSortedVisibleDatasetMetas(),i=n[e];for(let a=0,l=o.length;a<l;++a){const{index:c,data:d}=o[a],{lo:f,hi:g}=DC(o[a],e,i,s);for(let h=f;h<=g;++h){const m=d[h];m.skip||r(m,c,h)}}}function LC(t){const e=t.indexOf("x")!==-1,n=t.indexOf("y")!==-1;return function(r,s){const o=e?Math.abs(r.x-s.x):0,i=n?Math.abs(r.y-s.y):0;return Math.sqrt(Math.pow(o,2)+Math.pow(i,2))}}function Fo(t,e,n,r,s){const o=[];return!s&&!t.isPointInArea(e)||no(t,n,e,function(a,l,c){!s&&!_r(a,t.chartArea,0)||a.inRange(e.x,e.y,r)&&o.push({element:a,datasetIndex:l,index:c})},!0),o}function zC(t,e,n,r){let s=[];function o(i,a,l){const{startAngle:c,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=aS(i,{x:e.x,y:e.y});Bf(f,c,d)&&s.push({element:i,datasetIndex:a,index:l})}return no(t,n,e,o),s}function VC(t,e,n,r,s,o){let i=[];const a=LC(n);let l=Number.POSITIVE_INFINITY;function c(d,f,g){const h=d.inRange(e.x,e.y,s);if(r&&!h)return;const m=d.getCenterPoint(s);if(!(!!o||t.isPointInArea(m))&&!h)return;const y=a(e,m);y<l?(i=[{element:d,datasetIndex:f,index:g}],l=y):y===l&&i.push({element:d,datasetIndex:f,index:g})}return no(t,n,e,c),i}function Do(t,e,n,r,s,o){return!o&&!t.isPointInArea(e)?[]:n==="r"&&!r?zC(t,e,n,s):VC(t,e,n,r,s,o)}function Yl(t,e,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return no(t,n,e,(l,c,d)=>{l[i]&&l[i](e[n],s)&&(o.push({element:l,datasetIndex:c,index:d}),a=a||l.inRange(e.x,e.y,s))}),r&&!a?[]:o}var GC={modes:{index(t,e,n,r){const s=an(e,t),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?Fo(t,s,o,r,i):Do(t,s,o,!1,r,i),l=[];return a.length?(t.getSortedVisibleDatasetMetas().forEach(c=>{const d=a[0].index,f=c.data[d];f&&!f.skip&&l.push({element:f,datasetIndex:c.index,index:d})}),l):[]},dataset(t,e,n,r){const s=an(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;let a=n.intersect?Fo(t,s,o,r,i):Do(t,s,o,!1,r,i);if(a.length>0){const l=a[0].datasetIndex,c=t.getDatasetMeta(l).data;a=[];for(let d=0;d<c.length;++d)a.push({element:c[d],datasetIndex:l,index:d})}return a},point(t,e,n,r){const s=an(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;return Fo(t,s,o,r,i)},nearest(t,e,n,r){const s=an(e,t),o=n.axis||"xy",i=n.includeInvisible||!1;return Do(t,s,o,n.intersect,r,i)},x(t,e,n,r){const s=an(e,t);return Yl(t,s,"x",n.intersect,r)},y(t,e,n,r){const s=an(e,t);return Yl(t,s,"y",n.intersect,r)}}};const dh=["left","top","right","bottom"];function Qn(t,e){return t.filter(n=>n.pos===e)}function Kl(t,e){return t.filter(n=>dh.indexOf(n.pos)===-1&&n.box.axis===e)}function er(t,e){return t.sort((n,r)=>{const s=e?r:n,o=e?n:r;return s.weight===o.weight?s.index-o.index:s.weight-o.weight})}function UC(t){const e=[];let n,r,s,o,i,a;for(n=0,r=(t||[]).length;n<r;++n)s=t[n],{position:o,options:{stack:i,stackWeight:a=1}}=s,e.push({index:n,box:s,pos:o,horizontal:s.isHorizontal(),weight:s.weight,stack:i&&o+i,stackWeight:a});return e}function BC(t){const e={};for(const n of t){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!dh.includes(s))continue;const i=e[r]||(e[r]={count:0,placed:0,weight:0,size:0});i.count++,i.weight+=o}return e}function HC(t,e){const n=BC(t),{vBoxMaxWidth:r,hBoxMaxHeight:s}=e;let o,i,a;for(o=0,i=t.length;o<i;++o){a=t[o];const{fullSize:l}=a.box,c=n[a.stack],d=c&&a.stackWeight/c.weight;a.horizontal?(a.width=d?d*r:l&&e.availableWidth,a.height=s):(a.width=r,a.height=d?d*s:l&&e.availableHeight)}return n}function WC(t){const e=UC(t),n=er(e.filter(c=>c.box.fullSize),!0),r=er(Qn(e,"left"),!0),s=er(Qn(e,"right")),o=er(Qn(e,"top"),!0),i=er(Qn(e,"bottom")),a=Kl(e,"x"),l=Kl(e,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(l).concat(i).concat(a),chartArea:Qn(e,"chartArea"),vertical:r.concat(s).concat(l),horizontal:o.concat(i).concat(a)}}function Xl(t,e,n,r){return Math.max(t[n],e[n])+Math.max(t[r],e[r])}function uh(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function qC(t,e,n,r){const{pos:s,box:o}=n,i=t.maxPadding;if(!ie(s)){n.size&&(t[s]-=n.size);const f=r[n.stack]||{size:0,count:1};f.size=Math.max(f.size,n.horizontal?o.height:o.width),n.size=f.size/f.count,t[s]+=n.size}o.getPadding&&uh(i,o.getPadding());const a=Math.max(0,e.outerWidth-Xl(i,t,"left","right")),l=Math.max(0,e.outerHeight-Xl(i,t,"top","bottom")),c=a!==t.w,d=l!==t.h;return t.w=a,t.h=l,n.horizontal?{same:c,other:d}:{same:d,other:c}}function YC(t){const e=t.maxPadding;function n(r){const s=Math.max(e[r]-t[r],0);return t[r]+=s,s}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}function KC(t,e){const n=e.maxPadding;function r(s){const o={left:0,top:0,right:0,bottom:0};return s.forEach(i=>{o[i]=Math.max(e[i],n[i])}),o}return r(t?["left","right"]:["top","bottom"])}function lr(t,e,n,r){const s=[];let o,i,a,l,c,d;for(o=0,i=t.length,c=0;o<i;++o){a=t[o],l=a.box,l.update(a.width||e.w,a.height||e.h,KC(a.horizontal,e));const{same:f,other:g}=qC(e,n,a,r);c|=f&&s.length,d=d||g,l.fullSize||s.push(a)}return c&&lr(s,e,n,r)||d}function os(t,e,n,r,s){t.top=n,t.left=e,t.right=e+r,t.bottom=n+s,t.width=r,t.height=s}function Jl(t,e,n,r){const s=n.padding;let{x:o,y:i}=e;for(const a of t){const l=a.box,c=r[a.stack]||{placed:0,weight:1},d=a.stackWeight/c.weight||1;if(a.horizontal){const f=e.w*d,g=c.size||l.height;Os(c.start)&&(i=c.start),l.fullSize?os(l,s.left,i,n.outerWidth-s.right-s.left,g):os(l,e.left+c.placed,i,f,g),c.start=i,c.placed+=f,i=l.bottom}else{const f=e.h*d,g=c.size||l.width;Os(c.start)&&(o=c.start),l.fullSize?os(l,o,s.top,g,n.outerHeight-s.bottom-s.top):os(l,o,e.top+c.placed,g,f),c.start=o,c.placed+=f,o=l.right}}e.x=o,e.y=i}var is={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(n){e.draw(n)}}]},t.boxes.push(e)},removeBox(t,e){const n=t.boxes?t.boxes.indexOf(e):-1;n!==-1&&t.boxes.splice(n,1)},configure(t,e,n){e.fullSize=n.fullSize,e.position=n.position,e.weight=n.weight},update(t,e,n,r){if(!t)return;const s=Yt(t.options.layout.padding),o=Math.max(e-s.width,0),i=Math.max(n-s.height,0),a=WC(t.boxes),l=a.vertical,c=a.horizontal;ge(t.boxes,p=>{typeof p.beforeLayout=="function"&&p.beforeLayout()});const d=l.reduce((p,y)=>y.box.options&&y.box.options.display===!1?p:p+1,0)||1,f=Object.freeze({outerWidth:e,outerHeight:n,padding:s,availableWidth:o,availableHeight:i,vBoxMaxWidth:o/2/d,hBoxMaxHeight:i/2}),g=Object.assign({},s);uh(g,Yt(r));const h=Object.assign({maxPadding:g,w:o,h:i,x:s.left,y:s.top},s),m=HC(l.concat(c),f);lr(a.fullSize,h,f,m),lr(l,h,f,m),lr(c,h,f,m)&&lr(l,h,f,m),YC(h),Jl(a.leftAndTop,h,f,m),h.x+=h.w,h.y+=h.h,Jl(a.rightAndBottom,h,f,m),t.chartArea={left:h.left,top:h.top,right:h.left+h.w,bottom:h.top+h.h,height:h.h,width:h.w},ge(a.chartArea,p=>{const y=p.box;Object.assign(y,t.chartArea),y.update(h.w,h.h,{left:0,top:0,right:0,bottom:0})})}};class fh{acquireContext(e,n){}releaseContext(e){return!1}addEventListener(e,n,r){}removeEventListener(e,n,r){}getDevicePixelRatio(){return 1}getMaximumSize(e,n,r,s){return n=Math.max(0,n||e.width),r=r||e.height,{width:n,height:Math.max(0,s?Math.floor(n/s):r)}}isAttached(e){return!0}updateConfig(e){}}class XC extends fh{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const Ss="$chartjs",JC={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Zl=t=>t===null||t==="";function ZC(t,e){const n=t.style,r=t.getAttribute("height"),s=t.getAttribute("width");if(t[Ss]={initial:{height:r,width:s,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",Zl(s)){const o=Dl(t,"width");o!==void 0&&(t.width=o)}if(Zl(r))if(t.style.height==="")t.height=t.width/(e||2);else{const o=Dl(t,"height");o!==void 0&&(t.height=o)}return t}const hh=lC?{passive:!0}:!1;function QC(t,e,n){t&&t.addEventListener(e,n,hh)}function eR(t,e,n){t&&t.canvas&&t.canvas.removeEventListener(e,n,hh)}function tR(t,e){const n=JC[t.type]||t.type,{x:r,y:s}=an(t,e);return{type:n,chart:e,native:t,x:r!==void 0?r:null,y:s!==void 0?s:null}}function Fs(t,e){for(const n of t)if(n===e||n.contains(e))return!0}function nR(t,e,n){const r=t.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||Fs(a.addedNodes,r),i=i&&!Fs(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function rR(t,e,n){const r=t.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||Fs(a.removedNodes,r),i=i&&!Fs(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const Sr=new Map;let Ql=0;function gh(){const t=window.devicePixelRatio;t!==Ql&&(Ql=t,Sr.forEach((e,n)=>{n.currentDevicePixelRatio!==t&&e()}))}function sR(t,e){Sr.size||window.addEventListener("resize",gh),Sr.set(t,e)}function oR(t){Sr.delete(t),Sr.size||window.removeEventListener("resize",gh)}function iR(t,e,n){const r=t.canvas,s=r&&ya(r);if(!s)return;const o=Yf((a,l)=>{const c=s.clientWidth;n(a,l),c<s.clientWidth&&n()},window),i=new ResizeObserver(a=>{const l=a[0],c=l.contentRect.width,d=l.contentRect.height;c===0&&d===0||o(c,d)});return i.observe(s),sR(t,o),i}function Lo(t,e,n){n&&n.disconnect(),e==="resize"&&oR(t)}function aR(t,e,n){const r=t.canvas,s=Yf(o=>{t.ctx!==null&&n(tR(o,t))},t);return QC(r,e,s),s}class lR extends fh{acquireContext(e,n){const r=e&&e.getContext&&e.getContext("2d");return r&&r.canvas===e?(ZC(e,n),r):null}releaseContext(e){const n=e.canvas;if(!n[Ss])return!1;const r=n[Ss].initial;["height","width"].forEach(o=>{const i=r[o];xe(i)?n.removeAttribute(o):n.setAttribute(o,i)});const s=r.style||{};return Object.keys(s).forEach(o=>{n.style[o]=s[o]}),n.width=n.width,delete n[Ss],!0}addEventListener(e,n,r){this.removeEventListener(e,n);const s=e.$proxies||(e.$proxies={}),i={attach:nR,detach:rR,resize:iR}[n]||aR;s[n]=i(e,n,r)}removeEventListener(e,n){const r=e.$proxies||(e.$proxies={}),s=r[n];if(!s)return;({attach:Lo,detach:Lo,resize:Lo}[n]||eR)(e,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,n,r,s){return aC(e,n,r,s)}isAttached(e){const n=e&&ya(e);return!!(n&&n.isConnected)}}function cR(t){return!pa()||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas?XC:lR}class Pr{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(e){const{x:n,y:r}=this.getProps(["x","y"],e);return{x:n,y:r}}hasValue(){return wr(this.x)&&wr(this.y)}getProps(e,n){const r=this.$animations;if(!n||!r)return this;const s={};return e.forEach(o=>{s[o]=r[o]&&r[o].active()?r[o]._to:this[o]}),s}}function dR(t,e){const n=t.options.ticks,r=uR(t),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?hR(e):[],i=o.length,a=o[0],l=o[i-1],c=[];if(i>s)return gR(e,c,o,i/s),c;const d=fR(o,e,s);if(i>0){let f,g;const h=i>1?Math.round((l-a)/(i-1)):null;for(as(e,c,d,xe(h)?0:a-h,a),f=0,g=i-1;f<g;f++)as(e,c,d,o[f],o[f+1]);return as(e,c,d,l,xe(h)?e.length:l+h),c}return as(e,c,d),c}function uR(t){const e=t.options.offset,n=t._tickSize(),r=t._length/n+(e?0:1),s=t._maxLength/n;return Math.floor(Math.min(r,s))}function fR(t,e,n){const r=mR(t),s=e.length/n;if(!r)return Math.max(s,1);const o=nS(r);for(let i=0,a=o.length-1;i<a;i++){const l=o[i];if(l>s)return l}return Math.max(s,1)}function hR(t){const e=[];let n,r;for(n=0,r=t.length;n<r;n++)t[n].major&&e.push(n);return e}function gR(t,e,n,r){let s=0,o=n[0],i;for(r=Math.ceil(r),i=0;i<t.length;i++)i===o&&(e.push(t[i]),s++,o=n[s*r])}function as(t,e,n,r,s){const o=pe(r,0),i=Math.min(pe(s,t.length),t.length);let a=0,l,c,d;for(n=Math.ceil(n),s&&(l=s-r,n=l/Math.floor(l/n)),d=o;d<0;)a++,d=Math.round(o+a*n);for(c=Math.max(o,0);c<i;c++)c===d&&(e.push(t[c]),a++,d=Math.round(o+a*n))}function mR(t){const e=t.length;let n,r;if(e<2)return!1;for(r=t[0],n=1;n<e;++n)if(t[n]-t[n-1]!==r)return!1;return r}const pR=t=>t==="left"?"right":t==="right"?"left":t,ec=(t,e,n)=>e==="top"||e==="left"?t[e]+n:t[e]-n,tc=(t,e)=>Math.min(e||t,t);function nc(t,e){const n=[],r=t.length/e,s=t.length;let o=0;for(;o<s;o+=r)n.push(t[Math.floor(o)]);return n}function yR(t,e,n){const r=t.ticks.length,s=Math.min(e,r-1),o=t._startPixel,i=t._endPixel,a=1e-6;let l=t.getPixelForTick(s),c;if(!(n&&(r===1?c=Math.max(l-o,i-l):e===0?c=(t.getPixelForTick(1)-l)/2:c=(l-t.getPixelForTick(s-1))/2,l+=s<e?c:-c,l<o-a||l>i+a)))return l}function bR(t,e){ge(t,n=>{const r=n.gc,s=r.length/2;let o;if(s>e){for(o=0;o<s;++o)delete n.data[r[o]];r.splice(0,s)}})}function tr(t){return t.drawTicks?t.tickLength:0}function rc(t,e){if(!t.display)return 0;const n=_t(t.font,e),r=Yt(t.padding);return(Oe(t.text)?t.text.length:1)*n.lineHeight+r.height}function xR(t,e){return _n(t,{scale:e,type:"scale"})}function vR(t,e,n){return _n(t,{tick:n,index:e,type:"tick"})}function wR(t,e,n){let r=mS(t);return(n&&e!=="right"||!n&&e==="right")&&(r=pR(r)),r}function _R(t,e,n,r){const{top:s,left:o,bottom:i,right:a,chart:l}=t,{chartArea:c,scales:d}=l;let f=0,g,h,m;const p=i-s,y=a-o;if(t.isHorizontal()){if(h=Al(r,o,a),ie(n)){const b=Object.keys(n)[0],w=n[b];m=d[b].getPixelForValue(w)+p-e}else n==="center"?m=(c.bottom+c.top)/2+p-e:m=ec(t,n,e);g=a-o}else{if(ie(n)){const b=Object.keys(n)[0],w=n[b];h=d[b].getPixelForValue(w)-y+e}else n==="center"?h=(c.left+c.right)/2-y+e:h=ec(t,n,e);m=Al(r,i,s),f=n==="left"?-lt:lt}return{titleX:h,titleY:m,maxWidth:g,rotation:f}}class Wn extends Pr{constructor(e){super(),this.id=e.id,this.type=e.type,this.options=void 0,this.ctx=e.ctx,this.chart=e.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(e){this.options=e.setContext(this.getContext()),this.axis=e.axis,this._userMin=this.parse(e.min),this._userMax=this.parse(e.max),this._suggestedMin=this.parse(e.suggestedMin),this._suggestedMax=this.parse(e.suggestedMax)}parse(e,n){return e}getUserBounds(){let{_userMin:e,_userMax:n,_suggestedMin:r,_suggestedMax:s}=this;return e=ht(e,Number.POSITIVE_INFINITY),n=ht(n,Number.NEGATIVE_INFINITY),r=ht(r,Number.POSITIVE_INFINITY),s=ht(s,Number.NEGATIVE_INFINITY),{min:ht(e,r),max:ht(n,s),minDefined:Ue(e),maxDefined:Ue(n)}}getMinMax(e){let{min:n,max:r,minDefined:s,maxDefined:o}=this.getUserBounds(),i;if(s&&o)return{min:n,max:r};const a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;l<c;++l)i=a[l].controller.getMinMax(this,e),s||(n=Math.min(n,i.min)),o||(r=Math.max(r,i.max));return n=o&&n>r?r:n,r=s&&n>r?n:r,{min:ht(n,ht(r,n)),max:ht(r,ht(n,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){ke(this.options.beforeUpdate,[this])}update(e,n,r){const{beginAtZero:s,grace:o,ticks:i}=this.options,a=i.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=n,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=LS(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?nc(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=dR(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),l&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let e=this.options.reverse,n,r;this.isHorizontal()?(n=this.left,r=this.right):(n=this.top,r=this.bottom,e=!e),this._startPixel=n,this._endPixel=r,this._reversePixels=e,this._length=r-n,this._alignToPixels=this.options.alignToPixels}afterUpdate(){ke(this.options.afterUpdate,[this])}beforeSetDimensions(){ke(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){ke(this.options.afterSetDimensions,[this])}_callHooks(e){this.chart.notifyPlugins(e,this.getContext()),ke(this.options[e],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){ke(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(e){const n=this.options.ticks;let r,s,o;for(r=0,s=e.length;r<s;r++)o=e[r],o.label=ke(n.callback,[o.value,r,e],this)}afterTickToLabelConversion(){ke(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){ke(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const e=this.options,n=e.ticks,r=tc(this.ticks.length,e.ticks.maxTicksLimit),s=n.minRotation||0,o=n.maxRotation;let i=s,a,l,c;if(!this._isVisible()||!n.display||s>=o||r<=1||!this.isHorizontal()){this.labelRotation=s;return}const d=this._getLabelSizes(),f=d.widest.width,g=d.highest.height,h=it(this.chart.width-f,0,this.maxWidth);a=e.offset?this.maxWidth/r:h/(r-1),f+6>a&&(a=h/(r-(e.offset?.5:1)),l=this.maxHeight-tr(e.grid)-n.padding-rc(e.title,this.chart.options.font),c=Math.sqrt(f*f+g*g),i=iS(Math.min(Math.asin(it((d.highest.height+6)/a,-1,1)),Math.asin(it(l/c,-1,1))-Math.asin(it(g/c,-1,1)))),i=Math.max(s,Math.min(o,i))),this.labelRotation=i}afterCalculateLabelRotation(){ke(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){ke(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:n,options:{ticks:r,title:s,grid:o}}=this,i=this._isVisible(),a=this.isHorizontal();if(i){const l=rc(s,n.options.font);if(a?(e.width=this.maxWidth,e.height=tr(o)+l):(e.height=this.maxHeight,e.width=tr(o)+l),r.display&&this.ticks.length){const{first:c,last:d,widest:f,highest:g}=this._getLabelSizes(),h=r.padding*2,m=un(this.labelRotation),p=Math.cos(m),y=Math.sin(m);if(a){const b=r.mirror?0:y*f.width+p*g.height;e.height=Math.min(this.maxHeight,e.height+b+h)}else{const b=r.mirror?0:p*f.width+y*g.height;e.width=Math.min(this.maxWidth,e.width+b+h)}this._calculatePadding(c,d,y,p)}}this._handleMargins(),a?(this.width=this._length=n.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=n.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,n,r,s){const{ticks:{align:o,padding:i},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){const d=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let g=0,h=0;l?c?(g=s*e.width,h=r*n.height):(g=r*e.height,h=s*n.width):o==="start"?h=n.width:o==="end"?g=e.width:o!=="inner"&&(g=e.width/2,h=n.width/2),this.paddingLeft=Math.max((g-d+i)*this.width/(this.width-d),0),this.paddingRight=Math.max((h-f+i)*this.width/(this.width-f),0)}else{let d=n.height/2,f=e.height/2;o==="start"?(d=0,f=e.height):o==="end"&&(d=n.height,f=0),this.paddingTop=d+i,this.paddingBottom=f+i}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){ke(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:n}=this.options;return n==="top"||n==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let n,r;for(n=0,r=e.length;n<r;n++)xe(e[n].label)&&(e.splice(n,1),r--,n--);this.afterTickToLabelConversion()}_getLabelSizes(){let e=this._labelSizes;if(!e){const n=this.options.ticks.sampleSize;let r=this.ticks;n<r.length&&(r=nc(r,n)),this._labelSizes=e=this._computeLabelSizes(r,r.length,this.options.ticks.maxTicksLimit)}return e}_computeLabelSizes(e,n,r){const{ctx:s,_longestTextCache:o}=this,i=[],a=[],l=Math.floor(n/tc(n,r));let c=0,d=0,f,g,h,m,p,y,b,w,v,S,_;for(f=0;f<n;f+=l){if(m=e[f].label,p=this._resolveTickFontOptions(f),s.font=y=p.string,b=o[y]=o[y]||{data:{},gc:[]},w=p.lineHeight,v=S=0,!xe(m)&&!Oe(m))v=Ml(s,b.data,b.gc,v,m),S=w;else if(Oe(m))for(g=0,h=m.length;g<h;++g)_=m[g],!xe(_)&&!Oe(_)&&(v=Ml(s,b.data,b.gc,v,_),S+=w);i.push(v),a.push(S),c=Math.max(v,c),d=Math.max(S,d)}bR(o,n);const A=i.indexOf(c),C=a.indexOf(d),R=k=>({width:i[k]||0,height:a[k]||0});return{first:R(0),last:R(n-1),widest:R(A),highest:R(C),widths:i,heights:a}}getLabelForValue(e){return e}getPixelForValue(e,n){return NaN}getValueForPixel(e){}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const n=this._startPixel+e*this._length;return cS(this._alignToPixels?nn(this.chart,n,0):n)}getDecimalForPixel(e){const n=(e-this._startPixel)/this._length;return this._reversePixels?1-n:n}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:n}=this;return e<0&&n<0?n:e>0&&n>0?e:0}getContext(e){const n=this.ticks||[];if(e>=0&&e<n.length){const r=n[e];return r.$context||(r.$context=vR(this.getContext(),e,r))}return this.$context||(this.$context=xR(this.chart.getContext(),this))}_tickSize(){const e=this.options.ticks,n=un(this.labelRotation),r=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n)),o=this._getLabelSizes(),i=e.autoSkipPadding||0,a=o?o.widest.width+i:0,l=o?o.highest.height+i:0;return this.isHorizontal()?l*r>a*s?a/r:l/s:l*s<a*r?l/r:a/s}_isVisible(){const e=this.options.display;return e!=="auto"?!!e:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(e){const n=this.axis,r=this.chart,s=this.options,{grid:o,position:i,border:a}=s,l=o.offset,c=this.isHorizontal(),f=this.ticks.length+(l?1:0),g=tr(o),h=[],m=a.setContext(this.getContext()),p=m.display?m.width:0,y=p/2,b=function(T){return nn(r,T,p)};let w,v,S,_,A,C,R,k,M,F,D,P;if(i==="top")w=b(this.bottom),C=this.bottom-g,k=w-y,F=b(e.top)+y,P=e.bottom;else if(i==="bottom")w=b(this.top),F=e.top,P=b(e.bottom)-y,C=w+y,k=this.top+g;else if(i==="left")w=b(this.right),A=this.right-g,R=w-y,M=b(e.left)+y,D=e.right;else if(i==="right")w=b(this.left),M=e.left,D=b(e.right)-y,A=w+y,R=this.left+g;else if(n==="x"){if(i==="center")w=b((e.top+e.bottom)/2+.5);else if(ie(i)){const T=Object.keys(i)[0],B=i[T];w=b(this.chart.scales[T].getPixelForValue(B))}F=e.top,P=e.bottom,C=w+y,k=C+g}else if(n==="y"){if(i==="center")w=b((e.left+e.right)/2);else if(ie(i)){const T=Object.keys(i)[0],B=i[T];w=b(this.chart.scales[T].getPixelForValue(B))}A=w-y,R=A-g,M=e.left,D=e.right}const j=pe(s.ticks.maxTicksLimit,f),O=Math.max(1,Math.ceil(f/j));for(v=0;v<f;v+=O){const T=this.getContext(v),B=o.setContext(T),$=a.setContext(T),Q=B.lineWidth,oe=B.color,se=$.dash||[],ee=$.dashOffset,L=B.tickWidth,X=B.tickColor,ae=B.tickBorderDash||[],ve=B.tickBorderDashOffset;S=yR(this,v,l),S!==void 0&&(_=nn(r,S,Q),c?A=R=M=D=_:C=k=F=P=_,h.push({tx1:A,ty1:C,tx2:R,ty2:k,x1:M,y1:F,x2:D,y2:P,width:Q,color:oe,borderDash:se,borderDashOffset:ee,tickWidth:L,tickColor:X,tickBorderDash:ae,tickBorderDashOffset:ve}))}return this._ticksLength=f,this._borderValue=w,h}_computeLabelItems(e){const n=this.axis,r=this.options,{position:s,ticks:o}=r,i=this.isHorizontal(),a=this.ticks,{align:l,crossAlign:c,padding:d,mirror:f}=o,g=tr(r.grid),h=g+d,m=f?-d:h,p=-un(this.labelRotation),y=[];let b,w,v,S,_,A,C,R,k,M,F,D,P="middle";if(s==="top")A=this.bottom-m,C=this._getXAxisLabelAlignment();else if(s==="bottom")A=this.top+m,C=this._getXAxisLabelAlignment();else if(s==="left"){const O=this._getYAxisLabelAlignment(g);C=O.textAlign,_=O.x}else if(s==="right"){const O=this._getYAxisLabelAlignment(g);C=O.textAlign,_=O.x}else if(n==="x"){if(s==="center")A=(e.top+e.bottom)/2+h;else if(ie(s)){const O=Object.keys(s)[0],T=s[O];A=this.chart.scales[O].getPixelForValue(T)+h}C=this._getXAxisLabelAlignment()}else if(n==="y"){if(s==="center")_=(e.left+e.right)/2-h;else if(ie(s)){const O=Object.keys(s)[0],T=s[O];_=this.chart.scales[O].getPixelForValue(T)}C=this._getYAxisLabelAlignment(g).textAlign}n==="y"&&(l==="start"?P="top":l==="end"&&(P="bottom"));const j=this._getLabelSizes();for(b=0,w=a.length;b<w;++b){v=a[b],S=v.label;const O=o.setContext(this.getContext(b));R=this.getPixelForTick(b)+o.labelOffset,k=this._resolveTickFontOptions(b),M=k.lineHeight,F=Oe(S)?S.length:1;const T=F/2,B=O.color,$=O.textStrokeColor,Q=O.textStrokeWidth;let oe=C;i?(_=R,C==="inner"&&(b===w-1?oe=this.options.reverse?"left":"right":b===0?oe=this.options.reverse?"right":"left":oe="center"),s==="top"?c==="near"||p!==0?D=-F*M+M/2:c==="center"?D=-j.highest.height/2-T*M+M:D=-j.highest.height+M/2:c==="near"||p!==0?D=M/2:c==="center"?D=j.highest.height/2-T*M:D=j.highest.height-F*M,f&&(D*=-1),p!==0&&!O.showLabelBackdrop&&(_+=M/2*Math.sin(p))):(A=R,D=(1-F)*M/2);let se;if(O.showLabelBackdrop){const ee=Yt(O.backdropPadding),L=j.heights[b],X=j.widths[b];let ae=D-ee.top,ve=0-ee.left;switch(P){case"middle":ae-=L/2;break;case"bottom":ae-=L;break}switch(C){case"center":ve-=X/2;break;case"right":ve-=X;break;case"inner":b===w-1?ve-=X:b>0&&(ve-=X/2);break}se={left:ve,top:ae,width:X+ee.width,height:L+ee.height,color:O.backdropColor}}y.push({label:S,font:k,textOffset:D,options:{rotation:p,color:B,strokeColor:$,strokeWidth:Q,textAlign:oe,textBaseline:P,translation:[_,A],backdrop:se}})}return y}_getXAxisLabelAlignment(){const{position:e,ticks:n}=this.options;if(-un(this.labelRotation))return e==="top"?"left":"right";let s="center";return n.align==="start"?s="left":n.align==="end"?s="right":n.align==="inner"&&(s="inner"),s}_getYAxisLabelAlignment(e){const{position:n,ticks:{crossAlign:r,mirror:s,padding:o}}=this.options,i=this._getLabelSizes(),a=e+o,l=i.widest.width;let c,d;return n==="left"?s?(d=this.right+o,r==="near"?c="left":r==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,r==="near"?c="right":r==="center"?(c="center",d-=l/2):(c="left",d=this.left)):n==="right"?s?(d=this.left+o,r==="near"?c="right":r==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,r==="near"?c="left":r==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,n=this.options.position;if(n==="left"||n==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(n==="top"||n==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:n},left:r,top:s,width:o,height:i}=this;n&&(e.save(),e.fillStyle=n,e.fillRect(r,s,o,i),e.restore())}getLineWidthForValue(e){const n=this.options.grid;if(!this._isVisible()||!n.display)return 0;const s=this.ticks.findIndex(o=>o.value===e);return s>=0?n.setContext(this.getContext(s)).lineWidth:0}drawGrid(e){const n=this.options.grid,r=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let o,i;const a=(l,c,d)=>{!d.width||!d.color||(r.save(),r.lineWidth=d.width,r.strokeStyle=d.color,r.setLineDash(d.borderDash||[]),r.lineDashOffset=d.borderDashOffset,r.beginPath(),r.moveTo(l.x,l.y),r.lineTo(c.x,c.y),r.stroke(),r.restore())};if(n.display)for(o=0,i=s.length;o<i;++o){const l=s[o];n.drawOnChartArea&&a({x:l.x1,y:l.y1},{x:l.x2,y:l.y2},l),n.drawTicks&&a({x:l.tx1,y:l.ty1},{x:l.tx2,y:l.ty2},{color:l.tickColor,width:l.tickWidth,borderDash:l.tickBorderDash,borderDashOffset:l.tickBorderDashOffset})}}drawBorder(){const{chart:e,ctx:n,options:{border:r,grid:s}}=this,o=r.setContext(this.getContext()),i=r.display?o.width:0;if(!i)return;const a=s.setContext(this.getContext(0)).lineWidth,l=this._borderValue;let c,d,f,g;this.isHorizontal()?(c=nn(e,this.left,i)-i/2,d=nn(e,this.right,a)+a/2,f=g=l):(f=nn(e,this.top,i)-i/2,g=nn(e,this.bottom,a)+a/2,c=d=l),n.save(),n.lineWidth=o.width,n.strokeStyle=o.color,n.beginPath(),n.moveTo(c,f),n.lineTo(d,g),n.stroke(),n.restore()}drawLabels(e){if(!this.options.ticks.display)return;const r=this.ctx,s=this._computeLabelArea();s&&ua(r,s);const o=this.getLabelItems(e);for(const i of o){const a=i.options,l=i.font,c=i.label,d=i.textOffset;jl(r,c,0,d,l,a)}s&&fa(r)}drawTitle(){const{ctx:e,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=_t(r.font),i=Yt(r.padding),a=r.align;let l=o.lineHeight/2;n==="bottom"||n==="center"||ie(n)?(l+=i.bottom,Oe(r.text)&&(l+=o.lineHeight*(r.text.length-1))):l+=i.top;const{titleX:c,titleY:d,maxWidth:f,rotation:g}=_R(this,l,n,a);jl(e,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:g,textAlign:wR(a,n,s),textBaseline:"middle",translation:[c,d]})}draw(e){this._isVisible()&&(this.drawBackground(),this.drawGrid(e),this.drawBorder(),this.drawTitle(),this.drawLabels(e))}_layers(){const e=this.options,n=e.ticks&&e.ticks.z||0,r=pe(e.grid&&e.grid.z,-1),s=pe(e.border&&e.border.z,0);return!this._isVisible()||this.draw!==Wn.prototype.draw?[{z:n,draw:o=>{this.draw(o)}}]:[{z:r,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:n,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(e){const n=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",s=[];let o,i;for(o=0,i=n.length;o<i;++o){const a=n[o];a[r]===this.id&&(!e||a.type===e)&&s.push(a)}return s}_resolveTickFontOptions(e){const n=this.options.ticks.setContext(this.getContext(e));return _t(n.font)}_maxDigits(){const e=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/e}}class ls{constructor(e,n,r){this.type=e,this.scope=n,this.override=r,this.items=Object.create(null)}isForType(e){return Object.prototype.isPrototypeOf.call(this.type.prototype,e.prototype)}register(e){const n=Object.getPrototypeOf(e);let r;RR(n)&&(r=this.register(n));const s=this.items,o=e.id,i=this.scope+"."+o;if(!o)throw new Error("class does not have id: "+e);return o in s||(s[o]=e,SR(e,i,r),this.override&&Te.override(e.id,e.overrides)),i}get(e){return this.items[e]}unregister(e){const n=this.items,r=e.id,s=this.scope;r in n&&delete n[r],s&&r in Te[s]&&(delete Te[s][r],this.override&&delete yn[r])}}function SR(t,e,n){const r=vr(Object.create(null),[n?Te.get(n):{},Te.get(e),t.defaults]);Te.set(e,r),t.defaultRoutes&&CR(e,t.defaultRoutes),t.descriptors&&Te.describe(e,t.descriptors)}function CR(t,e){Object.keys(e).forEach(n=>{const r=n.split("."),s=r.pop(),o=[t].concat(r).join("."),i=e[n].split("."),a=i.pop(),l=i.join(".");Te.route(o,s,l,a)})}function RR(t){return"id"in t&&"defaults"in t}class AR{constructor(){this.controllers=new ls(ch,"datasets",!0),this.elements=new ls(Pr,"elements"),this.plugins=new ls(Object,"plugins"),this.scales=new ls(Wn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,n,r){[...n].forEach(s=>{const o=r||this._getRegistryForType(s);r||o.isForType(s)||o===this.plugins&&s.id?this._exec(e,o,s):ge(s,i=>{const a=r||this._getRegistryForType(i);this._exec(e,a,i)})})}_exec(e,n,r){const s=la(e);ke(r["before"+s],[],r),n[e](r),ke(r["after"+s],[],r)}_getRegistryForType(e){for(let n=0;n<this._typedRegistries.length;n++){const r=this._typedRegistries[n];if(r.isForType(e))return r}return this.plugins}_get(e,n,r){const s=n.get(e);if(s===void 0)throw new Error('"'+e+'" is not a registered '+r+".");return s}}var mt=new AR;class kR{constructor(){this._init=void 0}notify(e,n,r,s){if(n==="beforeInit"&&(this._init=this._createDescriptors(e,!0),this._notify(this._init,e,"install")),this._init===void 0)return;const o=s?this._descriptors(e).filter(s):this._descriptors(e),i=this._notify(o,e,n,r);return n==="afterDestroy"&&(this._notify(o,e,"stop"),this._notify(this._init,e,"uninstall"),this._init=void 0),i}_notify(e,n,r,s){s=s||{};for(const o of e){const i=o.plugin,a=i[r],l=[n,s,o.options];if(ke(a,l,i)===!1&&s.cancelable)return!1}return!0}invalidate(){xe(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(e){if(this._cache)return this._cache;const n=this._cache=this._createDescriptors(e);return this._notifyStateChanges(e),n}_createDescriptors(e,n){const r=e&&e.config,s=pe(r.options&&r.options.plugins,{}),o=ER(r);return s===!1&&!n?[]:TR(e,o,s,n)}_notifyStateChanges(e){const n=this._oldCache||[],r=this._cache,s=(o,i)=>o.filter(a=>!i.some(l=>a.plugin.id===l.plugin.id));this._notify(s(n,r),e,"stop"),this._notify(s(r,n),e,"start")}}function ER(t){const e={},n=[],r=Object.keys(mt.plugins.items);for(let o=0;o<r.length;o++)n.push(mt.getPlugin(r[o]));const s=t.plugins||[];for(let o=0;o<s.length;o++){const i=s[o];n.indexOf(i)===-1&&(n.push(i),e[i.id]=!0)}return{plugins:n,localIds:e}}function NR(t,e){return!e&&t===!1?null:t===!0?{}:t}function TR(t,{plugins:e,localIds:n},r,s){const o=[],i=t.getContext();for(const a of e){const l=a.id,c=NR(r[l],s);c!==null&&o.push({plugin:a,options:MR(t.config,{plugin:a,local:n[l]},c,i)})}return o}function MR(t,{plugin:e,local:n},r,s){const o=t.pluginScopeKeys(e),i=t.getOptionScopes(r,o);return n&&e.defaults&&i.push(e.defaults),t.createResolver(i,s,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function yi(t,e){const n=Te.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||n.indexAxis||"x"}function $R(t,e){let n=t;return t==="_index_"?n=e:t==="_value_"&&(n=e==="x"?"y":"x"),n}function jR(t,e){return t===e?"_index_":"_value_"}function sc(t){if(t==="x"||t==="y"||t==="r")return t}function OR(t){if(t==="top"||t==="bottom")return"x";if(t==="left"||t==="right")return"y"}function bi(t,...e){if(sc(t))return t;for(const n of e){const r=n.axis||OR(n.position)||t.length>1&&sc(t[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function oc(t,e,n){if(n[e+"AxisID"]===t)return{axis:e}}function IR(t,e){if(e.data&&e.data.datasets){const n=e.data.datasets.filter(r=>r.xAxisID===t||r.yAxisID===t);if(n.length)return oc(t,"x",n[0])||oc(t,"y",n[0])}return{}}function PR(t,e){const n=yn[t.type]||{scales:{}},r=e.scales||{},s=yi(t.type,e),o=Object.create(null);return Object.keys(r).forEach(i=>{const a=r[i];if(!ie(a))return console.error(`Invalid scale configuration for scale: ${i}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${i}`);const l=bi(i,a,IR(i,t),Te.scales[a.type]),c=jR(l,s),d=n.scales||{};o[i]=ur(Object.create(null),[{axis:l},a,d[l],d[c]])}),t.data.datasets.forEach(i=>{const a=i.type||t.type,l=i.indexAxis||yi(a,e),d=(yn[a]||{}).scales||{};Object.keys(d).forEach(f=>{const g=$R(f,l),h=i[g+"AxisID"]||g;o[h]=o[h]||Object.create(null),ur(o[h],[{axis:g},r[h],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];ur(a,[Te.scales[a.type],Te.scale])}),o}function mh(t){const e=t.options||(t.options={});e.plugins=pe(e.plugins,{}),e.scales=PR(t,e)}function ph(t){return t=t||{},t.datasets=t.datasets||[],t.labels=t.labels||[],t}function FR(t){return t=t||{},t.data=ph(t.data),mh(t),t}const ic=new Map,yh=new Set;function cs(t,e){let n=ic.get(t);return n||(n=e(),ic.set(t,n),yh.add(n)),n}const nr=(t,e,n)=>{const r=js(e,n);r!==void 0&&t.add(r)};class DR{constructor(e){this._config=FR(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=ph(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),mh(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return cs(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,n){return cs(`${e}.transition.${n}`,()=>[[`datasets.${e}.transitions.${n}`,`transitions.${n}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,n){return cs(`${e}-${n}`,()=>[[`datasets.${e}.elements.${n}`,`datasets.${e}`,`elements.${n}`,""]])}pluginScopeKeys(e){const n=e.id,r=this.type;return cs(`${r}-plugin-${n}`,()=>[[`plugins.${n}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,n){const r=this._scopeCache;let s=r.get(e);return(!s||n)&&(s=new Map,r.set(e,s)),s}getOptionScopes(e,n,r){const{options:s,type:o}=this,i=this._cachedScopes(e,r),a=i.get(n);if(a)return a;const l=new Set;n.forEach(d=>{e&&(l.add(e),d.forEach(f=>nr(l,e,f))),d.forEach(f=>nr(l,s,f)),d.forEach(f=>nr(l,yn[o]||{},f)),d.forEach(f=>nr(l,Te,f)),d.forEach(f=>nr(l,mi,f))});const c=Array.from(l);return c.length===0&&c.push(Object.create(null)),yh.has(n)&&i.set(n,c),c}chartOptionScopes(){const{options:e,type:n}=this;return[e,yn[n]||{},Te.datasets[n]||{},{type:n},Te,mi]}resolveNamedOptions(e,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=ac(this._resolverCache,e,s);let l=i;if(zR(i,n)){o.$shared=!1,r=qt(r)?r():r;const c=this.createResolver(e,r,a);l=Pn(i,r,c)}for(const c of n)o[c]=l[c];return o}createResolver(e,n,r=[""],s){const{resolver:o}=ac(this._resolverCache,e,r);return ie(n)?Pn(o,n,void 0,s):o}}function ac(t,e,n){let r=t.get(e);r||(r=new Map,t.set(e,r));const s=n.join();let o=r.get(s);return o||(o={resolver:ha(e,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const LR=t=>ie(t)&&Object.getOwnPropertyNames(t).some(e=>qt(t[e]));function zR(t,e){const{isScriptable:n,isIndexable:r}=Zf(t);for(const s of e){const o=n(s),i=r(s),a=(i||o)&&t[s];if(o&&(qt(a)||LR(a))||i&&Oe(a))return!0}return!1}var VR="4.5.1";const GR=["top","bottom","left","right","chartArea"];function lc(t,e){return t==="top"||t==="bottom"||GR.indexOf(t)===-1&&e==="x"}function cc(t,e){return function(n,r){return n[t]===r[t]?n[e]-r[e]:n[t]-r[t]}}function dc(t){const e=t.chart,n=e.options.animation;e.notifyPlugins("afterRender"),ke(n&&n.onComplete,[t],e)}function UR(t){const e=t.chart,n=e.options.animation;ke(n&&n.onProgress,[t],e)}function bh(t){return pa()&&typeof t=="string"?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cs={},uc=t=>{const e=bh(t);return Object.values(Cs).filter(n=>n.canvas===e).pop()};function BR(t,e,n){const r=Object.keys(t);for(const s of r){const o=+s;if(o>=e){const i=t[s];delete t[s],(n>0||o>e)&&(t[o+n]=i)}}}function HR(t,e,n,r){return!n||t.type==="mouseout"?null:r?e:t}let ro=class{static defaults=Te;static instances=Cs;static overrides=yn;static registry=mt;static version=VR;static getChart=uc;static register(...e){mt.add(...e),fc()}static unregister(...e){mt.remove(...e),fc()}constructor(e,n){const r=this.config=new DR(n),s=bh(e),o=uc(s);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const i=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||cR(s)),this.platform.updateConfig(r);const a=this.platform.acquireContext(s,i.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=q_(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,this._options=i,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new kR,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=gS(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],Cs[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}Nt.listen(this,"complete",dc),Nt.listen(this,"progress",UR),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:n},width:r,height:s,_aspectRatio:o}=this;return xe(e)?n&&o?o:s?r/s:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return mt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():Fl(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return $l(this.canvas,this.ctx),this}stop(){return Nt.stop(this),this}resize(e,n){Nt.running(this)?this._resizeBeforeDraw={width:e,height:n}:this._resize(e,n)}_resize(e,n){const r=this.options,s=this.canvas,o=r.maintainAspectRatio&&this.aspectRatio,i=this.platform.getMaximumSize(s,e,n,o),a=r.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=i.width,this.height=i.height,this._aspectRatio=this.aspectRatio,Fl(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),ke(r.onResize,[this,i],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};ge(n,(r,s)=>{r.id=s})}buildOrUpdateScales(){const e=this.options,n=e.scales,r=this.scales,s=Object.keys(r).reduce((i,a)=>(i[a]=!1,i),{});let o=[];n&&(o=o.concat(Object.keys(n).map(i=>{const a=n[i],l=bi(i,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),ge(o,i=>{const a=i.options,l=a.id,c=bi(l,a),d=pe(a.type,i.dtype);(a.position===void 0||lc(a.position,c)!==lc(i.dposition))&&(a.position=i.dposition),s[l]=!0;let f=null;if(l in r&&r[l].type===d)f=r[l];else{const g=mt.getScale(d);f=new g({id:l,type:d,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(a,e)}),ge(s,(i,a)=>{i||delete r[a]}),ge(r,i=>{is.configure(this,i,i.options),is.addBox(this,i)})}_updateMetasets(){const e=this._metasets,n=this.data.datasets.length,r=e.length;if(e.sort((s,o)=>s.index-o.index),r>n){for(let s=n;s<r;++s)this._destroyDatasetMeta(s);e.splice(n,r-n)}this._sortedMetasets=e.slice(0).sort(cc("order","index"))}_removeUnreferencedMetasets(){const{_metasets:e,data:{datasets:n}}=this;e.length>n.length&&delete this._stacks,e.forEach((r,s)=>{n.filter(o=>o===r._dataset).length===0&&this._destroyDatasetMeta(s)})}buildOrUpdateControllers(){const e=[],n=this.data.datasets;let r,s;for(this._removeUnreferencedMetasets(),r=0,s=n.length;r<s;r++){const o=n[r];let i=this.getDatasetMeta(r);const a=o.type||this.config.type;if(i.type&&i.type!==a&&(this._destroyDatasetMeta(r),i=this.getDatasetMeta(r)),i.type=a,i.indexAxis=o.indexAxis||yi(a,this.options),i.order=o.order||0,i.index=r,i.label=""+o.label,i.visible=this.isDatasetVisible(r),i.controller)i.controller.updateIndex(r),i.controller.linkScales();else{const l=mt.getController(a),{datasetElementType:c,dataElementType:d}=Te.datasets[a];Object.assign(l,{dataElementType:mt.getElement(d),datasetElementType:c&&mt.getElement(c)}),i.controller=new l(this,r),e.push(i.controller)}}return this._updateMetasets(),e}_resetElements(){ge(this.data.datasets,(e,n)=>{this.getDatasetMeta(n).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const n=this.config;n.update();const r=this._options=n.createResolver(n.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let i=0;for(let c=0,d=this.data.datasets.length;c<d;c++){const{controller:f}=this.getDatasetMeta(c),g=!s&&o.indexOf(f)===-1;f.buildOrUpdateElements(g),i=Math.max(+f.getMaxOverflow(),i)}i=this._minPadding=r.layout.autoPadding?i:0,this._updateLayout(i),s||ge(o,c=>{c.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(cc("z","_idx"));const{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){ge(this.scales,e=>{is.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(e.events);(!wl(n,r)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,n=this._getUniformDataChanges()||[];for(const{method:r,start:s,count:o}of n){const i=r==="_removeElements"?-o:o;BR(e,s,i)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const n=this.data.datasets.length,r=o=>new Set(e.filter(i=>i[0]===o).map((i,a)=>a+","+i.splice(1).join(","))),s=r(0);for(let o=1;o<n;o++)if(!wl(s,r(o)))return;return Array.from(s).map(o=>o.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;is.update(this,this.width,this.height,e);const n=this.chartArea,r=n.width<=0||n.height<=0;this._layers=[],ge(this.boxes,s=>{r&&s.position==="chartArea"||(s.configure&&s.configure(),this._layers.push(...s._layers()))},this),this._layers.forEach((s,o)=>{s._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let n=0,r=this.data.datasets.length;n<r;++n)this.getDatasetMeta(n).controller.configure();for(let n=0,r=this.data.datasets.length;n<r;++n)this._updateDataset(n,qt(e)?e({datasetIndex:n}):e);this.notifyPlugins("afterDatasetsUpdate",{mode:e})}}_updateDataset(e,n){const r=this.getDatasetMeta(e),s={meta:r,index:e,mode:n,cancelable:!0};this.notifyPlugins("beforeDatasetUpdate",s)!==!1&&(r.controller._update(n),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){this.notifyPlugins("beforeRender",{cancelable:!0})!==!1&&(Nt.has(this)?this.attached&&!Nt.running(this)&&Nt.start(this):(this.draw(),dc({chart:this})))}draw(){let e;if(this._resizeBeforeDraw){const{width:r,height:s}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(r,s)}if(this.clear(),this.width<=0||this.height<=0||this.notifyPlugins("beforeDraw",{cancelable:!0})===!1)return;const n=this._layers;for(e=0;e<n.length&&n[e].z<=0;++e)n[e].draw(this.chartArea);for(this._drawDatasets();e<n.length;++e)n[e].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(e){const n=this._sortedMetasets,r=[];let s,o;for(s=0,o=n.length;s<o;++s){const i=n[s];(!e||i.visible)&&r.push(i)}return r}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0})===!1)return;const e=this.getSortedVisibleDatasetMetas();for(let n=e.length-1;n>=0;--n)this._drawDataset(e[n]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const n=this.ctx,r={meta:e,index:e.index,cancelable:!0},s=ih(this,e);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(s&&ua(n,s),e.controller.draw(),s&&fa(n),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(e){return _r(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,n,r,s){const o=GC.modes[n];return typeof o=="function"?o(this,e,r,s):[]}getDatasetMeta(e){const n=this.data.datasets[e],r=this._metasets;let s=r.filter(o=>o&&o._dataset===n).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:n&&n.order||0,index:e,_dataset:n,_parsed:[],_sorted:!1},r.push(s)),s}getContext(){return this.$context||(this.$context=_n(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const n=this.data.datasets[e];if(!n)return!1;const r=this.getDatasetMeta(e);return typeof r.hidden=="boolean"?!r.hidden:!n.hidden}setDatasetVisibility(e,n){const r=this.getDatasetMeta(e);r.hidden=!n}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,n,r){const s=r?"show":"hide",o=this.getDatasetMeta(e),i=o.controller._resolveAnimations(void 0,s);Os(n)?(o.data[n].hidden=!r,this.update()):(this.setDatasetVisibility(e,r),i.update(o,{visible:r}),this.update(a=>a.datasetIndex===e?s:void 0))}hide(e,n){this._updateVisibility(e,n,!1)}show(e,n){this._updateVisibility(e,n,!0)}_destroyDatasetMeta(e){const n=this._metasets[e];n&&n.controller&&n.controller._destroy(),delete this._metasets[e]}_stop(){let e,n;for(this.stop(),Nt.remove(this),e=0,n=this.data.datasets.length;e<n;++e)this._destroyDatasetMeta(e)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:e,ctx:n}=this;this._stop(),this.config.clearCache(),e&&(this.unbindEvents(),$l(e,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete Cs[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...e){return this.canvas.toDataURL(...e)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const e=this._listeners,n=this.platform,r=(o,i)=>{n.addEventListener(this,o,i),e[o]=i},s=(o,i,a)=>{o.offsetX=i,o.offsetY=a,this._eventHandler(o)};ge(this.options.events,o=>r(o,s))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,n=this.platform,r=(l,c)=>{n.addEventListener(this,l,c),e[l]=c},s=(l,c)=>{e[l]&&(n.removeEventListener(this,l,c),delete e[l])},o=(l,c)=>{this.canvas&&this.resize(l,c)};let i;const a=()=>{s("attach",a),this.attached=!0,this.resize(),r("resize",o),r("detach",i)};i=()=>{this.attached=!1,s("resize",o),this._stop(),this._resize(0,0),r("attach",a)},n.isAttached(this.canvas)?a():i()}unbindEvents(){ge(this._listeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._listeners={},ge(this._responsiveListeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,n,r){const s=r?"set":"remove";let o,i,a,l;for(n==="dataset"&&(o=this.getDatasetMeta(e[0].datasetIndex),o.controller["_"+s+"DatasetHoverStyle"]()),a=0,l=e.length;a<l;++a){i=e[a];const c=i&&this.getDatasetMeta(i.datasetIndex).controller;c&&c[s+"HoverStyle"](i.element,i.datasetIndex,i.index)}}getActiveElements(){return this._active||[]}setActiveElements(e){const n=this._active||[],r=e.map(({datasetIndex:o,index:i})=>{const a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[i],index:i}});!Ms(r,n)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,n))}notifyPlugins(e,n,r){return this._plugins.notify(this,e,n,r)}isPluginEnabled(e){return this._plugins._cache.filter(n=>n.plugin.id===e).length===1}_updateHoverStyles(e,n,r){const s=this.options.hover,o=(l,c)=>l.filter(d=>!c.some(f=>d.datasetIndex===f.datasetIndex&&d.index===f.index)),i=o(n,e),a=r?e:o(e,n);i.length&&this.updateHoverStyle(i,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(e,n){const r={event:e,replay:n,cancelable:!0,inChartArea:this.isPointInArea(e)},s=i=>(i.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",r,s)===!1)return;const o=this._handleEvent(e,n,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,s),(o||r.changed)&&this.render(),this}_handleEvent(e,n,r){const{_active:s=[],options:o}=this,i=n,a=this._getActiveElements(e,s,r,i),l=Q_(e),c=HR(e,this._lastEvent,r,l);r&&(this._lastEvent=null,ke(o.onHover,[e,a,this],this),l&&ke(o.onClick,[e,a,this],this));const d=!Ms(a,s);return(d||n)&&(this._active=a,this._updateHoverStyles(a,s,n)),this._lastEvent=c,d}_getActiveElements(e,n,r,s){if(e.type==="mouseout")return[];if(!r)return n;const o=this.options.hover;return this.getElementsAtEventForMode(e,o.mode,o,s)}};function fc(){return ge(ro.instances,t=>t._plugins.invalidate())}function xh(t,e,n=e){t.lineCap=pe(n.borderCapStyle,e.borderCapStyle),t.setLineDash(pe(n.borderDash,e.borderDash)),t.lineDashOffset=pe(n.borderDashOffset,e.borderDashOffset),t.lineJoin=pe(n.borderJoinStyle,e.borderJoinStyle),t.lineWidth=pe(n.borderWidth,e.borderWidth),t.strokeStyle=pe(n.borderColor,e.borderColor)}function WR(t,e,n){t.lineTo(n.x,n.y)}function qR(t){return t.stepped?NS:t.tension||t.cubicInterpolationMode==="monotone"?TS:WR}function vh(t,e,n={}){const r=t.length,{start:s=0,end:o=r-1}=n,{start:i,end:a}=e,l=Math.max(s,i),c=Math.min(o,a),d=s<i&&o<i||s>a&&o>a;return{count:r,start:l,loop:e.loop,ilen:c<l&&!d?r+c-l:c-l}}function YR(t,e,n,r){const{points:s,options:o}=e,{count:i,start:a,loop:l,ilen:c}=vh(s,n,r),d=qR(o);let{move:f=!0,reverse:g}=r||{},h,m,p;for(h=0;h<=c;++h)m=s[(a+(g?c-h:h))%i],!m.skip&&(f?(t.moveTo(m.x,m.y),f=!1):d(t,p,m,g,o.stepped),p=m);return l&&(m=s[(a+(g?c:0))%i],d(t,p,m,g,o.stepped)),!!l}function KR(t,e,n,r){const s=e.points,{count:o,start:i,ilen:a}=vh(s,n,r),{move:l=!0,reverse:c}=r||{};let d=0,f=0,g,h,m,p,y,b;const w=S=>(i+(c?a-S:S))%o,v=()=>{p!==y&&(t.lineTo(d,y),t.lineTo(d,p),t.lineTo(d,b))};for(l&&(h=s[w(0)],t.moveTo(h.x,h.y)),g=0;g<=a;++g){if(h=s[w(g)],h.skip)continue;const S=h.x,_=h.y,A=S|0;A===m?(_<p?p=_:_>y&&(y=_),d=(f*d+S)/++f):(v(),t.lineTo(S,_),m=A,f=0,p=y=_),b=_}v()}function xi(t){const e=t.options,n=e.borderDash&&e.borderDash.length;return!t._decimated&&!t._loop&&!e.tension&&e.cubicInterpolationMode!=="monotone"&&!e.stepped&&!n?KR:YR}function XR(t){return t.stepped?cC:t.tension||t.cubicInterpolationMode==="monotone"?dC:ln}function JR(t,e,n,r){let s=e._path;s||(s=e._path=new Path2D,e.path(s,n,r)&&s.closePath()),xh(t,e.options),t.stroke(s)}function ZR(t,e,n,r){const{segments:s,options:o}=e,i=xi(e);for(const a of s)xh(t,o,a.style),t.beginPath(),i(t,e,a,{start:n,end:n+r-1})&&t.closePath(),t.stroke()}const QR=typeof Path2D=="function";function eA(t,e,n,r){QR&&!e.options.segment?JR(t,e,n,r):ZR(t,e,n,r)}class so extends Pr{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:e=>e!=="borderDash"&&e!=="fill"};constructor(e){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,e&&Object.assign(this,e)}updateControlPoints(e,n){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const s=r.spanGaps?this._loop:this._fullLoop;tC(this._points,r,e,s,n),this._pointsUpdated=!0}}set points(e){this._points=e,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=bC(this,this.options.segment))}first(){const e=this.segments,n=this.points;return e.length&&n[e[0].start]}last(){const e=this.segments,n=this.points,r=e.length;return r&&n[e[r-1].end]}interpolate(e,n){const r=this.options,s=e[n],o=this.points,i=oh(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],l=XR(r);let c,d;for(c=0,d=i.length;c<d;++c){const{start:f,end:g}=i[c],h=o[f],m=o[g];if(h===m){a.push(h);continue}const p=Math.abs((s-h[n])/(m[n]-h[n])),y=l(h,m,p,r.stepped);y[n]=e[n],a.push(y)}return a.length===1?a[0]:a}pathSegment(e,n,r){return xi(this)(e,this,n,r)}path(e,n,r){const s=this.segments,o=xi(this);let i=this._loop;n=n||0,r=r||this.points.length-n;for(const a of s)i&=o(e,this,a,{start:n,end:n+r-1});return!!i}draw(e,n,r,s){const o=this.options||{};(this.points||[]).length&&o.borderWidth&&(e.save(),eA(e,this,r,s),e.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function hc(t,e,n,r){const s=t.options,{[n]:o}=t.getProps([n],r);return Math.abs(e-o)<s.radius+s.hitRadius}class tA extends Pr{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(e){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,e&&Object.assign(this,e)}inRange(e,n,r){const s=this.options,{x:o,y:i}=this.getProps(["x","y"],r);return Math.pow(e-o,2)+Math.pow(n-i,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(e,n){return hc(this,e,"x",n)}inYRange(e,n){return hc(this,e,"y",n)}getCenterPoint(e){const{x:n,y:r}=this.getProps(["x","y"],e);return{x:n,y:r}}size(e){e=e||this.options||{};let n=e.radius||0;n=Math.max(n,n&&e.hoverRadius||0);const r=n&&e.borderWidth||0;return(n+r)*2}draw(e,n){const r=this.options;this.skip||r.radius<.1||!_r(this,n,this.size(r)/2)||(e.strokeStyle=r.borderColor,e.lineWidth=r.borderWidth,e.fillStyle=r.backgroundColor,pi(e,r,this.x,this.y))}getRange(){const e=this.options||{};return e.radius+e.hitRadius}}function nA(t,e,n){const r=t.segments,s=t.points,o=e.points,i=[];for(const a of r){let{start:l,end:c}=a;c=oo(l,c,s);const d=vi(n,s[l],s[c],a.loop);if(!e.segments){i.push({source:a,target:d,start:s[l],end:s[c]});continue}const f=oh(e,d);for(const g of f){const h=vi(n,o[g.start],o[g.end],g.loop),m=sh(a,s,h);for(const p of m)i.push({source:p,target:g,start:{[n]:gc(d,h,"start",Math.max)},end:{[n]:gc(d,h,"end",Math.min)}})}}return i}function vi(t,e,n,r){if(r)return;let s=e[t],o=n[t];return t==="angle"&&(s=pt(s),o=pt(o)),{property:t,start:s,end:o}}function rA(t,e){const{x:n=null,y:r=null}=t||{},s=e.points,o=[];return e.segments.forEach(({start:i,end:a})=>{a=oo(i,a,s);const l=s[i],c=s[a];r!==null?(o.push({x:l.x,y:r}),o.push({x:c.x,y:r})):n!==null&&(o.push({x:n,y:l.y}),o.push({x:n,y:c.y}))}),o}function oo(t,e,n){for(;e>t;e--){const r=n[e];if(!isNaN(r.x)&&!isNaN(r.y))break}return e}function gc(t,e,n,r){return t&&e?r(t[n],e[n]):t?t[n]:e?e[n]:0}function wh(t,e){let n=[],r=!1;return Oe(t)?(r=!0,n=t):n=rA(t,e),n.length?new so({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function mc(t){return t&&t.fill!==!1}function sA(t,e,n){let s=t[e].fill;const o=[e];let i;if(!n)return s;for(;s!==!1&&o.indexOf(s)===-1;){if(!Ue(s))return s;if(i=t[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function oA(t,e,n){const r=cA(t);if(ie(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return Ue(s)&&Math.floor(s)===s?iA(r[0],e,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function iA(t,e,n,r){return(t==="-"||t==="+")&&(n=e+n),n===e||n<0||n>=r?!1:n}function aA(t,e){let n=null;return t==="start"?n=e.bottom:t==="end"?n=e.top:ie(t)?n=e.getPixelForValue(t.value):e.getBasePixel&&(n=e.getBasePixel()),n}function lA(t,e,n){let r;return t==="start"?r=n:t==="end"?r=e.options.reverse?e.min:e.max:ie(t)?r=t.value:r=e.getBaseValue(),r}function cA(t){const e=t.options,n=e.fill;let r=pe(n&&n.target,n);return r===void 0&&(r=!!e.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function dA(t){const{scale:e,index:n,line:r}=t,s=[],o=r.segments,i=r.points,a=uA(e,n);a.push(wh({x:null,y:e.bottom},r));for(let l=0;l<o.length;l++){const c=o[l];for(let d=c.start;d<=c.end;d++)fA(s,i[d],a)}return new so({points:s,options:{}})}function uA(t,e){const n=[],r=t.getMatchingVisibleMetas("line");for(let s=0;s<r.length;s++){const o=r[s];if(o.index===e)break;o.hidden||n.unshift(o.dataset)}return n}function fA(t,e,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:l}=hA(o,e,"x");if(!(!l||i&&a)){if(i)r.unshift(l);else if(t.push(l),!a)break}}t.push(...r)}function hA(t,e,n){const r=t.interpolate(e,n);if(!r)return{};const s=r[n],o=t.segments,i=t.points;let a=!1,l=!1;for(let c=0;c<o.length;c++){const d=o[c],f=i[d.start][n],g=i[d.end][n];if(Hf(s,f,g)){a=s===f,l=s===g;break}}return{first:a,last:l,point:r}}class _h{constructor(e){this.x=e.x,this.y=e.y,this.radius=e.radius}pathSegment(e,n,r){const{x:s,y:o,radius:i}=this;return n=n||{start:0,end:Ct},e.arc(s,o,i,n.end,n.start,!0),!r.bounds}interpolate(e){const{x:n,y:r,radius:s}=this,o=e.angle;return{x:n+Math.cos(o)*s,y:r+Math.sin(o)*s,angle:o}}}function gA(t){const{chart:e,fill:n,line:r}=t;if(Ue(n))return mA(e,n);if(n==="stack")return dA(t);if(n==="shape")return!0;const s=pA(t);return s instanceof _h?s:wh(s,r)}function mA(t,e){const n=t.getDatasetMeta(e);return n&&t.isDatasetVisible(e)?n.dataset:null}function pA(t){return(t.scale||{}).getPointPositionForValue?bA(t):yA(t)}function yA(t){const{scale:e={},fill:n}=t,r=aA(n,e);if(Ue(r)){const s=e.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function bA(t){const{scale:e,fill:n}=t,r=e.options,s=e.getLabels().length,o=r.reverse?e.max:e.min,i=lA(n,e,o),a=[];if(r.grid.circular){const l=e.getPointPositionForValue(0,o);return new _h({x:l.x,y:l.y,radius:e.getDistanceFromCenterForValue(i)})}for(let l=0;l<s;++l)a.push(e.getPointPositionForValue(l,i));return a}function zo(t,e,n){const r=gA(e),{chart:s,index:o,line:i,scale:a,axis:l}=e,c=i.options,d=c.fill,f=c.backgroundColor,{above:g=f,below:h=f}=d||{},m=s.getDatasetMeta(o),p=ih(s,m);r&&i.points.length&&(ua(t,n),xA(t,{line:i,target:r,above:g,below:h,area:n,scale:a,axis:l,clip:p}),fa(t))}function xA(t,e){const{line:n,target:r,above:s,below:o,area:i,scale:a,clip:l}=e,c=n._loop?"angle":e.axis;t.save();let d=o;o!==s&&(c==="x"?(pc(t,r,i.top),Vo(t,{line:n,target:r,color:s,scale:a,property:c,clip:l}),t.restore(),t.save(),pc(t,r,i.bottom)):c==="y"&&(yc(t,r,i.left),Vo(t,{line:n,target:r,color:o,scale:a,property:c,clip:l}),t.restore(),t.save(),yc(t,r,i.right),d=s)),Vo(t,{line:n,target:r,color:d,scale:a,property:c,clip:l}),t.restore()}function pc(t,e,n){const{segments:r,points:s}=e;let o=!0,i=!1;t.beginPath();for(const a of r){const{start:l,end:c}=a,d=s[l],f=s[oo(l,c,s)];o?(t.moveTo(d.x,d.y),o=!1):(t.lineTo(d.x,n),t.lineTo(d.x,d.y)),i=!!e.pathSegment(t,a,{move:i}),i?t.closePath():t.lineTo(f.x,n)}t.lineTo(e.first().x,n),t.closePath(),t.clip()}function yc(t,e,n){const{segments:r,points:s}=e;let o=!0,i=!1;t.beginPath();for(const a of r){const{start:l,end:c}=a,d=s[l],f=s[oo(l,c,s)];o?(t.moveTo(d.x,d.y),o=!1):(t.lineTo(n,d.y),t.lineTo(d.x,d.y)),i=!!e.pathSegment(t,a,{move:i}),i?t.closePath():t.lineTo(n,f.y)}t.lineTo(n,e.first().y),t.closePath(),t.clip()}function Vo(t,e){const{line:n,target:r,property:s,color:o,scale:i,clip:a}=e,l=nA(n,r,s);for(const{source:c,target:d,start:f,end:g}of l){const{style:{backgroundColor:h=o}={}}=c,m=r!==!0;t.save(),t.fillStyle=h,vA(t,i,a,m&&vi(s,f,g)),t.beginPath();const p=!!n.pathSegment(t,c);let y;if(m){p?t.closePath():bc(t,r,g,s);const b=!!r.pathSegment(t,d,{move:p,reverse:!0});y=p&&b,y||bc(t,r,f,s)}t.closePath(),t.fill(y?"evenodd":"nonzero"),t.restore()}}function vA(t,e,n,r){const s=e.chart.chartArea,{property:o,start:i,end:a}=r||{};if(o==="x"||o==="y"){let l,c,d,f;o==="x"?(l=i,c=s.top,d=a,f=s.bottom):(l=s.left,c=i,d=s.right,f=a),t.beginPath(),n&&(l=Math.max(l,n.left),d=Math.min(d,n.right),c=Math.max(c,n.top),f=Math.min(f,n.bottom)),t.rect(l,c,d-l,f-c),t.clip()}}function bc(t,e,n,r){const s=e.interpolate(n,r);s&&t.lineTo(s.x,s.y)}var wA={id:"filler",afterDatasetsUpdate(t,e,n){const r=(t.data.datasets||[]).length,s=[];let o,i,a,l;for(i=0;i<r;++i)o=t.getDatasetMeta(i),a=o.dataset,l=null,a&&a.options&&a instanceof so&&(l={visible:t.isDatasetVisible(i),index:i,fill:oA(a,i,r),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:a}),o.$filler=l,s.push(l);for(i=0;i<r;++i)l=s[i],!(!l||l.fill===!1)&&(l.fill=sA(s,i,n.propagate))},beforeDraw(t,e,n){const r=n.drawTime==="beforeDraw",s=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let i=s.length-1;i>=0;--i){const a=s[i].$filler;a&&(a.line.updateControlPoints(o,a.axis),r&&a.fill&&zo(t.ctx,a,o))}},beforeDatasetsDraw(t,e,n){if(n.drawTime!=="beforeDatasetsDraw")return;const r=t.getSortedVisibleDatasetMetas();for(let s=r.length-1;s>=0;--s){const o=r[s].$filler;mc(o)&&zo(t.ctx,o,t.chartArea)}},beforeDatasetDraw(t,e,n){const r=e.meta.$filler;!mc(r)||n.drawTime!=="beforeDatasetDraw"||zo(t.ctx,r,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const cr={average(t){if(!t.length)return!1;let e,n,r=new Set,s=0,o=0;for(e=0,n=t.length;e<n;++e){const a=t[e].element;if(a&&a.hasValue()){const l=a.tooltipPosition();r.add(l.x),s+=l.y,++o}}return o===0||r.size===0?!1:{x:[...r].reduce((a,l)=>a+l)/r.size,y:s/o}},nearest(t,e){if(!t.length)return!1;let n=e.x,r=e.y,s=Number.POSITIVE_INFINITY,o,i,a;for(o=0,i=t.length;o<i;++o){const l=t[o].element;if(l&&l.hasValue()){const c=l.getCenterPoint(),d=gi(e,c);d<s&&(s=d,a=l)}}if(a){const l=a.tooltipPosition();n=l.x,r=l.y}return{x:n,y:r}}};function gt(t,e){return e&&(Oe(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Tt(t){return(typeof t=="string"||t instanceof String)&&t.indexOf(`
294
- `)>-1?t.split(`
295
- `):t}function _A(t,e){const{element:n,datasetIndex:r,index:s}=e,o=t.getDatasetMeta(r).controller,{label:i,value:a}=o.getLabelAndValue(s);return{chart:t,label:i,parsed:o.getParsed(s),raw:t.data.datasets[r].data[s],formattedValue:a,dataset:o.getDataset(),dataIndex:s,datasetIndex:r,element:n}}function xc(t,e){const n=t.chart.ctx,{body:r,footer:s,title:o}=t,{boxWidth:i,boxHeight:a}=e,l=_t(e.bodyFont),c=_t(e.titleFont),d=_t(e.footerFont),f=o.length,g=s.length,h=r.length,m=Yt(e.padding);let p=m.height,y=0,b=r.reduce((S,_)=>S+_.before.length+_.lines.length+_.after.length,0);if(b+=t.beforeBody.length+t.afterBody.length,f&&(p+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),b){const S=e.displayColors?Math.max(a,l.lineHeight):l.lineHeight;p+=h*S+(b-h)*l.lineHeight+(b-1)*e.bodySpacing}g&&(p+=e.footerMarginTop+g*d.lineHeight+(g-1)*e.footerSpacing);let w=0;const v=function(S){y=Math.max(y,n.measureText(S).width+w)};return n.save(),n.font=c.string,ge(t.title,v),n.font=l.string,ge(t.beforeBody.concat(t.afterBody),v),w=e.displayColors?i+2+e.boxPadding:0,ge(r,S=>{ge(S.before,v),ge(S.lines,v),ge(S.after,v)}),w=0,n.font=d.string,ge(t.footer,v),n.restore(),y+=m.width,{width:y,height:p}}function SA(t,e){const{y:n,height:r}=e;return n<r/2?"top":n>t.height-r/2?"bottom":"center"}function CA(t,e,n,r){const{x:s,width:o}=r,i=n.caretSize+n.caretPadding;if(t==="left"&&s+o+i>e.width||t==="right"&&s-o-i<0)return!0}function RA(t,e,n,r){const{x:s,width:o}=n,{width:i,chartArea:{left:a,right:l}}=t;let c="center";return r==="center"?c=s<=(a+l)/2?"left":"right":s<=o/2?c="left":s>=i-o/2&&(c="right"),CA(c,t,e,n)&&(c="center"),c}function vc(t,e,n){const r=n.yAlign||e.yAlign||SA(t,n);return{xAlign:n.xAlign||e.xAlign||RA(t,e,n,r),yAlign:r}}function AA(t,e){let{x:n,width:r}=t;return e==="right"?n-=r:e==="center"&&(n-=r/2),n}function kA(t,e,n){let{y:r,height:s}=t;return e==="top"?r+=n:e==="bottom"?r-=s+n:r-=s/2,r}function wc(t,e,n,r){const{caretSize:s,caretPadding:o,cornerRadius:i}=t,{xAlign:a,yAlign:l}=n,c=s+o,{topLeft:d,topRight:f,bottomLeft:g,bottomRight:h}=_s(i);let m=AA(e,a);const p=kA(e,l,c);return l==="center"?a==="left"?m+=c:a==="right"&&(m-=c):a==="left"?m-=Math.max(d,g)+s:a==="right"&&(m+=Math.max(f,h)+s),{x:it(m,0,r.width-e.width),y:it(p,0,r.height-e.height)}}function ds(t,e,n){const r=Yt(n.padding);return e==="center"?t.x+t.width/2:e==="right"?t.x+t.width-r.right:t.x+r.left}function _c(t){return gt([],Tt(t))}function EA(t,e,n){return _n(t,{tooltip:e,tooltipItems:n,type:"tooltip"})}function Sc(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const Sh={beforeTitle:Et,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,r=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex<r)return n[e.dataIndex]}return""},afterTitle:Et,beforeBody:Et,beforeLabel:Et,label(t){if(this&&this.options&&this.options.mode==="dataset")return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const n=t.formattedValue;return xe(n)||(e+=n),e},labelColor(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:n.borderColor,backgroundColor:n.backgroundColor,borderWidth:n.borderWidth,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:n.pointStyle,rotation:n.rotation}},afterLabel:Et,afterBody:Et,beforeFooter:Et,footer:Et,afterFooter:Et};function He(t,e,n,r){const s=t[e].call(n,r);return typeof s>"u"?Sh[e].call(n,r):s}class Cc extends Pr{static positioners=cr;constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const n=this.chart,r=this.options.setContext(this.getContext()),s=r.enabled&&n.options.animation&&r.animations,o=new ah(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=EA(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,n){const{callbacks:r}=n,s=He(r,"beforeTitle",this,e),o=He(r,"title",this,e),i=He(r,"afterTitle",this,e);let a=[];return a=gt(a,Tt(s)),a=gt(a,Tt(o)),a=gt(a,Tt(i)),a}getBeforeBody(e,n){return _c(He(n.callbacks,"beforeBody",this,e))}getBody(e,n){const{callbacks:r}=n,s=[];return ge(e,o=>{const i={before:[],lines:[],after:[]},a=Sc(r,o);gt(i.before,Tt(He(a,"beforeLabel",this,o))),gt(i.lines,He(a,"label",this,o)),gt(i.after,Tt(He(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(e,n){return _c(He(n.callbacks,"afterBody",this,e))}getFooter(e,n){const{callbacks:r}=n,s=He(r,"beforeFooter",this,e),o=He(r,"footer",this,e),i=He(r,"afterFooter",this,e);let a=[];return a=gt(a,Tt(s)),a=gt(a,Tt(o)),a=gt(a,Tt(i)),a}_createItems(e){const n=this._active,r=this.chart.data,s=[],o=[],i=[];let a=[],l,c;for(l=0,c=n.length;l<c;++l)a.push(_A(this.chart,n[l]));return e.filter&&(a=a.filter((d,f,g)=>e.filter(d,f,g,r))),e.itemSort&&(a=a.sort((d,f)=>e.itemSort(d,f,r))),ge(a,d=>{const f=Sc(e.callbacks,d);s.push(He(f,"labelColor",this,d)),o.push(He(f,"labelPointStyle",this,d)),i.push(He(f,"labelTextColor",this,d))}),this.labelColors=s,this.labelPointStyles=o,this.labelTextColors=i,this.dataPoints=a,a}update(e,n){const r=this.options.setContext(this.getContext()),s=this._active;let o,i=[];if(!s.length)this.opacity!==0&&(o={opacity:0});else{const a=cr[r.position].call(this,s,this._eventPosition);i=this._createItems(r),this.title=this.getTitle(i,r),this.beforeBody=this.getBeforeBody(i,r),this.body=this.getBody(i,r),this.afterBody=this.getAfterBody(i,r),this.footer=this.getFooter(i,r);const l=this._size=xc(this,r),c=Object.assign({},a,l),d=vc(this.chart,r,c),f=wc(r,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:f.x,y:f.y,width:l.width,height:l.height,caretX:a.x,caretY:a.y}}this._tooltipItems=i,this.$context=void 0,o&&this._resolveAnimations().update(this,o),e&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(e,n,r,s){const o=this.getCaretPosition(e,r,s);n.lineTo(o.x1,o.y1),n.lineTo(o.x2,o.y2),n.lineTo(o.x3,o.y3)}getCaretPosition(e,n,r){const{xAlign:s,yAlign:o}=this,{caretSize:i,cornerRadius:a}=r,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:f}=_s(a),{x:g,y:h}=e,{width:m,height:p}=n;let y,b,w,v,S,_;return o==="center"?(S=h+p/2,s==="left"?(y=g,b=y-i,v=S+i,_=S-i):(y=g+m,b=y+i,v=S-i,_=S+i),w=y):(s==="left"?b=g+Math.max(l,d)+i:s==="right"?b=g+m-Math.max(c,f)-i:b=this.caretX,o==="top"?(v=h,S=v-i,y=b-i,w=b+i):(v=h+p,S=v+i,y=b+i,w=b-i),_=v),{x1:y,x2:b,x3:w,y1:v,y2:S,y3:_}}drawTitle(e,n,r){const s=this.title,o=s.length;let i,a,l;if(o){const c=jo(r.rtl,this.x,this.width);for(e.x=ds(this,r.titleAlign,r),n.textAlign=c.textAlign(r.titleAlign),n.textBaseline="middle",i=_t(r.titleFont),a=r.titleSpacing,n.fillStyle=r.titleColor,n.font=i.string,l=0;l<o;++l)n.fillText(s[l],c.x(e.x),e.y+i.lineHeight/2),e.y+=i.lineHeight+a,l+1===o&&(e.y+=r.titleMarginBottom-a)}}_drawColorBox(e,n,r,s,o){const i=this.labelColors[r],a=this.labelPointStyles[r],{boxHeight:l,boxWidth:c}=o,d=_t(o.bodyFont),f=ds(this,"left",o),g=s.x(f),h=l<d.lineHeight?(d.lineHeight-l)/2:0,m=n.y+h;if(o.usePointStyle){const p={radius:Math.min(c,l)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},y=s.leftForLtr(g,c)+c/2,b=m+l/2;e.strokeStyle=o.multiKeyBackground,e.fillStyle=o.multiKeyBackground,pi(e,p,y,b),e.strokeStyle=i.borderColor,e.fillStyle=i.backgroundColor,pi(e,p,y,b)}else{e.lineWidth=ie(i.borderWidth)?Math.max(...Object.values(i.borderWidth)):i.borderWidth||1,e.strokeStyle=i.borderColor,e.setLineDash(i.borderDash||[]),e.lineDashOffset=i.borderDashOffset||0;const p=s.leftForLtr(g,c),y=s.leftForLtr(s.xPlus(g,1),c-2),b=_s(i.borderRadius);Object.values(b).some(w=>w!==0)?(e.beginPath(),e.fillStyle=o.multiKeyBackground,Ol(e,{x:p,y:m,w:c,h:l,radius:b}),e.fill(),e.stroke(),e.fillStyle=i.backgroundColor,e.beginPath(),Ol(e,{x:y,y:m+1,w:c-2,h:l-2,radius:b}),e.fill()):(e.fillStyle=o.multiKeyBackground,e.fillRect(p,m,c,l),e.strokeRect(p,m,c,l),e.fillStyle=i.backgroundColor,e.fillRect(y,m+1,c-2,l-2))}e.fillStyle=this.labelTextColors[r]}drawBody(e,n,r){const{body:s}=this,{bodySpacing:o,bodyAlign:i,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=r,f=_t(r.bodyFont);let g=f.lineHeight,h=0;const m=jo(r.rtl,this.x,this.width),p=function(R){n.fillText(R,m.x(e.x+h),e.y+g/2),e.y+=g+o},y=m.textAlign(i);let b,w,v,S,_,A,C;for(n.textAlign=i,n.textBaseline="middle",n.font=f.string,e.x=ds(this,y,r),n.fillStyle=r.bodyColor,ge(this.beforeBody,p),h=a&&y!=="right"?i==="center"?c/2+d:c+2+d:0,S=0,A=s.length;S<A;++S){for(b=s[S],w=this.labelTextColors[S],n.fillStyle=w,ge(b.before,p),v=b.lines,a&&v.length&&(this._drawColorBox(n,e,S,m,r),g=Math.max(f.lineHeight,l)),_=0,C=v.length;_<C;++_)p(v[_]),g=f.lineHeight;ge(b.after,p)}h=0,g=f.lineHeight,ge(this.afterBody,p),e.y-=o}drawFooter(e,n,r){const s=this.footer,o=s.length;let i,a;if(o){const l=jo(r.rtl,this.x,this.width);for(e.x=ds(this,r.footerAlign,r),e.y+=r.footerMarginTop,n.textAlign=l.textAlign(r.footerAlign),n.textBaseline="middle",i=_t(r.footerFont),n.fillStyle=r.footerColor,n.font=i.string,a=0;a<o;++a)n.fillText(s[a],l.x(e.x),e.y+i.lineHeight/2),e.y+=i.lineHeight+r.footerSpacing}}drawBackground(e,n,r,s){const{xAlign:o,yAlign:i}=this,{x:a,y:l}=e,{width:c,height:d}=r,{topLeft:f,topRight:g,bottomLeft:h,bottomRight:m}=_s(s.cornerRadius);n.fillStyle=s.backgroundColor,n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.beginPath(),n.moveTo(a+f,l),i==="top"&&this.drawCaret(e,n,r,s),n.lineTo(a+c-g,l),n.quadraticCurveTo(a+c,l,a+c,l+g),i==="center"&&o==="right"&&this.drawCaret(e,n,r,s),n.lineTo(a+c,l+d-m),n.quadraticCurveTo(a+c,l+d,a+c-m,l+d),i==="bottom"&&this.drawCaret(e,n,r,s),n.lineTo(a+h,l+d),n.quadraticCurveTo(a,l+d,a,l+d-h),i==="center"&&o==="left"&&this.drawCaret(e,n,r,s),n.lineTo(a,l+f),n.quadraticCurveTo(a,l,a+f,l),n.closePath(),n.fill(),s.borderWidth>0&&n.stroke()}_updateAnimationTarget(e){const n=this.chart,r=this.$animations,s=r&&r.x,o=r&&r.y;if(s||o){const i=cr[e.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=xc(this,e),l=Object.assign({},i,this._size),c=vc(n,e,l),d=wc(e,l,c,n);(s._to!==d.x||o._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(e){const n=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(n);const s={width:this.width,height:this.height},o={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const i=Yt(n.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&a&&(e.save(),e.globalAlpha=r,this.drawBackground(o,e,s,n),hC(e,n.textDirection),o.y+=i.top,this.drawTitle(o,e,n),this.drawBody(o,e,n),this.drawFooter(o,e,n),gC(e,n.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,n){const r=this._active,s=e.map(({datasetIndex:a,index:l})=>{const c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),o=!Ms(r,s),i=this._positionChanged(s,n);(o||i)&&(this._active=s,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,n,r=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,o=this._active||[],i=this._getActiveElements(e,o,n,r),a=this._positionChanged(i,e),l=n||!Ms(i,o)||a;return l&&(this._active=i,(s.enabled||s.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,n))),l}_getActiveElements(e,n,r,s){const o=this.options;if(e.type==="mouseout")return[];if(!s)return n.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);const i=this.chart.getElementsAtEventForMode(e,o.mode,o,r);return o.reverse&&i.reverse(),i}_positionChanged(e,n){const{caretX:r,caretY:s,options:o}=this,i=cr[o.position].call(this,e,n);return i!==!1&&(r!==i.x||s!==i.y)}}var NA={id:"tooltip",_element:Cc,positioners:cr,afterInit(t,e,n){n&&(t.tooltip=new Cc({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Sh},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>t!=="filter"&&t!=="itemSort"&&t!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const TA=(t,e,n,r)=>(typeof e=="string"?(n=t.push(e)-1,r.unshift({index:n,label:e})):isNaN(e)&&(n=null),n);function MA(t,e,n,r){const s=t.indexOf(e);if(s===-1)return TA(t,e,n,r);const o=t.lastIndexOf(e);return s!==o?n:s}const $A=(t,e)=>t===null?null:it(Math.round(t),0,e);function Rc(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}class jA extends Wn{static id="category";static defaults={ticks:{callback:Rc}};constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){const n=this._addedLabels;if(n.length){const r=this.getLabels();for(const{index:s,label:o}of n)r[s]===o&&r.splice(s,1);this._addedLabels=[]}super.init(e)}parse(e,n){if(xe(e))return null;const r=this.getLabels();return n=isFinite(n)&&r[n]===e?n:MA(r,e,pe(n,e),this._addedLabels),$A(n,r.length-1)}determineDataLimits(){const{minDefined:e,maxDefined:n}=this.getUserBounds();let{min:r,max:s}=this.getMinMax(!0);this.options.bounds==="ticks"&&(e||(r=0),n||(s=this.getLabels().length-1)),this.min=r,this.max=s}buildTicks(){const e=this.min,n=this.max,r=this.options.offset,s=[];let o=this.getLabels();o=e===0&&n===o.length-1?o:o.slice(e,n+1),this._valueRange=Math.max(o.length-(r?0:1),1),this._startValue=this.min-(r?.5:0);for(let i=e;i<=n;i++)s.push({value:i});return s}getLabelForValue(e){return Rc.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!="number"&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}function OA(t,e){const n=[],{bounds:s,step:o,min:i,max:a,precision:l,count:c,maxTicks:d,maxDigits:f,includeBounds:g}=t,h=o||1,m=d-1,{min:p,max:y}=e,b=!xe(i),w=!xe(a),v=!xe(c),S=(y-p)/(f+1);let _=Sl((y-p)/m/h)*h,A,C,R,k;if(_<1e-14&&!b&&!w)return[{value:p},{value:y}];k=Math.ceil(y/_)-Math.floor(p/_),k>m&&(_=Sl(k*_/m/h)*h),xe(l)||(A=Math.pow(10,l),_=Math.ceil(_*A)/A),s==="ticks"?(C=Math.floor(p/_)*_,R=Math.ceil(y/_)*_):(C=p,R=y),b&&w&&o&&sS((a-i)/o,_/1e3)?(k=Math.round(Math.min((a-i)/_,d)),_=(a-i)/k,C=i,R=a):v?(C=b?i:C,R=w?a:R,k=c-1,_=(R-C)/k):(k=(R-C)/_,fr(k,Math.round(k),_/1e3)?k=Math.round(k):k=Math.ceil(k));const M=Math.max(Cl(_),Cl(C));A=Math.pow(10,xe(l)?M:l),C=Math.round(C*A)/A,R=Math.round(R*A)/A;let F=0;for(b&&(g&&C!==i?(n.push({value:i}),C<i&&F++,fr(Math.round((C+F*_)*A)/A,i,Ac(i,S,t))&&F++):C<i&&F++);F<k;++F){const D=Math.round((C+F*_)*A)/A;if(w&&D>a)break;n.push({value:D})}return w&&g&&R!==a?n.length&&fr(n[n.length-1].value,a,Ac(a,S,t))?n[n.length-1].value=a:n.push({value:a}):(!w||R===a)&&n.push({value:R}),n}function Ac(t,e,{horizontal:n,minRotation:r}){const s=un(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*e*(""+t).length;return Math.min(e/o,i)}class IA extends Wn{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,n){return xe(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:n,maxDefined:r}=this.getUserBounds();let{min:s,max:o}=this;const i=l=>s=n?s:l,a=l=>o=r?o:l;if(e){const l=In(s),c=In(o);l<0&&c<0?a(0):l>0&&c>0&&i(0)}if(s===o){let l=o===0?1:Math.abs(o*.05);a(o+l),e||i(s-l)}this.min=s,this.max=o}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:n,stepSize:r}=e,s;return r?(s=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,s>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${s} ticks. Limiting to 1000.`),s=1e3)):(s=this.computeTickLimit(),n=n||11),n&&(s=Math.min(n,s)),s}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,n=e.ticks;let r=this.getTickLimit();r=Math.max(2,r);const s={maxTicks:r,bounds:e.bounds,min:e.min,max:e.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},o=this._range||this,i=OA(s,o);return e.bounds==="ticks"&&oS(i,this,"value"),e.reverse?(i.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),i}configure(){const e=this.ticks;let n=this.min,r=this.max;if(super.configure(),this.options.offset&&e.length){const s=(r-n)/Math.max(e.length-1,1)/2;n-=s,r+=s}this._startValue=n,this._endValue=r,this._valueRange=r-n}getLabelForValue(e){return Kf(e,this.chart.options.locale,this.options.ticks.format)}}class PA extends IA{static id="linear";static defaults={ticks:{callback:Xf.formatters.numeric}};determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=Ue(e)?e:0,this.max=Ue(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),n=e?this.width:this.height,r=un(this.options.ticks.minRotation),s=(e?Math.sin(r):Math.cos(r))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,o.lineHeight/s))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}const io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Ye=Object.keys(io);function kc(t,e){return t-e}function Ec(t,e){if(xe(e))return null;const n=t._adapter,{parser:r,round:s,isoWeekday:o}=t._parseOpts;let i=e;return typeof r=="function"&&(i=r(i)),Ue(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(wr(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function Nc(t,e,n,r){const s=Ye.length;for(let o=Ye.indexOf(t);o<s-1;++o){const i=io[Ye[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-e)/(a*i.size))<=r)return Ye[o]}return Ye[s-1]}function FA(t,e,n,r,s){for(let o=Ye.length-1;o>=Ye.indexOf(n);o--){const i=Ye[o];if(io[i].common&&t._adapter.diff(s,r,i)>=e-1)return i}return Ye[n?Ye.indexOf(n):0]}function DA(t){for(let e=Ye.indexOf(t)+1,n=Ye.length;e<n;++e)if(io[Ye[e]].common)return Ye[e]}function Tc(t,e,n){if(!n)t[e]=!0;else if(n.length){const{lo:r,hi:s}=ca(n,e),o=n[r]>=e?n[r]:n[s];t[o]=!0}}function LA(t,e,n,r){const s=t._adapter,o=+s.startOf(e[0].value,r),i=e[e.length-1].value;let a,l;for(a=o;a<=i;a=+s.add(a,1,r))l=n[a],l>=0&&(e[l].major=!0);return e}function Mc(t,e,n){const r=[],s={},o=e.length;let i,a;for(i=0;i<o;++i)a=e[i],s[a]=i,r.push({value:a,major:!1});return o===0||!n?r:LA(t,r,s,n)}class $c extends Wn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,n={}){const r=e.time||(e.time={}),s=this._adapter=new FC._date(e.adapters.date);s.init(n),ur(r.displayFormats,s.formats()),this._parseOpts={parser:r.parser,round:r.round,isoWeekday:r.isoWeekday},super.init(e),this._normalized=n.normalized}parse(e,n){return e===void 0?null:Ec(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const e=this.options,n=this._adapter,r=e.time.unit||"day";let{min:s,max:o,minDefined:i,maxDefined:a}=this.getUserBounds();function l(c){!i&&!isNaN(c.min)&&(s=Math.min(s,c.min)),!a&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!i||!a)&&(l(this._getLabelBounds()),(e.bounds!=="ticks"||e.ticks.source!=="labels")&&l(this.getMinMax(!1))),s=Ue(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=Ue(o)&&!isNaN(o)?o:+n.endOf(Date.now(),r)+1,this.min=Math.min(s,o-1),this.max=Math.max(s+1,o)}_getLabelBounds(){const e=this.getLabelTimestamps();let n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return e.length&&(n=e[0],r=e[e.length-1]),{min:n,max:r}}buildTicks(){const e=this.options,n=e.time,r=e.ticks,s=r.source==="labels"?this.getLabelTimestamps():this._generate();e.bounds==="ticks"&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const o=this.min,i=this.max,a=uS(s,o,i);return this._unit=n.unit||(r.autoSkip?Nc(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):FA(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:DA(this._unit),this.initOffsets(s),e.reverse&&a.reverse(),Mc(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+e.value))}initOffsets(e=[]){let n=0,r=0,s,o;this.options.offset&&e.length&&(s=this.getDecimalForValue(e[0]),e.length===1?n=1-s:n=(this.getDecimalForValue(e[1])-s)/2,o=this.getDecimalForValue(e[e.length-1]),e.length===1?r=o:r=(o-this.getDecimalForValue(e[e.length-2]))/2);const i=e.length<3?.5:.25;n=it(n,0,i),r=it(r,0,i),this._offsets={start:n,end:r,factor:1/(n+1+r)}}_generate(){const e=this._adapter,n=this.min,r=this.max,s=this.options,o=s.time,i=o.unit||Nc(o.minUnit,n,r,this._getLabelCapacity(n)),a=pe(s.ticks.stepSize,1),l=i==="week"?o.isoWeekday:!1,c=wr(l)||l===!0,d={};let f=n,g,h;if(c&&(f=+e.startOf(f,"isoWeek",l)),f=+e.startOf(f,c?"day":i),e.diff(r,n,i)>1e5*a)throw new Error(n+" and "+r+" are too far apart with stepSize of "+a+" "+i);const m=s.ticks.source==="data"&&this.getDataTimestamps();for(g=f,h=0;g<r;g=+e.add(g,a,i),h++)Tc(d,g,m);return(g===r||s.bounds==="ticks"||h===1)&&Tc(d,g,m),Object.keys(d).sort(kc).map(p=>+p)}getLabelForValue(e){const n=this._adapter,r=this.options.time;return r.tooltipFormat?n.format(e,r.tooltipFormat):n.format(e,r.displayFormats.datetime)}format(e,n){const s=this.options.time.displayFormats,o=this._unit,i=n||s[o];return this._adapter.format(e,i)}_tickFormatFunction(e,n,r,s){const o=this.options,i=o.ticks.callback;if(i)return ke(i,[e,n,r],this);const a=o.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],f=c&&a[c],g=r[n],h=c&&f&&g&&g.major;return this._adapter.format(e,s||(h?f:d))}generateTickLabels(e){let n,r,s;for(n=0,r=e.length;n<r;++n)s=e[n],s.label=this._tickFormatFunction(s.value,n,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){const n=this._offsets,r=this.getDecimalForValue(e);return this.getPixelForDecimal((n.start+r)*n.factor)}getValueForPixel(e){const n=this._offsets,r=this.getDecimalForPixel(e)/n.factor-n.end;return this.min+r*(this.max-this.min)}_getLabelSize(e){const n=this.options.ticks,r=this.ctx.measureText(e).width,s=un(this.isHorizontal()?n.maxRotation:n.minRotation),o=Math.cos(s),i=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:r*o+a*i,h:r*i+a*o}}_getLabelCapacity(e){const n=this.options.time,r=n.displayFormats,s=r[n.unit]||r.millisecond,o=this._tickFormatFunction(e,0,Mc(this,[e],this._majorUnit),s),i=this._getLabelSize(o),a=Math.floor(this.isHorizontal()?this.width/i.w:this.height/i.h)-1;return a>0?a:1}getDataTimestamps(){let e=this._cache.data||[],n,r;if(e.length)return e;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(n=0,r=s.length;n<r;++n)e=e.concat(s[n].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){const e=this._cache.labels||[];let n,r;if(e.length)return e;const s=this.getLabels();for(n=0,r=s.length;n<r;++n)e.push(Ec(this,s[n]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return hS(e.sort(kc))}}function us(t,e,n){let r=0,s=t.length-1,o,i,a,l;n?(e>=t[r].pos&&e<=t[s].pos&&({lo:r,hi:s}=fn(t,"pos",e)),{pos:o,time:a}=t[r],{pos:i,time:l}=t[s]):(e>=t[r].time&&e<=t[s].time&&({lo:r,hi:s}=fn(t,"time",e)),{time:o,pos:a}=t[r],{time:i,pos:l}=t[s]);const c=i-o;return c?a+(l-a)*(e-o)/c:a}class k1 extends $c{static id="timeseries";static defaults=$c.defaults;constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(e);this._minPos=us(n,this.min),this._tableRange=us(n,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:n,max:r}=this,s=[],o=[];let i,a,l,c,d;for(i=0,a=e.length;i<a;++i)c=e[i],c>=n&&c<=r&&s.push(c);if(s.length<2)return[{time:n,pos:0},{time:r,pos:1}];for(i=0,a=s.length;i<a;++i)d=s[i+1],l=s[i-1],c=s[i],Math.round((d+l)/2)!==c&&o.push({time:c,pos:i/(a-1)});return o}_generate(){const e=this.min,n=this.max;let r=super.getDataTimestamps();return(!r.includes(e)||!r.length)&&r.splice(0,0,e),(!r.includes(n)||r.length===1)&&r.push(n),r.sort((s,o)=>s-o)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const n=this.getDataTimestamps(),r=this.getLabelTimestamps();return n.length&&r.length?e=this.normalize(n.concat(r)):e=n.length?n:r,e=this._cache.all=e,e}getDecimalForValue(e){return(us(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const n=this._offsets,r=this.getDecimalForPixel(e)/n.factor-n.end;return us(this._table,r*this._tableRange+this._minPos,!0)}}const Ch="label";function jc(t,e){typeof t=="function"?t(e):t&&(t.current=e)}function zA(t,e){const n=t.options;n&&e&&Object.assign(n,e)}function Rh(t,e){t.labels=e}function Ah(t,e,n=Ch){const r=[];t.datasets=e.map(s=>{const o=t.datasets.find(i=>i[n]===s[n]);return!o||!s.data||r.includes(o)?{...s}:(r.push(o),Object.assign(o,s),o)})}function VA(t,e=Ch){const n={labels:[],datasets:[]};return Rh(n,t.labels),Ah(n,t.datasets,e),n}function GA(t,e){const{height:n=150,width:r=300,redraw:s=!1,datasetIdKey:o,type:i,data:a,options:l,plugins:c=[],fallbackContent:d,updateMode:f,...g}=t,h=x.useRef(null),m=x.useRef(null),p=()=>{h.current&&(m.current=new ro(h.current,{type:i,data:VA(a,o),options:l&&{...l},plugins:c}),jc(e,m.current))},y=()=>{jc(e,null),m.current&&(m.current.destroy(),m.current=null)};return x.useEffect(()=>{!s&&m.current&&l&&zA(m.current,l)},[s,l]),x.useEffect(()=>{!s&&m.current&&Rh(m.current.config.data,a.labels)},[s,a.labels]),x.useEffect(()=>{!s&&m.current&&a.datasets&&Ah(m.current.config.data,a.datasets,o)},[s,a.datasets]),x.useEffect(()=>{m.current&&(s?(y(),setTimeout(p)):m.current.update(f))},[s,l,a.labels,a.datasets,f]),x.useEffect(()=>{m.current&&(y(),setTimeout(p))},[i]),x.useEffect(()=>(p(),()=>y()),[]),u.jsx("canvas",{ref:h,role:"img",height:n,width:r,...g,children:d})}const UA=x.forwardRef(GA);function BA(t,e){return ro.register(e),x.forwardRef((n,r)=>u.jsx(UA,{...n,ref:r,type:t}))}const HA=BA("line",PC);ro.register(jA,PA,tA,so,wA,NA);function WA({data:t,growthPercentage:e,isLoading:n=!1,className:r=""}){if(n)return u.jsxs("div",{"data-testid":"activity-chart-skeleton",className:`animate-pulse bg-white rounded-2xl p-6 ${r}`,children:[u.jsx("div",{className:"h-6 bg-gray-200 rounded w-1/3 mb-2"}),u.jsx("div",{className:"h-4 bg-gray-200 rounded w-1/2 mb-8"}),u.jsx("div",{className:"h-40 bg-gray-200 rounded"})]});if(!t||t.length===0)return u.jsx("div",{className:`bg-white rounded-2xl p-6 text-center ${r}`,children:u.jsx("p",{className:"text-gray-500",children:"No activity data available"})});const s={labels:t.map(l=>l.day),datasets:[{label:"Questions Solved",data:t.map(l=>l.count),borderColor:"#2563EB",backgroundColor:l=>{const d=l.chart.ctx.createLinearGradient(0,0,0,160);return d.addColorStop(0,"rgba(37, 99, 235, 0.2)"),d.addColorStop(1,"rgba(37, 99, 235, 0)"),d},borderWidth:3,pointBackgroundColor:"#fff",pointBorderColor:"#2563EB",pointBorderWidth:2,pointRadius:4,pointHoverRadius:6,fill:!0,tension:.4}]},o={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{backgroundColor:"#1F2937",padding:10,cornerRadius:8,displayColors:!1}},scales:{x:{grid:{display:!1},ticks:{color:"#9CA3AF",font:{size:10}}},y:{grid:{color:"#F3F4F6",tickLength:0},ticks:{display:!1},beginAtZero:!0}},interaction:{mode:"index",intersect:!1}},i=(e??0)>=0,a=i?"text-green-500":"text-red-500";return u.jsxs("div",{"data-testid":"activity-chart-container",className:`bg-white rounded-2xl p-6 ${r}`,children:[u.jsxs("div",{className:"flex justify-between items-end mb-4",children:[u.jsxs("div",{children:[u.jsx("div",{className:"text-sm font-bold text-gray-900",children:"Recent Activity"}),u.jsx("div",{className:"text-xs text-gray-500",children:"Last 7 days practice questions"})]}),e!==void 0&&u.jsxs("div",{className:"text-right",children:[u.jsxs("div",{className:`text-sm font-bold ${a}`,children:[i?"+":"",e,"%"]}),u.jsx("div",{className:"text-xs text-gray-500",children:"vs last week"})]})]}),u.jsx("div",{className:"h-40 w-full relative",children:u.jsx("div",{"data-testid":"activity-chart-canvas",children:u.jsx(HA,{data:s,options:o})})})]})}function qA({userName:t,userLevel:e,userAvatar:n,streakDays:r,coins:s,notifications:o=0,onSearch:i,onLanguageSwitch:a,onNotificationClick:l,onProfileClick:c,className:d=""}){const[f,g]=x.useState(""),h=m=>{const p=m.target.value;g(p),i?.(p)};return u.jsxs("header",{className:`h-[72px] bg-white/80 backdrop-blur-md px-8 flex justify-between items-center border-b border-gray-100 ${d}`,role:"banner",children:[u.jsxs("div",{className:"flex items-center gap-4 w-1/3",children:[u.jsx("h1",{className:"text-xl font-extrabold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-purple-600","data-testid":"logo",children:"MathWiz"}),u.jsxs("div",{className:"relative w-64 hidden md:block",children:[u.jsx(Z.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",size:16}),u.jsx(H.Input,{type:"text",placeholder:"Search skills, topics... / 搜索技能、知识点...",value:f,onChange:h,classNames:{input:"bg-gray-100 rounded-full py-2 pl-10 pr-4 text-sm",inputWrapper:"bg-gray-100 rounded-full h-10"},tabIndex:0,"aria-label":"Search skills and topics"})]})]}),u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsxs("p",{className:"hidden xl:block text-sm font-semibold text-gray-500 max-w-[180px] truncate",children:["Welcome back, ",t]}),u.jsxs(H.Button,{variant:"light",size:"sm",className:"text-gray-500 hover:text-blue-600",onPress:a,tabIndex:0,"aria-label":"Switch language",children:[u.jsx(Z.Globe,{size:16,className:"mr-1"}),"EN/中"]}),u.jsx("div",{className:"h-6 w-px bg-gray-200"}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx(ui,{type:"streak",value:r,label:"Day Streak",size:"md"}),u.jsx(ui,{type:"coin",value:s,size:"md"})]}),u.jsx("div",{className:"h-6 w-px bg-gray-200"}),u.jsxs("button",{className:"flex items-center gap-3 cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-600 rounded-lg p-1",onClick:c,tabIndex:0,"aria-label":"User profile",children:[u.jsx("img",{src:n,alt:t,className:"w-10 h-10 rounded-full border-2 border-blue-100"}),u.jsxs("div",{className:"hidden lg:block text-left",children:[u.jsx("div",{className:"font-bold text-sm text-gray-900",children:t}),u.jsx("div",{className:"text-xs text-gray-500",children:e})]})]}),u.jsxs("button",{className:"relative ml-2 text-gray-400 hover:text-gray-600 p-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600",onClick:l,tabIndex:0,"aria-label":"Notifications",children:[u.jsx(Z.Bell,{size:20}),o>0&&u.jsx("span",{className:"absolute top-0 right-0 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-white","data-testid":"notification-badge"})]})]})]})}const YA=[{id:"home",label:"Home",icon:Z.Home},{id:"browse",label:"Browse",icon:Z.LayoutGrid},{id:"analytics",label:"Analytics",icon:Z.BarChart3},{id:"settings",label:"Settings",icon:Z.Settings}];function KA({activeItemId:t="home",onNavigate:e,className:n=""}){const r=s=>{s!==t&&e?.(s)};return u.jsxs("aside",{className:`w-20 bg-white shadow-sm flex flex-col items-center py-6 gap-8 z-20 shrink-0 ${n}`,role:"complementary","aria-label":"Sidebar",children:[u.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-2xl flex items-center justify-center text-white font-bold text-xl shadow-md","data-testid":"logo",children:"M"}),u.jsx("nav",{className:"flex flex-col gap-6 w-full items-center",role:"navigation","aria-label":"Main navigation",children:YA.map(s=>{const o=s.icon,i=s.id===t;return u.jsx("button",{onClick:()=>r(s.id),tabIndex:0,"aria-label":s.label,className:`
296
- w-12 h-12 rounded-2xl flex items-center justify-center transition-colors
297
- ${i?"bg-blue-50 text-blue-600":"text-gray-400 hover:bg-gray-50 hover:text-gray-600"}
298
- `,"aria-current":i?"page":void 0,children:u.jsx(o,{size:24})},s.id)})})]})}const XA=(t,e,n)=>Math.min(Math.max(t,e),n),JA=t=>{const e={sm:"pathway-node--sm",md:"pathway-node--md",lg:"pathway-node--lg"};return e[t]||e.md},Oc=t=>{const e="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0";switch(t){case"completed":return`${e} bg-green-500`;case"current":return`${e} bg-brand-50`;case"locked":return`${e} bg-gray-300`;default:return e}},ZA=t=>{const e="font-medium";switch(t){case"completed":return`${e} line-through text-gray-400`;case"current":return`${e} text-gray-900`;case"locked":return`${e} text-gray-400`;default:return`${e} text-gray-900`}},kh=({status:t,title:e,subtitle:n,progress:r=0,avatarSrc:s,onAction:o,size:i="md",className:a="",showConnector:l=!1,isLast:c=!1})=>{const d=XA(r,0,100),f=JA(i),g=()=>{switch(t){case"completed":return u.jsx("div",{"data-testid":"pathway-node-icon-container",className:Oc("completed"),children:u.jsx(Z.Check,{"data-testid":"pathway-node-check-icon",className:"w-5 h-5 text-white"})});case"locked":return u.jsx("div",{"data-testid":"pathway-node-icon-container",className:Oc("locked"),children:u.jsx(Z.Lock,{"data-testid":"pathway-node-lock-icon",className:"w-5 h-5 text-white"})});default:return u.jsx("div",{"data-testid":"pathway-node-avatar-container",className:"w-10 h-10 rounded-full ring-2 ring-brand-500 flex items-center justify-center flex-shrink-0 overflow-hidden",children:s?u.jsx("img",{"data-testid":"pathway-node-avatar",src:s,alt:e,className:"w-full h-full object-cover"}):u.jsx("div",{"data-testid":"pathway-node-avatar",className:"w-full h-full bg-brand-100 flex items-center justify-center text-brand-600 font-bold",children:e.charAt(0).toUpperCase()})})}},h=()=>{const m=ZA(t);return t==="current"?u.jsxs("div",{"data-testid":"pathway-node-card",role:"article","aria-label":`${e} - Current Progress`,className:"flex-1 bg-brand-50 rounded-lg p-4 border border-brand-100",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[u.jsx("span",{className:"text-xs font-semibold text-brand-600 tracking-wide",children:"CURRENT"}),u.jsx("span",{className:"text-xs text-brand-400",children:"/ 当前进度"})]}),u.jsxs("div",{className:"mb-3",children:[u.jsx("h3",{className:m,children:e}),n&&u.jsx("p",{className:"text-sm text-gray-500 mt-1",children:n})]}),u.jsxs("div",{"data-testid":"pathway-node-progress",className:"mb-3",children:[u.jsxs("div",{className:"flex items-center justify-between mb-1",children:[u.jsx("span",{className:"text-xs text-gray-500",children:"Progress"}),u.jsxs("span",{className:"text-xs font-semibold text-brand-600",children:[d,"%"]})]}),u.jsx("div",{className:"w-full h-2 bg-gray-200 rounded-full overflow-hidden",children:u.jsx("div",{className:"h-full bg-brand-500 rounded-full transition-all duration-300",style:{width:`${d}%`}})})]}),u.jsx("button",{type:"button",onClick:o,"aria-label":`Go to ${e}`,className:"w-full py-2 px-4 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2",children:"Go"})]}):u.jsxs("div",{className:"flex-1",children:[u.jsx("h3",{className:m,children:e}),n&&u.jsx("p",{className:"text-sm text-gray-500 mt-1",children:n})]})};return u.jsxs("div",{"data-testid":"pathway-node",className:`flex items-start gap-4 ${f} ${a}`,children:[g(),h(),l&&!c&&u.jsx("div",{"data-testid":"pathway-node-connector",className:"absolute left-5 top-14 w-0.5 h-8 bg-gray-200",style:{transform:"translateX(-50%)"}})]})},QA={weakness:{gradient:"from-blue-400 to-blue-700",buttonText:"text-blue-600",BadgeIcon:Z.Target,BackgroundIcon:Z.SquareRadical},challenge:{gradient:"from-orange-300 to-orange-600",buttonText:"text-orange-600",BadgeIcon:Z.Zap,BackgroundIcon:Z.Flame},explore:{gradient:"from-purple-500 to-indigo-600",buttonText:"text-purple-600",BadgeIcon:Z.Compass,BackgroundIcon:Z.Lightbulb}},e1=({variant:t,badgeText:e,reasoning:n,title:r,contentNode:s,onAction:o,actionText:i="Try this >",className:a="",isDisabled:l=!1})=>{const c=QA[t],{BadgeIcon:d,BackgroundIcon:f}=c;return u.jsxs(H.Card,{"data-testid":"recommendation-card",className:`
299
- h-56 w-full
300
- bg-gradient-to-br ${c.gradient}
301
- rounded-2xl
302
- border-none
303
- text-white
304
- overflow-hidden
305
- relative
306
- transition-all duration-300 ease-out
307
- hover:-translate-y-1 hover:shadow-xl
308
- ${a}
309
- `,children:[u.jsx("div",{"data-testid":"background-icon",className:"absolute top-4 right-4 opacity-10 pointer-events-none",children:u.jsx(f,{size:80,strokeWidth:1})}),u.jsxs(H.CardBody,{className:"p-5 flex flex-col justify-between h-full relative z-10",children:[u.jsxs("div",{"data-testid":"recommendation-badge",className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white/20 backdrop-blur-sm w-fit",children:[u.jsx(d,{size:14,className:"text-white"}),u.jsx("span",{className:"text-xs font-medium text-white",children:e})]}),u.jsxs("div",{className:"flex-1 flex flex-col justify-center gap-2",children:[u.jsx("p",{className:"text-xs text-white/80 leading-loose",children:n}),u.jsx("h3",{className:"text-lg font-bold text-white leading-loose",children:r}),s&&u.jsx("div",{className:"mt-2",children:s})]}),u.jsx("div",{className:"mt-auto",children:u.jsx(H.Button,{size:"sm",className:`
310
- bg-white ${c.buttonText}
311
- rounded-full
312
- px-4 py-2
313
- font-medium
314
- text-sm
315
- hover:opacity-90
316
- transition-opacity
317
- `,onPress:o,isDisabled:l,children:i})})]})]})};function t1({nameEn:t,nameZh:e,percentage:n,color:r}){const a=2*Math.PI*29,l=a-n/100*a;return u.jsxs("div",{"data-testid":"skill-ring",className:"flex flex-col items-center",children:[u.jsxs("div",{className:"relative w-16 h-16 mb-2",children:[u.jsxs("svg",{width:64,height:64,viewBox:"0 0 64 64",children:[u.jsx("circle",{cx:64/2,cy:64/2,r:29,fill:"none",stroke:"#F3F4F6",strokeWidth:6}),u.jsx("circle",{cx:64/2,cy:64/2,r:29,fill:"none",stroke:r,strokeWidth:6,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:l,transform:`rotate(-90 ${64/2} ${64/2})`,style:{transition:"stroke-dashoffset 0.5s ease-in-out"}})]}),u.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-sm font-bold",style:{color:r},children:[n,"%"]})]}),u.jsx("div",{className:"text-xs font-bold text-gray-900",children:t}),u.jsx("div",{className:"text-[10px] text-gray-500",children:e})]})}function n1({skills:t,isLoading:e=!1,className:n=""}){return e?u.jsxs("div",{"data-testid":"skill-rings-skeleton",className:`animate-pulse bg-white rounded-2xl p-6 ${n}`,children:[u.jsx("div",{className:"h-5 bg-gray-200 rounded w-1/3 mb-2"}),u.jsx("div",{className:"h-4 bg-gray-200 rounded w-1/4 mb-6"}),u.jsx("div",{className:"flex justify-around",children:[1,2,3].map(r=>u.jsxs("div",{className:"flex flex-col items-center",children:[u.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full mb-2"}),u.jsx("div",{className:"h-3 bg-gray-200 rounded w-12 mb-1"}),u.jsx("div",{className:"h-2 bg-gray-200 rounded w-8"})]},r))})]}):!t||t.length===0?u.jsx("div",{className:`bg-white rounded-2xl p-6 text-center ${n}`,children:u.jsx("p",{className:"text-gray-500",children:"No skills data available"})}):u.jsxs("div",{"data-testid":"skill-rings-container",className:`bg-white rounded-2xl p-6 h-full ${n}`,children:[u.jsx("div",{className:"text-sm font-bold text-gray-900 mb-1",children:"Skill Mastery"}),u.jsx("div",{className:"text-xs text-gray-500 mb-4",children:"能力雷达图"}),u.jsx("div",{className:"flex justify-around items-center",children:t.map((r,s)=>u.jsx(t1,{nameEn:r.nameEn,nameZh:r.nameZh,percentage:r.percentage,color:r.color},s))})]})}const r1=({currentXP:t,targetXP:e,tasks:n,onTaskToggle:r,className:s=""})=>{const o=x.useMemo(()=>{if(e<=0)return 0;const a=Math.round(t/e*100);return Math.max(0,Math.min(100,a))},[t,e]),i=(a,l)=>{l||r?.(a,!0)};return u.jsxs("div",{"data-testid":"daily-milestones",className:`bg-white rounded-2xl shadow-sm p-6 relative overflow-hidden h-full ${s}`,children:[u.jsxs("div",{className:"flex items-center justify-between mb-6",children:[u.jsxs("div",{className:"flex items-baseline gap-2",children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 leading-loose",children:"Daily Milestones"}),u.jsx("span",{className:"text-sm text-gray-500 leading-loose",children:"/ 今日目标"})]}),u.jsx("span",{className:"text-4xl opacity-10 select-none","aria-hidden":"true",children:"🎉"})]}),u.jsxs("div",{"data-testid":"milestones-content",className:"flex flex-col md:flex-row items-start gap-6",children:[u.jsx(Pf,{value:o,size:"lg",maxLabel:`/${e} XP`}),u.jsx("div",{"data-testid":"task-list",className:"flex-1 w-full flex flex-col gap-4",children:n.map(a=>u.jsx(Df,{isCompleted:a.isCompleted,titleEn:a.titleEn,titleZh:a.titleZh,onToggle:()=>i(a.id,a.isCompleted)},a.id))})]})]})};function s1({activeTab:t,lessons:e,title:n="Learning Pathways",onTabChange:r,onLessonAction:s,currentLessonId:o,isLoading:i=!1,emptyState:a,className:l=""}){const c=[{id:"curriculum",label:"Curriculum Track",icon:u.jsx(Z.BookOpen,{size:20})},{id:"skillTree",label:"Skill Tree",icon:u.jsx(Z.TreePine,{size:20})}],d=g=>{r?.(g)},f=g=>{s?.(g)};return i?u.jsx("div",{"data-testid":"learning-pathway-skeleton",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,children:u.jsxs("div",{className:"animate-pulse space-y-4",children:[u.jsx("div",{className:"h-6 bg-gray-200 rounded w-1/2"}),u.jsx("div",{className:"h-10 bg-gray-200 rounded-full"}),[1,2,3].map(g=>u.jsx("div",{"data-testid":"skeleton-item",className:"h-16 bg-gray-200 rounded-lg"},g))]})}):e.length===0?u.jsxs("div",{"data-testid":"learning-pathway",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,role:"region","aria-label":n,children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 mb-4",children:n}),a||u.jsx("div",{"data-testid":"empty-state",className:"text-center py-8 text-gray-500",children:"No lessons available"})]}):u.jsxs("div",{"data-testid":"learning-pathway",className:`bg-white rounded-2xl border border-gray-200 p-6 h-full ${l}`,role:"region","aria-label":n,children:[u.jsx("h2",{className:"text-lg font-bold text-gray-900 mb-4 leading-loose",children:n}),u.jsx(Ff,{tabs:c,activeId:t,onChange:d,className:"mb-6","aria-label":"Learning pathway tabs"}),t==="curriculum"?u.jsx("div",{"data-testid":"curriculum-content",className:"flex flex-col gap-4 border-l-2 border-dashed border-gray-200 pl-4",role:"list","aria-label":"Curriculum lessons",children:e.map((g,h)=>{const p=o===g.id?"current":g.status;return u.jsx("div",{role:"listitem",children:u.jsx(kh,{status:p,title:g.title,subtitle:g.subtitle,progress:g.progress,avatarSrc:g.avatarSrc,onAction:p==="current"?()=>f(g.id):void 0,isLast:h===e.length-1})},g.id)})}):u.jsxs("div",{"data-testid":"skill-tree-placeholder",className:"text-center py-12 text-gray-500",children:[u.jsx(Z.TreePine,{size:48,className:"mx-auto mb-4 opacity-50"}),u.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Skill Tree"}),u.jsx("p",{children:"Visual skill progression map coming soon"})]})]})}const o1=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
318
- 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AICopilot=Of;exports.AbilityAssessmentDashboard=Ab;exports.AbilityProgressBar=fu;exports.ActionHeroCard=C_;exports.ActivityChart=WA;exports.AnswerStatusConst=Qy;exports.AreaGeometrySessionPage=o_;exports.AreaGeometrySessionPageIXL=c_;exports.Badge=f_;exports.Button=Pt;exports.ContentAccordion=Fc;exports.DEFAULT_IXL_CONFIG=pb;exports.DEFAULT_MAX_IMAGES=xf;exports.DEFAULT_PLACEHOLDER=bf;exports.DEFAULT_QUICK_ACTIONS=vf;exports.DEFAULT_WELCOME_MESSAGE=ra;exports.DailyMilestones=r1;exports.DashboardHeader=qA;exports.DashboardRecommendationCard=e1;exports.DashboardSidebar=KA;exports.DecimalNumberRecognitionSessionPage=Iw;exports.EquationRender=Gn;exports.ExplanationScene=Un;exports.FactorTable=Di;exports.GEOMETRY_CONFIG=Uw;exports.GamifiedToken=ui;exports.GeometryProblemAdapterV4=Ex;exports.GeometryTransform=Dd;exports.GradeNavigation=xb;exports.GradeUnitBrowserPage=Vb;exports.GradeUnitBrowserProvider=yu;exports.GraphContainer=Jd;exports.HundredChart=Ii;exports.IXLStyleCard=jn;exports.IXL_COLORS=yb;exports.IXL_LABELS=bb;exports.ImageStatusConst=Jw;exports.InputValidator=si;exports.IntentTypeConst=Xw;exports.LearningPathway=s1;exports.LongDivision=Gi;exports.MOCK_USER_COURSE_PROGRESS=pf;exports.MOCK_USER_GRADE_UNITS_NAV=Yw;exports.MOCK_USER_GRADE_UNITS_PROGRESS=Kw;exports.MathCard=o1;exports.MathCardV2=Be;exports.MathCell=Vi;exports.MathCellStatusConst=r_;exports.MathCellTypeConst=s_;exports.MathContainerModeConst=Zy;exports.MathContainerTypeConst=Jy;exports.MathGraph=Nr;exports.MathPracticeSessionPage=$w;exports.MathSessionContainer=df;exports.MathSessionPage=bw;exports.MathVisualizer=x_;exports.MathWizHeader=ld;exports.MessageRoleConst=di;exports.OptionCard=Ei;exports.OptionGroup=Ni;exports.OutputValidator=oi;exports.ParallelogramAreaCalculationSessionPage=ov;exports.PathwayNode=kh;exports.PersonalizedAdvicePanel=hu;exports.QuestionScene=xn;exports.RadarChart=uu;exports.RadialProgress=Pf;exports.RecommendationCard=gu;exports.RememberModule=vu;exports.ReviewModule=qi;exports.SCHEMA_VERSION=Pu;exports.SegmentedTabs=Ff;exports.ShortDivision=Li;exports.Sidebar=Dc;exports.SkillRings=n1;exports.SolveModule=Yi;exports.StatBlock=cd;exports.Submenu=wi;exports.SuccessScene=vn;exports.Table=Ad;exports.TaskCheckbox=Df;exports.TriangleAreaCalculationSessionPage=iv;exports.UserProfile=ad;exports.VERSION=Nx;exports.ValidationManager=pn;exports.VerticalMultiplication=zi;exports.adaptGeometryData=Ki;exports.adaptGeometryDataAsync=Ki;exports.adaptGeometryDataSync=wn;exports.adaptGeometryDataV4=wn;exports.benchmarkAdapter=kx;exports.calculateBoundingBox=Pi;exports.calculateDragRange=Ud;exports.calculateFilledCells=Vd;exports.calculateGamePoints=Pw;exports.calculateValueFromDrag=Bd;exports.categoryIcons=mr;exports.checkCompatibility=Tx;exports.comparePointArrays=zw;exports.courseData=Re;exports.createAICopilotStore=wf;exports.createAsyncAdapter=Iu;exports.createGeometryDataAdapter=Iu;exports.createSyncAdapter=Ou;exports.exploreItems=Mb;exports.formatPercentage=Fy;exports.generateCellData=Gd;exports.generateMockUserCourseProgress=mf;exports.getBasicGemDefinitions=Gw;exports.getBasicLineDefinitions=Vw;exports.getUnitNavItem=Ww;exports.getUserCourseProgress=ta;exports.getUserGradeUnitsNav=na;exports.getUserLessonProgress=Bw;exports.getUserUnitProgress=yf;exports.isGeometryProblem=Mx;exports.isPointInTriangle=Dw;exports.isV4Format=Fu;exports.loadGeometryProblemData=ju;exports.loadGeometryProblemDataAsync=ju;exports.loadGeometryProblemDataSync=$u;exports.loadGeometryProblemDataV4=$u;exports.pointOnLine=at;exports.statusColors=Eb;exports.statusMapping=kb;exports.toPixelCoordinates=Fw;exports.trianglesMatch=Lw;exports.updateUnitActiveStatus=qw;exports.updateUserLessonProgress=Hw;exports.useAICopilotStore=Or;exports.useAbortController=Qw;exports.useAnswerCorrectness=Wb;exports.useAnswerFormVisibility=Hi;exports.useCurrentScene=Ui;exports.useDataAdapter=Hd;exports.useDecimalAnswerFormVisibility=hf;exports.useDecimalCurrentScene=uf;exports.useDecimalSessionActions=gf;exports.useDecimalUserAnswer=ff;exports.useFactorTable=Qd;exports.useGeometryManagement=lf;exports.useGradeUnitBrowser=pu;exports.useHundredChartDrag=zd;exports.useHundredChartStore=Oi;exports.useHundredChartValue=Ld;exports.useIXLStyle=cu;exports.useImageState=Sf;exports.useInputState=_f;exports.useLongDivision=nu;exports.useMathPracticeSessionStore=Kt;exports.usePanelState=Cf;exports.useProblemData=qb;exports.useResponsive=du;exports.useSessionActions=Wi;exports.useSessionCalculations=af;exports.useSessionEventHandlers=cf;exports.useSessionStore=Ce;exports.useShortDivision=eu;exports.useTableCore=hy;exports.useTableState=Rd;exports.useUserAnswer=Bi;exports.useValidationError=xu;exports.useVerticalMultiplication=tu;exports.userData=$b;exports.validateGeometryData=Ax;exports.validateValue=ms;
317
+ The large square represents 1 whole.`},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}]}},explanation:[],answer:{value:.12,unit:"",explanation:"模型中100个方格有12个被涂色,代表12/100,即0.12。"}},CA=({className:t="",problemData:e})=>{const n=uh(),r=fh(),s=hh(),o=_A(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:l,setProblemData:c}=gh(),d=x.useMemo(()=>e||SA,[e]);return x.useEffect(()=>{c(d)},[d,c]),u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[d.grade,"年级 - ",d.unit]}),u.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[n==="question"&&u.jsx(vn,{problemData:d,userAnswer:r,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),n==="explanation"&&u.jsx(lA,{problemData:d,userAnswer:r,onNextQuestion:l}),n==="success"&&u.jsx(wn,{problemData:d,onNextQuestion:l})]}),u.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[n==="question"&&"请识别百格图代表的小数",n==="explanation"&&"查看详细解释",n==="success"&&"恭喜!答案正确"]})]})},at=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),RA=()=>{const t={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},n={x:.9,y:.75,name:"C"},r={...at(t,e,1/3),name:"D"},s={...at(t,n,1/3),name:"E"},o={...at(t,e,2/3),name:"M"},i={...at(t,n,2/3),name:"N"},a={...at(e,n,1/3),name:"P"},l={...at(e,n,2/3),name:"Q"},c={...at(r,s,1/3),name:"U"},d={...at(r,s,2/3),name:"S"},f={...at(o,i,1/3),name:"K"},g={...at(o,i,2/3),name:"L"};return{A:t,B:e,C:n,D:r,E:s,M:o,N:i,P:a,Q:l,U:c,S:d,K:f,L:g}},AA=(t,e,n)=>{const r={};for(const[s,o]of Object.entries(t))r[s]={...o,x:o.x*e,y:o.y*n};return r},NA=(t,e)=>{const[n,r,s]=e,{x:o,y:i}=t,a=(r.y-s.y)*(n.x-s.x)+(s.x-r.x)*(n.y-s.y);if(Math.abs(a)<1e-4)return!1;const l=((r.y-s.y)*(o-s.x)+(s.x-r.x)*(i-s.y))/a,c=((s.y-n.y)*(o-s.x)+(n.x-s.x)*(i-s.y))/a,d=1-l-c;return l>=-.001&&c>=-.001&&d>=-.001},EA=(t,e)=>{if(!t||!e||t.length!==3||e.length!==3)return!1;const n=t.map(s=>s.name).sort(),r=e.map(s=>s.name).sort();return n.every((s,o)=>s===r[o])},kA=(t,e)=>{if(!t||!e||t.length!==e.length)return!1;const n=t.map(s=>s.name).sort(),r=e.map(s=>s.name).sort();return n.join("")===r.join("")},TA=()=>[{from:"A",to:"B"},{from:"A",to:"C"},{from:"B",to:"C"},{from:"D",to:"E"},{from:"M",to:"N"},{from:"P",to:"Q"},{from:"A",to:"D"},{from:"A",to:"E"},{from:"A",to:"M"},{from:"A",to:"N"},{from:"A",to:"P"},{from:"A",to:"Q"},{from:"D",to:"U"},{from:"U",to:"S"},{from:"S",to:"E"},{from:"M",to:"K"},{from:"K",to:"L"},{from:"L",to:"N"},{from:"B",to:"P"},{from:"P",to:"Q"},{from:"Q",to:"C"}],MA=()=>[{id:"gem_1",vertices:["A","B","P"],points:10,category:"basic"},{id:"gem_2",vertices:["A","P","Q"],points:10,category:"basic"},{id:"gem_3",vertices:["A","Q","C"],points:10,category:"basic"},{id:"gem_4",vertices:["A","B","Q"],points:15,category:"medium"},{id:"gem_5",vertices:["A","P","C"],points:15,category:"medium"},{id:"gem_6",vertices:["A","B","C"],points:20,category:"large"},{id:"gem_7",vertices:["A","D","U"],points:12,category:"ade_small"},{id:"gem_8",vertices:["A","U","S"],points:12,category:"ade_small"},{id:"gem_9",vertices:["A","S","E"],points:12,category:"ade_small"},{id:"gem_10",vertices:["A","D","S"],points:18,category:"ade_medium"},{id:"gem_11",vertices:["A","U","E"],points:18,category:"ade_medium"},{id:"gem_12",vertices:["A","D","E"],points:25,category:"ade_large"},{id:"gem_13",vertices:["A","M","K"],points:14,category:"amn_small"},{id:"gem_14",vertices:["A","K","L"],points:14,category:"amn_small"},{id:"gem_15",vertices:["A","L","N"],points:14,category:"amn_small"},{id:"gem_16",vertices:["A","M","L"],points:20,category:"amn_medium"},{id:"gem_17",vertices:["A","K","N"],points:20,category:"amn_medium"},{id:"gem_18",vertices:["A","M","N"],points:30,category:"amn_large"}],jA={TOTAL_GEMS:18,CANVAS_RATIO:4/3,DEFAULT_VIEWBOX:{width:700,height:600},POINT_RADIUS:{default:6,selected:9},TOLERANCE:.001,MIN_TRIANGLE_AREA:.001,COORDINATE_PRECISION:1e-4,BARYCENTRIC_TOLERANCE:-.001},mh=(t=Tr.id)=>{const e=Re.units.map((s,o)=>{const i=Math.min(100,Math.max(0,o*15+Math.random()*20)),a=Math.floor(s.lessons.length*i/100),l=s.lessons.map((c,d)=>{const f=Math.min(100,Math.max(0,i-d*10+Math.random()*30));return{lessonId:c.id,status:f>=100?"completed":f>0?"in-progress":"not-started",progressPercentage:Math.round(f),lastAccessed:f>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:f>0?Math.floor(Math.random()*120+10):void 0,score:f>=100?Math.floor(Math.random()*21+80):void 0,attempts:f>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:s.id,userId:t,totalLessons:s.lessons.length,completedLessons:a,progressPercentage:Math.round(i),status:i>=100?"completed":i>0?"in-progress":"not-started",lastAccessed:i>0?new Date(Date.now()-Math.random()*14*24*60*60*1e3).toISOString():void 0,lessons:l}}),n=e.reduce((s,o)=>s+o.progressPercentage,0)/e.length,r=e.filter(s=>s.status==="completed").length;return{courseId:Re.id,userId:t,totalUnits:e.length,completedUnits:r,progressPercentage:Math.round(n),status:n>=100?"completed":n>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},ph=mh(),ma=(t,e)=>t===Tr.id&&e===Re.id?ph:null,yh=(t,e,n)=>{const r=ma(t,e);return r&&r.units.find(s=>s.unitId===n)||null},$A=(t,e,n,r)=>{const s=yh(t,e,n);return s&&s.lessons.find(o=>o.lessonId===r)||null},OA=(t,e,n,r,s)=>(console.log("Updating lesson progress:",{userId:t,courseId:e,unitId:n,lessonId:r,progress:s}),!0),pa=(t,e)=>{const n=ma(t,e);if(!n)return null;const r=Re.units.map((s,o)=>{const i=n.units.find(a=>a.unitId===s.id);return{unitId:s.id,title:s.title,description:s.description,moduleCategory:s.moduleCategory,estimatedDuration:s.estimatedDuration,totalLessons:s.lessons.length,completedLessons:i?.completedLessons||0,progressPercentage:i?.progressPercentage||0,status:i?.status||"not-started",lastAccessed:i?.lastAccessed,isActive:o===0,route:`/math/grade-${Re.level}/unit/${s.id}`}});return{userId:t,courseId:Re.id,courseTitle:Re.title,courseLevel:Re.level,totalUnits:r.length,completedUnits:r.filter(s=>s.status==="completed").length,overallProgress:n.progressPercentage,status:n.status,lastAccessed:n.lastAccessed,units:r}},IA=(t,e,n)=>{const r=pa(t,e);return r&&r.units.find(s=>s.unitId===n)||null},PA=(t,e,n,r)=>(console.log("Updating unit active status:",{userId:t,courseId:e,unitId:n,isActive:r}),!0),FA=pa(Tr.id,Re.id),DA={userId:Tr.id,courseId:Re.id,courseTitle:Re.title,courseLevel:Re.level,totalUnits:Re.units.length,completedUnits:3,overallProgress:45,status:"in-progress",lastAccessed:"2024-01-15T10:30:00Z",units:[{unitId:"unit_1",title:"小数乘法",description:"学习小数乘法的计算方法及应用",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:10,completedLessons:8,progressPercentage:80,status:"completed",lastAccessed:"2024-01-10T14:20:00Z",isActive:!1,route:"/math/grade-5/unit/unit_1",icon:"🔢"},{unitId:"unit_2",title:"小数除法",description:"学习小数除法的计算方法及应用",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:12,completedLessons:6,progressPercentage:50,status:"in-progress",lastAccessed:"2024-01-15T10:30:00Z",isActive:!0,route:"/math/grade-5/unit/unit_2",icon:"➗"},{unitId:"unit_3",title:"简易方程",description:"学习用字母表示数和解简易方程",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"4周",totalLessons:14,completedLessons:2,progressPercentage:14,status:"in-progress",lastAccessed:"2024-01-12T16:45:00Z",isActive:!1,route:"/math/grade-5/unit/unit_3",icon:"📝"},{unitId:"unit_4",title:"多边形的面积",description:"学习平行四边形、三角形、梯形和组合图形的面积计算",moduleCategory:"Graphics and Geometry",estimatedDuration:"3周",totalLessons:12,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_4",icon:"📐"},{unitId:"unit_5",title:"因数与倍数",description:"学习因数、倍数、质数、合数等概念",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:10,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_5",icon:"🔢"},{unitId:"unit_6",title:"长方体和正方体",description:"学习长方体和正方体的特征、表面积和体积计算",moduleCategory:"Graphics and Geometry",estimatedDuration:"4周",totalLessons:14,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_6",icon:"📦"},{unitId:"unit_7",title:"分数的意义和性质",description:"学习分数的意义、性质和约分、通分等方法",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"4周",totalLessons:16,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_7",icon:"½"},{unitId:"unit_8",title:"分数的加法和减法",description:"学习同分母分数、异分母分数的加法和减法",moduleCategory:"Arithmetic and Algebra",estimatedDuration:"3周",totalLessons:12,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_8",icon:"➕"},{unitId:"unit_9",title:"折线统计图",description:"学习单式折线统计图和复式折线统计图的认识和制作",moduleCategory:"Probability and Statistics",estimatedDuration:"2周",totalLessons:6,completedLessons:0,progressPercentage:0,status:"not-started",isActive:!1,route:"/math/grade-5/unit/unit_9",icon:"📊"}]},xi={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},LA={HINT:"hint",EXPLANATION:"explanation",SOLUTION:"solution",FOLLOW_UP:"follow_up",GENERAL:"general"},zA={PENDING:"pending",UPLOADING:"uploading",SUCCESS:"success",ERROR:"error"},ya="你好!我是你的数学学习助手。你可以问我任何数学问题,或者上传题目图片让我帮你解答。",bh="输入消息...",xh=4,vh=[{id:"1",label:"怎么解",message:"这道题怎么解?",icon:"HelpCircle"},{id:"2",label:"检查答案",message:"请检查我的答案",icon:"CheckCircle"},{id:"3",label:"类似题目",message:"给我一道类似的题目",icon:"Copy"},{id:"4",label:"知识点",message:"这道题涉及哪些知识点?",icon:"BookOpen"}],VA={inputValue:"",isInputFocused:!1,pendingImages:[],isContextBarCollapsed:!1,isHistoryOpen:!1,abortController:null},wh=()=>Dn.create((t,e)=>({...VA,setInputValue:n=>{t({inputValue:n})},setInputFocused:n=>{t({isInputFocused:n})},clearInput:()=>{t({inputValue:"",pendingImages:[]})},addPendingImage:n=>{const{pendingImages:r}=e();if(r.length>=4){console.warn("[AICopilot] 最多只能添加4张图片");return}t({pendingImages:[...r,n]})},removePendingImage:n=>{const{pendingImages:r}=e();t({pendingImages:r.filter(s=>s.id!==n)})},clearPendingImages:()=>{t({pendingImages:[]})},updateImageStatus:(n,r)=>{const{pendingImages:s}=e();t({pendingImages:s.map(o=>o.id===n?{...o,status:r}:o)})},toggleContextBar:()=>{const{isContextBarCollapsed:n}=e();t({isContextBarCollapsed:!n})},collapseContextBar:()=>{t({isContextBarCollapsed:!0})},expandContextBar:()=>{t({isContextBarCollapsed:!1})},setHistoryOpen:n=>{t({isHistoryOpen:n})},toggleHistory:()=>{const{isHistoryOpen:n}=e();t({isHistoryOpen:!n})},setAbortController:n=>{t({abortController:n})}})),Pr=wh(),_h=()=>Pr(bn.useShallow(t=>({inputValue:t.inputValue,isInputFocused:t.isInputFocused,setInputValue:t.setInputValue,setInputFocused:t.setInputFocused,clearInput:t.clearInput}))),Sh=()=>Pr(bn.useShallow(t=>({pendingImages:t.pendingImages,addPendingImage:t.addPendingImage,removePendingImage:t.removePendingImage,clearPendingImages:t.clearPendingImages,updateImageStatus:t.updateImageStatus}))),Ch=()=>Pr(bn.useShallow(t=>({isContextBarCollapsed:t.isContextBarCollapsed,isHistoryOpen:t.isHistoryOpen,toggleContextBar:t.toggleContextBar,collapseContextBar:t.collapseContextBar,expandContextBar:t.expandContextBar,setHistoryOpen:t.setHistoryOpen,toggleHistory:t.toggleHistory}))),GA=()=>Pr(bn.useShallow(t=>({abortController:t.abortController,setAbortController:t.setAbortController}))),UA=t=>{try{return new Date(t).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}catch{return"未知时间"}},Rh=x.memo(({message:t,showProblemTag:e=!1,className:n=""})=>{const r=t.role===xi.USER,s=t.role===xi.ASSISTANT,o=r?"mathwiz-chat-message--user flex-row-reverse":"mathwiz-chat-message--assistant flex-row",i=r?"mathwiz-chat-bubble--user bg-primary-100 text-primary-900":"mathwiz-chat-bubble--assistant bg-default-100 text-default-900",a=r?"用户消息":s?"AI助手消息":"系统消息",l=r?"你":"AI助手",c=r?"primary":"success";return u.jsxs("article",{className:`mathwiz-chat-message flex gap-3 p-4 ${o} ${n}`,"aria-label":a,"data-message-id":t.messageId,"data-role":t.role,children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx(H.Avatar,{size:"sm",color:c,className:"mathwiz-chat-avatar","aria-label":l,children:r?"U":"AI"})}),u.jsxs("div",{className:`flex-1 ${r?"text-right":"text-left"}`,children:[u.jsxs("div",{className:`flex items-center gap-2 mb-1 ${r?"justify-end":"justify-start"}`,children:[u.jsx("span",{className:"text-sm font-medium text-default-700",children:l}),u.jsx("span",{className:"text-xs text-default-400",children:UA(t.timestamp)})]}),e&&t.referencedProblemTitle&&u.jsx("div",{className:`mb-2 ${r?"text-right":"text-left"}`,children:u.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs rounded-full bg-default-200 text-default-600",children:["关联题目: ",t.referencedProblemTitle]})}),u.jsx("div",{className:`inline-block max-w-[80%] px-4 py-2 rounded-2xl text-left ${i}`,children:u.jsx("p",{className:"whitespace-pre-wrap break-words",children:t.content})}),t.images&&t.images.length>0&&u.jsx("div",{className:`flex gap-2 mt-2 flex-wrap ${r?"justify-end":"justify-start"}`,children:t.images.map((d,f)=>u.jsx("div",{className:"mathwiz-chat-image-preview relative w-20 h-20 rounded-lg overflow-hidden border border-default-200",children:u.jsx("img",{src:d.url,alt:`上传图片 ${f+1}`,className:"w-full h-full object-cover",loading:"lazy"})},d.id))})]})]})});Rh.displayName="ChatMessage";const BA=()=>u.jsxs("div",{className:"mathwiz-typing-indicator flex items-center gap-1 px-2 py-3","data-testid":"typing-indicator",children:[u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"0ms"}}),u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"150ms"}}),u.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"300ms"}})]}),Ah=x.memo(({content:t,className:e=""})=>{const n=t&&t.trim().length>0;return u.jsxs("article",{className:`mathwiz-stream-message flex gap-3 p-4 ${e}`,"aria-label":"AI正在输入","aria-live":"polite","aria-busy":"true",children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx(H.Avatar,{size:"sm",color:"success",className:"mathwiz-chat-avatar","aria-label":"AI助手",children:"AI"})}),u.jsxs("div",{className:"flex-1",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.jsx("span",{className:"text-sm font-medium text-default-700",children:"AI助手"}),u.jsx("span",{className:"text-xs text-default-400",children:"正在输入..."})]}),u.jsx("div",{className:"inline-block max-w-[80%] px-4 py-2 rounded-2xl bg-default-100 text-default-900",children:n?u.jsx("p",{className:"whitespace-pre-wrap break-words",children:t}):u.jsx(BA,{})}),!n&&u.jsxs("div",{className:"mt-2 space-y-2 max-w-[60%]",children:[u.jsx(H.Skeleton,{className:"h-3 w-full rounded-lg"}),u.jsx(H.Skeleton,{className:"h-3 w-3/4 rounded-lg"})]})]})]})});Ah.displayName="StreamMessage";const Nh=x.memo(({welcomeMessage:t=ya})=>u.jsxs("div",{className:"mathwiz-empty-state flex flex-col items-center justify-center h-full p-8 text-center",children:[u.jsx("div",{className:"w-16 h-16 mb-4 rounded-full bg-primary-100 flex items-center justify-center","data-testid":"empty-state-icon",children:u.jsx(Z.Bot,{size:32,className:"text-primary-600"})}),u.jsx("h3",{className:"text-lg font-semibold text-default-900 mb-2",children:"AI 数学助手"}),u.jsx("p",{className:"text-sm text-default-600 max-w-md",children:t}),u.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-default-400",children:[u.jsx(Z.MessageSquare,{size:14}),u.jsx("span",{children:"开始你的数学学习之旅"})]})]}));Nh.displayName="EmptyState";const Eh=x.memo(({messages:t,isStreaming:e=!1,streamingContent:n="",welcomeMessage:r,className:s=""})=>{const o=t.length>0,i=x.useRef(null);return x.useEffect(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[t,n]),u.jsx(H.ScrollShadow,{hideScrollBar:!0,className:`mathwiz-chat-container flex-1 overflow-y-auto ${s}`,role:"log","aria-label":"消息列表","aria-live":"polite",children:o?u.jsxs("div",{className:"pb-4",children:[t.map((a,l)=>{const c=a.role==="user"&&!!a.referencedProblemTitle&&t.findIndex(d=>d.referencedProblemId===a.referencedProblemId)===l;return u.jsx(Rh,{message:a,showProblemTag:c},a.messageId)}),e&&u.jsx(Ah,{content:n}),u.jsx("div",{ref:i})]}):u.jsx(Nh,{welcomeMessage:r})})});Eh.displayName="ChatContainer";const kh=x.memo(({value:t,onChange:e,onSend:n,onAbort:r,isStreaming:s=!1,pendingImages:o,onImageAdd:i,onImageRemove:a,onImageUpload:l,placeholder:c="输入消息...",maxImages:d=4,disabled:f=!1,className:g=""})=>{const h=x.useRef(null),m=t.trim().length>0||o.length>0,p=o.length>=d,y=x.useCallback(async v=>{const S=v.target.files?.[0];if(S){if(l)try{const _=await l(S);i(_)}catch(_){console.error("图片上传失败:",_)}else{const _=URL.createObjectURL(S);i({id:`local_${Date.now()}`,url:_,file:S,status:"pending"})}h.current&&(h.current.value="")}},[i,l]),b=x.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),m&&!f&&!s&&n())},[m,f,s,n]),w=x.useCallback(()=>{s&&r?r():m&&!f&&n()},[s,m,f,r,n]);return u.jsxs("div",{className:`mathwiz-chat-input bg-background border-t border-default-200 ${g}`,children:[o.length>0&&u.jsx("div",{className:"flex gap-2 p-3 overflow-x-auto",children:o.map((v,S)=>u.jsxs("div",{className:"mathwiz-pending-image relative flex-shrink-0 w-16 h-16 rounded-lg overflow-hidden border border-default-200",children:[u.jsx("img",{src:v.url,alt:`待发送图片 ${S+1}`,className:"w-full h-full object-cover"}),u.jsx("button",{onClick:()=>a(v.id),className:"absolute top-0.5 right-0.5 p-0.5 bg-default-900/50 hover:bg-default-900/70 rounded-full text-white transition-colors","aria-label":"移除图片",children:u.jsx(Z.X,{size:12})})]},v.id))}),u.jsxs("div",{className:"flex items-end gap-2 p-3",children:[u.jsx(H.Tooltip,{content:p?`最多${d}张图片`:"上传图片",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",isDisabled:p||f||s,onPress:()=>h.current?.click(),"aria-label":"上传图片",children:u.jsx(Z.ImagePlus,{size:20})})}),u.jsx("input",{ref:h,type:"file",accept:"image/*",className:"hidden",onChange:y,"aria-hidden":"true"}),u.jsx(H.Textarea,{value:t,onChange:v=>e(v.target.value),onKeyDown:b,placeholder:c,minRows:1,maxRows:4,isDisabled:f,className:"flex-1",classNames:{input:"min-h-[40px] py-2"}}),s?u.jsx(H.Button,{isIconOnly:!0,color:"danger",variant:"solid",size:"sm",onPress:w,"aria-label":"停止生成",children:u.jsx(Z.Square,{size:18,fill:"currentColor"})}):u.jsx(H.Button,{isIconOnly:!0,color:"primary",variant:"solid",size:"sm",isDisabled:!m||f,onPress:w,"aria-label":"发送消息",children:u.jsx(Z.Send,{size:18})})]})]})});kh.displayName="ChatInput";const HA=t=>{const e={size:16,className:"mr-1"};switch(t.icon){case"HelpCircle":return u.jsx(Z.HelpCircle,{...e});case"CheckCircle":return u.jsx(Z.CheckCircle,{...e});case"Copy":return u.jsx(Z.Copy,{...e});case"BookOpen":return u.jsx(Z.BookOpen,{...e});default:return u.jsx(Z.Sparkles,{...e})}},Th=x.memo(({actions:t,onActionClick:e,className:n=""})=>!t||t.length===0?null:u.jsx(H.ScrollShadow,{orientation:"horizontal",hideScrollBar:!0,className:`mathwiz-quick-actions w-full ${n}`,role:"region","aria-label":"快捷操作",children:u.jsx("div",{className:"flex gap-2 px-4 py-2",children:t.map(r=>u.jsx(H.Button,{variant:"flat",size:"sm",className:"mathwiz-quick-action-btn flex-shrink-0",startContent:HA(r),onPress:()=>e(r),"aria-label":r.label,children:r.label},r.id))})}));Th.displayName="QuickActions";const Mh=x.memo(({difficulty:t})=>{const e=Array.from({length:5},(n,r)=>r<t);return u.jsx("div",{className:"flex gap-0.5","aria-label":`难度等级: ${t}/5`,children:e.map((n,r)=>u.jsx(Z.Star,{size:14,"data-testid":"difficulty-star",className:n?"text-warning fill-warning":"text-default-300"},r))})});Mh.displayName="DifficultyStars";const jh=x.memo(({problemContext:t,isCollapsed:e,onToggle:n,onChangeProblem:r,className:s=""})=>{const{title:o,difficulty:i,knowledgePoints:a}=t;return u.jsx(H.Card,{className:`mathwiz-context-bar mx-4 mb-4 ${s}`,role:"region","aria-label":"当前题目上下文",children:u.jsxs(H.CardBody,{className:"p-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Z.BookOpen,{size:18,className:"text-primary"}),u.jsx("h3",{className:"font-medium text-default-900",children:o})]}),u.jsxs("div",{className:"flex items-center gap-1",children:[r&&u.jsx(H.Tooltip,{content:"更换题目",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:r,"aria-label":"更换题目",children:u.jsx(Z.RefreshCw,{size:16})})}),u.jsx(H.Tooltip,{content:e?"展开":"折叠",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:n,"aria-label":e?"展开":"折叠",children:e?u.jsx(Z.ChevronDown,{size:16}):u.jsx(Z.ChevronUp,{size:16})})})]})]}),!e&&u.jsxs("div",{className:"mt-3 pt-3 border-t border-default-200",children:[u.jsx("div",{className:"flex items-center gap-4",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-xs text-default-500",children:"难度:"}),u.jsx(Mh,{difficulty:i})]})}),a.length>0&&u.jsxs("div",{className:"mt-2 flex items-center gap-2 flex-wrap",children:[u.jsx("span",{className:"text-xs text-default-500",children:"知识点:"}),a.map(l=>u.jsx(H.Chip,{size:"sm",variant:"flat",color:"primary",children:l.name},l.id))]})]})]})})});jh.displayName="CollapsibleContextBar";const $h=x.memo(({onLoadHistory:t,onNewSession:e})=>u.jsxs(H.Navbar,{className:"mathwiz-copilot-header border-b border-default-200",shouldHideOnScroll:!1,children:[u.jsx(H.NavbarContent,{justify:"start",children:u.jsx(H.NavbarItem,{children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Z.MessageSquare,{className:"text-primary",size:24}),u.jsx("span",{className:"font-bold text-lg",children:"AI 数学助手"})]})})}),u.jsxs(H.NavbarContent,{justify:"end",children:[e&&u.jsx(H.NavbarItem,{children:u.jsx(H.Tooltip,{content:"新建会话",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:e,"aria-label":"新建会话",children:u.jsx(Z.Plus,{size:20})})})}),t&&u.jsx(H.NavbarItem,{children:u.jsx(H.Tooltip,{content:"历史记录",children:u.jsx(H.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:t,"aria-label":"历史记录",children:u.jsx(Z.History,{size:20})})})})]})]}));$h.displayName="Header";const Oh=x.memo(({messages:t,problemContext:e,isStreaming:n=!1,streamingContent:r="",onSendMessage:s,onAbortStreaming:o,onLoadHistory:i,onNewSession:a,onChangeProblem:l,onImageUpload:c,quickActions:d=vh,welcomeMessage:f=ya,placeholder:g=bh,maxImages:h=xh,className:m=""})=>{const{inputValue:p,setInputValue:y,clearInput:b}=_h(),{pendingImages:w,addPendingImage:v,removePendingImage:S}=Sh(),{isContextBarCollapsed:_,toggleContextBar:A}=Ch(),C=x.useCallback(()=>{!p.trim()&&w.length===0||(s(p,{problemId:e?.problemId,images:w.length>0?w:void 0}),b())},[p,w,e?.problemId,s,b]),R=x.useCallback(N=>{s(N.message,{problemId:e?.problemId})},[s,e?.problemId]);return u.jsxs("div",{className:`mathwiz-copilot flex flex-col h-full bg-background ${m}`,role:"main","aria-label":"AI数学助手",children:[u.jsx($h,{onLoadHistory:i,onNewSession:a}),e&&u.jsx(jh,{problemContext:e,isCollapsed:_,onToggle:A,onChangeProblem:l}),u.jsx(Eh,{messages:t,isStreaming:n,streamingContent:r,welcomeMessage:f}),u.jsx(Th,{actions:d,onActionClick:R}),u.jsx(kh,{value:p,onChange:y,onSend:C,onAbort:o,isStreaming:n,pendingImages:w,onImageAdd:v,onImageRemove:S,onImageUpload:c,placeholder:g,maxImages:h})]})});Oh.displayName="AICopilot";const WA={CORRECT:"correct",INCORRECT:"incorrect",IDLE:"idle"},qA={LABEL:"label",INPUT:"input",RESULT:"result",PLACEHOLDER:"placeholder"},YA=({className:t="",problemData:e,children:n})=>{const r=Qs(),s=eo(),o=to(),i=no(),{updateUserAnswer:a,submitAnswer:l,nextQuestion:c,setProblemData:d}=ro();x.useEffect(()=>{e&&d(e)},[e,d]);const g=(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"text-cyan-600",label:"三角形面积"};case"parallelogram":return{titleColor:"text-blue-600",label:"平行四边形面积"};case"trapezoid":return{titleColor:"text-green-600",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"text-purple-600",label:"年龄问题"}:{titleColor:"text-slate-600",label:"数学问题"}}})();return u.jsxs("div",{className:`bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center p-4 font-sans ${t}`,children:[u.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[u.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${g.titleColor}`,children:e?.title||"数学问题练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),u.jsx("div",{className:"mt-4 md:mt-0",children:u.jsx("span",{className:"inline-block px-3 py-1 text-sm font-medium rounded-full bg-white border border-slate-200 text-slate-700",children:g.label})})]}),e?.description&&u.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),u.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm",children:e?u.jsxs(u.Fragment,{children:[r==="question"&&u.jsx(vn,{problemData:e,userAnswer:s,showAnswerForm:o,onAnswerSubmit:l,onAnswerChange:a,validationError:i}),r==="explanation"&&u.jsx(Bn,{problemData:e,userAnswer:s,onNextQuestion:c}),r==="success"&&u.jsx(wn,{problemData:e,onNextQuestion:c})]}):u.jsxs("div",{className:"p-8 text-center",children:[u.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),u.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),u.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),u.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:u.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[u.jsx("div",{className:"mb-4 md:mb-0",children:u.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),u.jsx("div",{children:u.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),n&&u.jsx("div",{className:"w-full max-w-4xl mt-8",children:n})]})},KA=()=>u.jsxs("div",{className:"ixl-dashboard-panels",children:[u.jsxs("div",{className:"ixl-dashboard-card ixl-questions-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Questions",u.jsx("br",{}),"answered"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-time-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Time",u.jsx("br",{}),"elapsed"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsxs("div",{className:"ixl-time-display",children:[u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"hr"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"min"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"06"}),u.jsx("div",{className:"ixl-time-label",children:"sec"})]})]})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-score-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["SmartScore",u.jsx("span",{className:"ixl-score-subtitle",children:"out of 100"}),u.jsx("span",{className:"ixl-help-icon",title:"What is this?",children:"?"})]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsx("p",{className:"ixl-dashboard-note",children:"*在实际业务项目中集成StatBlock组件显示实时数据"})]}),XA=()=>u.jsxs("div",{className:"ixl-scaffolding-links",children:[u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),u.jsx("span",{children:"Learn with an example"})]}),u.jsx("span",{className:"ixl-scaffolding-separator",children:"or"}),u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"currentColor",viewBox:"0 0 20 20",children:u.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"})}),u.jsx("span",{children:"Watch a video"})]})]}),JA=()=>{const t=[{icon:"💎",title:"Understanding area of a triangle",isPurple:!1},{icon:"💎",title:"Multiply two decimals: products up to hundredths",isPurple:!1},{icon:"💎",title:"Division with decimal divisors",isPurple:!1},{icon:"📚",title:"Lesson: Area of triangles",isPurple:!0}];return u.jsx("div",{className:"ixl-work-it-out-grid",children:t.map((e,n)=>u.jsxs("a",{href:"#",className:`ixl-work-it-out-card ${e.isPurple?"ixl-work-it-out-card-purple":""}`,children:[u.jsx("span",{className:`ixl-work-it-out-icon ${e.isPurple?"ixl-work-it-out-icon-purple":""}`,children:e.icon}),u.jsx("span",{className:"ixl-work-it-out-text",children:e.title})]},n))})},ZA=({className:t="",problemData:e,children:n})=>{const r=Qs(),s=eo(),o=to(),i=no(),{updateUserAnswer:a,submitAnswer:l,nextQuestion:c,setProblemData:d}=ro();return x.useEffect(()=>{e&&d(e)},[e,d]),(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"ixl-title-color-triangle",label:"三角形面积"};case"parallelogram":return{titleColor:"ixl-title-color-parallelogram",label:"平行四边形面积"};case"trapezoid":return{titleColor:"ixl-title-color-trapezoid",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"ixl-title-color-age",label:"年龄问题"}:{titleColor:"ixl-title-color-default",label:"数学问题"}}})(),u.jsxs("div",{className:`ixl-immersive-container ${t}`,children:[u.jsx("div",{className:"ixl-top-nav",children:u.jsxs("div",{className:"ixl-breadcrumb",children:[u.jsx("span",{className:"ixl-breadcrumb-item",children:"Sixth grade"}),u.jsx("span",{className:"ixl-breadcrumb-separator",children:"›"}),u.jsx("span",{className:"ixl-breadcrumb-item",children:"GG.6 Area of triangles"}),u.jsx("span",{className:"ixl-breadcrumb-tag",children:"C8S"})]})}),u.jsxs("main",{className:"ixl-main-layout",children:[u.jsxs("div",{className:"ixl-content-area",children:[u.jsxs("div",{className:"ixl-main-card",children:[u.jsx(XA,{}),u.jsxs("div",{className:"ixl-status-banner",children:[u.jsx("strong",{children:"Parent results not recorded."})," Continue practicing or ",u.jsx("a",{href:"#",className:"ixl-status-link",children:"switch user"}),"."]}),u.jsx("div",{className:"ixl-question-display",children:e?u.jsxs(u.Fragment,{children:[r==="question"&&u.jsx(vn,{problemData:e,userAnswer:s,showAnswerForm:o,onAnswerSubmit:l,onAnswerChange:a,validationError:i}),r==="explanation"&&u.jsx(Bn,{problemData:e,userAnswer:s,onNextQuestion:c}),r==="success"&&u.jsx(wn,{problemData:e,onNextQuestion:c})]}):u.jsxs("div",{className:"ixl-no-data-message",children:[u.jsx("div",{className:"ixl-no-data-icon",children:"⚠️"}),u.jsx("h3",{className:"ixl-no-data-title",children:"缺少问题数据"}),u.jsx("p",{className:"ixl-no-data-desc",children:"请提供有效的problemData prop"})]})})]}),u.jsxs("div",{className:"ixl-review-area",children:[u.jsxs("div",{className:"ixl-review-header",children:[u.jsx("h3",{className:"ixl-review-title",children:"Work it out"}),u.jsx("p",{className:"ixl-review-subtitle",children:"Not feeling ready yet? These can help:"})]}),u.jsx(JA,{})]})]}),u.jsx("aside",{className:"ixl-dashboard-area",children:u.jsx(KA,{})})]}),n&&u.jsx("div",{className:"ixl-children-area",children:n})]})},QA={brand:"primary",growth:"success",motivation:"warning",neutral:"default"},jc={sm:"text-[10px] px-2 py-0.5",md:"text-xs px-3 py-1"},e1={brand:{solid:"bg-brand-600 text-white",outline:"bg-brand-100 border-brand-500 text-brand-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},growth:{solid:"bg-growth-500 text-white",outline:"bg-growth-50 border-growth-500 text-growth-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},motivation:{solid:"bg-motivation-500 text-white",outline:"bg-motivation-50 border-motivation-500 text-motivation-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"},neutral:{solid:"bg-gray-500 text-white",outline:"bg-gray-100 border-gray-500 text-gray-600",glass:"bg-white/20 backdrop-blur-md text-white border border-white/30"}},t1=({variant:t="solid",color:e="brand",size:n="md",icon:r,children:s,className:o,"aria-label":i})=>{const a="inline-flex items-center gap-1.5 font-bold uppercase tracking-wider rounded-full";if(t==="glass"){const d=[a,jc[n],e1[e].glass,o].join(" ");return u.jsxs("span",{className:d,"aria-label":i,children:[r&&u.jsx("i",{className:r,"aria-hidden":"true"}),s]})}const l=t==="outline"?"flat":"solid",c=QA[e];return u.jsxs(H.Badge,{variant:l,color:c,className:`${a} ${jc[n]} ${o||""}`,"aria-label":i,children:[r&&u.jsx("i",{className:r,"aria-hidden":"true"}),s]})},ba={sm:{segmentWidth:16,barHeight:24,fontSize:16,operatorWidth:24,gap:2},md:{segmentWidth:20,barHeight:32,fontSize:24,operatorWidth:32,gap:2}},Ih={add:"+",subtract:"-",multiply:"×",divide:"÷"},vi={filled:"#10B981",empty:"#E5E7EB",operator:"#9CA3AF"};function $c(t,e){const n=ba[e];return t*n.segmentWidth+(t-1)*n.gap}function Oc(t,e,n,r){const s=ba[r],o=[];for(let i=0;i<e;i++){const a=n+i*(s.segmentWidth+s.gap),l=i<t;o.push(u.jsx("rect",{x:a,y:0,width:s.segmentWidth,height:s.barHeight,rx:3,fill:l?vi.filled:vi.empty,className:`math-visualizer__segment ${l?"math-visualizer__segment--filled":"math-visualizer__segment--empty"}`},`segment-${i}`))}return o}const n1=({data:t,size:e})=>{const n=t,{fraction1:r,fraction2:s,operation:o}=n,i=ba[e],a=!!s&&!!o,l=$c(r.denominator,e),c=a?$c(s.denominator,e):0,d=a?i.operatorWidth:0,f=a?l+d+c:l,g=i.barHeight,h=l+d/2,m=l+d;return u.jsxs("svg",{width:f,height:g,viewBox:`0 0 ${f} ${g}`,className:"math-visualizer__svg",children:[u.jsx("g",{className:"math-visualizer__bar",children:Oc(r.numerator,r.denominator,0,e)}),a&&u.jsx("text",{x:h,y:g/2,dy:"0.35em",textAnchor:"middle",fill:vi.operator,fontSize:i.fontSize,fontWeight:"bold",className:"math-visualizer__operator",children:Ih[o]||o}),a&&s&&u.jsx("g",{className:"math-visualizer__bar",transform:`translate(${m}, 0)`,children:Oc(s.numerator,s.denominator,0,e)})]})},r1=({data:t,size:e})=>{const n=t,r=e==="sm"?"math-visualizer__formula--sm":"math-visualizer__formula--md";return u.jsx("div",{className:`math-visualizer__formula ${r}`,children:u.jsx("code",{className:"math-visualizer__formula-text",children:n.formula})})};function s1(t,e){if(t==="formula")return`Mathematical formula: ${e.formula}`;const n=e,{fraction1:r,fraction2:s,operation:o}=n;let i=`Fraction visualization: ${r.numerator} out of ${r.denominator} parts filled`;if(s&&o){const a=Ih[o]||o;i+=` ${a} ${s.numerator} out of ${s.denominator} parts filled`}return i}const o1=({type:t,data:e,size:n="md",className:r="","aria-label":s})=>{const o="math-visualizer",i=`${o}--${n}`,a=`${o} ${i} ${r}`.trim(),l=s||s1(t,e);return u.jsx("div",{className:a,role:"img","aria-label":l,children:t==="visual"?u.jsx(n1,{data:e,size:n}):u.jsx(r1,{data:e,size:n})})},i1=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
318
+ 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AICopilot=Oh;exports.AbilityAssessmentDashboard=Ob;exports.AbilityProgressBar=fu;exports.ActionHeroCard=vu;exports.ActivityChart=yf;exports.AnswerStatusConst=ab;exports.AreaGeometrySessionPage=YA;exports.AreaGeometrySessionPageIXL=ZA;exports.Badge=t1;exports.Button=Pt;exports.ContentAccordion=Fc;exports.DEFAULT_IXL_CONFIG=Cb;exports.DEFAULT_MAX_IMAGES=xh;exports.DEFAULT_PLACEHOLDER=bh;exports.DEFAULT_QUICK_ACTIONS=vh;exports.DEFAULT_WELCOME_MESSAGE=ya;exports.DailyMilestones=Su;exports.DashboardHeader=bu;exports.DashboardPage=T_;exports.DashboardRecommendationCard=Nu;exports.DashboardSidebar=xu;exports.DecimalNumberRecognitionSessionPage=CA;exports.EquationRender=Gn;exports.ExplanationScene=Bn;exports.FactorTable=Di;exports.GEOMETRY_CONFIG=jA;exports.GamifiedToken=si;exports.GeometryProblemAdapterV4=yS;exports.GeometryTransform=Dd;exports.GradeNavigation=Nb;exports.GradeUnitBrowserPage=Kb;exports.GradeUnitBrowserProvider=yu;exports.GraphContainer=Jd;exports.HundredChart=Ii;exports.IXLStyleCard=$n;exports.IXL_COLORS=Rb;exports.IXL_LABELS=Ab;exports.ImageStatusConst=zA;exports.InputValidator=hi;exports.IntentTypeConst=LA;exports.LearningPathway=Au;exports.LongDivision=Gi;exports.MOCK_USER_COURSE_PROGRESS=ph;exports.MOCK_USER_GRADE_UNITS_NAV=FA;exports.MOCK_USER_GRADE_UNITS_PROGRESS=DA;exports.MathCard=i1;exports.MathCardV2=Be;exports.MathCell=Vi;exports.MathCellStatusConst=WA;exports.MathCellTypeConst=qA;exports.MathContainerModeConst=ib;exports.MathContainerTypeConst=ob;exports.MathGraph=kr;exports.MathPracticeSessionPage=wA;exports.MathSessionContainer=dh;exports.MathSessionPage=aA;exports.MathVisualizer=o1;exports.MathWizHeader=ld;exports.MessageRoleConst=xi;exports.OptionCard=Ei;exports.OptionGroup=ki;exports.OutputValidator=gi;exports.ParallelogramAreaCalculationSessionPage=YC;exports.PathwayNode=Ru;exports.PersonalizedAdvicePanel=hu;exports.QuestionScene=vn;exports.RadarChart=uu;exports.RadialProgress=wu;exports.RecommendationCard=gu;exports.RememberModule=wf;exports.ReviewModule=aa;exports.SCHEMA_VERSION=Ff;exports.SegmentedTabs=Cu;exports.ShortDivision=Li;exports.Sidebar=Dc;exports.SkillRings=bf;exports.SolveModule=la;exports.StatBlock=cd;exports.Submenu=wi;exports.SuccessScene=wn;exports.Table=Ad;exports.TaskCheckbox=_u;exports.TriangleAreaCalculationSessionPage=KC;exports.UserProfile=ad;exports.VERSION=bS;exports.ValidationManager=yn;exports.VerticalMultiplication=zi;exports.adaptGeometryData=ca;exports.adaptGeometryDataAsync=ca;exports.adaptGeometryDataSync=_n;exports.adaptGeometryDataV4=_n;exports.benchmarkAdapter=pS;exports.calculateBoundingBox=Pi;exports.calculateDragRange=Ud;exports.calculateFilledCells=Vd;exports.calculateGamePoints=RA;exports.calculateValueFromDrag=Bd;exports.categoryIcons=mr;exports.checkCompatibility=xS;exports.comparePointArrays=kA;exports.courseData=Re;exports.createAICopilotStore=wh;exports.createAsyncAdapter=Pf;exports.createGeometryDataAdapter=Pf;exports.createSyncAdapter=If;exports.exploreItems=Lb;exports.formatPercentage=Hy;exports.generateCellData=Gd;exports.generateMockUserCourseProgress=mh;exports.getBasicGemDefinitions=MA;exports.getBasicLineDefinitions=TA;exports.getUnitNavItem=IA;exports.getUserCourseProgress=ma;exports.getUserGradeUnitsNav=pa;exports.getUserLessonProgress=$A;exports.getUserUnitProgress=yh;exports.isGeometryProblem=vS;exports.isPointInTriangle=NA;exports.isV4Format=Df;exports.loadGeometryProblemData=Of;exports.loadGeometryProblemDataAsync=Of;exports.loadGeometryProblemDataSync=$f;exports.loadGeometryProblemDataV4=$f;exports.pointOnLine=at;exports.statusColors=Pb;exports.statusMapping=Ib;exports.toPixelCoordinates=AA;exports.trianglesMatch=EA;exports.updateUnitActiveStatus=PA;exports.updateUserLessonProgress=OA;exports.useAICopilotStore=Pr;exports.useAbortController=GA;exports.useAnswerCorrectness=I_;exports.useAnswerFormVisibility=oa;exports.useCurrentScene=ra;exports.useDataAdapter=Hd;exports.useDecimalAnswerFormVisibility=hh;exports.useDecimalCurrentScene=uh;exports.useDecimalSessionActions=gh;exports.useDecimalUserAnswer=fh;exports.useFactorTable=Qd;exports.useGeometryManagement=lh;exports.useGradeUnitBrowser=pu;exports.useHundredChartDrag=zd;exports.useHundredChartStore=Oi;exports.useHundredChartValue=Ld;exports.useIXLStyle=cu;exports.useImageState=Sh;exports.useInputState=_h;exports.useLongDivision=nu;exports.useMathPracticeSessionStore=Kt;exports.usePanelState=Ch;exports.useProblemData=P_;exports.useResponsive=du;exports.useSessionActions=ia;exports.useSessionCalculations=ah;exports.useSessionEventHandlers=ch;exports.useSessionStore=Ce;exports.useShortDivision=eu;exports.useTableCore=wy;exports.useTableState=Rd;exports.useUserAnswer=sa;exports.useValidationError=vf;exports.useVerticalMultiplication=tu;exports.userData=zb;exports.validateGeometryData=mS;exports.validateValue=ms;
319
319
  //# sourceMappingURL=index.cjs.map