@mathwiz/ui-components 0.1.26 → 0.1.27

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,24 +1,19 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("react"),vi=require("@heroui/progress"),Or=require("@heroui/card"),Vr=require("lucide-react"),ke=require("@heroui/react"),_i=require("katex"),vo=require("jsxgraph"),Ut=require("zustand"),_o=require("zustand/shallow"),on=require("zustand/react/shallow"),wi=require("zustand/middleware");function Ai(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Fe=Ai(b);var Zt={exports:{}},$t={};var Mn;function Ri(){if(Mn)return $t;Mn=1;var r=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(n,o,s){var i=null;if(s!==void 0&&(i=""+s),o.key!==void 0&&(i=""+o.key),"key"in o){s={};for(var a in o)a!=="key"&&(s[a]=o[a])}else s=o;return o=s.ref,{$$typeof:r,type:n,key:i,ref:o!==void 0?o:null,props:s}}return $t.Fragment=e,$t.jsx=t,$t.jsxs=t,$t}var kt={};var In;function Si(){return In||(In=1,process.env.NODE_ENV!=="production"&&(function(){function r(A){if(A==null)return null;if(typeof A=="function")return A.$$typeof===Y?null:A.displayName||A.name||null;if(typeof A=="string")return A;switch(A){case p:return"Fragment";case C:return"Profiler";case x:return"StrictMode";case j:return"Suspense";case w:return"SuspenseList";case O:return"Activity"}if(typeof A=="object")switch(typeof A.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),A.$$typeof){case g:return"Portal";case E:return A.displayName||"Context";case S:return(A._context.displayName||"Context")+".Consumer";case _:var F=A.render;return A=A.displayName,A||(A=F.displayName||F.name||"",A=A!==""?"ForwardRef("+A+")":"ForwardRef"),A;case P:return F=A.displayName||null,F!==null?F:r(A.type)||"Memo";case $:F=A._payload,A=A._init;try{return r(A(F))}catch{}}return null}function e(A){return""+A}function t(A){try{e(A);var F=!1}catch{F=!0}if(F){F=console;var V=F.error,te=typeof Symbol=="function"&&Symbol.toStringTag&&A[Symbol.toStringTag]||A.constructor.name||"Object";return V.call(F,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",te),e(A)}}function n(A){if(A===p)return"<>";if(typeof A=="object"&&A!==null&&A.$$typeof===$)return"<...>";try{var F=r(A);return F?"<"+F+">":"<...>"}catch{return"<...>"}}function o(){var A=q.A;return A===null?null:A.getOwner()}function s(){return Error("react-stack-top-frame")}function i(A){if(I.call(A,"key")){var F=Object.getOwnPropertyDescriptor(A,"key").get;if(F&&F.isReactWarning)return!1}return A.key!==void 0}function a(A,F){function V(){M||(M=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",F))}V.isReactWarning=!0,Object.defineProperty(A,"key",{get:V,configurable:!0})}function d(){var A=r(this.type);return ge[A]||(ge[A]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),A=this.props.ref,A!==void 0?A:null}function l(A,F,V,te,je,Le){var oe=V.ref;return A={$$typeof:h,type:A,key:F,props:V,_owner:te},(oe!==void 0?oe:null)!==null?Object.defineProperty(A,"ref",{enumerable:!1,get:d}):Object.defineProperty(A,"ref",{enumerable:!1,value:null}),A._store={},Object.defineProperty(A._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(A,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(A,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:je}),Object.defineProperty(A,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Le}),Object.freeze&&(Object.freeze(A.props),Object.freeze(A)),A}function c(A,F,V,te,je,Le){var oe=F.children;if(oe!==void 0)if(te)if(G(oe)){for(te=0;te<oe.length;te++)u(oe[te]);Object.freeze&&Object.freeze(oe)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else u(oe);if(I.call(F,"key")){oe=r(A);var Ue=Object.keys(F).filter(function(k){return k!=="key"});te=0<Ue.length?"{key: someKey, "+Ue.join(": ..., ")+": ...}":"{key: someKey}",fe[oe+te]||(Ue=0<Ue.length?"{"+Ue.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
- let props = %s;
3
- <%s {...props} />
4
- React keys must be passed directly to JSX without using spread:
5
- let props = %s;
6
- <%s key={someKey} {...props} />`,te,oe,Ue,oe),fe[oe+te]=!0)}if(oe=null,V!==void 0&&(t(V),oe=""+V),i(F)&&(t(F.key),oe=""+F.key),"key"in F){V={};for(var mt in F)mt!=="key"&&(V[mt]=F[mt])}else V=F;return oe&&a(V,typeof A=="function"?A.displayName||A.name||"Unknown":A),l(A,oe,V,o(),je,Le)}function u(A){y(A)?A._store&&(A._store.validated=1):typeof A=="object"&&A!==null&&A.$$typeof===$&&(A._payload.status==="fulfilled"?y(A._payload.value)&&A._payload.value._store&&(A._payload.value._store.validated=1):A._store&&(A._store.validated=1))}function y(A){return typeof A=="object"&&A!==null&&A.$$typeof===h}var m=b,h=Symbol.for("react.transitional.element"),g=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),x=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),E=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),O=Symbol.for("react.activity"),Y=Symbol.for("react.client.reference"),q=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,I=Object.prototype.hasOwnProperty,G=Array.isArray,H=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(A){return A()}};var M,ge={},se=m.react_stack_bottom_frame.bind(m,s)(),W=H(n(s)),fe={};kt.Fragment=p,kt.jsx=function(A,F,V){var te=1e4>q.recentlyCreatedOwnerStacks++;return c(A,F,V,!1,te?Error("react-stack-top-frame"):se,te?H(n(A)):W)},kt.jsxs=function(A,F,V){var te=1e4>q.recentlyCreatedOwnerStacks++;return c(A,F,V,!0,te?Error("react-stack-top-frame"):se,te?H(n(A)):W)}})()),kt}var Fn;function Ci(){return Fn||(Fn=1,process.env.NODE_ENV==="production"?Zt.exports=Ri():Zt.exports=Si()),Zt.exports}var f=Ci();const xt=({progress:r,variant:e="solid",size:t="md",radius:n="md",children:o,className:s="",loading:i,...a})=>{const l=r!==void 0?(u=>u===0?"button--primary":u===100?"button--success":"button--secondary")(r):"button--primary",c=["button",`button--${t}`,`button--${e}`,`button--radius-${n}`,l,i&&"button--loading",s].filter(Boolean).join(" ");return f.jsx("button",{type:"button",className:c,"data-progress":r,disabled:i||a.disabled,...a,children:i?"加载中...":o})},Pn=r=>r===0?"开始学习":r===100?"复习":"继续学习",Ei=r=>{if(r.length===0)return 0;const e=r.reduce((t,n)=>t+n.progress,0);return Math.round(e/r.length)},Ti=({knowledgeItem:r,onLearnAction:e})=>{const t=()=>{e(r)};return console.log("KnowledgeCard render:",{progress:r.progress,text:Pn(r.progress)}),f.jsxs(Or.Card,{className:"content-accordion__knowledge-card",children:[f.jsxs(Or.CardBody,{children:[f.jsx("h3",{className:"content-accordion__knowledge-title",children:r.title}),f.jsx("p",{className:"content-accordion__knowledge-description",children:r.description})]}),f.jsxs(Or.CardFooter,{className:"content-accordion__knowledge-actions",children:[f.jsxs("div",{className:"content-accordion__progress-container",children:[f.jsx(vi.Progress,{value:r.progress,size:"sm",color:"primary","aria-label":`${r.title} 进度`,className:"content-accordion__progress-bar"}),f.jsxs("span",{className:"content-accordion__progress-text",children:[r.progress,"%"]})]}),f.jsx(xt,{size:"sm",radius:"md",onClick:t,progress:r.progress,variant:r.progress===100?"light":r.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:Pn(r.progress)})]})]})},Ni=({lesson:r,isExpanded:e,onToggle:t,onLearnAction:n})=>{const o=()=>{t(r.id)},s=Ei(r.knowledgeItems);return f.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[f.jsxs("div",{className:"content-accordion__lesson-header",onClick:o,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${r.title},点击${e?"收起":"展开"}`,children:[f.jsxs("div",{className:"content-accordion__lesson-header-content",children:[f.jsx("h2",{className:"content-accordion__lesson-title",children:r.title}),f.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",r.duration," 分钟"]})]}),f.jsxs("div",{className:"content-accordion__lesson-actions",children:[f.jsxs("span",{className:"content-accordion__lesson-progress",children:[s,"%"]}),e?f.jsx(Vr.ChevronDown,{className:"content-accordion__lesson-icon"}):f.jsx(Vr.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&f.jsx("div",{className:"content-accordion__knowledge-list",children:r.knowledgeItems.map(i=>f.jsx(Ti,{knowledgeItem:i,onLearnAction:n},i.id))})]})},wo=({unit:r,activeLessonIds:e,onToggleLesson:t,onLearnAction:n,loading:o=!1,className:s="",emptyState:i})=>o?f.jsx("div",{className:"content-accordion content-accordion--loading",children:f.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):r?f.jsxs("div",{className:`content-accordion ${s}`,children:[f.jsxs("header",{className:"content-accordion__header",children:[f.jsx("h1",{className:"content-accordion__unit-title",children:r.title}),f.jsx("p",{className:"content-accordion__unit-description",children:r.description}),f.jsxs("div",{className:"content-accordion__unit-meta",children:[f.jsxs("span",{children:["总共 ",r.totalLessons," 节课"]}),f.jsx("span",{children:"•"}),f.jsxs("span",{children:["预计学习 ",r.estimatedDuration]})]})]}),f.jsx("div",{className:"content-accordion__lessons",children:r.lessons.map(a=>f.jsx(Ni,{lesson:a,isExpanded:e.includes(a.id),onToggle:t,onLearnAction:n},a.id))})]}):f.jsx("div",{className:"content-accordion content-accordion--empty",children:i||f.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),$i=r=>{switch(r){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},Ao=({data:r,loading:e=!1,error:t=null,collapsed:n=!1,onToggleCollapse:o,activeUnitId:s=null,onUnitSelect:i,renderUnitItem:a,className:d="",unitItemClassName:l="",style:c={},unitItemStyle:u={}})=>{const y=(p,x)=>{x.preventDefault(),i?.(p)},m=()=>{o?.()},h=p=>f.jsxs("div",{className:`sidebar__unit-item ${l} ${s===p.unitId?"sidebar__unit-item--active":""} ${p.status?`sidebar__unit-item--${p.status}`:""}`,style:u,onClick:x=>y(p.unitId,x),role:"button",tabIndex:0,"aria-label":`${p.title},进度 ${p.progressPercentage}%`,children:[f.jsxs("div",{className:"sidebar__unit-item__content",children:[p.icon&&f.jsx("span",{className:"sidebar__unit-item__icon",children:p.icon}),!n&&f.jsx("span",{className:"sidebar__unit-item__title",children:p.title})]}),!n&&p.progressPercentage!==void 0&&f.jsxs("div",{className:"sidebar__unit-item__progress",children:[f.jsx(ke.Progress,{value:p.progressPercentage,size:"sm",color:$i(p.status),"aria-label":`${p.title} 进度`}),f.jsxs("span",{className:"progress-percentage",children:[p.progressPercentage,"%"]})]})]},p.unitId),g=()=>e?f.jsx("div",{className:"sidebar__loading",children:"加载中..."}):t?f.jsxs("div",{className:"sidebar__error",children:["加载失败: ",t.message]}):r?f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"sidebar__header",children:[f.jsx("button",{className:"sidebar__toggle-btn",onClick:m,"aria-label":"切换侧边栏折叠状态",children:n?"→":"←"}),!n&&f.jsxs("div",{className:"sidebar__course-info",children:[f.jsx("h3",{className:"sidebar__course-title",children:r.courseTitle}),f.jsxs("span",{className:"sidebar__course-level",children:[r.courseLevel,"年级"]})]})]}),f.jsx("nav",{className:"sidebar__content",children:f.jsx("ul",{className:"sidebar__unit-list",children:r.units&&r.units.length>0?r.units.map(p=>f.jsx("li",{children:a?a(p,p):h(p)},p.unitId)):f.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):f.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return f.jsx("aside",{className:`sidebar ${d} ${n?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${t?"sidebar--error":""}`,style:c,"aria-label":"课程导航侧边栏",role:"complementary",children:g()})},sn=({trigger:r,items:e,position:t="bottom",alignment:n="start",openDelay:o=300,closeDelay:s=100,onOpen:i,onClose:a,renderItem:d,itemConfig:l={},className:c,menuClassName:u,itemClassName:y})=>{const[m,h]=b.useState(!1),g=b.useRef(null),p=b.useRef(null),x=()=>{g.current&&clearTimeout(g.current),p.current&&clearTimeout(p.current)},C=()=>{x(),g.current=setTimeout(()=>{h(!0),i?.()},o)},S=()=>{x(),p.current=setTimeout(()=>{h(!1),a?.()},s)},E=w=>{!w.disabled&&w.onClick&&w.onClick(w)};b.useEffect(()=>()=>x(),[]);const _=w=>f.jsxs("div",{className:`submenu-item ${w.disabled?"is-disabled":""} ${y||""}`,onClick:()=>E(w),children:[w.icon&&f.jsx("span",{className:"submenu-item-icon",children:w.icon}),f.jsx("span",{children:w.label})]},w.id),j=()=>{const w=["submenu-panel"];return u&&w.push(u),w.push(`position-${t}`),n!=="start"&&w.push(`alignment-${n}`),m&&w.push("is-open"),w.join(" ")};return f.jsxs("div",{className:`submenu-container ${c||""}`,onMouseEnter:C,onMouseLeave:S,children:[f.jsx("div",{className:"submenu-trigger",children:r}),f.jsx("div",{className:j(),children:e.map(w=>d?d(w,l):_(w))})]})};function Ro(r,e){return function(){return r.apply(e,arguments)}}const{toString:ki}=Object.prototype,{getPrototypeOf:an}=Object,{iterator:_r,toStringTag:So}=Symbol,wr=(r=>e=>{const t=ki.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),De=r=>(r=r.toLowerCase(),e=>wr(e)===r),Ar=r=>e=>typeof e===r,{isArray:Rt}=Array,vt=Ar("undefined");function Gt(r){return r!==null&&!vt(r)&&r.constructor!==null&&!vt(r.constructor)&&Ce(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const Co=De("ArrayBuffer");function Oi(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&Co(r.buffer),e}const ji=Ar("string"),Ce=Ar("function"),Eo=Ar("number"),zt=r=>r!==null&&typeof r=="object",Mi=r=>r===!0||r===!1,ar=r=>{if(wr(r)!=="object")return!1;const e=an(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(So in r)&&!(_r in r)},Ii=r=>{if(!zt(r)||Gt(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Fi=De("Date"),Pi=De("File"),Di=De("Blob"),Li=De("FileList"),Ui=r=>zt(r)&&Ce(r.pipe),Gi=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Ce(r.append)&&((e=wr(r))==="formdata"||e==="object"&&Ce(r.toString)&&r.toString()==="[object FormData]"))},zi=De("URLSearchParams"),[Bi,Vi,Wi,qi]=["ReadableStream","Request","Response","Headers"].map(De),Yi=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Bt(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,o;if(typeof r!="object"&&(r=[r]),Rt(r))for(n=0,o=r.length;n<o;n++)e.call(null,r[n],n,r);else{if(Gt(r))return;const s=t?Object.getOwnPropertyNames(r):Object.keys(r),i=s.length;let a;for(n=0;n<i;n++)a=s[n],e.call(null,r[a],a,r)}}function To(r,e){if(Gt(r))return null;e=e.toLowerCase();const t=Object.keys(r);let n=t.length,o;for(;n-- >0;)if(o=t[n],e===o.toLowerCase())return o;return null}const lt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,No=r=>!vt(r)&&r!==lt;function Wr(){const{caseless:r,skipUndefined:e}=No(this)&&this||{},t={},n=(o,s)=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;const i=r&&To(t,s)||s;ar(t[i])&&ar(o)?t[i]=Wr(t[i],o):ar(o)?t[i]=Wr({},o):Rt(o)?t[i]=o.slice():(!e||!vt(o))&&(t[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Bt(arguments[o],n);return t}const Hi=(r,e,t,{allOwnKeys:n}={})=>(Bt(e,(o,s)=>{t&&Ce(o)?Object.defineProperty(r,s,{value:Ro(o,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(r,s,{value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),r),Ki=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),Xi=(r,e,t,n)=>{r.prototype=Object.create(e.prototype,n),Object.defineProperty(r.prototype,"constructor",{value:r,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},Ji=(r,e,t,n)=>{let o,s,i;const a={};if(e=e||{},r==null)return e;do{for(o=Object.getOwnPropertyNames(r),s=o.length;s-- >0;)i=o[s],(!n||n(i,r,e))&&!a[i]&&(e[i]=r[i],a[i]=!0);r=t!==!1&&an(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},Zi=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const n=r.indexOf(e,t);return n!==-1&&n===t},Qi=r=>{if(!r)return null;if(Rt(r))return r;let e=r.length;if(!Eo(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},ea=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&an(Uint8Array)),ta=(r,e)=>{const n=(r&&r[_r]).call(r);let o;for(;(o=n.next())&&!o.done;){const s=o.value;e.call(r,s[0],s[1])}},ra=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},na=De("HTMLFormElement"),oa=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,o){return n.toUpperCase()+o}),Dn=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),sa=De("RegExp"),$o=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};Bt(t,(o,s)=>{let i;(i=e(o,s,r))!==!1&&(n[s]=i||o)}),Object.defineProperties(r,n)},ia=r=>{$o(r,(e,t)=>{if(Ce(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(Ce(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},aa=(r,e)=>{const t={},n=o=>{o.forEach(s=>{t[s]=!0})};return Rt(r)?n(r):n(String(r).split(e)),t},la=()=>{},ca=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function da(r){return!!(r&&Ce(r.append)&&r[So]==="FormData"&&r[_r])}const fa=r=>{const e=new Array(10),t=(n,o)=>{if(zt(n)){if(e.indexOf(n)>=0)return;if(Gt(n))return n;if(!("toJSON"in n)){e[o]=n;const s=Rt(n)?[]:{};return Bt(n,(i,a)=>{const d=t(i,o+1);!vt(d)&&(s[a]=d)}),e[o]=void 0,s}}return n};return t(r,0)},ua=De("AsyncFunction"),ma=r=>r&&(zt(r)||Ce(r))&&Ce(r.then)&&Ce(r.catch),ko=((r,e)=>r?setImmediate:e?((t,n)=>(lt.addEventListener("message",({source:o,data:s})=>{o===lt&&s===t&&n.length&&n.shift()()},!1),o=>{n.push(o),lt.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Ce(lt.postMessage)),ha=typeof queueMicrotask<"u"?queueMicrotask.bind(lt):typeof process<"u"&&process.nextTick||ko,ga=r=>r!=null&&Ce(r[_r]),v={isArray:Rt,isArrayBuffer:Co,isBuffer:Gt,isFormData:Gi,isArrayBufferView:Oi,isString:ji,isNumber:Eo,isBoolean:Mi,isObject:zt,isPlainObject:ar,isEmptyObject:Ii,isReadableStream:Bi,isRequest:Vi,isResponse:Wi,isHeaders:qi,isUndefined:vt,isDate:Fi,isFile:Pi,isBlob:Di,isRegExp:sa,isFunction:Ce,isStream:Ui,isURLSearchParams:zi,isTypedArray:ea,isFileList:Li,forEach:Bt,merge:Wr,extend:Hi,trim:Yi,stripBOM:Ki,inherits:Xi,toFlatObject:Ji,kindOf:wr,kindOfTest:De,endsWith:Zi,toArray:Qi,forEachEntry:ta,matchAll:ra,isHTMLForm:na,hasOwnProperty:Dn,hasOwnProp:Dn,reduceDescriptors:$o,freezeMethods:ia,toObjectSet:aa,toCamelCase:oa,noop:la,toFiniteNumber:ca,findKey:To,global:lt,isContextDefined:No,isSpecCompliantForm:da,toJSONObject:fa,isAsyncFn:ua,isThenable:ma,setImmediate:ko,asap:ha,isIterable:ga};let L=class Oo extends Error{static from(e,t,n,o,s,i){const a=new Oo(e.message,t||e.code,n,o,s);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,t,n,o,s){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),n&&(this.config=n),o&&(this.request=o),s&&(this.response=s,this.status=s.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:v.toJSONObject(this.config),code:this.code,status:this.status}}};L.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";L.ERR_BAD_OPTION="ERR_BAD_OPTION";L.ECONNABORTED="ECONNABORTED";L.ETIMEDOUT="ETIMEDOUT";L.ERR_NETWORK="ERR_NETWORK";L.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";L.ERR_DEPRECATED="ERR_DEPRECATED";L.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";L.ERR_BAD_REQUEST="ERR_BAD_REQUEST";L.ERR_CANCELED="ERR_CANCELED";L.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";L.ERR_INVALID_URL="ERR_INVALID_URL";const pa=null;function qr(r){return v.isPlainObject(r)||v.isArray(r)}function jo(r){return v.endsWith(r,"[]")?r.slice(0,-2):r}function Ln(r,e,t){return r?r.concat(e).map(function(o,s){return o=jo(o),!t&&s?"["+o+"]":o}).join(t?".":""):e}function ya(r){return v.isArray(r)&&!r.some(qr)}const ba=v.toFlatObject(v,{},null,function(e){return/^is[A-Z]/.test(e)});function Rr(r,e,t){if(!v.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=v.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,p){return!v.isUndefined(p[g])});const n=t.metaTokens,o=t.visitor||c,s=t.dots,i=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&v.isSpecCompliantForm(e);if(!v.isFunction(o))throw new TypeError("visitor must be a function");function l(h){if(h===null)return"";if(v.isDate(h))return h.toISOString();if(v.isBoolean(h))return h.toString();if(!d&&v.isBlob(h))throw new L("Blob is not supported. Use a Buffer instead.");return v.isArrayBuffer(h)||v.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function c(h,g,p){let x=h;if(h&&!p&&typeof h=="object"){if(v.endsWith(g,"{}"))g=n?g:g.slice(0,-2),h=JSON.stringify(h);else if(v.isArray(h)&&ya(h)||(v.isFileList(h)||v.endsWith(g,"[]"))&&(x=v.toArray(h)))return g=jo(g),x.forEach(function(S,E){!(v.isUndefined(S)||S===null)&&e.append(i===!0?Ln([g],E,s):i===null?g:g+"[]",l(S))}),!1}return qr(h)?!0:(e.append(Ln(p,g,s),l(h)),!1)}const u=[],y=Object.assign(ba,{defaultVisitor:c,convertValue:l,isVisitable:qr});function m(h,g){if(!v.isUndefined(h)){if(u.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));u.push(h),v.forEach(h,function(x,C){(!(v.isUndefined(x)||x===null)&&o.call(e,x,v.isString(C)?C.trim():C,g,y))===!0&&m(x,g?g.concat(C):[C])}),u.pop()}}if(!v.isObject(r))throw new TypeError("data must be an object");return m(r),e}function Un(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function ln(r,e){this._pairs=[],r&&Rr(r,this,e)}const Mo=ln.prototype;Mo.append=function(e,t){this._pairs.push([e,t])};Mo.toString=function(e){const t=e?function(n){return e.call(this,n,Un)}:Un;return this._pairs.map(function(o){return t(o[0])+"="+t(o[1])},"").join("&")};function xa(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Io(r,e,t){if(!e)return r;const n=t&&t.encode||xa,o=v.isFunction(t)?{serialize:t}:t,s=o&&o.serialize;let i;if(s?i=s(e,o):i=v.isURLSearchParams(e)?e.toString():new ln(e,o).toString(n),i){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+i}return r}class Gn{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){v.forEach(this.handlers,function(n){n!==null&&e(n)})}}const cn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},va=typeof URLSearchParams<"u"?URLSearchParams:ln,_a=typeof FormData<"u"?FormData:null,wa=typeof Blob<"u"?Blob:null,Aa={isBrowser:!0,classes:{URLSearchParams:va,FormData:_a,Blob:wa},protocols:["http","https","file","blob","url","data"]},dn=typeof window<"u"&&typeof document<"u",Yr=typeof navigator=="object"&&navigator||void 0,Ra=dn&&(!Yr||["ReactNative","NativeScript","NS"].indexOf(Yr.product)<0),Sa=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ca=dn&&window.location.href||"http://localhost",Ea=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:dn,hasStandardBrowserEnv:Ra,hasStandardBrowserWebWorkerEnv:Sa,navigator:Yr,origin:Ca},Symbol.toStringTag,{value:"Module"})),Ae={...Ea,...Aa};function Ta(r,e){return Rr(r,new Ae.classes.URLSearchParams,{visitor:function(t,n,o,s){return Ae.isNode&&v.isBuffer(t)?(this.append(n,t.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function Na(r){return v.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function $a(r){const e={},t=Object.keys(r);let n;const o=t.length;let s;for(n=0;n<o;n++)s=t[n],e[s]=r[s];return e}function Fo(r){function e(t,n,o,s){let i=t[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),d=s>=t.length;return i=!i&&v.isArray(o)?o.length:i,d?(v.hasOwnProp(o,i)?o[i]=[o[i],n]:o[i]=n,!a):((!o[i]||!v.isObject(o[i]))&&(o[i]=[]),e(t,n,o[i],s)&&v.isArray(o[i])&&(o[i]=$a(o[i])),!a)}if(v.isFormData(r)&&v.isFunction(r.entries)){const t={};return v.forEachEntry(r,(n,o)=>{e(Na(n),o,t,0)}),t}return null}function ka(r,e,t){if(v.isString(r))try{return(e||JSON.parse)(r),v.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const Vt={transitional:cn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",o=n.indexOf("application/json")>-1,s=v.isObject(e);if(s&&v.isHTMLForm(e)&&(e=new FormData(e)),v.isFormData(e))return o?JSON.stringify(Fo(e)):e;if(v.isArrayBuffer(e)||v.isBuffer(e)||v.isStream(e)||v.isFile(e)||v.isBlob(e)||v.isReadableStream(e))return e;if(v.isArrayBufferView(e))return e.buffer;if(v.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Ta(e,this.formSerializer).toString();if((a=v.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return Rr(a?{"files[]":e}:e,d&&new d,this.formSerializer)}}return s||o?(t.setContentType("application/json",!1),ka(e)):e}],transformResponse:[function(e){const t=this.transitional||Vt.transitional,n=t&&t.forcedJSONParsing,o=this.responseType==="json";if(v.isResponse(e)||v.isReadableStream(e))return e;if(e&&v.isString(e)&&(n&&!this.responseType||o)){const i=!(t&&t.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?L.from(a,L.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:Ae.classes.FormData,Blob:Ae.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};v.forEach(["delete","get","head","post","put","patch"],r=>{Vt.headers[r]={}});const Oa=v.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"]),ja=r=>{const e={};let t,n,o;return r&&r.split(`
7
- `).forEach(function(i){o=i.indexOf(":"),t=i.substring(0,o).trim().toLowerCase(),n=i.substring(o+1).trim(),!(!t||e[t]&&Oa[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},zn=Symbol("internals");function Ot(r){return r&&String(r).trim().toLowerCase()}function lr(r){return r===!1||r==null?r:v.isArray(r)?r.map(lr):String(r)}function Ma(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(r);)e[n[1]]=n[2];return e}const Ia=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function jr(r,e,t,n,o){if(v.isFunction(n))return n.call(this,e,t);if(o&&(e=t),!!v.isString(e)){if(v.isString(n))return e.indexOf(n)!==-1;if(v.isRegExp(n))return n.test(e)}}function Fa(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function Pa(r,e){const t=v.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(o,s,i){return this[n].call(this,e,o,s,i)},configurable:!0})})}let Ee=class{constructor(e){e&&this.set(e)}set(e,t,n){const o=this;function s(a,d,l){const c=Ot(d);if(!c)throw new Error("header name must be a non-empty string");const u=v.findKey(o,c);(!u||o[u]===void 0||l===!0||l===void 0&&o[u]!==!1)&&(o[u||d]=lr(a))}const i=(a,d)=>v.forEach(a,(l,c)=>s(l,c,d));if(v.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(v.isString(e)&&(e=e.trim())&&!Ia(e))i(ja(e),t);else if(v.isObject(e)&&v.isIterable(e)){let a={},d,l;for(const c of e){if(!v.isArray(c))throw TypeError("Object iterator must return a key-value pair");a[l=c[0]]=(d=a[l])?v.isArray(d)?[...d,c[1]]:[d,c[1]]:c[1]}i(a,t)}else e!=null&&s(t,e,n);return this}get(e,t){if(e=Ot(e),e){const n=v.findKey(this,e);if(n){const o=this[n];if(!t)return o;if(t===!0)return Ma(o);if(v.isFunction(t))return t.call(this,o,n);if(v.isRegExp(t))return t.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ot(e),e){const n=v.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||jr(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let o=!1;function s(i){if(i=Ot(i),i){const a=v.findKey(n,i);a&&(!t||jr(n,n[a],a,t))&&(delete n[a],o=!0)}}return v.isArray(e)?e.forEach(s):s(e),o}clear(e){const t=Object.keys(this);let n=t.length,o=!1;for(;n--;){const s=t[n];(!e||jr(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const t=this,n={};return v.forEach(this,(o,s)=>{const i=v.findKey(n,s);if(i){t[i]=lr(o),delete t[s];return}const a=e?Fa(s):String(s).trim();a!==s&&delete t[s],t[a]=lr(o),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return v.forEach(this,(n,o)=>{n!=null&&n!==!1&&(t[o]=e&&v.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
8
- `)}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,...t){const n=new this(e);return t.forEach(o=>n.set(o)),n}static accessor(e){const n=(this[zn]=this[zn]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Ot(i);n[a]||(Pa(o,i),n[a]=!0)}return v.isArray(e)?e.forEach(s):s(e),this}};Ee.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);v.reduceDescriptors(Ee.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});v.freezeMethods(Ee);function Mr(r,e){const t=this||Vt,n=e||t,o=Ee.from(n.headers);let s=n.data;return v.forEach(r,function(a){s=a.call(t,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Po(r){return!!(r&&r.__CANCEL__)}let Wt=class extends L{constructor(e,t,n){super(e??"canceled",L.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function Do(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new L("Request failed with status code "+t.status,[L.ERR_BAD_REQUEST,L.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function Da(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function La(r,e){r=r||10;const t=new Array(r),n=new Array(r);let o=0,s=0,i;return e=e!==void 0?e:1e3,function(d){const l=Date.now(),c=n[s];i||(i=l),t[o]=d,n[o]=l;let u=s,y=0;for(;u!==o;)y+=t[u++],u=u%r;if(o=(o+1)%r,o===s&&(s=(s+1)%r),l-i<e)return;const m=c&&l-c;return m?Math.round(y*1e3/m):void 0}}function Ua(r,e){let t=0,n=1e3/e,o,s;const i=(l,c=Date.now())=>{t=c,o=null,s&&(clearTimeout(s),s=null),r(...l)};return[(...l)=>{const c=Date.now(),u=c-t;u>=n?i(l,c):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},n-u)))},()=>o&&i(o)]}const yr=(r,e,t=3)=>{let n=0;const o=La(50,250);return Ua(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,d=i-n,l=o(d),c=i<=a;n=i;const u={loaded:i,total:a,progress:a?i/a:void 0,bytes:d,rate:l||void 0,estimated:l&&a&&c?(a-i)/l:void 0,event:s,lengthComputable:a!=null,[e?"download":"upload"]:!0};r(u)},t)},Bn=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},Vn=r=>(...e)=>v.asap(()=>r(...e)),Ga=Ae.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,Ae.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(Ae.origin),Ae.navigator&&/(msie|trident)/i.test(Ae.navigator.userAgent)):()=>!0,za=Ae.hasStandardBrowserEnv?{write(r,e,t,n,o,s,i){if(typeof document>"u")return;const a=[`${r}=${encodeURIComponent(e)}`];v.isNumber(t)&&a.push(`expires=${new Date(t).toUTCString()}`),v.isString(n)&&a.push(`path=${n}`),v.isString(o)&&a.push(`domain=${o}`),s===!0&&a.push("secure"),v.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(r){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+r+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(r){this.write(r,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Ba(r){return typeof r!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function Va(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Lo(r,e,t){let n=!Ba(e);return r&&(n||t==!1)?Va(r,e):e}const Wn=r=>r instanceof Ee?{...r}:r;function dt(r,e){e=e||{};const t={};function n(l,c,u,y){return v.isPlainObject(l)&&v.isPlainObject(c)?v.merge.call({caseless:y},l,c):v.isPlainObject(c)?v.merge({},c):v.isArray(c)?c.slice():c}function o(l,c,u,y){if(v.isUndefined(c)){if(!v.isUndefined(l))return n(void 0,l,u,y)}else return n(l,c,u,y)}function s(l,c){if(!v.isUndefined(c))return n(void 0,c)}function i(l,c){if(v.isUndefined(c)){if(!v.isUndefined(l))return n(void 0,l)}else return n(void 0,c)}function a(l,c,u){if(u in e)return n(l,c);if(u in r)return n(void 0,l)}const d={url:s,method:s,data:s,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:(l,c,u)=>o(Wn(l),Wn(c),u,!0)};return v.forEach(Object.keys({...r,...e}),function(c){if(c==="__proto__"||c==="constructor"||c==="prototype")return;const u=v.hasOwnProp(d,c)?d[c]:o,y=u(r[c],e[c],c);v.isUndefined(y)&&u!==a||(t[c]=y)}),t}const Uo=r=>{const e=dt({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=e;if(e.headers=i=Ee.from(i),e.url=Io(Lo(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),v.isFormData(t)){if(Ae.hasStandardBrowserEnv||Ae.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(v.isFunction(t.getHeaders)){const d=t.getHeaders(),l=["content-type","content-length"];Object.entries(d).forEach(([c,u])=>{l.includes(c.toLowerCase())&&i.set(c,u)})}}if(Ae.hasStandardBrowserEnv&&(n&&v.isFunction(n)&&(n=n(e)),n||n!==!1&&Ga(e.url))){const d=o&&s&&za.read(s);d&&i.set(o,d)}return e},Wa=typeof XMLHttpRequest<"u",qa=Wa&&function(r){return new Promise(function(t,n){const o=Uo(r);let s=o.data;const i=Ee.from(o.headers).normalize();let{responseType:a,onUploadProgress:d,onDownloadProgress:l}=o,c,u,y,m,h;function g(){m&&m(),h&&h(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let p=new XMLHttpRequest;p.open(o.method.toUpperCase(),o.url,!0),p.timeout=o.timeout;function x(){if(!p)return;const S=Ee.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!a||a==="text"||a==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:r,request:p};Do(function(w){t(w),g()},function(w){n(w),g()},_),p=null}"onloadend"in p?p.onloadend=x:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(x)},p.onabort=function(){p&&(n(new L("Request aborted",L.ECONNABORTED,r,p)),p=null)},p.onerror=function(E){const _=E&&E.message?E.message:"Network Error",j=new L(_,L.ERR_NETWORK,r,p);j.event=E||null,n(j),p=null},p.ontimeout=function(){let E=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const _=o.transitional||cn;o.timeoutErrorMessage&&(E=o.timeoutErrorMessage),n(new L(E,_.clarifyTimeoutError?L.ETIMEDOUT:L.ECONNABORTED,r,p)),p=null},s===void 0&&i.setContentType(null),"setRequestHeader"in p&&v.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),v.isUndefined(o.withCredentials)||(p.withCredentials=!!o.withCredentials),a&&a!=="json"&&(p.responseType=o.responseType),l&&([y,h]=yr(l,!0),p.addEventListener("progress",y)),d&&p.upload&&([u,m]=yr(d),p.upload.addEventListener("progress",u),p.upload.addEventListener("loadend",m)),(o.cancelToken||o.signal)&&(c=S=>{p&&(n(!S||S.type?new Wt(null,r,p):S),p.abort(),p=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const C=Da(o.url);if(C&&Ae.protocols.indexOf(C)===-1){n(new L("Unsupported protocol "+C+":",L.ERR_BAD_REQUEST,r));return}p.send(s||null)})},Ya=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,o;const s=function(l){if(!o){o=!0,a();const c=l instanceof Error?l:this.reason;n.abort(c instanceof L?c:new Wt(c instanceof Error?c.message:c))}};let i=e&&setTimeout(()=>{i=null,s(new L(`timeout of ${e}ms exceeded`,L.ETIMEDOUT))},e);const a=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),r=null)};r.forEach(l=>l.addEventListener("abort",s));const{signal:d}=n;return d.unsubscribe=()=>v.asap(a),d}},Ha=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let n=0,o;for(;n<t;)o=n+e,yield r.slice(n,o),n=o},Ka=async function*(r,e){for await(const t of Xa(r))yield*Ha(t,e)},Xa=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},qn=(r,e,t,n)=>{const o=Ka(r,e);let s=0,i,a=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:l,value:c}=await o.next();if(l){a(),d.close();return}let u=c.byteLength;if(t){let y=s+=u;t(y)}d.enqueue(new Uint8Array(c))}catch(l){throw a(l),l}},cancel(d){return a(d),o.return()}},{highWaterMark:2})},Yn=64*1024,{isFunction:Qt}=v,Ja=(({Request:r,Response:e})=>({Request:r,Response:e}))(v.global),{ReadableStream:Hn,TextEncoder:Kn}=v.global,Xn=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Za=r=>{r=v.merge.call({skipUndefined:!0},Ja,r);const{fetch:e,Request:t,Response:n}=r,o=e?Qt(e):typeof fetch=="function",s=Qt(t),i=Qt(n);if(!o)return!1;const a=o&&Qt(Hn),d=o&&(typeof Kn=="function"?(h=>g=>h.encode(g))(new Kn):async h=>new Uint8Array(await new t(h).arrayBuffer())),l=s&&a&&Xn(()=>{let h=!1;const g=new t(Ae.origin,{body:new Hn,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),c=i&&a&&Xn(()=>v.isReadableStream(new n("").body)),u={stream:c&&(h=>h.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!u[h]&&(u[h]=(g,p)=>{let x=g&&g[h];if(x)return x.call(g);throw new L(`Response type '${h}' is not supported`,L.ERR_NOT_SUPPORT,p)})});const y=async h=>{if(h==null)return 0;if(v.isBlob(h))return h.size;if(v.isSpecCompliantForm(h))return(await new t(Ae.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(v.isArrayBufferView(h)||v.isArrayBuffer(h))return h.byteLength;if(v.isURLSearchParams(h)&&(h=h+""),v.isString(h))return(await d(h)).byteLength},m=async(h,g)=>{const p=v.toFiniteNumber(h.getContentLength());return p??y(g)};return async h=>{let{url:g,method:p,data:x,signal:C,cancelToken:S,timeout:E,onDownloadProgress:_,onUploadProgress:j,responseType:w,headers:P,withCredentials:$="same-origin",fetchOptions:O}=Uo(h),Y=e||fetch;w=w?(w+"").toLowerCase():"text";let q=Ya([C,S&&S.toAbortSignal()],E),I=null;const G=q&&q.unsubscribe&&(()=>{q.unsubscribe()});let H;try{if(j&&l&&p!=="get"&&p!=="head"&&(H=await m(P,x))!==0){let A=new t(g,{method:"POST",body:x,duplex:"half"}),F;if(v.isFormData(x)&&(F=A.headers.get("content-type"))&&P.setContentType(F),A.body){const[V,te]=Bn(H,yr(Vn(j)));x=qn(A.body,Yn,V,te)}}v.isString($)||($=$?"include":"omit");const M=s&&"credentials"in t.prototype,ge={...O,signal:q,method:p.toUpperCase(),headers:P.normalize().toJSON(),body:x,duplex:"half",credentials:M?$:void 0};I=s&&new t(g,ge);let se=await(s?Y(I,O):Y(g,ge));const W=c&&(w==="stream"||w==="response");if(c&&(_||W&&G)){const A={};["status","statusText","headers"].forEach(je=>{A[je]=se[je]});const F=v.toFiniteNumber(se.headers.get("content-length")),[V,te]=_&&Bn(F,yr(Vn(_),!0))||[];se=new n(qn(se.body,Yn,V,()=>{te&&te(),G&&G()}),A)}w=w||"text";let fe=await u[v.findKey(u,w)||"text"](se,h);return!W&&G&&G(),await new Promise((A,F)=>{Do(A,F,{data:fe,headers:Ee.from(se.headers),status:se.status,statusText:se.statusText,config:h,request:I})})}catch(M){throw G&&G(),M&&M.name==="TypeError"&&/Load failed|fetch/i.test(M.message)?Object.assign(new L("Network Error",L.ERR_NETWORK,h,I,M&&M.response),{cause:M.cause||M}):L.from(M,M&&M.code,h,I,M&&M.response)}}},Qa=new Map,Go=r=>{let e=r&&r.env||{};const{fetch:t,Request:n,Response:o}=e,s=[n,o,t];let i=s.length,a=i,d,l,c=Qa;for(;a--;)d=s[a],l=c.get(d),l===void 0&&c.set(d,l=a?new Map:Za(e)),c=l;return l};Go();const fn={http:pa,xhr:qa,fetch:{get:Go}};v.forEach(fn,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const Jn=r=>`- ${r}`,el=r=>v.isFunction(r)||r===null||r===!1;function tl(r,e){r=v.isArray(r)?r:[r];const{length:t}=r;let n,o;const s={};for(let i=0;i<t;i++){n=r[i];let a;if(o=n,!el(n)&&(o=fn[(a=String(n)).toLowerCase()],o===void 0))throw new L(`Unknown adapter '${a}'`);if(o&&(v.isFunction(o)||(o=o.get(e))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([d,l])=>`adapter ${d} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=t?i.length>1?`since :
9
- `+i.map(Jn).join(`
10
- `):" "+Jn(i[0]):"as no adapter specified";throw new L("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o}const zo={getAdapter:tl,adapters:fn};function Ir(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Wt(null,r)}function Zn(r){return Ir(r),r.headers=Ee.from(r.headers),r.data=Mr.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),zo.getAdapter(r.adapter||Vt.adapter,r)(r).then(function(n){return Ir(r),n.data=Mr.call(r,r.transformResponse,n),n.headers=Ee.from(n.headers),n},function(n){return Po(n)||(Ir(r),n&&n.response&&(n.response.data=Mr.call(r,r.transformResponse,n.response),n.response.headers=Ee.from(n.response.headers))),Promise.reject(n)})}const Bo="1.13.5",Sr={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{Sr[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const Qn={};Sr.transitional=function(e,t,n){function o(s,i){return"[Axios v"+Bo+"] Transitional option '"+s+"'"+i+(n?". "+n:"")}return(s,i,a)=>{if(e===!1)throw new L(o(i," has been removed"+(t?" in "+t:"")),L.ERR_DEPRECATED);return t&&!Qn[i]&&(Qn[i]=!0,console.warn(o(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(s,i,a):!0}};Sr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function rl(r,e,t){if(typeof r!="object")throw new L("options must be an object",L.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let o=n.length;for(;o-- >0;){const s=n[o],i=e[s];if(i){const a=r[s],d=a===void 0||i(a,s,r);if(d!==!0)throw new L("option "+s+" must be "+d,L.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new L("Unknown option "+s,L.ERR_BAD_OPTION)}}const cr={assertOptions:rl,validators:Sr},Me=cr.validators;let ct=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Gn,response:new Gn}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=`
11
- `+s):n.stack=s}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=dt(this.defaults,t);const{transitional:n,paramsSerializer:o,headers:s}=t;n!==void 0&&cr.assertOptions(n,{silentJSONParsing:Me.transitional(Me.boolean),forcedJSONParsing:Me.transitional(Me.boolean),clarifyTimeoutError:Me.transitional(Me.boolean),legacyInterceptorReqResOrdering:Me.transitional(Me.boolean)},!1),o!=null&&(v.isFunction(o)?t.paramsSerializer={serialize:o}:cr.assertOptions(o,{encode:Me.function,serialize:Me.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),cr.assertOptions(t,{baseUrl:Me.spelling("baseURL"),withXsrfToken:Me.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&v.merge(s.common,s[t.method]);s&&v.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),t.headers=Ee.concat(i,s);const a=[];let d=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(t)===!1)return;d=d&&g.synchronous;const p=t.transitional||cn;p&&p.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});const l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let c,u=0,y;if(!d){const h=[Zn.bind(this),void 0];for(h.unshift(...a),h.push(...l),y=h.length,c=Promise.resolve(t);u<y;)c=c.then(h[u++],h[u++]);return c}y=a.length;let m=t;for(;u<y;){const h=a[u++],g=a[u++];try{m=h(m)}catch(p){g.call(this,p);break}}try{c=Zn.call(this,m)}catch(h){return Promise.reject(h)}for(u=0,y=l.length;u<y;)c=c.then(l[u++],l[u++]);return c}getUri(e){e=dt(this.defaults,e);const t=Lo(e.baseURL,e.url,e.allowAbsoluteUrls);return Io(t,e.params,e.paramsSerializer)}};v.forEach(["delete","get","head","options"],function(e){ct.prototype[e]=function(t,n){return this.request(dt(n||{},{method:e,url:t,data:(n||{}).data}))}});v.forEach(["post","put","patch"],function(e){function t(n){return function(s,i,a){return this.request(dt(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}ct.prototype[e]=t(),ct.prototype[e+"Form"]=t(!0)});let nl=class Vo{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(s){t=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{n.subscribe(a),s=a}).then(o);return i.cancel=function(){n.unsubscribe(s)},i},e(function(s,i,a){n.reason||(n.reason=new Wt(s,i,a),t(n.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 t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Vo(function(o){e=o}),cancel:e}}};function ol(r){return function(t){return r.apply(null,t)}}function sl(r){return v.isObject(r)&&r.isAxiosError===!0}const Hr={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(Hr).forEach(([r,e])=>{Hr[e]=r});function Wo(r){const e=new ct(r),t=Ro(ct.prototype.request,e);return v.extend(t,ct.prototype,e,{allOwnKeys:!0}),v.extend(t,e,null,{allOwnKeys:!0}),t.create=function(o){return Wo(dt(r,o))},t}const le=Wo(Vt);le.Axios=ct;le.CanceledError=Wt;le.CancelToken=nl;le.isCancel=Po;le.VERSION=Bo;le.toFormData=Rr;le.AxiosError=L;le.Cancel=le.CanceledError;le.all=function(e){return Promise.all(e)};le.spread=ol;le.isAxiosError=sl;le.mergeConfig=dt;le.AxiosHeaders=Ee;le.formToJSON=r=>Fo(v.isHTMLForm(r)?new FormData(r):r);le.getAdapter=zo.getAdapter;le.HttpStatusCode=Hr;le.default=le;const{Axios:km,AxiosError:Om,CanceledError:jm,isCancel:Mm,CancelToken:Im,VERSION:Fm,all:Pm,Cancel:Dm,isAxiosError:Lm,spread:Um,toFormData:Gm,AxiosHeaders:zm,HttpStatusCode:Bm,formToJSON:Vm,getAdapter:Wm,mergeConfig:qm}=le,il=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),al=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),ll=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),cl=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),dl=[{id:"profile",label:"个人主页",icon:f.jsx(il,{})},{id:"settings",label:"设置",icon:f.jsx(al,{})},{id:"help",label:"帮助",icon:f.jsx(ll,{})},{id:"logout",label:"退出",icon:f.jsx(cl,{})}],qo=({userId:r,userName:e,userAvatar:t,apiConfig:n,menuItems:o=dl,avatarSize:s="md",isLoading:i=!1,error:a=null,avatarClassName:d,userNameClassName:l,containerClassName:c,onMenuOpen:u,onMenuClose:y,onMenuItemClick:m,onLogout:h,renderMenuItem:g,renderUserInfo:p})=>{const[x,C]=b.useState({id:r||"",name:e||"",avatar:t||"",level:0,badges:[]}),[S,E]=b.useState(i),[_,j]=b.useState(a);b.useEffect(()=>{r&&n&&!e&&!t&&w()},[r,n,e,t]);const w=async()=>{E(!0),j(null);try{const I=n.endpoints.userProfile.replace(":userId",r),G=await le.get(`${n.baseURL}${I}`,{headers:n.headers});C(G.data)}catch(I){j(I)}finally{E(!1)}},P=I=>{m?.(I.id),I.id==="logout"&&h?.()},$=()=>{u?.()},O=()=>{y?.()},Y=()=>f.jsxs("div",{className:"user-profile-trigger",children:[f.jsx(ke.Avatar,{src:x.avatar,size:s,className:d,alt:"用户头像"}),f.jsx("span",{className:`user-name ${l||""}`,children:x.name})]}),q=I=>f.jsxs("div",{className:"submenu-item",onClick:()=>P(I),children:[I.icon&&f.jsx("span",{className:"submenu-item-icon",children:I.icon}),f.jsx("span",{children:I.label})]},I.id);return S?f.jsx("div",{className:`user-profile-container ${c||""} is-loading`,children:f.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):_?f.jsx("div",{className:`user-profile-container ${c||""} has-error`,children:f.jsxs("div",{className:"user-profile-error",children:["错误: ",_.message]})}):x.name?f.jsx("div",{className:`user-profile-container ${c||""}`,children:f.jsx(sn,{trigger:p?p(x):Y(),items:o.map(I=>({...I,onClick:()=>P(I)})),position:"bottom",alignment:"end",onOpen:$,onClose:O,renderItem:g?I=>g(I,x):q})}):f.jsx("div",{className:`user-profile-container ${c||""}`,children:f.jsx("div",{className:"user-profile-loading",children:"未登录"})})},fl=r=>f.jsxs("div",{className:"explore-menu-item",onClick:()=>r.onClick?.(r),children:[f.jsx("span",{className:"explore-item-label",children:r.label}),r.status&&f.jsx("span",{className:`explore-item-status status-${r.status.toLowerCase().replace("%","").replace(" ","-")}`,children:r.status})]},r.id),ul=({className:r})=>f.jsxs("button",{className:r,"aria-label":"探索数学课程",children:[f.jsx("span",{className:"explore-icon",children:"🌍"}),f.jsx("span",{className:"explore-text",children:"探索"})]}),ml=({className:r="",style:e,logoHref:t="/",logoText:n="MathWiz",onLogoClick:o,exploreItems:s=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:d,renderExploreItem:l=fl,userData:c,userMenuItems:u,onUserMenuItemClick:y,onLogout:m,isLoading:h=!1,error:g=null,headerClassName:p="",logoClassName:x="",exploreClassName:C="",userProfileClassName:S="",variant:E="gradient",color:_,background:j,height:w,gradientFrom:P,gradientTo:$,gradientVia:O,logoColor:Y,logoSize:q="md",exploreButtonVariant:I="flat",exploreButtonColor:G="primary","aria-label":H,"aria-labelledby":M,...ge})=>{const se=s.map(V=>({id:V.id,label:l(V),onClick:()=>d?.(V)})),W=["mathwiz-header",`mathwiz-header--${E}`,_&&`mathwiz-header--color-${_}`,p,r].filter(Boolean).join(" "),fe=["logo",`logo--${q}`,x].filter(Boolean).join(" "),A=["explore-button",`explore-button--${I}`,`explore-button--color-${G}`,C].filter(Boolean).join(" "),F={...e,...w&&{height:typeof w=="number"?`${w}px`:w},...j&&{"--custom-bg":j},...Y&&{"--logo-color":Y},...P&&$&&{"--header-bg":O?`linear-gradient(to right, ${P}, ${O}, ${$})`:`linear-gradient(to right, ${P}, ${$})`}};return f.jsx("header",{className:W,style:F,"aria-label":H,"aria-labelledby":M,role:"banner",...ge,children:f.jsxs("div",{className:"header-content",children:[f.jsx("div",{className:"header-section left",children:f.jsx(sn,{trigger:f.jsx(ul,{className:A}),items:se,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),f.jsx("div",{className:"header-section center",children:f.jsx("a",{href:t,className:fe,onClick:o,"aria-label":"MathWiz 首页",children:n})}),f.jsx("div",{className:"header-section right",children:f.jsx(qo,{userName:c?.name,userAvatar:c?.avatar,menuItems:u,onMenuItemClick:y,onLogout:m,containerClassName:S,isLoading:h,error:g})})]})})},Yo=b.memo(ml,(r,e)=>r.logoText===e.logoText&&r.logoHref===e.logoHref&&r.className===e.className&&r.headerClassName===e.headerClassName&&r.logoClassName===e.logoClassName&&r.exploreClassName===e.exploreClassName&&r.userProfileClassName===e.userProfileClassName&&r["aria-label"]===e["aria-label"]&&r["aria-labelledby"]===e["aria-labelledby"]&&r.isLoading===e.isLoading&&r.error===e.error&&r.variant===e.variant&&r.color===e.color&&r.background===e.background&&r.height===e.height&&r.gradientFrom===e.gradientFrom&&r.gradientTo===e.gradientTo&&r.gradientVia===e.gradientVia&&r.logoColor===e.logoColor&&r.logoSize===e.logoSize&&r.exploreButtonVariant===e.exploreButtonVariant&&r.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(r.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(r.userData)===JSON.stringify(e.userData)&&JSON.stringify(r.userMenuItems)===JSON.stringify(e.userMenuItems)),qt=b.memo(({parts:r=[],children:e=null,fontSize:t="1rem",color:n="#333333",displayMode:o=!1,className:s=""})=>{b.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(u=>{try{return u.href&&u.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react/jsx-runtime"),b=require("react"),hi=require("@heroui/progress"),Tr=require("@heroui/card"),Ur=require("lucide-react"),Ne=require("@heroui/react"),gi=require("katex"),ms=require("jsxgraph"),Ft=require("zustand"),hs=require("zustand/shallow"),en=require("zustand/react/shallow"),pi=require("zustand/middleware");function yi(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const je=yi(b),pt=({progress:r,variant:e="solid",size:t="md",radius:n="md",children:s,className:o="",loading:i,...a})=>{const l=r!==void 0?(u=>u===0?"button--primary":u===100?"button--success":"button--secondary")(r):"button--primary",d=["button",`button--${t}`,`button--${e}`,`button--radius-${n}`,l,i&&"button--loading",o].filter(Boolean).join(" ");return f.jsx("button",{type:"button",className:d,"data-progress":r,disabled:i||a.disabled,...a,children:i?"加载中...":s})},kn=r=>r===0?"开始学习":r===100?"复习":"继续学习",bi=r=>{if(r.length===0)return 0;const e=r.reduce((t,n)=>t+n.progress,0);return Math.round(e/r.length)},xi=({knowledgeItem:r,onLearnAction:e})=>{const t=()=>{e(r)};return console.log("KnowledgeCard render:",{progress:r.progress,text:kn(r.progress)}),f.jsxs(Tr.Card,{className:"content-accordion__knowledge-card",children:[f.jsxs(Tr.CardBody,{children:[f.jsx("h3",{className:"content-accordion__knowledge-title",children:r.title}),f.jsx("p",{className:"content-accordion__knowledge-description",children:r.description})]}),f.jsxs(Tr.CardFooter,{className:"content-accordion__knowledge-actions",children:[f.jsxs("div",{className:"content-accordion__progress-container",children:[f.jsx(hi.Progress,{value:r.progress,size:"sm",color:"primary","aria-label":`${r.title} 进度`,className:"content-accordion__progress-bar"}),f.jsxs("span",{className:"content-accordion__progress-text",children:[r.progress,"%"]})]}),f.jsx(pt,{size:"sm",radius:"md",onClick:t,progress:r.progress,variant:r.progress===100?"light":r.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:kn(r.progress)})]})]})},vi=({lesson:r,isExpanded:e,onToggle:t,onLearnAction:n})=>{const s=()=>{t(r.id)},o=bi(r.knowledgeItems);return f.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[f.jsxs("div",{className:"content-accordion__lesson-header",onClick:s,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${r.title},点击${e?"收起":"展开"}`,children:[f.jsxs("div",{className:"content-accordion__lesson-header-content",children:[f.jsx("h2",{className:"content-accordion__lesson-title",children:r.title}),f.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",r.duration," 分钟"]})]}),f.jsxs("div",{className:"content-accordion__lesson-actions",children:[f.jsxs("span",{className:"content-accordion__lesson-progress",children:[o,"%"]}),e?f.jsx(Ur.ChevronDown,{className:"content-accordion__lesson-icon"}):f.jsx(Ur.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&f.jsx("div",{className:"content-accordion__knowledge-list",children:r.knowledgeItems.map(i=>f.jsx(xi,{knowledgeItem:i,onLearnAction:n},i.id))})]})},gs=({unit:r,activeLessonIds:e,onToggleLesson:t,onLearnAction:n,loading:s=!1,className:o="",emptyState:i})=>s?f.jsx("div",{className:"content-accordion content-accordion--loading",children:f.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):r?f.jsxs("div",{className:`content-accordion ${o}`,children:[f.jsxs("header",{className:"content-accordion__header",children:[f.jsx("h1",{className:"content-accordion__unit-title",children:r.title}),f.jsx("p",{className:"content-accordion__unit-description",children:r.description}),f.jsxs("div",{className:"content-accordion__unit-meta",children:[f.jsxs("span",{children:["总共 ",r.totalLessons," 节课"]}),f.jsx("span",{children:"•"}),f.jsxs("span",{children:["预计学习 ",r.estimatedDuration]})]})]}),f.jsx("div",{className:"content-accordion__lessons",children:r.lessons.map(a=>f.jsx(vi,{lesson:a,isExpanded:e.includes(a.id),onToggle:t,onLearnAction:n},a.id))})]}):f.jsx("div",{className:"content-accordion content-accordion--empty",children:i||f.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),_i=r=>{switch(r){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},ps=({data:r,loading:e=!1,error:t=null,collapsed:n=!1,onToggleCollapse:s,activeUnitId:o=null,onUnitSelect:i,renderUnitItem:a,className:c="",unitItemClassName:l="",style:d={},unitItemStyle:u={}})=>{const y=(p,x)=>{x.preventDefault(),i?.(p)},m=()=>{s?.()},h=p=>f.jsxs("div",{className:`sidebar__unit-item ${l} ${o===p.unitId?"sidebar__unit-item--active":""} ${p.status?`sidebar__unit-item--${p.status}`:""}`,style:u,onClick:x=>y(p.unitId,x),role:"button",tabIndex:0,"aria-label":`${p.title},进度 ${p.progressPercentage}%`,children:[f.jsxs("div",{className:"sidebar__unit-item__content",children:[p.icon&&f.jsx("span",{className:"sidebar__unit-item__icon",children:p.icon}),!n&&f.jsx("span",{className:"sidebar__unit-item__title",children:p.title})]}),!n&&p.progressPercentage!==void 0&&f.jsxs("div",{className:"sidebar__unit-item__progress",children:[f.jsx(Ne.Progress,{value:p.progressPercentage,size:"sm",color:_i(p.status),"aria-label":`${p.title} 进度`}),f.jsxs("span",{className:"progress-percentage",children:[p.progressPercentage,"%"]})]})]},p.unitId),g=()=>e?f.jsx("div",{className:"sidebar__loading",children:"加载中..."}):t?f.jsxs("div",{className:"sidebar__error",children:["加载失败: ",t.message]}):r?f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"sidebar__header",children:[f.jsx("button",{className:"sidebar__toggle-btn",onClick:m,"aria-label":"切换侧边栏折叠状态",children:n?"→":"←"}),!n&&f.jsxs("div",{className:"sidebar__course-info",children:[f.jsx("h3",{className:"sidebar__course-title",children:r.courseTitle}),f.jsxs("span",{className:"sidebar__course-level",children:[r.courseLevel,"年级"]})]})]}),f.jsx("nav",{className:"sidebar__content",children:f.jsx("ul",{className:"sidebar__unit-list",children:r.units&&r.units.length>0?r.units.map(p=>f.jsx("li",{children:a?a(p,p):h(p)},p.unitId)):f.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):f.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return f.jsx("aside",{className:`sidebar ${c} ${n?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${t?"sidebar--error":""}`,style:d,"aria-label":"课程导航侧边栏",role:"complementary",children:g()})},tn=({trigger:r,items:e,position:t="bottom",alignment:n="start",openDelay:s=300,closeDelay:o=100,onOpen:i,onClose:a,renderItem:c,itemConfig:l={},className:d,menuClassName:u,itemClassName:y})=>{const[m,h]=b.useState(!1),g=b.useRef(null),p=b.useRef(null),x=()=>{g.current&&clearTimeout(g.current),p.current&&clearTimeout(p.current)},S=()=>{x(),g.current=setTimeout(()=>{h(!0),i?.()},s)},R=()=>{x(),p.current=setTimeout(()=>{h(!1),a?.()},o)},C=w=>{!w.disabled&&w.onClick&&w.onClick(w)};b.useEffect(()=>()=>x(),[]);const _=w=>f.jsxs("div",{className:`submenu-item ${w.disabled?"is-disabled":""} ${y||""}`,onClick:()=>C(w),children:[w.icon&&f.jsx("span",{className:"submenu-item-icon",children:w.icon}),f.jsx("span",{children:w.label})]},w.id),O=()=>{const w=["submenu-panel"];return u&&w.push(u),w.push(`position-${t}`),n!=="start"&&w.push(`alignment-${n}`),m&&w.push("is-open"),w.join(" ")};return f.jsxs("div",{className:`submenu-container ${d||""}`,onMouseEnter:S,onMouseLeave:R,children:[f.jsx("div",{className:"submenu-trigger",children:r}),f.jsx("div",{className:O(),children:e.map(w=>c?c(w,l):_(w))})]})};function ys(r,e){return function(){return r.apply(e,arguments)}}const{toString:wi}=Object.prototype,{getPrototypeOf:rn}=Object,{iterator:pr,toStringTag:bs}=Symbol,yr=(r=>e=>{const t=wi.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Ie=r=>(r=r.toLowerCase(),e=>yr(e)===r),br=r=>e=>typeof e===r,{isArray:_t}=Array,yt=br("undefined");function Pt(r){return r!==null&&!yt(r)&&r.constructor!==null&&!yt(r.constructor)&&Ae(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const xs=Ie("ArrayBuffer");function Ai(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&xs(r.buffer),e}const Ri=br("string"),Ae=br("function"),vs=br("number"),Dt=r=>r!==null&&typeof r=="object",Si=r=>r===!0||r===!1,rr=r=>{if(yr(r)!=="object")return!1;const e=rn(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(bs in r)&&!(pr in r)},Ci=r=>{if(!Dt(r)||Pt(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Ei=Ie("Date"),Ti=Ie("File"),Ni=Ie("Blob"),$i=Ie("FileList"),ki=r=>Dt(r)&&Ae(r.pipe),Oi=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Ae(r.append)&&((e=yr(r))==="formdata"||e==="object"&&Ae(r.toString)&&r.toString()==="[object FormData]"))},ji=Ie("URLSearchParams"),[Mi,Ii,Fi,Pi]=["ReadableStream","Request","Response","Headers"].map(Ie),Di=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Lt(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),_t(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(Pt(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),i=o.length;let a;for(n=0;n<i;n++)a=o[n],e.call(null,r[a],a,r)}}function _s(r,e){if(Pt(r))return null;e=e.toLowerCase();const t=Object.keys(r);let n=t.length,s;for(;n-- >0;)if(s=t[n],e===s.toLowerCase())return s;return null}const ot=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ws=r=>!yt(r)&&r!==ot;function Gr(){const{caseless:r,skipUndefined:e}=ws(this)&&this||{},t={},n=(s,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const i=r&&_s(t,o)||o;rr(t[i])&&rr(s)?t[i]=Gr(t[i],s):rr(s)?t[i]=Gr({},s):_t(s)?t[i]=s.slice():(!e||!yt(s))&&(t[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&Lt(arguments[s],n);return t}const Li=(r,e,t,{allOwnKeys:n}={})=>(Lt(e,(s,o)=>{t&&Ae(s)?Object.defineProperty(r,o,{value:ys(s,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),r),Ui=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),Gi=(r,e,t,n)=>{r.prototype=Object.create(e.prototype,n),Object.defineProperty(r.prototype,"constructor",{value:r,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},zi=(r,e,t,n)=>{let s,o,i;const a={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)i=s[o],(!n||n(i,r,e))&&!a[i]&&(e[i]=r[i],a[i]=!0);r=t!==!1&&rn(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},Bi=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const n=r.indexOf(e,t);return n!==-1&&n===t},Vi=r=>{if(!r)return null;if(_t(r))return r;let e=r.length;if(!vs(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},qi=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&rn(Uint8Array)),Wi=(r,e)=>{const n=(r&&r[pr]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},Hi=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Yi=Ie("HTMLFormElement"),Ki=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),On=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Xi=Ie("RegExp"),As=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};Lt(t,(s,o)=>{let i;(i=e(s,o,r))!==!1&&(n[o]=i||s)}),Object.defineProperties(r,n)},Ji=r=>{As(r,(e,t)=>{if(Ae(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(Ae(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},Zi=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return _t(r)?n(r):n(String(r).split(e)),t},Qi=()=>{},ea=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function ta(r){return!!(r&&Ae(r.append)&&r[bs]==="FormData"&&r[pr])}const ra=r=>{const e=new Array(10),t=(n,s)=>{if(Dt(n)){if(e.indexOf(n)>=0)return;if(Pt(n))return n;if(!("toJSON"in n)){e[s]=n;const o=_t(n)?[]:{};return Lt(n,(i,a)=>{const c=t(i,s+1);!yt(c)&&(o[a]=c)}),e[s]=void 0,o}}return n};return t(r,0)},na=Ie("AsyncFunction"),sa=r=>r&&(Dt(r)||Ae(r))&&Ae(r.then)&&Ae(r.catch),Rs=((r,e)=>r?setImmediate:e?((t,n)=>(ot.addEventListener("message",({source:s,data:o})=>{s===ot&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),ot.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Ae(ot.postMessage)),oa=typeof queueMicrotask<"u"?queueMicrotask.bind(ot):typeof process<"u"&&process.nextTick||Rs,ia=r=>r!=null&&Ae(r[pr]),v={isArray:_t,isArrayBuffer:xs,isBuffer:Pt,isFormData:Oi,isArrayBufferView:Ai,isString:Ri,isNumber:vs,isBoolean:Si,isObject:Dt,isPlainObject:rr,isEmptyObject:Ci,isReadableStream:Mi,isRequest:Ii,isResponse:Fi,isHeaders:Pi,isUndefined:yt,isDate:Ei,isFile:Ti,isBlob:Ni,isRegExp:Xi,isFunction:Ae,isStream:ki,isURLSearchParams:ji,isTypedArray:qi,isFileList:$i,forEach:Lt,merge:Gr,extend:Li,trim:Di,stripBOM:Ui,inherits:Gi,toFlatObject:zi,kindOf:yr,kindOfTest:Ie,endsWith:Bi,toArray:Vi,forEachEntry:Wi,matchAll:Hi,isHTMLForm:Yi,hasOwnProperty:On,hasOwnProp:On,reduceDescriptors:As,freezeMethods:Ji,toObjectSet:Zi,toCamelCase:Ki,noop:Qi,toFiniteNumber:ea,findKey:_s,global:ot,isContextDefined:ws,isSpecCompliantForm:ta,toJSONObject:ra,isAsyncFn:na,isThenable:sa,setImmediate:Rs,asap:oa,isIterable:ia};let P=class Ss extends Error{static from(e,t,n,s,o,i){const a=new Ss(e.message,t||e.code,n,s,o);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,t,n,s,o){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),n&&(this.config=n),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:v.toJSONObject(this.config),code:this.code,status:this.status}}};P.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";P.ERR_BAD_OPTION="ERR_BAD_OPTION";P.ECONNABORTED="ECONNABORTED";P.ETIMEDOUT="ETIMEDOUT";P.ERR_NETWORK="ERR_NETWORK";P.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";P.ERR_DEPRECATED="ERR_DEPRECATED";P.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";P.ERR_BAD_REQUEST="ERR_BAD_REQUEST";P.ERR_CANCELED="ERR_CANCELED";P.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";P.ERR_INVALID_URL="ERR_INVALID_URL";const aa=null;function zr(r){return v.isPlainObject(r)||v.isArray(r)}function Cs(r){return v.endsWith(r,"[]")?r.slice(0,-2):r}function jn(r,e,t){return r?r.concat(e).map(function(s,o){return s=Cs(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function la(r){return v.isArray(r)&&!r.some(zr)}const ca=v.toFlatObject(v,{},null,function(e){return/^is[A-Z]/.test(e)});function xr(r,e,t){if(!v.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=v.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,p){return!v.isUndefined(p[g])});const n=t.metaTokens,s=t.visitor||d,o=t.dots,i=t.indexes,c=(t.Blob||typeof Blob<"u"&&Blob)&&v.isSpecCompliantForm(e);if(!v.isFunction(s))throw new TypeError("visitor must be a function");function l(h){if(h===null)return"";if(v.isDate(h))return h.toISOString();if(v.isBoolean(h))return h.toString();if(!c&&v.isBlob(h))throw new P("Blob is not supported. Use a Buffer instead.");return v.isArrayBuffer(h)||v.isTypedArray(h)?c&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function d(h,g,p){let x=h;if(h&&!p&&typeof h=="object"){if(v.endsWith(g,"{}"))g=n?g:g.slice(0,-2),h=JSON.stringify(h);else if(v.isArray(h)&&la(h)||(v.isFileList(h)||v.endsWith(g,"[]"))&&(x=v.toArray(h)))return g=Cs(g),x.forEach(function(R,C){!(v.isUndefined(R)||R===null)&&e.append(i===!0?jn([g],C,o):i===null?g:g+"[]",l(R))}),!1}return zr(h)?!0:(e.append(jn(p,g,o),l(h)),!1)}const u=[],y=Object.assign(ca,{defaultVisitor:d,convertValue:l,isVisitable:zr});function m(h,g){if(!v.isUndefined(h)){if(u.indexOf(h)!==-1)throw Error("Circular reference detected in "+g.join("."));u.push(h),v.forEach(h,function(x,S){(!(v.isUndefined(x)||x===null)&&s.call(e,x,v.isString(S)?S.trim():S,g,y))===!0&&m(x,g?g.concat(S):[S])}),u.pop()}}if(!v.isObject(r))throw new TypeError("data must be an object");return m(r),e}function Mn(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function nn(r,e){this._pairs=[],r&&xr(r,this,e)}const Es=nn.prototype;Es.append=function(e,t){this._pairs.push([e,t])};Es.toString=function(e){const t=e?function(n){return e.call(this,n,Mn)}:Mn;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function da(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ts(r,e,t){if(!e)return r;const n=t&&t.encode||da,s=v.isFunction(t)?{serialize:t}:t,o=s&&s.serialize;let i;if(o?i=o(e,s):i=v.isURLSearchParams(e)?e.toString():new nn(e,s).toString(n),i){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+i}return r}class In{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){v.forEach(this.handlers,function(n){n!==null&&e(n)})}}const sn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},fa=typeof URLSearchParams<"u"?URLSearchParams:nn,ua=typeof FormData<"u"?FormData:null,ma=typeof Blob<"u"?Blob:null,ha={isBrowser:!0,classes:{URLSearchParams:fa,FormData:ua,Blob:ma},protocols:["http","https","file","blob","url","data"]},on=typeof window<"u"&&typeof document<"u",Br=typeof navigator=="object"&&navigator||void 0,ga=on&&(!Br||["ReactNative","NativeScript","NS"].indexOf(Br.product)<0),pa=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ya=on&&window.location.href||"http://localhost",ba=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:on,hasStandardBrowserEnv:ga,hasStandardBrowserWebWorkerEnv:pa,navigator:Br,origin:ya},Symbol.toStringTag,{value:"Module"})),ve={...ba,...ha};function xa(r,e){return xr(r,new ve.classes.URLSearchParams,{visitor:function(t,n,s,o){return ve.isNode&&v.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function va(r){return v.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function _a(r){const e={},t=Object.keys(r);let n;const s=t.length;let o;for(n=0;n<s;n++)o=t[n],e[o]=r[o];return e}function Ns(r){function e(t,n,s,o){let i=t[o++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),c=o>=t.length;return i=!i&&v.isArray(s)?s.length:i,c?(v.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!a):((!s[i]||!v.isObject(s[i]))&&(s[i]=[]),e(t,n,s[i],o)&&v.isArray(s[i])&&(s[i]=_a(s[i])),!a)}if(v.isFormData(r)&&v.isFunction(r.entries)){const t={};return v.forEachEntry(r,(n,s)=>{e(va(n),s,t,0)}),t}return null}function wa(r,e,t){if(v.isString(r))try{return(e||JSON.parse)(r),v.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const Ut={transitional:sn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=v.isObject(e);if(o&&v.isHTMLForm(e)&&(e=new FormData(e)),v.isFormData(e))return s?JSON.stringify(Ns(e)):e;if(v.isArrayBuffer(e)||v.isBuffer(e)||v.isStream(e)||v.isFile(e)||v.isBlob(e)||v.isReadableStream(e))return e;if(v.isArrayBufferView(e))return e.buffer;if(v.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return xa(e,this.formSerializer).toString();if((a=v.isFileList(e))||n.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return xr(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),wa(e)):e}],transformResponse:[function(e){const t=this.transitional||Ut.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(v.isResponse(e)||v.isReadableStream(e))return e;if(e&&v.isString(e)&&(n&&!this.responseType||s)){const i=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?P.from(a,P.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}}};v.forEach(["delete","get","head","post","put","patch"],r=>{Ut.headers[r]={}});const Aa=v.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"]),Ra=r=>{const e={};let t,n,s;return r&&r.split(`
2
+ `).forEach(function(i){s=i.indexOf(":"),t=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!t||e[t]&&Aa[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},Fn=Symbol("internals");function Tt(r){return r&&String(r).trim().toLowerCase()}function nr(r){return r===!1||r==null?r:v.isArray(r)?r.map(nr):String(r)}function Sa(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(r);)e[n[1]]=n[2];return e}const Ca=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Nr(r,e,t,n,s){if(v.isFunction(n))return n.call(this,e,t);if(s&&(e=t),!!v.isString(e)){if(v.isString(n))return e.indexOf(n)!==-1;if(v.isRegExp(n))return n.test(e)}}function Ea(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function Ta(r,e){const t=v.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}let Re=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function o(a,c,l){const d=Tt(c);if(!d)throw new Error("header name must be a non-empty string");const u=v.findKey(s,d);(!u||s[u]===void 0||l===!0||l===void 0&&s[u]!==!1)&&(s[u||c]=nr(a))}const i=(a,c)=>v.forEach(a,(l,d)=>o(l,d,c));if(v.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(v.isString(e)&&(e=e.trim())&&!Ca(e))i(Ra(e),t);else if(v.isObject(e)&&v.isIterable(e)){let a={},c,l;for(const d of e){if(!v.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[l=d[0]]=(c=a[l])?v.isArray(c)?[...c,d[1]]:[c,d[1]]:d[1]}i(a,t)}else e!=null&&o(t,e,n);return this}get(e,t){if(e=Tt(e),e){const n=v.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return Sa(s);if(v.isFunction(t))return t.call(this,s,n);if(v.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Tt(e),e){const n=v.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||Nr(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function o(i){if(i=Tt(i),i){const a=v.findKey(n,i);a&&(!t||Nr(n,n[a],a,t))&&(delete n[a],s=!0)}}return v.isArray(e)?e.forEach(o):o(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const o=t[n];(!e||Nr(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,n={};return v.forEach(this,(s,o)=>{const i=v.findKey(n,o);if(i){t[i]=nr(s),delete t[o];return}const a=e?Ea(o):String(o).trim();a!==o&&delete t[o],t[a]=nr(s),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return v.forEach(this,(n,s)=>{n!=null&&n!==!1&&(t[s]=e&&v.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).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,...t){const n=new this(e);return t.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[Fn]=this[Fn]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=Tt(i);n[a]||(Ta(s,i),n[a]=!0)}return v.isArray(e)?e.forEach(o):o(e),this}};Re.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);v.reduceDescriptors(Re.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});v.freezeMethods(Re);function $r(r,e){const t=this||Ut,n=e||t,s=Re.from(n.headers);let o=n.data;return v.forEach(r,function(a){o=a.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function $s(r){return!!(r&&r.__CANCEL__)}let Gt=class extends P{constructor(e,t,n){super(e??"canceled",P.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function ks(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new P("Request failed with status code "+t.status,[P.ERR_BAD_REQUEST,P.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function Na(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function $a(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),d=n[o];i||(i=l),t[s]=c,n[s]=l;let u=o,y=0;for(;u!==s;)y+=t[u++],u=u%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),l-i<e)return;const m=d&&l-d;return m?Math.round(y*1e3/m):void 0}}function ka(r,e){let t=0,n=1e3/e,s,o;const i=(l,d=Date.now())=>{t=d,s=null,o&&(clearTimeout(o),o=null),r(...l)};return[(...l)=>{const d=Date.now(),u=d-t;u>=n?i(l,d):(s=l,o||(o=setTimeout(()=>{o=null,i(s)},n-u)))},()=>s&&i(s)]}const ur=(r,e,t=3)=>{let n=0;const s=$a(50,250);return ka(o=>{const i=o.loaded,a=o.lengthComputable?o.total:void 0,c=i-n,l=s(c),d=i<=a;n=i;const u={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&d?(a-i)/l:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};r(u)},t)},Pn=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},Dn=r=>(...e)=>v.asap(()=>r(...e)),Oa=ve.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,ve.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(ve.origin),ve.navigator&&/(msie|trident)/i.test(ve.navigator.userAgent)):()=>!0,ja=ve.hasStandardBrowserEnv?{write(r,e,t,n,s,o,i){if(typeof document>"u")return;const a=[`${r}=${encodeURIComponent(e)}`];v.isNumber(t)&&a.push(`expires=${new Date(t).toUTCString()}`),v.isString(n)&&a.push(`path=${n}`),v.isString(s)&&a.push(`domain=${s}`),o===!0&&a.push("secure"),v.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(r){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+r+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(r){this.write(r,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Ma(r){return typeof r!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function Ia(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Os(r,e,t){let n=!Ma(e);return r&&(n||t==!1)?Ia(r,e):e}const Ln=r=>r instanceof Re?{...r}:r;function at(r,e){e=e||{};const t={};function n(l,d,u,y){return v.isPlainObject(l)&&v.isPlainObject(d)?v.merge.call({caseless:y},l,d):v.isPlainObject(d)?v.merge({},d):v.isArray(d)?d.slice():d}function s(l,d,u,y){if(v.isUndefined(d)){if(!v.isUndefined(l))return n(void 0,l,u,y)}else return n(l,d,u,y)}function o(l,d){if(!v.isUndefined(d))return n(void 0,d)}function i(l,d){if(v.isUndefined(d)){if(!v.isUndefined(l))return n(void 0,l)}else return n(void 0,d)}function a(l,d,u){if(u in e)return n(l,d);if(u in r)return n(void 0,l)}const c={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:(l,d,u)=>s(Ln(l),Ln(d),u,!0)};return v.forEach(Object.keys({...r,...e}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const u=v.hasOwnProp(c,d)?c[d]:s,y=u(r[d],e[d],d);v.isUndefined(y)&&u!==a||(t[d]=y)}),t}const js=r=>{const e=at({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;if(e.headers=i=Re.from(i),e.url=Ts(Os(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),v.isFormData(t)){if(ve.hasStandardBrowserEnv||ve.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(v.isFunction(t.getHeaders)){const c=t.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([d,u])=>{l.includes(d.toLowerCase())&&i.set(d,u)})}}if(ve.hasStandardBrowserEnv&&(n&&v.isFunction(n)&&(n=n(e)),n||n!==!1&&Oa(e.url))){const c=s&&o&&ja.read(o);c&&i.set(s,c)}return e},Fa=typeof XMLHttpRequest<"u",Pa=Fa&&function(r){return new Promise(function(t,n){const s=js(r);let o=s.data;const i=Re.from(s.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=s,d,u,y,m,h;function g(){m&&m(),h&&h(),s.cancelToken&&s.cancelToken.unsubscribe(d),s.signal&&s.signal.removeEventListener("abort",d)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function x(){if(!p)return;const R=Re.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!a||a==="text"||a==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:R,config:r,request:p};ks(function(w){t(w),g()},function(w){n(w),g()},_),p=null}"onloadend"in p?p.onloadend=x:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(x)},p.onabort=function(){p&&(n(new P("Request aborted",P.ECONNABORTED,r,p)),p=null)},p.onerror=function(C){const _=C&&C.message?C.message:"Network Error",O=new P(_,P.ERR_NETWORK,r,p);O.event=C||null,n(O),p=null},p.ontimeout=function(){let C=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const _=s.transitional||sn;s.timeoutErrorMessage&&(C=s.timeoutErrorMessage),n(new P(C,_.clarifyTimeoutError?P.ETIMEDOUT:P.ECONNABORTED,r,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&v.forEach(i.toJSON(),function(C,_){p.setRequestHeader(_,C)}),v.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),a&&a!=="json"&&(p.responseType=s.responseType),l&&([y,h]=ur(l,!0),p.addEventListener("progress",y)),c&&p.upload&&([u,m]=ur(c),p.upload.addEventListener("progress",u),p.upload.addEventListener("loadend",m)),(s.cancelToken||s.signal)&&(d=R=>{p&&(n(!R||R.type?new Gt(null,r,p):R),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(d),s.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d)));const S=Na(s.url);if(S&&ve.protocols.indexOf(S)===-1){n(new P("Unsupported protocol "+S+":",P.ERR_BAD_REQUEST,r));return}p.send(o||null)})},Da=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(l){if(!s){s=!0,a();const d=l instanceof Error?l:this.reason;n.abort(d instanceof P?d:new Gt(d instanceof Error?d.message:d))}};let i=e&&setTimeout(()=>{i=null,o(new P(`timeout of ${e}ms exceeded`,P.ETIMEDOUT))},e);const a=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),r=null)};r.forEach(l=>l.addEventListener("abort",o));const{signal:c}=n;return c.unsubscribe=()=>v.asap(a),c}},La=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let n=0,s;for(;n<t;)s=n+e,yield r.slice(n,s),n=s},Ua=async function*(r,e){for await(const t of Ga(r))yield*La(t,e)},Ga=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},Un=(r,e,t,n)=>{const s=Ua(r,e);let o=0,i,a=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{const{done:l,value:d}=await s.next();if(l){a(),c.close();return}let u=d.byteLength;if(t){let y=o+=u;t(y)}c.enqueue(new Uint8Array(d))}catch(l){throw a(l),l}},cancel(c){return a(c),s.return()}},{highWaterMark:2})},Gn=64*1024,{isFunction:Yt}=v,za=(({Request:r,Response:e})=>({Request:r,Response:e}))(v.global),{ReadableStream:zn,TextEncoder:Bn}=v.global,Vn=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Ba=r=>{r=v.merge.call({skipUndefined:!0},za,r);const{fetch:e,Request:t,Response:n}=r,s=e?Yt(e):typeof fetch=="function",o=Yt(t),i=Yt(n);if(!s)return!1;const a=s&&Yt(zn),c=s&&(typeof Bn=="function"?(h=>g=>h.encode(g))(new Bn):async h=>new Uint8Array(await new t(h).arrayBuffer())),l=o&&a&&Vn(()=>{let h=!1;const g=new t(ve.origin,{body:new zn,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!g}),d=i&&a&&Vn(()=>v.isReadableStream(new n("").body)),u={stream:d&&(h=>h.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!u[h]&&(u[h]=(g,p)=>{let x=g&&g[h];if(x)return x.call(g);throw new P(`Response type '${h}' is not supported`,P.ERR_NOT_SUPPORT,p)})});const y=async h=>{if(h==null)return 0;if(v.isBlob(h))return h.size;if(v.isSpecCompliantForm(h))return(await new t(ve.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(v.isArrayBufferView(h)||v.isArrayBuffer(h))return h.byteLength;if(v.isURLSearchParams(h)&&(h=h+""),v.isString(h))return(await c(h)).byteLength},m=async(h,g)=>{const p=v.toFiniteNumber(h.getContentLength());return p??y(g)};return async h=>{let{url:g,method:p,data:x,signal:S,cancelToken:R,timeout:C,onDownloadProgress:_,onUploadProgress:O,responseType:w,headers:F,withCredentials:$="same-origin",fetchOptions:k}=js(h),B=e||fetch;w=w?(w+"").toLowerCase():"text";let W=Da([S,R&&R.toAbortSignal()],C),M=null;const L=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let J;try{if(O&&l&&p!=="get"&&p!=="head"&&(J=await m(F,x))!==0){let ae=new t(g,{method:"POST",body:x,duplex:"half"}),ge;if(v.isFormData(x)&&(ge=ae.headers.get("content-type"))&&F.setContentType(ge),ae.body){const[Ce,We]=Pn(J,ur(Dn(O)));x=Un(ae.body,Gn,Ce,We)}}v.isString($)||($=$?"include":"omit");const j=o&&"credentials"in t.prototype,he={...k,signal:W,method:p.toUpperCase(),headers:F.normalize().toJSON(),body:x,duplex:"half",credentials:j?$:void 0};M=o&&new t(g,he);let oe=await(o?B(M,k):B(g,he));const z=d&&(w==="stream"||w==="response");if(d&&(_||z&&L)){const ae={};["status","statusText","headers"].forEach(Je=>{ae[Je]=oe[Je]});const ge=v.toFiniteNumber(oe.headers.get("content-length")),[Ce,We]=_&&Pn(ge,ur(Dn(_),!0))||[];oe=new n(Un(oe.body,Gn,Ce,()=>{We&&We(),L&&L()}),ae)}w=w||"text";let de=await u[v.findKey(u,w)||"text"](oe,h);return!z&&L&&L(),await new Promise((ae,ge)=>{ks(ae,ge,{data:de,headers:Re.from(oe.headers),status:oe.status,statusText:oe.statusText,config:h,request:M})})}catch(j){throw L&&L(),j&&j.name==="TypeError"&&/Load failed|fetch/i.test(j.message)?Object.assign(new P("Network Error",P.ERR_NETWORK,h,M,j&&j.response),{cause:j.cause||j}):P.from(j,j&&j.code,h,M,j&&j.response)}}},Va=new Map,Ms=r=>{let e=r&&r.env||{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let i=o.length,a=i,c,l,d=Va;for(;a--;)c=o[a],l=d.get(c),l===void 0&&d.set(c,l=a?new Map:Ba(e)),d=l;return l};Ms();const an={http:aa,xhr:Pa,fetch:{get:Ms}};v.forEach(an,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const qn=r=>`- ${r}`,qa=r=>v.isFunction(r)||r===null||r===!1;function Wa(r,e){r=v.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let i=0;i<t;i++){n=r[i];let a;if(s=n,!qa(n)&&(s=an[(a=String(n)).toLowerCase()],s===void 0))throw new P(`Unknown adapter '${a}'`);if(s&&(v.isFunction(s)||(s=s.get(e))))break;o[a||"#"+i]=s}if(!s){const i=Object.entries(o).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=t?i.length>1?`since :
4
+ `+i.map(qn).join(`
5
+ `):" "+qn(i[0]):"as no adapter specified";throw new P("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const Is={getAdapter:Wa,adapters:an};function kr(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Gt(null,r)}function Wn(r){return kr(r),r.headers=Re.from(r.headers),r.data=$r.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Is.getAdapter(r.adapter||Ut.adapter,r)(r).then(function(n){return kr(r),n.data=$r.call(r,r.transformResponse,n),n.headers=Re.from(n.headers),n},function(n){return $s(n)||(kr(r),n&&n.response&&(n.response.data=$r.call(r,r.transformResponse,n.response),n.response.headers=Re.from(n.response.headers))),Promise.reject(n)})}const Fs="1.13.5",vr={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{vr[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const Hn={};vr.transitional=function(e,t,n){function s(o,i){return"[Axios v"+Fs+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,a)=>{if(e===!1)throw new P(s(i," has been removed"+(t?" in "+t:"")),P.ERR_DEPRECATED);return t&&!Hn[i]&&(Hn[i]=!0,console.warn(s(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,i,a):!0}};vr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Ha(r,e,t){if(typeof r!="object")throw new P("options must be an object",P.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const o=n[s],i=e[o];if(i){const a=r[o],c=a===void 0||i(a,o,r);if(c!==!0)throw new P("option "+o+" must be "+c,P.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new P("Unknown option "+o,P.ERR_BAD_OPTION)}}const sr={assertOptions:Ha,validators:vr},ke=sr.validators;let it=class{constructor(e){this.defaults=e||{},this.interceptors={request:new In,response:new In}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
6
+ `+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=at(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:o}=t;n!==void 0&&sr.assertOptions(n,{silentJSONParsing:ke.transitional(ke.boolean),forcedJSONParsing:ke.transitional(ke.boolean),clarifyTimeoutError:ke.transitional(ke.boolean),legacyInterceptorReqResOrdering:ke.transitional(ke.boolean)},!1),s!=null&&(v.isFunction(s)?t.paramsSerializer={serialize:s}:sr.assertOptions(s,{encode:ke.function,serialize:ke.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),sr.assertOptions(t,{baseUrl:ke.spelling("baseURL"),withXsrfToken:ke.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&v.merge(o.common,o[t.method]);o&&v.forEach(["delete","get","head","post","put","patch","common"],h=>{delete o[h]}),t.headers=Re.concat(i,o);const a=[];let c=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(t)===!1)return;c=c&&g.synchronous;const p=t.transitional||sn;p&&p.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});const l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let d,u=0,y;if(!c){const h=[Wn.bind(this),void 0];for(h.unshift(...a),h.push(...l),y=h.length,d=Promise.resolve(t);u<y;)d=d.then(h[u++],h[u++]);return d}y=a.length;let m=t;for(;u<y;){const h=a[u++],g=a[u++];try{m=h(m)}catch(p){g.call(this,p);break}}try{d=Wn.call(this,m)}catch(h){return Promise.reject(h)}for(u=0,y=l.length;u<y;)d=d.then(l[u++],l[u++]);return d}getUri(e){e=at(this.defaults,e);const t=Os(e.baseURL,e.url,e.allowAbsoluteUrls);return Ts(t,e.params,e.paramsSerializer)}};v.forEach(["delete","get","head","options"],function(e){it.prototype[e]=function(t,n){return this.request(at(n||{},{method:e,url:t,data:(n||{}).data}))}});v.forEach(["post","put","patch"],function(e){function t(n){return function(o,i,a){return this.request(at(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}it.prototype[e]=t(),it.prototype[e+"Form"]=t(!0)});let Ya=class Ps{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(o){t=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{n.subscribe(a),o=a}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,a){n.reason||(n.reason=new Gt(o,i,a),t(n.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 t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Ps(function(s){e=s}),cancel:e}}};function Ka(r){return function(t){return r.apply(null,t)}}function Xa(r){return v.isObject(r)&&r.isAxiosError===!0}const Vr={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(Vr).forEach(([r,e])=>{Vr[e]=r});function Ds(r){const e=new it(r),t=ys(it.prototype.request,e);return v.extend(t,it.prototype,e,{allOwnKeys:!0}),v.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Ds(at(r,s))},t}const re=Ds(Ut);re.Axios=it;re.CanceledError=Gt;re.CancelToken=Ya;re.isCancel=$s;re.VERSION=Fs;re.toFormData=xr;re.AxiosError=P;re.Cancel=re.CanceledError;re.all=function(e){return Promise.all(e)};re.spread=Ka;re.isAxiosError=Xa;re.mergeConfig=at;re.AxiosHeaders=Re;re.formToJSON=r=>Ns(v.isHTMLForm(r)?new FormData(r):r);re.getAdapter=Is.getAdapter;re.HttpStatusCode=Vr;re.default=re;const{Axios:wm,AxiosError:Am,CanceledError:Rm,isCancel:Sm,CancelToken:Cm,VERSION:Em,all:Tm,Cancel:Nm,isAxiosError:$m,spread:km,toFormData:Om,AxiosHeaders:jm,HttpStatusCode:Mm,formToJSON:Im,getAdapter:Fm,mergeConfig:Pm}=re,Ja=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),Za=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),Qa=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),el=()=>f.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),tl=[{id:"profile",label:"个人主页",icon:f.jsx(Ja,{})},{id:"settings",label:"设置",icon:f.jsx(Za,{})},{id:"help",label:"帮助",icon:f.jsx(Qa,{})},{id:"logout",label:"退出",icon:f.jsx(el,{})}],Ls=({userId:r,userName:e,userAvatar:t,apiConfig:n,menuItems:s=tl,avatarSize:o="md",isLoading:i=!1,error:a=null,avatarClassName:c,userNameClassName:l,containerClassName:d,onMenuOpen:u,onMenuClose:y,onMenuItemClick:m,onLogout:h,renderMenuItem:g,renderUserInfo:p})=>{const[x,S]=b.useState({id:r||"",name:e||"",avatar:t||"",level:0,badges:[]}),[R,C]=b.useState(i),[_,O]=b.useState(a);b.useEffect(()=>{r&&n&&!e&&!t&&w()},[r,n,e,t]);const w=async()=>{C(!0),O(null);try{const M=n.endpoints.userProfile.replace(":userId",r),L=await re.get(`${n.baseURL}${M}`,{headers:n.headers});S(L.data)}catch(M){O(M)}finally{C(!1)}},F=M=>{m?.(M.id),M.id==="logout"&&h?.()},$=()=>{u?.()},k=()=>{y?.()},B=()=>f.jsxs("div",{className:"user-profile-trigger",children:[f.jsx(Ne.Avatar,{src:x.avatar,size:o,className:c,alt:"用户头像"}),f.jsx("span",{className:`user-name ${l||""}`,children:x.name})]}),W=M=>f.jsxs("div",{className:"submenu-item",onClick:()=>F(M),children:[M.icon&&f.jsx("span",{className:"submenu-item-icon",children:M.icon}),f.jsx("span",{children:M.label})]},M.id);return R?f.jsx("div",{className:`user-profile-container ${d||""} is-loading`,children:f.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):_?f.jsx("div",{className:`user-profile-container ${d||""} has-error`,children:f.jsxs("div",{className:"user-profile-error",children:["错误: ",_.message]})}):x.name?f.jsx("div",{className:`user-profile-container ${d||""}`,children:f.jsx(tn,{trigger:p?p(x):B(),items:s.map(M=>({...M,onClick:()=>F(M)})),position:"bottom",alignment:"end",onOpen:$,onClose:k,renderItem:g?M=>g(M,x):W})}):f.jsx("div",{className:`user-profile-container ${d||""}`,children:f.jsx("div",{className:"user-profile-loading",children:"未登录"})})},rl=r=>f.jsxs("div",{className:"explore-menu-item",onClick:()=>r.onClick?.(r),children:[f.jsx("span",{className:"explore-item-label",children:r.label}),r.status&&f.jsx("span",{className:`explore-item-status status-${r.status.toLowerCase().replace("%","").replace(" ","-")}`,children:r.status})]},r.id),nl=({className:r})=>f.jsxs("button",{className:r,"aria-label":"探索数学课程",children:[f.jsx("span",{className:"explore-icon",children:"🌍"}),f.jsx("span",{className:"explore-text",children:"探索"})]}),sl=({className:r="",style:e,logoHref:t="/",logoText:n="MathWiz",onLogoClick:s,exploreItems:o=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:c,renderExploreItem:l=rl,userData:d,userMenuItems:u,onUserMenuItemClick:y,onLogout:m,isLoading:h=!1,error:g=null,headerClassName:p="",logoClassName:x="",exploreClassName:S="",userProfileClassName:R="",variant:C="gradient",color:_,background:O,height:w,gradientFrom:F,gradientTo:$,gradientVia:k,logoColor:B,logoSize:W="md",exploreButtonVariant:M="flat",exploreButtonColor:L="primary","aria-label":J,"aria-labelledby":j,...he})=>{const oe=o.map(Ce=>({id:Ce.id,label:l(Ce),onClick:()=>c?.(Ce)})),z=["mathwiz-header",`mathwiz-header--${C}`,_&&`mathwiz-header--color-${_}`,p,r].filter(Boolean).join(" "),de=["logo",`logo--${W}`,x].filter(Boolean).join(" "),ae=["explore-button",`explore-button--${M}`,`explore-button--color-${L}`,S].filter(Boolean).join(" "),ge={...e,...w&&{height:typeof w=="number"?`${w}px`:w},...O&&{"--custom-bg":O},...B&&{"--logo-color":B},...F&&$&&{"--header-bg":k?`linear-gradient(to right, ${F}, ${k}, ${$})`:`linear-gradient(to right, ${F}, ${$})`}};return f.jsx("header",{className:z,style:ge,"aria-label":J,"aria-labelledby":j,role:"banner",...he,children:f.jsxs("div",{className:"header-content",children:[f.jsx("div",{className:"header-section left",children:f.jsx(tn,{trigger:f.jsx(nl,{className:ae}),items:oe,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),f.jsx("div",{className:"header-section center",children:f.jsx("a",{href:t,className:de,onClick:s,"aria-label":"MathWiz 首页",children:n})}),f.jsx("div",{className:"header-section right",children:f.jsx(Ls,{userName:d?.name,userAvatar:d?.avatar,menuItems:u,onMenuItemClick:y,onLogout:m,containerClassName:R,isLoading:h,error:g})})]})})},Us=b.memo(sl,(r,e)=>r.logoText===e.logoText&&r.logoHref===e.logoHref&&r.className===e.className&&r.headerClassName===e.headerClassName&&r.logoClassName===e.logoClassName&&r.exploreClassName===e.exploreClassName&&r.userProfileClassName===e.userProfileClassName&&r["aria-label"]===e["aria-label"]&&r["aria-labelledby"]===e["aria-labelledby"]&&r.isLoading===e.isLoading&&r.error===e.error&&r.variant===e.variant&&r.color===e.color&&r.background===e.background&&r.height===e.height&&r.gradientFrom===e.gradientFrom&&r.gradientTo===e.gradientTo&&r.gradientVia===e.gradientVia&&r.logoColor===e.logoColor&&r.logoSize===e.logoSize&&r.exploreButtonVariant===e.exploreButtonVariant&&r.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(r.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(r.userData)===JSON.stringify(e.userData)&&JSON.stringify(r.userMenuItems)===JSON.stringify(e.userMenuItems)),zt=b.memo(({parts:r=[],children:e=null,fontSize:t="1rem",color:n="#333333",displayMode:s=!1,className:o=""})=>{b.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(u=>{try{return u.href&&u.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
12
7
  import 'katex/dist/katex.min.css';
13
- 更多详情请参考组件库文档。`))},[]);const i=b.useMemo(()=>r.length===0?[]:r.map((c,u)=>{try{return _i.renderToString(c,{displayMode:o,throwOnError:!1,errorColor:"#ff0000"})}catch(y){return console.error(`KaTeX rendering error in part ${u}:`,y),'<span style="color: red;">KaTeX Error</span>'}}),[r,o]);if(r.length===0)return null;const a=o?"div":"span",d=b.Children.toArray(e),l=[];return i.forEach((c,u)=>{l.push(f.jsx("span",{dangerouslySetInnerHTML:{__html:c},style:{display:"inline-block"}},`part-${u}`)),u<d.length&&u<r.length-1&&l.push(f.jsx("span",{style:{display:"inline-block"},children:d[u]},`slot-${u}`))}),f.jsx(a,{className:`equation-render ${s}`.trim(),style:{fontSize:t,color:n,display:"flex",alignItems:"center",gap:"0.3em",...o?{justifyContent:"center",margin:"1em 0"}:{}},children:l})});function Mt(r){return r.type!=="composite"}function It(r){return r.type==="composite"}function hl(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function _t(r){if(!r)return hl();if(r.type==="composite"&&Array.isArray(r.transforms))return{type:"composite",transforms:r.transforms.map(s=>_t(s)),executionMode:r.executionMode||"sequential"};if(r.type&&r.config)return r;const e=r;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((s,i)=>_t(s)),executionMode:"sequential"};let t,n="translation";return e.rotation?(n="rotation",t=e.rotation):e.translation?(n="translation",t=e.translation):e.scale?(n="scale",t=e.scale):(n="translation",t={direction:"horizontal",distance:0}),{type:n,config:t,targetGroup:e.targetGroup}}const Cr=r=>{if(r.length===0)return[0,0];let e=0,t=0;for(const[n,o]of r)e+=n,t+=o;return[e/r.length,t/r.length]},Kr=r=>{if(Mt(r)){const e=r;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 t=e.config;if(t.startScale<=0||t.endScale<=0)return"缩放比例必须大于0";break}return null}if(It(r)){const e=r;if(!e.transforms)return"复合变换缺少transforms字段";for(const t of e.transforms){const n=Kr(t);if(n)return`复合变换子配置错误: ${n}`}return null}return"未知的变换配置类型"},gl=(r,e,t,n)=>{if(r<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(t.animated.length===0)return"至少需要一个动画图形";const o=Kr(n);if(o)return`全局变换配置错误: ${o}`;for(const s of t.animated)if(s.transform){const i=_t(s.transform),a=Kr(i);if(a)return`形状"${s.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const s of[...t.static,...t.animated]){if(!s.vertices||s.vertices.length<2)return`形状"${s.metadata?.id||"未知"}"缺少有效的顶点数据`;for(const i of s.vertices){if(!Array.isArray(i)||i.length!==2)return`形状"${s.metadata?.id||"未知"}"顶点格式错误`;const[a,d]=i;if(typeof a!="number"||typeof d!="number"||!isFinite(a)||!isFinite(d))return`形状"${s.metadata?.id||"未知"}"顶点坐标无效`}}return null},pl=r=>{const{base:e,height:t,shapes:n,transform:o}=r,s=_t(o),i=gl(e,t,n,s);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},yl=r=>{if(r.slider){const{slider:e}=r;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},bl=r=>{if(!r)return null;if(r.boundingBox){const[e,t,n,o]=r.boundingBox;if(e>=n||t<=o)return"画板边界框配置无效:left < right 且 top > bottom"}return r.gridSize!==void 0&&r.gridSize<=0?"网格大小必须大于0":null},xl=r=>{const e=pl({base:r.base,height:r.height,shapes:r.shapes,transform:r.transform});if(e)return e;const t=yl(r.animation);if(t)return{code:"INVALID_CONFIG",message:t,timestamp:new Date().toISOString()};const n=bl(r.boardConfig);return n?{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()}:r.autoCompleteThreshold!==void 0&&(r.autoCompleteThreshold<0||r.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class Er{validateNumber(e,t,n,o){if(typeof e!="number"||isNaN(e))return`${t}必须是有效的数字`;if(n!==void 0&&e<n)return`${t}不能小于${n}`;if(o!==void 0&&e>o)return`${t}不能大于${o}`}validateArray(e,t,n){if(!Array.isArray(e))return`${t}必须是数组`;if(n!==void 0&&e.length!==n)return`${t}必须是长度为${n}的数组`}validateString(e,t,n){if(typeof e!="string")return`${t}必须是字符串`;if(n!==void 0&&!n.includes(e))return`${t}必须是以下值之一: ${n.join(", ")}`}createValidationResult(e,t,n){return{isValid:e,errors:t?.filter(Boolean),warnings:n?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let t=0;t<e.length;t++){const n=e[t],o=this.validateArray(n,`顶点[${t}]`,2);if(o)return o;const[s,i]=n,a=this.validateNumber(s,`顶点[${t}].x`),d=this.validateNumber(i,`顶点[${t}].y`);if(a||d)return`${a||d} (顶点[${t}])`}}}const vl=(r,e,t)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:r,progress:e,config:t,distance:t.distance,distanceType:typeof t.distance,direction:t.direction,directionType:typeof t.direction,configType:typeof t,configKeys:Object.keys(t)});let n;t.direction==="horizontal"?n=[t.distance,0]:t.direction==="vertical"?n=[0,t.distance]:n=[t.direction[0]*t.distance,t.direction[1]*t.distance];const o=n[0]*e,s=n[1]*e;return process.env.NODE_ENV==="development"&&console.log("📐 [calculateTranslation] 计算结果:",{directionVector:n,offsetX:o,offsetY:s,firstVertexOriginal:r[0],firstVertexTransformed:[r[0][0]+o,r[0][1]+s]}),r.map(([i,a])=>[i+o,a+s])},_l=(r,e,t)=>{const n=t.center==="auto"?Cr(r):t.center,[o,s]=n,i=t.endAngle-t.startAngle,a=t.direction==="clockwise"?-1:1,d=t.startAngle+i*e*a;return r.map(([l,c])=>{const u=l-o,y=c-s,m=Math.cos(d),h=Math.sin(d);return[o+u*m-y*h,s+u*h+y*m]})},wl=(r,e,t)=>{const n=t.center==="centroid"?Cr(r):t.center,[o,s]=n,i=t.endScale-t.startScale,a=t.startScale+i*e;return r.map(([d,l])=>{const c=d-o,u=l-s;return[o+c*a,s+u*a]})},Al=(r,e=.95)=>r>=e;class Rl extends Er{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,t,n){return vl(e,t,n)}validate(e){const t=[],n=[];if(typeof e.direction=="string"){const s=this.validateString(e.direction,"direction",["horizontal","vertical"]);s&&t.push(s)}else if(Array.isArray(e.direction)){const s=this.validateArray(e.direction,"direction",2);if(s)t.push(s);else{const[i,a]=e.direction,d=this.validateNumber(i,"direction[0]"),l=this.validateNumber(a,"direction[1]");d&&t.push(d),l&&t.push(l)}}else t.push("direction必须是字符串或数组");const o=this.validateNumber(e.distance,"distance",0);if(o&&t.push(o),e.startOffset!==void 0){const s=this.validateNumber(e.startOffset,"startOffset",0,1);s&&n.push(s)}if(Array.isArray(e.direction)){const[s,i]=e.direction;Math.sqrt(s*s+i*i)<.001&&n.push("方向向量长度过小,可能导致变换效果不明显")}return this.createValidationResult(t.length===0,t,n)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,t){const n=this.getDirectionVector(e),o=e.startOffset||0,s=Math.max(0,Math.min(1,t-o))/(1-o);return[n[0]*e.distance*s,n[1]*e.distance*s]}}class Sl extends Er{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,t,n){return _l(e,t,n)}validate(e){const t=[],n=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)t.push(a);else{const[d,l]=e.center,c=this.validateNumber(d,"center[0]"),u=this.validateNumber(l,"center[1]");c&&t.push(c),u&&t.push(u)}}else t.push('center必须是"auto"或数组[x, y]');const o=this.validateNumber(e.startAngle,"startAngle");o&&t.push(o);const s=this.validateNumber(e.endAngle,"endAngle");if(s&&t.push(s),!o&&!s){const a=Math.abs(e.endAngle-e.startAngle);a<.001&&n.push("角度范围过小,可能导致变换效果不明显"),a>4*Math.PI&&n.push("角度范围过大,可能超过2圈")}const i=this.validateString(e.direction,"direction",["clockwise","counterclockwise","horizontal","vertical"]);return i&&t.push(i),this.createValidationResult(t.length===0,t,n)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=e[0][0],n=e[0][0],o=e[0][1],s=e[0][1];for(let i=1;i<e.length;i++){const[a,d]=e[i];t=Math.min(t,a),n=Math.max(n,a),o=Math.min(o,d),s=Math.max(s,d)}return{minX:t,maxX:n,minY:o,maxY:s}}getActualCenter(e,t){return t.center==="auto"?Cr(e):t.center}calculateCurrentAngle(e,t){const n=e.endAngle-e.startAngle,o=e.direction==="clockwise"?-1:1;return e.startAngle+n*t*o}}class Cl extends Er{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,t,n){return wl(e,t,n)}validate(e){const t=[],n=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)t.push(i);else{const[a,d]=e.center,l=this.validateNumber(a,"center[0]"),c=this.validateNumber(d,"center[1]");l&&t.push(l),c&&t.push(c)}}else t.push('center必须是"centroid"或数组[x, y]');const o=this.validateNumber(e.startScale,"startScale",.01);o&&t.push(o);const s=this.validateNumber(e.endScale,"endScale",.01);if(s&&t.push(s),!o&&!s){const i=e.endScale/e.startScale;Math.abs(e.endScale-e.startScale)<.01&&n.push("缩放比例变化过小,可能导致变换效果不明显"),i>10&&n.push("缩放比例过大,可能导致图形变形严重"),i<.1&&n.push("缩放比例过小,可能导致图形几乎不可见")}return typeof e.uniform!="boolean"?t.push("uniform必须是布尔值"):e.uniform||n.push("非均匀缩放可能导致图形变形"),this.createValidationResult(t.length===0,t,n)}getActualCenter(e,t){return t.center==="centroid"?Cr(e):t.center}calculateCurrentScale(e,t){const n=e.endScale-e.startScale;return e.startScale+n*t}calculateSizeChange(e,t,n){if(e.length<2)return{widthChange:0,heightChange:0,areaChange:0};const o=this.calculateBounds(e),s=o.maxX-o.minX,i=o.maxY-o.minY,a=s*i,d=this.calculateCurrentScale(t,n),l=(t.uniform,d),c=s*l,u=i*l,y=c*u;return{widthChange:(c-s)/s,heightChange:(u-i)/i,areaChange:(y-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=e[0][0],n=e[0][0],o=e[0][1],s=e[0][1];for(let i=1;i<e.length;i++){const[a,d]=e[i];t=Math.min(t,a),n=Math.max(n,a),o=Math.min(o,d),s=Math.max(s,d)}return{minX:t,maxX:n,minY:o,maxY:s}}}function eo(r){let e=r.trim().replace(/^#/,"");if((e.length===3||e.length===4)&&(e=e.split("").map(s=>s+s).join("")),e.length!==6&&e.length!==8)throw new Error(`无效的十六进制颜色格式: ${r}`);const t=parseInt(e.substring(0,2),16),n=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16);if(isNaN(t)||isNaN(n)||isNaN(o))throw new Error(`无效的十六进制颜色值: ${r}`);return[t,n,o]}function El(r,e,t){const n=a=>Math.max(0,Math.min(255,Math.round(a))),o=n(r).toString(16).padStart(2,"0"),s=n(e).toString(16).padStart(2,"0"),i=n(t).toString(16).padStart(2,"0");return`#${o}${s}${i}`.toUpperCase()}function Xr(r){const e=r.trim();if(e.startsWith("#"))return eo(e);const t=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(t){const s=parseInt(t[1],10),i=parseInt(t[2],10),a=parseInt(t[3],10);if(s>=0&&s<=255&&i>=0&&i<=255&&a>=0&&a<=255)return[s,i,a]}const n={red:"#FF0000",green:"#00FF00",blue:"#0000FF",yellow:"#FFFF00",cyan:"#00FFFF",magenta:"#FF00FF",black:"#000000",white:"#FFFFFF",gray:"#808080",grey:"#808080",transparent:"transparent"},o=e.toLowerCase();if(n[o])return o==="transparent"?[0,0,0]:eo(n[o]);throw new Error(`无法解析的颜色格式: ${r}`)}function br(r){try{return Xr(r),!0}catch{return!1}}function Tl(r,e,t){if(t<=0)return r;if(t>=1)return e;try{const n=Xr(r),o=Xr(e),s=n[0]+(o[0]-n[0])*t,i=n[1]+(o[1]-n[1])*t,a=n[2]+(o[2]-n[2])*t;return El(s,i,a)}catch(n){return console.warn("颜色插值失败,返回起始颜色:",n),r}}function Ho(r,e,t,n="linear"){let o=t;switch(n){case"ease-in":o=t*t;break;case"ease-out":o=1-(1-t)*(1-t);break;case"ease-in-out":o=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break;case"step":o=t>=1?1:0;break}return Tl(r,e,o)}class Nl extends Er{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,t,n){return e}validate(e){const t=[],n=[];if(!e.targetColor||typeof e.targetColor!="string"?t.push("targetColor 是必需的且必须是字符串"):br(e.targetColor)||t.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?t.push("fromColor 必须是字符串"):br(e.fromColor)||t.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const o=this.validateNumber(e.startAt,"startAt",0,1);o&&t.push(o)}if(e.endAt!==void 0){const o=this.validateNumber(e.endAt,"endAt",0,1);o&&t.push(o)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&t.push("startAt 必须小于 endAt"),e.easing!==void 0){const o=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);o&&t.push(o)}return e.targetColor&&e.fromColor,this.createValidationResult(t.length===0,t,n)}calculateCurrentColor(e,t,n){const o=t.fromColor||n,s=t.targetColor,i=this.calculateEffectiveProgress(e,t);return Ho(o,s,i,t.easing)}calculateEffectiveProgress(e,t){const n=t.startAt??0,o=t.endAt??1;return e<=n?0:e>=o?1:(e-n)/(o-n)}isActive(e,t){const n=t.startAt??0,o=t.endAt??1;return e>=n&&e<=o}}class $l{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[t,n]of this.executors)e[t]=n.getDisplayName();return e}validateConfig(e,t){const n=this.get(e);return n?n.validate(t):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,t,n,o){const s=this.get(e);if(!s)return console.error(`不支持变换类型: ${e}`),t;const i=s.validate(o);return i.isValid?s.execute(t,n,o):(console.error("配置验证失败:",i.errors),t)}executeTransforms(e,t,n){let o=t;for(const s of e){const i=this.get(s.type);if(!i){console.warn(`跳过不支持的变换类型: ${s.type}`);continue}o=i.execute(o,n,s.config)}return o}getDefaultConfig(e){return this.get(e)?.getDefaultConfig()}clear(){this.executors.clear()}size(){return this.executors.size}}let nt=null;function Ko(){return nt||(nt=new $l,nt.register(new Rl),nt.register(new Sl),nt.register(new Cl),nt.register(new Nl)),nt}class Jr{static matchesShape(e,t,n){if(!t)return!n||this.extractGroupId(e)===n;if("targetGroup"in t&&t.targetGroup)return this.matchesSimpleGroup(e,t.targetGroup,t.metadataField);if("pattern"in t){if(t.strategy==="any")return this.matchesWithConfig(e,t);if(t.pattern)return this.matchesWithConfig(e,t)}return!1}static matchesSimpleGroup(e,t,n){const o=this.extractGroupId(e,n);if(!o)return!1;if(t.includes("*")){const s=t.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(o)}return o===t}static matchesWithConfig(e,t){const n=this.extractGroupId(e,t.metadataField);if(!n)return!1;const o=t.pattern,s=t.strategy||"exact",i=t.caseSensitive||!1;switch(s){case"exact":return i?n===o:n.toLowerCase()===o.toLowerCase();case"wildcard":const a=o.replace(/\*/g,".*");return new RegExp(`^${a}$`,i?"":"i").test(n);case"regex":return(o instanceof RegExp?o:new RegExp(o,i?"":"i")).test(n);case"multiple":return(Array.isArray(o)?o:o.split(",")).some(c=>this.matchesSimpleGroup(e,c,t.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,t="rotationGroup"){if(!e)return;const n=t.split(".");let o=e;for(const s of n){if(o==null)return;o=o[s]}return typeof o=="string"?o:void 0}static validateConfig(e){const t=[],n=[];if(!e||typeof e!="object")return t.push("配置必须是对象"),{isValid:!1,errors:t,warnings:n};switch(e.pattern||t.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&t.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&t.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&t.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:t.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&t.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&t.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&n.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:t.length===0,errors:t,warnings:n}}static convertToGroupMatchConfig(e,t){if(!e)return;const n=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:n,metadataField:t}}}function kl(r,e,t){return!e&&!t?r.filter(n=>!n.targetGroup&&!n.groupMatch):r.filter(n=>{if(n.groupMatch&&t)return Jr.matchesShape(t,n.groupMatch);if(n.targetGroup){if(!e)return!1;if(n.targetGroup.includes("*")){const o=n.targetGroup.replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}return n.targetGroup===e}return!e})}class Ol{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,t,n,o,s){const i=this.validate(n);if(!i.isValid)return console.error("复合变换配置验证失败:",i.errors),e;const a=this.filterTransformsByGroup(n.transforms,o,s);if(a.length===0)return e;switch(n.executionMode){case"sequential":return this.executeSequentially(e,t,a);case"parallel":return this.executeInParallel(e,t,a);default:return console.warn(`未知的执行模式: ${n.executionMode},使用顺序执行`),this.executeSequentially(e,t,a)}}validate(e){const t=[],n=[];if(!e||e.type!=="composite")return t.push("配置必须是复合变换类型"),this.createValidationResult(!1,t,n);if(!Array.isArray(e.transforms))return t.push("transforms必须是数组"),this.createValidationResult(!1,t,n);e.transforms.length===0&&n.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&t.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],d=this.validateSingleTransform(a,i);d&&t.push(d)}const o=e.transforms.map(i=>i.id).filter(Boolean),s=new Set(o);return o.length!==s.size&&n.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(t.length===0,t,n)}getTransformInfo(e){const t=e.transforms.map(o=>o.type),n=Array.from(new Set(e.transforms.map(o=>o.targetGroup).filter(o=>o!==void 0)));return{count:e.transforms.length,types:t,groups:n,executionMode:e.executionMode}}filterTransformsByGroup(e,t,n){return kl(e,t,n)}getTransformsForGroup(e,t,n){return this.filterTransformsByGroup(e.transforms,t,n)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,t,n){let o=e;for(const s of n){const i=this.registry.get(s.type);if(!i){console.warn(`跳过不支持的变换类型: ${s.type}`);continue}const a=i.validate(s.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${s.type}`,a.errors);continue}o=i.execute(o,t,s.config)}return o}executeInParallel(e,t,n){if(n.length===0)return e;if(n.length===1)return this.executeSequentially(e,t,n);const o=[];for(const s of n){const i=this.registry.get(s.type);if(!i){console.warn(`跳过不支持的变换类型: ${s.type}`);continue}const a=i.validate(s.config);if(!a.isValid){console.warn(`子变换配置验证失败: ${s.type}`,a.errors);continue}const d=i.execute(e,t,s.config);o.push(d)}return o.length===0?e:this.calculateAverageVertices(o)}calculateAverageVertices(e){if(e.length===0)return[];const t=e[0].length;for(const o of e)if(o.length!==t)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const n=[];for(let o=0;o<t;o++){let s=0,i=0;for(const a of e)s+=a[o][0],i+=a[o][1];n.push([s/e.length,i/e.length])}return n}validateSingleTransform(e,t){if(!e||typeof e!="object")return`变换[${t}]必须是对象`;if(!e.type)return`变换[${t}]缺少type字段`;if(!e.config)return`变换[${t}]缺少config字段`;const n=this.registry.get(e.type);if(!n)return`变换[${t}]不支持的变换类型: ${e.type}`;const o=n.validate(e.config);if(!o.isValid)return`变换[${t}]配置验证失败: ${o.errors?.join(", ")}`}createValidationResult(e,t,n){return{isValid:e,errors:t?.filter(Boolean),warnings:n?.filter(Boolean)}}getDefaultRegistry(){return Ko()}}class jl{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new Ol(this.registry)}executeShapeTransform(e,t,n){const o=this.getEffectiveTransform(e,n);return o?this.executeTransform(e.vertices,t,o,e.metadata):e.vertices}executeTransform(e,t,n,o){if(!n)return e;const s=Jr.extractGroupId(o,"rotationGroup");return Mt(n)?this.executeSingleTransform(e,t,n,o,s):It(n)?this.compositor.execute(e,t,n,s,o):(console.error("未知的变换类型:",n),e)}getEffectiveTransform(e,t){return e.transform?e.transform:t}getTransformInfo(e){return e?Mt(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:It(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?Mt(e)?this.validateSingleTransform(e):It(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?Mt(e)?!1:It(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,t,n){return e.map(o=>({...o,vertices:this.executeShapeTransform(o,t,n)}))}executeSingleTransform(e,t,n,o,s){if(!Jr.matchesShape(o,n.groupMatch||(n.targetGroup?{targetGroup:n.targetGroup}:void 0),s))return e;const a=this.registry.get(n.type);if(!a)return console.error(`不支持变换类型: ${n.type}`),e;const d=a.validate(n.config);return d.isValid?a.execute(e,t,n.config):(console.error("变换配置验证失败:",d.errors),e)}validateSingleTransform(e){const t=this.registry.get(e.type);return t?t.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return Ko()}}const Ml=()=>{const r=b.useRef(null),e=b.useCallback((o,s,i=50)=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{s&&s(o)},i)},[]),t=b.useCallback((o,s)=>{const i=Math.round(o*100);return s&&s>1?`阶段 ${o>=1?s:Math.min(Math.floor(o*s)+1,s)}/${s} (${i}%)`:`${i}%`},[]),n=b.useCallback(()=>(r.current&&(clearTimeout(r.current),r.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:Al,getProgressLabel:t,resetProgress:n}},Il=()=>{const r=b.useCallback((t,n,o=.05)=>{let s=n;switch(t.key){case"ArrowRight":case"ArrowUp":s=Math.min(n+o,1);break;case"ArrowLeft":case"ArrowDown":s=Math.max(n-o,0);break;case"Home":s=0;break;case"End":s=1;break;case"PageUp":s=Math.min(n+o*2,1);break;case"PageDown":s=Math.max(n-o*2,0);break;case" ":case"Enter":s=n>=.95?0:1;break;case"Escape":s=0;break;default:return null}return t.preventDefault(),s},[]),e=b.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
14
- `),[]);return{handleKeyDown:r,getNavigationInstructions:e}},to=vo.JSXGraph,Fl=r=>{const{base:e,height:t,unit:n,layoutDensity:o="default",boardHeight:s,shapes:i,transform:a,animation:d,boardConfig:l={},theme:c="light",className:u="",enableRigidityVerification:y=!1,enableKeyboardNavigation:m=!0,autoCompleteThreshold:h=.95,boardWidth:g,onTransformStart:p,onTransformChange:x,onTransformComplete:C,onError:S}=r,[E,_]=b.useState(0),[j,w]=b.useState(null),[P,$]=b.useState(0),[O,Y]=b.useState(null),[q,I]=b.useState({width:800,height:560}),G=b.useMemo(()=>new jl,[]),H=b.useMemo(()=>_t(a),[a]),M=b.useRef(null),ge=b.useRef({}),se=b.useRef(null),{handleProgressChange:W,shouldAutoComplete:fe,resetProgress:A}=Ml(),{handleKeyDown:F,getNavigationInstructions:V}=Il();b.useEffect(()=>{const k=()=>{if(se.current){const{clientWidth:R}=se.current;if(R>0){const J=l.boundingBox||[0,7,10,0],re=J[2]-J[0],D=J[1]-J[3];let z;s?z=s:z=Math.round(R*(D/re)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:J,ratio:`${D}:${re}`,containerWidth:R,calculatedHeight:z,isCustomHeight:!!s}),I({width:R,height:z})}}};k(),window.addEventListener("resize",k);const T=new ResizeObserver(k);return se.current&&T.observe(se.current),()=>{window.removeEventListener("resize",k),T.disconnect()}},[l.boundingBox,s]);const te={width:g??`${q.width}px`,height:`${q.height}px`},je=b.useCallback((k,T)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:k.metadata?.id,shapeType:k.type,progress:T,hasMetadata:!!k.metadata,hasDynamicAppearance:!!k.metadata?.dynamicAppearance,dynamicAppearance:k.metadata?.dynamicAppearance});const R=k.metadata?.dynamicAppearance,J=k.style||{};let re;if(k.transform?.type==="fillcolor_set"&&k.transform.fillColorSet){const ne=k.transform.fillColorSet,{targetColor:ue,startAt:pe=0,endAt:xe=1,easing:Ne="linear",fromColor:ze}=ne;if(br(ue)&&(!ze||br(ze))){let $e=T;T<pe?$e=0:T>xe?$e=1:$e=(T-pe)/(xe-pe);const Nt=ze||J.fillColor||"#FFFFFF";re=Ho(Nt,ue,$e,Ne),console.log("🎨 fillcolor_set applied:",{shapeId:k.metadata?.id,progress:T,effectiveProgress:$e,startColor:Nt,targetColor:ue,resultColor:re})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:ue,fromColor:ze})}if(!R)return console.log("📝 No dynamicAppearance, returning base style"),re?{...J,fillColor:re}:J;const D=ne=>{if(!ne)return 1;const ue=ne.threshold??.5,pe=ne.startValue??0,xe=ne.endValue??1,Ne=ne.type??"step";if(Ne==="step")return T>=ue?xe:pe;if(Ne==="fade"){if(T<ue)return pe;{const ze=Math.min((T-ue)/(1-ue),1);return pe+(xe-pe)*ze}}return 1},z={...J};let tt=!0;const Ge=D(R.visibility),rt=D(R.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:k.metadata?.id,progress:T,visibilityValue:Ge,labelVisibilityValue:rt,hasVisibility:!!R.visibility,hasLabelVisibility:!!R.labelVisibility}),R.visibility&&(z.fillOpacity===void 0&&(z.fillOpacity=1),z.fillOpacity*=Ge,Ge===0&&(z.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),z.strokeColor,tt=Ge>0,console.log("👁️ Shape visibility:",{shapeId:k.metadata?.id,visible:tt,visibilityValue:Ge})),R.labelVisibility){const ne=rt>0;z.labelVisible=ne,console.log("🏷️ Label visibility:",{shapeId:k.metadata?.id,labelVisible:ne,labelVisibilityValue:rt,hasLabel:!!k.metadata?.label})}if(R.opacity){const ne=R.opacity,ue=ne.startAt??0,pe=ne.endAt??1,xe=ne.from??1,Ne=ne.to??1,ze=ne.type??"linear";let $e=xe;if(T<ue)$e=xe;else if(T>pe)$e=Ne;else{const Nt=(T-ue)/(pe-ue);$e=xe+(Ne-xe)*Nt}z.fillOpacity=$e}if(re)z.fillColor=re,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:k.metadata?.id,transformColor:re});else if(R.color){const ne=R.color,ue=ne.startAt??0,pe=ne.endAt??1,xe=ne.from??z.fillColor,Ne=ne.to??z.fillColor,ze=ne.type??"gradient";if(xe&&Ne)if(T<ue)z.fillColor=xe;else if(T>pe)z.fillColor=Ne;else{const $e=(T-ue)/(pe-ue);ze==="gradient"?z.fillColor=Ne:z.fillColor=$e>=.5?Ne:xe}}return z.visible=tt,z.labelVisible===void 0&&(z.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:k.metadata?.id,visible:z.visible,labelVisible:z.labelVisible,fillOpacity:z.fillOpacity,strokeWidth:z.strokeWidth}),z},[]),Le=b.useCallback((k,T,R=!1,J=0)=>{console.log("🎨 createShape called:",{shapeId:T.metadata?.id,shapeType:T.type,isStatic:R,progress:J,verticesLength:T.vertices?.length,hasMetadata:!!T.metadata,hasDynamicAppearance:!!T.metadata?.dynamicAppearance});const re=T.type==="point"?1:2;if(!k||!T.vertices||T.vertices.length<re)return console.warn(`⚠️ createShape: invalid board or vertices for ${T.type}`,{shapeId:T.metadata?.id,shapeType:T.type,verticesLength:T.vertices?.length,minVertices:re}),null;const D=je(T,J);let z;switch(T.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const tt=D.labelVisible!==void 0?D.labelVisible:T.style?.labelVisible!==void 0?T.style.labelVisible:!1,Ge=T.metadata?.label||T.metadata?.id||"";z=k.create("polygon",T.vertices,{name:Ge,fillColor:D.fillColor!==void 0?D.fillColor:R?"#8ec5fc":"#6a5acd",fillOpacity:D.fillOpacity!==void 0?D.fillOpacity:R?.3:.7,strokeColor:D.strokeColor!==void 0?D.strokeColor:R?"#0074d9":"#4b0082",strokeWidth:D.strokeWidth!==void 0?D.strokeWidth:R?1:2,dash:D.dashStyle!==void 0?D.dashStyle:0,fixed:R,highlight:!R,withLabel:tt,visible:D.visible!==void 0?D.visible:!0});break;case"circle":if(T.vertices.length>=2){const[rt,ne]=T.vertices,ue=D.labelVisible!==void 0?D.labelVisible:T.style?.labelVisible!==void 0?T.style.labelVisible:!1,pe=T.metadata?.label||T.metadata?.id||"";z=k.create("circle",[rt,ne],{name:pe,fillColor:D.fillColor!==void 0?D.fillColor:R?"#8ec5fc":"#6a5acd",fillOpacity:D.fillOpacity!==void 0?D.fillOpacity:R?.3:.7,strokeColor:D.strokeColor!==void 0?D.strokeColor:R?"#0074d9":"#4b0082",strokeWidth:D.strokeWidth!==void 0?D.strokeWidth:R?1:2,dash:D.dashStyle!==void 0?D.dashStyle:0,fixed:R,highlight:!R,withLabel:ue})}break;case"point":if(T.vertices.length>=1){const[rt,ne]=T.vertices[0],ue=D.labelVisible!==void 0?D.labelVisible:T.style?.labelVisible!==void 0?T.style.labelVisible:!1,pe=T.metadata?.label||T.metadata?.id||"";z=k.create("point",[rt,ne],{name:pe,withLabel:ue,fixed:R,size:4,strokeColor:D.strokeColor!==void 0?D.strokeColor:R?"#0074d9":"#4b0082",fillColor:D.fillColor!==void 0?D.fillColor:R?"#8ec5fc":"#6a5acd",visible:D.visible!==void 0?D.visible:!0,highlight:!R})}break;default:return console.warn(`Unsupported shape type: ${T.type}`),null}return console.log("✅ createShape finished:",{shapeId:T.metadata?.id,elementType:z?.type,elementName:z?.name,fillOpacity:z?.getAttribute?.("fillOpacity"),strokeWidth:z?.getAttribute?.("strokeWidth"),labelVisible:D.labelVisible,hasLabel:!!T.metadata?.label,withLabel:!!T.metadata?.label&&D.labelVisible}),z},[je]);b.useEffect(()=>{if(!(e>0&&t>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:t,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:t>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,shapesAnimatedLength:r.shapes?.animated?.length,shapesStaticLength:r.shapes?.static?.length,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig});const T=xl(r);console.log("🔍 GeometryTransform: 验证结果 =",T),w(T),T&&S&&S(T)},[e,t,i,a,d,l,S,r]),b.useEffect(()=>{if(M.current){try{const k=l.boundingBox||[0,7,10,0],T=c==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",l.boundingBox),console.warn(" - Container dimensions:",q.width,"x",q.height),console.warn(" - Container actual dimensions:",M.current.clientWidth,"x",M.current.clientHeight);const R=to.initBoard(M.current,{boundingbox:k,keepaspectratio:l.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:l.showAxis??!0,grid:l.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),J=l.axisColor||(T?"#ffffff":"#000000"),re=l.gridColor||(T?"#444444":"#dddddd");R.defaultAxes?.x&&R.defaultAxes.x.setAttribute({strokeColor:J}),R.defaultAxes?.y&&R.defaultAxes.y.setAttribute({strokeColor:J}),R.defaultGrid&&R.defaultGrid.setAttribute({strokeColor:re}),Y(R)}catch(k){const T={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:k,timestamp:new Date().toISOString()};w(T),S?.(T)}return()=>{if(O)try{to.freeBoard(O)}catch(k){k instanceof Error&&k.name!=="AbortError"&&console.warn("Board cleanup warning:",k)}}}},[q]),b.useEffect(()=>{if(O)try{O.suspendUpdate(),Object.values(ge.current).forEach(k=>{if(k&&O.removeObject)try{O.removeObject(k)}catch{}}),ge.current={},i.static.forEach((k,T)=>{const R=k.metadata?.id||`static-${T}`,J=Le(O,k,!0,0);J&&(ge.current[R]=J)}),i.animated.forEach((k,T)=>{const R=k.metadata?.id||`animated-${T}`,J=Le(O,k,!1,0);J&&(ge.current[R]=J)}),O.unsuspendUpdate(),p&&p()}catch(k){const T={code:"RENDER_ERROR",message:"图形渲染失败",details:k,timestamp:new Date().toISOString()};w(T),S?.(T)}},[O,i,e,t]),b.useEffect(()=>{if(O){O.suspendUpdate();try{i.animated.forEach((R,J)=>{const re=R.metadata?.id||`animated-${J}`,D=ge.current[re];if(D){try{O.removeObject(D)}catch{}delete ge.current[re]}}),i.animated.forEach((R,J)=>{const re=R.metadata?.id||`animated-${J}`,D=R.transform?{...R,transform:_t(R.transform)}:R,z=G.executeShapeTransform(D,E,H),tt={...R,vertices:z,metadata:{...R.metadata,id:re,transformSource:R.transform?"shape":"global"}},Ge=Le(O,tt,!1,E);Ge&&(ge.current[re]=Ge)});const k=d.progressIndicator?.stages||1,T=Math.min(Math.floor(E*k),k-1);$(T)}catch(k){if(k instanceof Error&&k.name==="AbortError")return;console.warn("Transform update failed:",k)}finally{try{O.unsuspendUpdate()}catch{}}}},[O,E,i,a,d,Le,H,G]);const oe=b.useCallback(k=>{const T=Array.isArray(k)?k[0]:k;_(T),W(T,R=>{x?.(R)}),fe(T,h)&&(_(1),C?.())},[x,C,h,W,fe]);b.useEffect(()=>{if(!m)return;const k=T=>{const R=F(T,E);R!==null&&R!==E&&oe(R)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[m,E,oe,F]),b.useCallback(()=>{_(0),$(0),A()},[A]);const Ue=b.useCallback(()=>{w(null),_(0),$(0),A()},[A]);return e>0&&t>0&&i?.animated?.length>0?j?f.jsx(ke.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${u}`,children:f.jsx(ke.CardBody,{"data-testid":"card-body",children:f.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[f.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:f.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),f.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),f.jsx("h3",{children:"几何变换演示加载失败"}),f.jsx("p",{children:j.message}),j.details&&f.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[f.jsx("summary",{children:"查看错误详情"}),f.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(j.details,null,2)})]}),f.jsx("div",{className:"geometry-transform__error-actions",children:f.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:Ue,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):f.jsx(ke.Card,{"data-testid":"card",className:`geometry-transform ${o==="compact"?"geometry-transform--compact":""} ${c==="dark"?"geometry-transform--dark":""} ${u}`,children:f.jsxs(ke.CardBody,{"data-testid":"card-body",children:[f.jsxs("div",{ref:se,className:"geometry-transform__board-container",children:[f.jsx("div",{ref:M,id:"geometry-board",className:"geometry-transform__board",style:te,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),f.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),f.jsxs("div",{className:"geometry-transform__controls",children:[f.jsx("div",{className:"geometry-transform__slider-group",children:f.jsx(ke.Slider,{id:"transform-slider","data-testid":"slider",value:E,onChange:oe,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),m&&f.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:f.jsxs("details",{children:[f.jsx("summary",{children:"键盘导航说明"}),f.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:V()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:t,shapesAnimatedLength:i?.animated?.length,error:j}),f.jsx(ke.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${u}`,children:f.jsx(ke.CardBody,{"data-testid":"card-body",children:f.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},Xo=b.memo(Fl,(r,e)=>{if(r.base!==e.base||r.height!==e.height||r.unit!==e.unit||r.theme!==e.theme||r.className!==e.className||r.enableRigidityVerification!==e.enableRigidityVerification||r.enableKeyboardNavigation!==e.enableKeyboardNavigation||r.autoCompleteThreshold!==e.autoCompleteThreshold||r.onTransformStart!==e.onTransformStart||r.onTransformChange!==e.onTransformChange||r.onTransformComplete!==e.onTransformComplete||r.onError!==e.onError)return!1;const t=JSON.stringify({shapes:r.shapes,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig}),n=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return t===n}),un=Ut.create((r,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:t=>{r({internalValue:Math.max(0,Math.min(1,t))})},startDrag:t=>{r({isDragging:!0,dragState:{isDragging:!0,startIndex:t,currentIndex:t,direction:null}})},updateDrag:t=>{const{dragState:n}=e();let o=null;if(n.startIndex!==-1&&t!==-1){const s=Math.floor(n.startIndex/10),i=n.startIndex%10,a=Math.floor(t/10),d=t%10;a===s?o=d>i?"ltr":"rtl":d===i&&(o=a>s?"ttb":"btt")}r({dragState:{...n,currentIndex:t,direction:o}})},endDrag:()=>{r({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{r({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Jo=()=>un(_o.useShallow(r=>({internalValue:r.internalValue,setInternalValue:r.setInternalValue}))),Zo=()=>un(_o.useShallow(r=>({isDragging:r.isDragging,dragState:r.dragState,startDrag:r.startDrag,updateDrag:r.updateDrag,endDrag:r.endDrag,resetDrag:r.resetDrag}))),Qo=r=>{const{totalCells:e,fillRatio:t,direction:n,rows:o,cols:s}=r,i=Math.round(e*t),a=[];if(n==="ltr")for(let d=0;d<i;d++)a.push(d);else for(let d=0;d<o;d++)for(let l=0;l<s;l++){const c=d*s+l;a.length<i&&a.push(c)}return{filledCells:a,filledCount:i,actualRatio:i/e}},es=(r,e,t,n)=>{const o=[];for(let s=0;s<r;s++)for(let i=0;i<e;i++){const a=s*e+i;o.push({index:a,row:s,col:i,filled:n.includes(a),x:i*t,y:s*t})}return o},ts=(r,e,t,n,o)=>{if(r===-1||e===-1||!t)return[];const s=Math.floor(r/o),i=r%o,a=Math.floor(e/o),d=e%o,l=[];switch(t){case"ltr":for(let c=i;c<=d;c++)l.push(s*o+c);break;case"rtl":for(let c=i;c>=d;c--)l.push(s*o+c);break;case"ttb":for(let c=s;c<=a;c++)l.push(c*o+i);break;case"btt":for(let c=s;c>=a;c--)l.push(c*o+i);break}return l},rs=(r,e)=>Math.max(0,Math.min(1,r.length/e)),dr=r=>Math.max(0,Math.min(1,r)),Pl=r=>`${Math.round(r*100)}%`,ns=({value:r,defaultValue:e=0,mode:t="readonly",onChange:n,rows:o=10,cols:s=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:d="#f3f4f6",strokeColor:l="#d1d5db",shadingDirection:c="ltr",hasShadow:u=!0,className:y=""})=>{const{internalValue:m,setInternalValue:h}=Jo(),{isDragging:g,dragState:p,startDrag:x,updateDrag:C,endDrag:S}=Zo(),E=r!==void 0,_=E?dr(r):m,[j,w]=b.useState(!1);!j&&!E&&(h(dr(e)),w(!0));const P=b.useMemo(()=>{const fe={totalCells:o*s,fillRatio:_,direction:c,rows:o,cols:s};return Qo(fe).filledCells},[_,o,s,c]),$=b.useMemo(()=>es(o,s,i,P),[o,s,i,P]),O=b.useMemo(()=>!g||p.startIndex===-1||p.currentIndex===-1?[]:ts(p.startIndex,p.currentIndex,p.direction,o,s),[g,p,o,s]),Y=b.useCallback(W=>{if(t!=="edit")return;const fe=dr((W+1)/(o*s));E||h(fe),n?.(fe)},[t,o,s,E,n,h]),q=b.useCallback(W=>{t==="edit"&&x(W)},[t,x]),I=b.useCallback(W=>{t!=="edit"||!g||C(W)},[t,g,C]),G=b.useCallback(()=>{if(!(t!=="edit"||!g)){if(O.length>0){const W=rs(O,o*s);E||h(W),n?.(W)}S()}},[t,g,O,o,s,E,n,h,S]),H=s*i,M=o*i,ge=["hundred-chart-container",`hundred-chart--${t}`,u&&"hundred-chart--has-shadow",y].filter(Boolean).join(" "),se=Math.round(_*100);return f.jsx("div",{className:ge,"data-testid":"hundred-chart-container",children:f.jsx("svg",{width:H,height:M,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${se}% 已填充`,children:$.map(W=>{const fe=P.includes(W.index),A=O.includes(W.index),F=fe||A;return f.jsx("rect",{x:W.x,y:W.y,width:i,height:i,fill:F?a:d,stroke:l,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":fe,"data-drag":A,"aria-label":`第${W.row+1}行第${W.col+1}列,${F?"已填充":"未填充"}`,tabIndex:t==="edit"?0:-1,onClick:()=>Y(W.index),onMouseDown:()=>q(W.index),onMouseEnter:()=>I(W.index),onMouseUp:G,onKeyDown:V=>{t==="edit"&&V.key==="Enter"&&Y(W.index)}},W.index)})})})},Dl=b.createContext(void 0),os=(r,e)=>b.useMemo(()=>{const t=r.scenes?.[e];return{...r,content:t?.content||r.content,layout:t?.layout||r.layout,renderer:t?.renderer||r.renderer}},[r,e]),ss=({children:r,padding:e,shadow:t=!0,border:n=!0,theme:o="light",className:s=""})=>{const i=o==="dark"?"theme-dark":"",a=t?"with-shadow":"",d=n?"with-border":"",l=e?{"--mc-card-padding":e}:void 0;return f.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${d} ${s}`,style:l,"data-testid":"mathcard-v2-container",children:r})},is=({children:r,columns:e,gap:t,responsive:n=!0,className:o=""})=>{const s={"--grid-columns":e,"--grid-gap":t},i=n?"mathcard-v2-grid-responsive":"";return f.jsx("div",{style:s,className:`mathcard-v2-grid ${i} ${o}`,"data-testid":"grid-layout",children:r})},as=({children:r,direction:e="vertical",gap:t,wrap:n=!1,className:o=""})=>{const s={"--flow-gap":t,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":n?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=n?"wrap":"";return f.jsx("div",{style:s,className:`mathcard-v2-flow ${i} ${a} ${o}`,"data-testid":"flow-layout",children:r})},ls=({content:r,style:e={},onInteraction:t,className:n=""})=>f.jsx("div",{className:`mathcard-v2-text ${n}`,style:e,onClick:()=>t?.({type:"click",content:r}),"data-testid":"text-content",children:r}),cs=({parts:r,children:e,displayMode:t=!1,style:n={},className:o=""})=>f.jsx("div",{className:`mathcard-v2-formula ${o}`,style:n,"data-testid":"equation-render",children:f.jsx(qt,{parts:r,children:e,displayMode:t})});class Ll extends b.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("MathGraph Error:",e,t.componentStack)}render(){return this.state.hasError?f.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[f.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),f.jsx("p",{className:"text-red-700",children:this.state.error?.message}),f.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 Ul(r){if(typeof r!="string")throw new Error(`parseFunctionString expects a string, got ${typeof r}`);const e=r.trim(),t=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(t){const n=(t[3]||t[4]||"").trim();if(!n)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return Gl(n)}catch(o){throw new Error(`Failed to create function from "${e}": ${o}`)}}throw new Error(`Invalid function string format: "${e}". Expected arrow function like "() => progress * Math.PI"`)}function Gl(r){const e=r.trim();if(e==="progress * Math.PI"||e==="progress*Math.PI")return d=>d*Math.PI;if(e==="progress * Math.PI * 2"||e==="progress*Math.PI*2")return d=>d*Math.PI*2;const t=/^progress\s*\*\s*([0-9.]+)$/,n=e.match(t);if(n){const d=parseFloat(n[1]);return l=>l*d}const o=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,s=e.match(o);if(s){const d=parseFloat(s[1]);return l=>l*Math.PI*d}if(e.includes("Math.sin")&&e.includes("progress"))return d=>Math.sin(d*Math.PI);if(e.includes("Math.cos")&&e.includes("progress"))return d=>Math.cos(d*Math.PI);const i=/^([0-9.]+)$/,a=e.match(i);if(a){const d=parseFloat(a[1]);return()=>d}return e==="progress"?d=>d:e.includes("control.value")?(console.warn(`Expression contains control.value: ${e}. Will be handled by parseParamsWithControl.`),d=>d*Math.PI):(console.warn(`Unsupported expression pattern: "${e}". Using generic evaluator.`),d=>{let l=e.replace(/\bprogress\b/g,d.toString());return l=l.replace(/Math\.PI/g,Math.PI.toString()),l=l.replace(/Math\.E/g,Math.E.toString()),zl(l)})}function zl(r){const e=r.replace(/\s/g,"");function t(n){for(;n.includes("(");){const a=n.match(/\(([^()]+)\)/);if(!a)break;const d=t(a[1]);n=n.replace(a[0],d.toString())}const o=n.match(/(-?\d+\.?\d*)([*/])(-?\d+\.?\d*)/);if(o){const a=parseFloat(o[1]),d=o[2],l=parseFloat(o[3]),c=d==="*"?a*l:a/l;return n=n.replace(o[0],c.toString()),t(n)}const s=n.match(/(-?\d+\.?\d*)([+\-])(-?\d+\.?\d*)/);if(s){const a=parseFloat(s[1]),d=s[2],l=parseFloat(s[3]),c=d==="+"?a+l:a-l;return n=n.replace(s[0],c.toString()),t(n)}const i=parseFloat(n);if(isNaN(i))throw new Error(`Invalid expression: ${n}`);return i}return t(e)}function Bl(r){return typeof r=="string"&&(r.includes("=>")||r.includes("progress"))}function ve(r,e=0){return typeof r=="function"?r(e):r}function Fr(r,e,t){switch(r.params.type){case"translate":{const n=r.params,o=typeof n.x=="function"&&t?function(){const i=t.Value();return n.x(i)}:ve(n.x,e),s=typeof n.y=="function"&&t?function(){const i=t.Value();return n.y(i)}:ve(n.y,e);return[o,s]}case"rotate":{const n=r.params,o=n.center||[0,0];return typeof n.angle=="function"&&t?[function(){const i=t.Value();return n.angle(i)},o[0],o[1]]:[ve(n.angle,e),o[0],o[1]]}case"scale":{const n=r.params,o=typeof n.scaleX=="function"&&t?function(){const i=t.Value();return n.scaleX(i)}:ve(n.scaleX,e),s=typeof n.scaleY=="function"&&t?function(){const i=t.Value();return n.scaleY(i)}:ve(n.scaleY,e);return[o,s]}case"reflect":{const n=r.params;if(n.line)return[n.line];if(n.point1&&n.point2)return[n.point1,n.point2];if(n.p1&&n.p2)return[n.p1,n.p2];throw new Error(`Reflect transform requires one of:
8
+ 更多详情请参考组件库文档。`))},[]);const i=b.useMemo(()=>r.length===0?[]:r.map((d,u)=>{try{return gi.renderToString(d,{displayMode:s,throwOnError:!1,errorColor:"#ff0000"})}catch(y){return console.error(`KaTeX rendering error in part ${u}:`,y),'<span style="color: red;">KaTeX Error</span>'}}),[r,s]);if(r.length===0)return null;const a=s?"div":"span",c=b.Children.toArray(e),l=[];return i.forEach((d,u)=>{l.push(f.jsx("span",{dangerouslySetInnerHTML:{__html:d},style:{display:"inline-block"}},`part-${u}`)),u<c.length&&u<r.length-1&&l.push(f.jsx("span",{style:{display:"inline-block"},children:c[u]},`slot-${u}`))}),f.jsx(a,{className:`equation-render ${o}`.trim(),style:{fontSize:t,color:n,display:"flex",alignItems:"center",gap:"0.3em",...s?{justifyContent:"center",margin:"1em 0"}:{}},children:l})});function $t(r){return r.type!=="composite"}function kt(r){return r.type==="composite"}function ol(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function bt(r){if(!r)return ol();if(r.type==="composite"&&Array.isArray(r.transforms))return{type:"composite",transforms:r.transforms.map(o=>bt(o)),executionMode:r.executionMode||"sequential"};if(r.type&&r.config)return r;const e=r;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((o,i)=>bt(o)),executionMode:"sequential"};let t,n="translation";return e.rotation?(n="rotation",t=e.rotation):e.translation?(n="translation",t=e.translation):e.scale?(n="scale",t=e.scale):(n="translation",t={direction:"horizontal",distance:0}),{type:n,config:t,targetGroup:e.targetGroup}}const _r=r=>{if(r.length===0)return[0,0];let e=0,t=0;for(const[n,s]of r)e+=n,t+=s;return[e/r.length,t/r.length]},qr=r=>{if($t(r)){const e=r;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 t=e.config;if(t.startScale<=0||t.endScale<=0)return"缩放比例必须大于0";break}return null}if(kt(r)){const e=r;if(!e.transforms)return"复合变换缺少transforms字段";for(const t of e.transforms){const n=qr(t);if(n)return`复合变换子配置错误: ${n}`}return null}return"未知的变换配置类型"},il=(r,e,t,n)=>{if(r<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(t.animated.length===0)return"至少需要一个动画图形";const s=qr(n);if(s)return`全局变换配置错误: ${s}`;for(const o of t.animated)if(o.transform){const i=bt(o.transform),a=qr(i);if(a)return`形状"${o.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const o of[...t.static,...t.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,c]=i;if(typeof a!="number"||typeof c!="number"||!isFinite(a)||!isFinite(c))return`形状"${o.metadata?.id||"未知"}"顶点坐标无效`}}return null},al=r=>{const{base:e,height:t,shapes:n,transform:s}=r,o=bt(s),i=il(e,t,n,o);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},ll=r=>{if(r.slider){const{slider:e}=r;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},cl=r=>{if(!r)return null;if(r.boundingBox){const[e,t,n,s]=r.boundingBox;if(e>=n||t<=s)return"画板边界框配置无效:left < right 且 top > bottom"}return r.gridSize!==void 0&&r.gridSize<=0?"网格大小必须大于0":null},dl=r=>{const e=al({base:r.base,height:r.height,shapes:r.shapes,transform:r.transform});if(e)return e;const t=ll(r.animation);if(t)return{code:"INVALID_CONFIG",message:t,timestamp:new Date().toISOString()};const n=cl(r.boardConfig);return n?{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()}:r.autoCompleteThreshold!==void 0&&(r.autoCompleteThreshold<0||r.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class wr{validateNumber(e,t,n,s){if(typeof e!="number"||isNaN(e))return`${t}必须是有效的数字`;if(n!==void 0&&e<n)return`${t}不能小于${n}`;if(s!==void 0&&e>s)return`${t}不能大于${s}`}validateArray(e,t,n){if(!Array.isArray(e))return`${t}必须是数组`;if(n!==void 0&&e.length!==n)return`${t}必须是长度为${n}的数组`}validateString(e,t,n){if(typeof e!="string")return`${t}必须是字符串`;if(n!==void 0&&!n.includes(e))return`${t}必须是以下值之一: ${n.join(", ")}`}createValidationResult(e,t,n){return{isValid:e,errors:t?.filter(Boolean),warnings:n?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let t=0;t<e.length;t++){const n=e[t],s=this.validateArray(n,`顶点[${t}]`,2);if(s)return s;const[o,i]=n,a=this.validateNumber(o,`顶点[${t}].x`),c=this.validateNumber(i,`顶点[${t}].y`);if(a||c)return`${a||c} (顶点[${t}])`}}}const fl=(r,e,t)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:r,progress:e,config:t,distance:t.distance,distanceType:typeof t.distance,direction:t.direction,directionType:typeof t.direction,configType:typeof t,configKeys:Object.keys(t)});let n;t.direction==="horizontal"?n=[t.distance,0]:t.direction==="vertical"?n=[0,t.distance]:n=[t.direction[0]*t.distance,t.direction[1]*t.distance];const s=n[0]*e,o=n[1]*e;return process.env.NODE_ENV==="development"&&console.log("📐 [calculateTranslation] 计算结果:",{directionVector:n,offsetX:s,offsetY:o,firstVertexOriginal:r[0],firstVertexTransformed:[r[0][0]+s,r[0][1]+o]}),r.map(([i,a])=>[i+s,a+o])},ul=(r,e,t)=>{const n=t.center==="auto"?_r(r):t.center,[s,o]=n,i=t.endAngle-t.startAngle,a=t.direction==="clockwise"?-1:1,c=t.startAngle+i*e*a;return r.map(([l,d])=>{const u=l-s,y=d-o,m=Math.cos(c),h=Math.sin(c);return[s+u*m-y*h,o+u*h+y*m]})},ml=(r,e,t)=>{const n=t.center==="centroid"?_r(r):t.center,[s,o]=n,i=t.endScale-t.startScale,a=t.startScale+i*e;return r.map(([c,l])=>{const d=c-s,u=l-o;return[s+d*a,o+u*a]})},hl=(r,e=.95)=>r>=e;class gl extends wr{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,t,n){return fl(e,t,n)}validate(e){const t=[],n=[];if(typeof e.direction=="string"){const o=this.validateString(e.direction,"direction",["horizontal","vertical"]);o&&t.push(o)}else if(Array.isArray(e.direction)){const o=this.validateArray(e.direction,"direction",2);if(o)t.push(o);else{const[i,a]=e.direction,c=this.validateNumber(i,"direction[0]"),l=this.validateNumber(a,"direction[1]");c&&t.push(c),l&&t.push(l)}}else t.push("direction必须是字符串或数组");const s=this.validateNumber(e.distance,"distance",0);if(s&&t.push(s),e.startOffset!==void 0){const o=this.validateNumber(e.startOffset,"startOffset",0,1);o&&n.push(o)}if(Array.isArray(e.direction)){const[o,i]=e.direction;Math.sqrt(o*o+i*i)<.001&&n.push("方向向量长度过小,可能导致变换效果不明显")}return this.createValidationResult(t.length===0,t,n)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,t){const n=this.getDirectionVector(e),s=e.startOffset||0,o=Math.max(0,Math.min(1,t-s))/(1-s);return[n[0]*e.distance*o,n[1]*e.distance*o]}}class pl extends wr{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,t,n){return ul(e,t,n)}validate(e){const t=[],n=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)t.push(a);else{const[c,l]=e.center,d=this.validateNumber(c,"center[0]"),u=this.validateNumber(l,"center[1]");d&&t.push(d),u&&t.push(u)}}else t.push('center必须是"auto"或数组[x, y]');const s=this.validateNumber(e.startAngle,"startAngle");s&&t.push(s);const o=this.validateNumber(e.endAngle,"endAngle");if(o&&t.push(o),!s&&!o){const a=Math.abs(e.endAngle-e.startAngle);a<.001&&n.push("角度范围过小,可能导致变换效果不明显"),a>4*Math.PI&&n.push("角度范围过大,可能超过2圈")}const i=this.validateString(e.direction,"direction",["clockwise","counterclockwise","horizontal","vertical"]);return i&&t.push(i),this.createValidationResult(t.length===0,t,n)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=e[0][0],n=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,c]=e[i];t=Math.min(t,a),n=Math.max(n,a),s=Math.min(s,c),o=Math.max(o,c)}return{minX:t,maxX:n,minY:s,maxY:o}}getActualCenter(e,t){return t.center==="auto"?_r(e):t.center}calculateCurrentAngle(e,t){const n=e.endAngle-e.startAngle,s=e.direction==="clockwise"?-1:1;return e.startAngle+n*t*s}}class yl extends wr{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,t,n){return ml(e,t,n)}validate(e){const t=[],n=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)t.push(i);else{const[a,c]=e.center,l=this.validateNumber(a,"center[0]"),d=this.validateNumber(c,"center[1]");l&&t.push(l),d&&t.push(d)}}else t.push('center必须是"centroid"或数组[x, y]');const s=this.validateNumber(e.startScale,"startScale",.01);s&&t.push(s);const o=this.validateNumber(e.endScale,"endScale",.01);if(o&&t.push(o),!s&&!o){const i=e.endScale/e.startScale;Math.abs(e.endScale-e.startScale)<.01&&n.push("缩放比例变化过小,可能导致变换效果不明显"),i>10&&n.push("缩放比例过大,可能导致图形变形严重"),i<.1&&n.push("缩放比例过小,可能导致图形几乎不可见")}return typeof e.uniform!="boolean"?t.push("uniform必须是布尔值"):e.uniform||n.push("非均匀缩放可能导致图形变形"),this.createValidationResult(t.length===0,t,n)}getActualCenter(e,t){return t.center==="centroid"?_r(e):t.center}calculateCurrentScale(e,t){const n=e.endScale-e.startScale;return e.startScale+n*t}calculateSizeChange(e,t,n){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,c=this.calculateCurrentScale(t,n),l=(t.uniform,c),d=o*l,u=i*l,y=d*u;return{widthChange:(d-o)/o,heightChange:(u-i)/i,areaChange:(y-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=e[0][0],n=e[0][0],s=e[0][1],o=e[0][1];for(let i=1;i<e.length;i++){const[a,c]=e[i];t=Math.min(t,a),n=Math.max(n,a),s=Math.min(s,c),o=Math.max(o,c)}return{minX:t,maxX:n,minY:s,maxY:o}}}function Yn(r){let e=r.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(`无效的十六进制颜色格式: ${r}`);const t=parseInt(e.substring(0,2),16),n=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);if(isNaN(t)||isNaN(n)||isNaN(s))throw new Error(`无效的十六进制颜色值: ${r}`);return[t,n,s]}function bl(r,e,t){const n=a=>Math.max(0,Math.min(255,Math.round(a))),s=n(r).toString(16).padStart(2,"0"),o=n(e).toString(16).padStart(2,"0"),i=n(t).toString(16).padStart(2,"0");return`#${s}${o}${i}`.toUpperCase()}function Wr(r){const e=r.trim();if(e.startsWith("#"))return Yn(e);const t=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(t){const o=parseInt(t[1],10),i=parseInt(t[2],10),a=parseInt(t[3],10);if(o>=0&&o<=255&&i>=0&&i<=255&&a>=0&&a<=255)return[o,i,a]}const n={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(n[s])return s==="transparent"?[0,0,0]:Yn(n[s]);throw new Error(`无法解析的颜色格式: ${r}`)}function mr(r){try{return Wr(r),!0}catch{return!1}}function xl(r,e,t){if(t<=0)return r;if(t>=1)return e;try{const n=Wr(r),s=Wr(e),o=n[0]+(s[0]-n[0])*t,i=n[1]+(s[1]-n[1])*t,a=n[2]+(s[2]-n[2])*t;return bl(o,i,a)}catch(n){return console.warn("颜色插值失败,返回起始颜色:",n),r}}function Gs(r,e,t,n="linear"){let s=t;switch(n){case"ease-in":s=t*t;break;case"ease-out":s=1-(1-t)*(1-t);break;case"ease-in-out":s=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break;case"step":s=t>=1?1:0;break}return xl(r,e,s)}class vl extends wr{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,t,n){return e}validate(e){const t=[],n=[];if(!e.targetColor||typeof e.targetColor!="string"?t.push("targetColor 是必需的且必须是字符串"):mr(e.targetColor)||t.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?t.push("fromColor 必须是字符串"):mr(e.fromColor)||t.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const s=this.validateNumber(e.startAt,"startAt",0,1);s&&t.push(s)}if(e.endAt!==void 0){const s=this.validateNumber(e.endAt,"endAt",0,1);s&&t.push(s)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&t.push("startAt 必须小于 endAt"),e.easing!==void 0){const s=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);s&&t.push(s)}return e.targetColor&&e.fromColor,this.createValidationResult(t.length===0,t,n)}calculateCurrentColor(e,t,n){const s=t.fromColor||n,o=t.targetColor,i=this.calculateEffectiveProgress(e,t);return Gs(s,o,i,t.easing)}calculateEffectiveProgress(e,t){const n=t.startAt??0,s=t.endAt??1;return e<=n?0:e>=s?1:(e-n)/(s-n)}isActive(e,t){const n=t.startAt??0,s=t.endAt??1;return e>=n&&e<=s}}class _l{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[t,n]of this.executors)e[t]=n.getDisplayName();return e}validateConfig(e,t){const n=this.get(e);return n?n.validate(t):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,t,n,s){const o=this.get(e);if(!o)return console.error(`不支持变换类型: ${e}`),t;const i=o.validate(s);return i.isValid?o.execute(t,n,s):(console.error("配置验证失败:",i.errors),t)}executeTransforms(e,t,n){let s=t;for(const o of e){const i=this.get(o.type);if(!i){console.warn(`跳过不支持的变换类型: ${o.type}`);continue}s=i.execute(s,n,o.config)}return s}getDefaultConfig(e){return this.get(e)?.getDefaultConfig()}clear(){this.executors.clear()}size(){return this.executors.size}}let et=null;function zs(){return et||(et=new _l,et.register(new gl),et.register(new pl),et.register(new yl),et.register(new vl)),et}class Hr{static matchesShape(e,t,n){if(!t)return!n||this.extractGroupId(e)===n;if("targetGroup"in t&&t.targetGroup)return this.matchesSimpleGroup(e,t.targetGroup,t.metadataField);if("pattern"in t){if(t.strategy==="any")return this.matchesWithConfig(e,t);if(t.pattern)return this.matchesWithConfig(e,t)}return!1}static matchesSimpleGroup(e,t,n){const s=this.extractGroupId(e,n);if(!s)return!1;if(t.includes("*")){const o=t.replace(/\*/g,".*");return new RegExp(`^${o}$`).test(s)}return s===t}static matchesWithConfig(e,t){const n=this.extractGroupId(e,t.metadataField);if(!n)return!1;const s=t.pattern,o=t.strategy||"exact",i=t.caseSensitive||!1;switch(o){case"exact":return i?n===s:n.toLowerCase()===s.toLowerCase();case"wildcard":const a=s.replace(/\*/g,".*");return new RegExp(`^${a}$`,i?"":"i").test(n);case"regex":return(s instanceof RegExp?s:new RegExp(s,i?"":"i")).test(n);case"multiple":return(Array.isArray(s)?s:s.split(",")).some(d=>this.matchesSimpleGroup(e,d,t.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,t="rotationGroup"){if(!e)return;const n=t.split(".");let s=e;for(const o of n){if(s==null)return;s=s[o]}return typeof s=="string"?s:void 0}static validateConfig(e){const t=[],n=[];if(!e||typeof e!="object")return t.push("配置必须是对象"),{isValid:!1,errors:t,warnings:n};switch(e.pattern||t.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&t.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&t.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&t.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:t.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&t.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&t.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&n.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:t.length===0,errors:t,warnings:n}}static convertToGroupMatchConfig(e,t){if(!e)return;const n=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:n,metadataField:t}}}function wl(r,e,t){return!e&&!t?r.filter(n=>!n.targetGroup&&!n.groupMatch):r.filter(n=>{if(n.groupMatch&&t)return Hr.matchesShape(t,n.groupMatch);if(n.targetGroup){if(!e)return!1;if(n.targetGroup.includes("*")){const s=n.targetGroup.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return n.targetGroup===e}return!e})}class Al{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,t,n,s,o){const i=this.validate(n);if(!i.isValid)return console.error("复合变换配置验证失败:",i.errors),e;const a=this.filterTransformsByGroup(n.transforms,s,o);if(a.length===0)return e;switch(n.executionMode){case"sequential":return this.executeSequentially(e,t,a);case"parallel":return this.executeInParallel(e,t,a);default:return console.warn(`未知的执行模式: ${n.executionMode},使用顺序执行`),this.executeSequentially(e,t,a)}}validate(e){const t=[],n=[];if(!e||e.type!=="composite")return t.push("配置必须是复合变换类型"),this.createValidationResult(!1,t,n);if(!Array.isArray(e.transforms))return t.push("transforms必须是数组"),this.createValidationResult(!1,t,n);e.transforms.length===0&&n.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&t.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],c=this.validateSingleTransform(a,i);c&&t.push(c)}const s=e.transforms.map(i=>i.id).filter(Boolean),o=new Set(s);return s.length!==o.size&&n.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(t.length===0,t,n)}getTransformInfo(e){const t=e.transforms.map(s=>s.type),n=Array.from(new Set(e.transforms.map(s=>s.targetGroup).filter(s=>s!==void 0)));return{count:e.transforms.length,types:t,groups:n,executionMode:e.executionMode}}filterTransformsByGroup(e,t,n){return wl(e,t,n)}getTransformsForGroup(e,t,n){return this.filterTransformsByGroup(e.transforms,t,n)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,t,n){let s=e;for(const o of n){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,t,o.config)}return s}executeInParallel(e,t,n){if(n.length===0)return e;if(n.length===1)return this.executeSequentially(e,t,n);const s=[];for(const o of n){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 c=i.execute(e,t,o.config);s.push(c)}return s.length===0?e:this.calculateAverageVertices(s)}calculateAverageVertices(e){if(e.length===0)return[];const t=e[0].length;for(const s of e)if(s.length!==t)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const n=[];for(let s=0;s<t;s++){let o=0,i=0;for(const a of e)o+=a[s][0],i+=a[s][1];n.push([o/e.length,i/e.length])}return n}validateSingleTransform(e,t){if(!e||typeof e!="object")return`变换[${t}]必须是对象`;if(!e.type)return`变换[${t}]缺少type字段`;if(!e.config)return`变换[${t}]缺少config字段`;const n=this.registry.get(e.type);if(!n)return`变换[${t}]不支持的变换类型: ${e.type}`;const s=n.validate(e.config);if(!s.isValid)return`变换[${t}]配置验证失败: ${s.errors?.join(", ")}`}createValidationResult(e,t,n){return{isValid:e,errors:t?.filter(Boolean),warnings:n?.filter(Boolean)}}getDefaultRegistry(){return zs()}}class Rl{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new Al(this.registry)}executeShapeTransform(e,t,n){const s=this.getEffectiveTransform(e,n);return s?this.executeTransform(e.vertices,t,s,e.metadata):e.vertices}executeTransform(e,t,n,s){if(!n)return e;const o=Hr.extractGroupId(s,"rotationGroup");return $t(n)?this.executeSingleTransform(e,t,n,s,o):kt(n)?this.compositor.execute(e,t,n,o,s):(console.error("未知的变换类型:",n),e)}getEffectiveTransform(e,t){return e.transform?e.transform:t}getTransformInfo(e){return e?$t(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:kt(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?$t(e)?this.validateSingleTransform(e):kt(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?$t(e)?!1:kt(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,t,n){return e.map(s=>({...s,vertices:this.executeShapeTransform(s,t,n)}))}executeSingleTransform(e,t,n,s,o){if(!Hr.matchesShape(s,n.groupMatch||(n.targetGroup?{targetGroup:n.targetGroup}:void 0),o))return e;const a=this.registry.get(n.type);if(!a)return console.error(`不支持变换类型: ${n.type}`),e;const c=a.validate(n.config);return c.isValid?a.execute(e,t,n.config):(console.error("变换配置验证失败:",c.errors),e)}validateSingleTransform(e){const t=this.registry.get(e.type);return t?t.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return zs()}}const Sl=()=>{const r=b.useRef(null),e=b.useCallback((s,o,i=50)=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{o&&o(s)},i)},[]),t=b.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}%`},[]),n=b.useCallback(()=>(r.current&&(clearTimeout(r.current),r.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:hl,getProgressLabel:t,resetProgress:n}},Cl=()=>{const r=b.useCallback((t,n,s=.05)=>{let o=n;switch(t.key){case"ArrowRight":case"ArrowUp":o=Math.min(n+s,1);break;case"ArrowLeft":case"ArrowDown":o=Math.max(n-s,0);break;case"Home":o=0;break;case"End":o=1;break;case"PageUp":o=Math.min(n+s*2,1);break;case"PageDown":o=Math.max(n-s*2,0);break;case" ":case"Enter":o=n>=.95?0:1;break;case"Escape":o=0;break;default:return null}return t.preventDefault(),o},[]),e=b.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
9
+ `),[]);return{handleKeyDown:r,getNavigationInstructions:e}},Kn=ms.JSXGraph,El=r=>{const{base:e,height:t,unit:n,layoutDensity:s="default",boardHeight:o,shapes:i,transform:a,animation:c,boardConfig:l={},theme:d="light",className:u="",enableRigidityVerification:y=!1,enableKeyboardNavigation:m=!0,autoCompleteThreshold:h=.95,boardWidth:g,onTransformStart:p,onTransformChange:x,onTransformComplete:S,onError:R}=r,[C,_]=b.useState(0),[O,w]=b.useState(null),[F,$]=b.useState(0),[k,B]=b.useState(null),[W,M]=b.useState({width:800,height:560}),L=b.useMemo(()=>new Rl,[]),J=b.useMemo(()=>bt(a),[a]),j=b.useRef(null),he=b.useRef({}),oe=b.useRef(null),{handleProgressChange:z,shouldAutoComplete:de,resetProgress:ae}=Sl(),{handleKeyDown:ge,getNavigationInstructions:Ce}=Cl();b.useEffect(()=>{const N=()=>{if(oe.current){const{clientWidth:A}=oe.current;if(A>0){const H=l.boundingBox||[0,7,10,0],Z=H[2]-H[0],I=H[1]-H[3];let U;o?U=o:U=Math.round(A*(I/Z)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:H,ratio:`${I}:${Z}`,containerWidth:A,calculatedHeight:U,isCustomHeight:!!o}),M({width:A,height:U})}}};N(),window.addEventListener("resize",N);const E=new ResizeObserver(N);return oe.current&&E.observe(oe.current),()=>{window.removeEventListener("resize",N),E.disconnect()}},[l.boundingBox,o]);const We={width:g??`${W.width}px`,height:`${W.height}px`},Je=b.useCallback((N,E)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:N.metadata?.id,shapeType:N.type,progress:E,hasMetadata:!!N.metadata,hasDynamicAppearance:!!N.metadata?.dynamicAppearance,dynamicAppearance:N.metadata?.dynamicAppearance});const A=N.metadata?.dynamicAppearance,H=N.style||{};let Z;if(N.transform?.type==="fillcolor_set"&&N.transform.fillColorSet){const Q=N.transform.fillColorSet,{targetColor:ie,startAt:fe=0,endAt:pe=1,easing:Ee="linear",fromColor:Pe}=Q;if(mr(ie)&&(!Pe||mr(Pe))){let Te=E;E<fe?Te=0:E>pe?Te=1:Te=(E-fe)/(pe-fe);const Et=Pe||H.fillColor||"#FFFFFF";Z=Gs(Et,ie,Te,Ee),console.log("🎨 fillcolor_set applied:",{shapeId:N.metadata?.id,progress:E,effectiveProgress:Te,startColor:Et,targetColor:ie,resultColor:Z})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:ie,fromColor:Pe})}if(!A)return console.log("📝 No dynamicAppearance, returning base style"),Z?{...H,fillColor:Z}:H;const I=Q=>{if(!Q)return 1;const ie=Q.threshold??.5,fe=Q.startValue??0,pe=Q.endValue??1,Ee=Q.type??"step";if(Ee==="step")return E>=ie?pe:fe;if(Ee==="fade"){if(E<ie)return fe;{const Pe=Math.min((E-ie)/(1-ie),1);return fe+(pe-fe)*Pe}}return 1},U={...H};let Ze=!0;const Fe=I(A.visibility),Qe=I(A.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:N.metadata?.id,progress:E,visibilityValue:Fe,labelVisibilityValue:Qe,hasVisibility:!!A.visibility,hasLabelVisibility:!!A.labelVisibility}),A.visibility&&(U.fillOpacity===void 0&&(U.fillOpacity=1),U.fillOpacity*=Fe,Fe===0&&(U.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),U.strokeColor,Ze=Fe>0,console.log("👁️ Shape visibility:",{shapeId:N.metadata?.id,visible:Ze,visibilityValue:Fe})),A.labelVisibility){const Q=Qe>0;U.labelVisible=Q,console.log("🏷️ Label visibility:",{shapeId:N.metadata?.id,labelVisible:Q,labelVisibilityValue:Qe,hasLabel:!!N.metadata?.label})}if(A.opacity){const Q=A.opacity,ie=Q.startAt??0,fe=Q.endAt??1,pe=Q.from??1,Ee=Q.to??1,Pe=Q.type??"linear";let Te=pe;if(E<ie)Te=pe;else if(E>fe)Te=Ee;else{const Et=(E-ie)/(fe-ie);Te=pe+(Ee-pe)*Et}U.fillOpacity=Te}if(Z)U.fillColor=Z,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:N.metadata?.id,transformColor:Z});else if(A.color){const Q=A.color,ie=Q.startAt??0,fe=Q.endAt??1,pe=Q.from??U.fillColor,Ee=Q.to??U.fillColor,Pe=Q.type??"gradient";if(pe&&Ee)if(E<ie)U.fillColor=pe;else if(E>fe)U.fillColor=Ee;else{const Te=(E-ie)/(fe-ie);Pe==="gradient"?U.fillColor=Ee:U.fillColor=Te>=.5?Ee:pe}}return U.visible=Ze,U.labelVisible===void 0&&(U.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:N.metadata?.id,visible:U.visible,labelVisible:U.labelVisible,fillOpacity:U.fillOpacity,strokeWidth:U.strokeWidth}),U},[]),dt=b.useCallback((N,E,A=!1,H=0)=>{console.log("🎨 createShape called:",{shapeId:E.metadata?.id,shapeType:E.type,isStatic:A,progress:H,verticesLength:E.vertices?.length,hasMetadata:!!E.metadata,hasDynamicAppearance:!!E.metadata?.dynamicAppearance});const Z=E.type==="point"?1:2;if(!N||!E.vertices||E.vertices.length<Z)return console.warn(`⚠️ createShape: invalid board or vertices for ${E.type}`,{shapeId:E.metadata?.id,shapeType:E.type,verticesLength:E.vertices?.length,minVertices:Z}),null;const I=Je(E,H);let U;switch(E.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const Ze=I.labelVisible!==void 0?I.labelVisible:E.style?.labelVisible!==void 0?E.style.labelVisible:!1,Fe=E.metadata?.label||E.metadata?.id||"";U=N.create("polygon",E.vertices,{name:Fe,fillColor:I.fillColor!==void 0?I.fillColor:A?"#8ec5fc":"#6a5acd",fillOpacity:I.fillOpacity!==void 0?I.fillOpacity:A?.3:.7,strokeColor:I.strokeColor!==void 0?I.strokeColor:A?"#0074d9":"#4b0082",strokeWidth:I.strokeWidth!==void 0?I.strokeWidth:A?1:2,dash:I.dashStyle!==void 0?I.dashStyle:0,fixed:A,highlight:!A,withLabel:Ze,visible:I.visible!==void 0?I.visible:!0});break;case"circle":if(E.vertices.length>=2){const[Qe,Q]=E.vertices,ie=I.labelVisible!==void 0?I.labelVisible:E.style?.labelVisible!==void 0?E.style.labelVisible:!1,fe=E.metadata?.label||E.metadata?.id||"";U=N.create("circle",[Qe,Q],{name:fe,fillColor:I.fillColor!==void 0?I.fillColor:A?"#8ec5fc":"#6a5acd",fillOpacity:I.fillOpacity!==void 0?I.fillOpacity:A?.3:.7,strokeColor:I.strokeColor!==void 0?I.strokeColor:A?"#0074d9":"#4b0082",strokeWidth:I.strokeWidth!==void 0?I.strokeWidth:A?1:2,dash:I.dashStyle!==void 0?I.dashStyle:0,fixed:A,highlight:!A,withLabel:ie})}break;case"point":if(E.vertices.length>=1){const[Qe,Q]=E.vertices[0],ie=I.labelVisible!==void 0?I.labelVisible:E.style?.labelVisible!==void 0?E.style.labelVisible:!1,fe=E.metadata?.label||E.metadata?.id||"";U=N.create("point",[Qe,Q],{name:fe,withLabel:ie,fixed:A,size:4,strokeColor:I.strokeColor!==void 0?I.strokeColor:A?"#0074d9":"#4b0082",fillColor:I.fillColor!==void 0?I.fillColor:A?"#8ec5fc":"#6a5acd",visible:I.visible!==void 0?I.visible:!0,highlight:!A})}break;default:return console.warn(`Unsupported shape type: ${E.type}`),null}return console.log("✅ createShape finished:",{shapeId:E.metadata?.id,elementType:U?.type,elementName:U?.name,fillOpacity:U?.getAttribute?.("fillOpacity"),strokeWidth:U?.getAttribute?.("strokeWidth"),labelVisible:I.labelVisible,hasLabel:!!E.metadata?.label,withLabel:!!E.metadata?.label&&I.labelVisible}),U},[Je]);b.useEffect(()=>{if(!(e>0&&t>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:t,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:t>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,shapesAnimatedLength:r.shapes?.animated?.length,shapesStaticLength:r.shapes?.static?.length,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig});const E=dl(r);console.log("🔍 GeometryTransform: 验证结果 =",E),w(E),E&&R&&R(E)},[e,t,i,a,c,l,R,r]),b.useEffect(()=>{if(j.current){try{const N=l.boundingBox||[0,7,10,0],E=d==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",l.boundingBox),console.warn(" - Container dimensions:",W.width,"x",W.height),console.warn(" - Container actual dimensions:",j.current.clientWidth,"x",j.current.clientHeight);const A=Kn.initBoard(j.current,{boundingbox:N,keepaspectratio:l.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:l.showAxis??!0,grid:l.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),H=l.axisColor||(E?"#ffffff":"#000000"),Z=l.gridColor||(E?"#444444":"#dddddd");A.defaultAxes?.x&&A.defaultAxes.x.setAttribute({strokeColor:H}),A.defaultAxes?.y&&A.defaultAxes.y.setAttribute({strokeColor:H}),A.defaultGrid&&A.defaultGrid.setAttribute({strokeColor:Z}),B(A)}catch(N){const E={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:N,timestamp:new Date().toISOString()};w(E),R?.(E)}return()=>{if(k)try{Kn.freeBoard(k)}catch(N){N instanceof Error&&N.name!=="AbortError"&&console.warn("Board cleanup warning:",N)}}}},[W]),b.useEffect(()=>{if(k)try{k.suspendUpdate(),Object.values(he.current).forEach(N=>{if(N&&k.removeObject)try{k.removeObject(N)}catch{}}),he.current={},i.static.forEach((N,E)=>{const A=N.metadata?.id||`static-${E}`,H=dt(k,N,!0,0);H&&(he.current[A]=H)}),i.animated.forEach((N,E)=>{const A=N.metadata?.id||`animated-${E}`,H=dt(k,N,!1,0);H&&(he.current[A]=H)}),k.unsuspendUpdate(),p&&p()}catch(N){const E={code:"RENDER_ERROR",message:"图形渲染失败",details:N,timestamp:new Date().toISOString()};w(E),R?.(E)}},[k,i,e,t]),b.useEffect(()=>{if(k){k.suspendUpdate();try{i.animated.forEach((A,H)=>{const Z=A.metadata?.id||`animated-${H}`,I=he.current[Z];if(I){try{k.removeObject(I)}catch{}delete he.current[Z]}}),i.animated.forEach((A,H)=>{const Z=A.metadata?.id||`animated-${H}`,I=A.transform?{...A,transform:bt(A.transform)}:A,U=L.executeShapeTransform(I,C,J),Ze={...A,vertices:U,metadata:{...A.metadata,id:Z,transformSource:A.transform?"shape":"global"}},Fe=dt(k,Ze,!1,C);Fe&&(he.current[Z]=Fe)});const N=c.progressIndicator?.stages||1,E=Math.min(Math.floor(C*N),N-1);$(E)}catch(N){if(N instanceof Error&&N.name==="AbortError")return;console.warn("Transform update failed:",N)}finally{try{k.unsuspendUpdate()}catch{}}}},[k,C,i,a,c,dt,J,L]);const Ct=b.useCallback(N=>{const E=Array.isArray(N)?N[0]:N;_(E),z(E,A=>{x?.(A)}),de(E,h)&&(_(1),S?.())},[x,S,h,z,de]);b.useEffect(()=>{if(!m)return;const N=E=>{const A=ge(E,C);A!==null&&A!==C&&Ct(A)};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[m,C,Ct,ge]),b.useCallback(()=>{_(0),$(0),ae()},[ae]);const Er=b.useCallback(()=>{w(null),_(0),$(0),ae()},[ae]);return e>0&&t>0&&i?.animated?.length>0?O?f.jsx(Ne.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${u}`,children:f.jsx(Ne.CardBody,{"data-testid":"card-body",children:f.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[f.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:f.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),f.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),f.jsx("h3",{children:"几何变换演示加载失败"}),f.jsx("p",{children:O.message}),O.details&&f.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[f.jsx("summary",{children:"查看错误详情"}),f.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(O.details,null,2)})]}),f.jsx("div",{className:"geometry-transform__error-actions",children:f.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:Er,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):f.jsx(Ne.Card,{"data-testid":"card",className:`geometry-transform ${s==="compact"?"geometry-transform--compact":""} ${d==="dark"?"geometry-transform--dark":""} ${u}`,children:f.jsxs(Ne.CardBody,{"data-testid":"card-body",children:[f.jsxs("div",{ref:oe,className:"geometry-transform__board-container",children:[f.jsx("div",{ref:j,id:"geometry-board",className:"geometry-transform__board",style:We,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),f.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),f.jsxs("div",{className:"geometry-transform__controls",children:[f.jsx("div",{className:"geometry-transform__slider-group",children:f.jsx(Ne.Slider,{id:"transform-slider","data-testid":"slider",value:C,onChange:Ct,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),m&&f.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:f.jsxs("details",{children:[f.jsx("summary",{children:"键盘导航说明"}),f.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:Ce()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:t,shapesAnimatedLength:i?.animated?.length,error:O}),f.jsx(Ne.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${u}`,children:f.jsx(Ne.CardBody,{"data-testid":"card-body",children:f.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},Bs=b.memo(El,(r,e)=>{if(r.base!==e.base||r.height!==e.height||r.unit!==e.unit||r.theme!==e.theme||r.className!==e.className||r.enableRigidityVerification!==e.enableRigidityVerification||r.enableKeyboardNavigation!==e.enableKeyboardNavigation||r.autoCompleteThreshold!==e.autoCompleteThreshold||r.onTransformStart!==e.onTransformStart||r.onTransformChange!==e.onTransformChange||r.onTransformComplete!==e.onTransformComplete||r.onError!==e.onError)return!1;const t=JSON.stringify({shapes:r.shapes,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig}),n=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return t===n}),ln=Ft.create((r,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:t=>{r({internalValue:Math.max(0,Math.min(1,t))})},startDrag:t=>{r({isDragging:!0,dragState:{isDragging:!0,startIndex:t,currentIndex:t,direction:null}})},updateDrag:t=>{const{dragState:n}=e();let s=null;if(n.startIndex!==-1&&t!==-1){const o=Math.floor(n.startIndex/10),i=n.startIndex%10,a=Math.floor(t/10),c=t%10;a===o?s=c>i?"ltr":"rtl":c===i&&(s=a>o?"ttb":"btt")}r({dragState:{...n,currentIndex:t,direction:s}})},endDrag:()=>{r({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{r({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Vs=()=>ln(hs.useShallow(r=>({internalValue:r.internalValue,setInternalValue:r.setInternalValue}))),qs=()=>ln(hs.useShallow(r=>({isDragging:r.isDragging,dragState:r.dragState,startDrag:r.startDrag,updateDrag:r.updateDrag,endDrag:r.endDrag,resetDrag:r.resetDrag}))),Ws=r=>{const{totalCells:e,fillRatio:t,direction:n,rows:s,cols:o}=r,i=Math.round(e*t),a=[];if(n==="ltr")for(let c=0;c<i;c++)a.push(c);else for(let c=0;c<s;c++)for(let l=0;l<o;l++){const d=c*o+l;a.length<i&&a.push(d)}return{filledCells:a,filledCount:i,actualRatio:i/e}},Hs=(r,e,t,n)=>{const s=[];for(let o=0;o<r;o++)for(let i=0;i<e;i++){const a=o*e+i;s.push({index:a,row:o,col:i,filled:n.includes(a),x:i*t,y:o*t})}return s},Ys=(r,e,t,n,s)=>{if(r===-1||e===-1||!t)return[];const o=Math.floor(r/s),i=r%s,a=Math.floor(e/s),c=e%s,l=[];switch(t){case"ltr":for(let d=i;d<=c;d++)l.push(o*s+d);break;case"rtl":for(let d=i;d>=c;d--)l.push(o*s+d);break;case"ttb":for(let d=o;d<=a;d++)l.push(d*s+i);break;case"btt":for(let d=o;d>=a;d--)l.push(d*s+i);break}return l},Ks=(r,e)=>Math.max(0,Math.min(1,r.length/e)),or=r=>Math.max(0,Math.min(1,r)),Tl=r=>`${Math.round(r*100)}%`,Xs=({value:r,defaultValue:e=0,mode:t="readonly",onChange:n,rows:s=10,cols:o=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:c="#f3f4f6",strokeColor:l="#d1d5db",shadingDirection:d="ltr",hasShadow:u=!0,className:y=""})=>{const{internalValue:m,setInternalValue:h}=Vs(),{isDragging:g,dragState:p,startDrag:x,updateDrag:S,endDrag:R}=qs(),C=r!==void 0,_=C?or(r):m,[O,w]=b.useState(!1);!O&&!C&&(h(or(e)),w(!0));const F=b.useMemo(()=>{const de={totalCells:s*o,fillRatio:_,direction:d,rows:s,cols:o};return Ws(de).filledCells},[_,s,o,d]),$=b.useMemo(()=>Hs(s,o,i,F),[s,o,i,F]),k=b.useMemo(()=>!g||p.startIndex===-1||p.currentIndex===-1?[]:Ys(p.startIndex,p.currentIndex,p.direction,s,o),[g,p,s,o]),B=b.useCallback(z=>{if(t!=="edit")return;const de=or((z+1)/(s*o));C||h(de),n?.(de)},[t,s,o,C,n,h]),W=b.useCallback(z=>{t==="edit"&&x(z)},[t,x]),M=b.useCallback(z=>{t!=="edit"||!g||S(z)},[t,g,S]),L=b.useCallback(()=>{if(!(t!=="edit"||!g)){if(k.length>0){const z=Ks(k,s*o);C||h(z),n?.(z)}R()}},[t,g,k,s,o,C,n,h,R]),J=o*i,j=s*i,he=["hundred-chart-container",`hundred-chart--${t}`,u&&"hundred-chart--has-shadow",y].filter(Boolean).join(" "),oe=Math.round(_*100);return f.jsx("div",{className:he,"data-testid":"hundred-chart-container",children:f.jsx("svg",{width:J,height:j,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${oe}% 已填充`,children:$.map(z=>{const de=F.includes(z.index),ae=k.includes(z.index),ge=de||ae;return f.jsx("rect",{x:z.x,y:z.y,width:i,height:i,fill:ge?a:c,stroke:l,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":de,"data-drag":ae,"aria-label":`第${z.row+1}行第${z.col+1}列,${ge?"已填充":"未填充"}`,tabIndex:t==="edit"?0:-1,onClick:()=>B(z.index),onMouseDown:()=>W(z.index),onMouseEnter:()=>M(z.index),onMouseUp:L,onKeyDown:Ce=>{t==="edit"&&Ce.key==="Enter"&&B(z.index)}},z.index)})})})},Nl=b.createContext(void 0),Js=(r,e)=>b.useMemo(()=>{const t=r.scenes?.[e];return{...r,content:t?.content||r.content,layout:t?.layout||r.layout,renderer:t?.renderer||r.renderer}},[r,e]),Zs=({children:r,padding:e,shadow:t=!0,border:n=!0,theme:s="light",className:o=""})=>{const i=s==="dark"?"theme-dark":"",a=t?"with-shadow":"",c=n?"with-border":"",l=e?{"--mc-card-padding":e}:void 0;return f.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${c} ${o}`,style:l,"data-testid":"mathcard-v2-container",children:r})},Qs=({children:r,columns:e,gap:t,responsive:n=!0,className:s=""})=>{const o={"--grid-columns":e,"--grid-gap":t},i=n?"mathcard-v2-grid-responsive":"";return f.jsx("div",{style:o,className:`mathcard-v2-grid ${i} ${s}`,"data-testid":"grid-layout",children:r})},eo=({children:r,direction:e="vertical",gap:t,wrap:n=!1,className:s=""})=>{const o={"--flow-gap":t,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":n?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=n?"wrap":"";return f.jsx("div",{style:o,className:`mathcard-v2-flow ${i} ${a} ${s}`,"data-testid":"flow-layout",children:r})},to=({content:r,style:e={},onInteraction:t,className:n=""})=>f.jsx("div",{className:`mathcard-v2-text ${n}`,style:e,onClick:()=>t?.({type:"click",content:r}),"data-testid":"text-content",children:r}),ro=({parts:r,children:e,displayMode:t=!1,style:n={},className:s=""})=>f.jsx("div",{className:`mathcard-v2-formula ${s}`,style:n,"data-testid":"equation-render",children:f.jsx(zt,{parts:r,children:e,displayMode:t})});class $l extends b.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("MathGraph Error:",e,t.componentStack)}render(){return this.state.hasError?f.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[f.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),f.jsx("p",{className:"text-red-700",children:this.state.error?.message}),f.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 kl(r){if(typeof r!="string")throw new Error(`parseFunctionString expects a string, got ${typeof r}`);const e=r.trim(),t=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(t){const n=(t[3]||t[4]||"").trim();if(!n)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return Ol(n)}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 Ol(r){const e=r.trim();if(e==="progress * Math.PI"||e==="progress*Math.PI")return c=>c*Math.PI;if(e==="progress * Math.PI * 2"||e==="progress*Math.PI*2")return c=>c*Math.PI*2;const t=/^progress\s*\*\s*([0-9.]+)$/,n=e.match(t);if(n){const c=parseFloat(n[1]);return l=>l*c}const s=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,o=e.match(s);if(o){const c=parseFloat(o[1]);return l=>l*Math.PI*c}if(e.includes("Math.sin")&&e.includes("progress"))return c=>Math.sin(c*Math.PI);if(e.includes("Math.cos")&&e.includes("progress"))return c=>Math.cos(c*Math.PI);const i=/^([0-9.]+)$/,a=e.match(i);if(a){const c=parseFloat(a[1]);return()=>c}return e==="progress"?c=>c:e.includes("control.value")?(console.warn(`Expression contains control.value: ${e}. Will be handled by parseParamsWithControl.`),c=>c*Math.PI):(console.warn(`Unsupported expression pattern: "${e}". Using generic evaluator.`),c=>{let l=e.replace(/\bprogress\b/g,c.toString());return l=l.replace(/Math\.PI/g,Math.PI.toString()),l=l.replace(/Math\.E/g,Math.E.toString()),jl(l)})}function jl(r){const e=r.replace(/\s/g,"");function t(n){for(;n.includes("(");){const a=n.match(/\(([^()]+)\)/);if(!a)break;const c=t(a[1]);n=n.replace(a[0],c.toString())}const s=n.match(/(-?\d+\.?\d*)([*/])(-?\d+\.?\d*)/);if(s){const a=parseFloat(s[1]),c=s[2],l=parseFloat(s[3]),d=c==="*"?a*l:a/l;return n=n.replace(s[0],d.toString()),t(n)}const o=n.match(/(-?\d+\.?\d*)([+\-])(-?\d+\.?\d*)/);if(o){const a=parseFloat(o[1]),c=o[2],l=parseFloat(o[3]),d=c==="+"?a+l:a-l;return n=n.replace(o[0],d.toString()),t(n)}const i=parseFloat(n);if(isNaN(i))throw new Error(`Invalid expression: ${n}`);return i}return t(e)}function Ml(r){return typeof r=="string"&&(r.includes("=>")||r.includes("progress"))}function ye(r,e=0){return typeof r=="function"?r(e):r}function Or(r,e,t){switch(r.params.type){case"translate":{const n=r.params,s=typeof n.x=="function"&&t?function(){const i=t.Value();return n.x(i)}:ye(n.x,e),o=typeof n.y=="function"&&t?function(){const i=t.Value();return n.y(i)}:ye(n.y,e);return[s,o]}case"rotate":{const n=r.params,s=n.center||[0,0];return typeof n.angle=="function"&&t?[function(){const i=t.Value();return n.angle(i)},s[0],s[1]]:[ye(n.angle,e),s[0],s[1]]}case"scale":{const n=r.params,s=typeof n.scaleX=="function"&&t?function(){const i=t.Value();return n.scaleX(i)}:ye(n.scaleX,e),o=typeof n.scaleY=="function"&&t?function(){const i=t.Value();return n.scaleY(i)}:ye(n.scaleY,e);return[s,o]}case"reflect":{const n=r.params;if(n.line)return[n.line];if(n.point1&&n.point2)return[n.point1,n.point2];if(n.p1&&n.p2)return[n.p1,n.p2];throw new Error(`Reflect transform requires one of:
15
10
  1. line ID (string)
16
11
  2. point1 + point2 IDs
17
12
  3. p1 + p2 coordinates
18
- Received: ${JSON.stringify(n)}`)}case"shear":{const n=r.params,o=ve(n.shearX,e),s=ve(n.shearY,e);return[o,s]}case"generic":{const n=r.params;return[ve(n.a,e),ve(n.b,e),ve(n.c,e),ve(n.d,e),ve(n.e,e),ve(n.f,e),ve(n.g,e),ve(n.h,e),ve(n.i,e)]}case"matrix":{const n=r.params;if(!Array.isArray(n.matrix)||n.matrix.length!==3||!n.matrix.every(o=>Array.isArray(o)&&o.length===3))throw new Error("Matrix transform requires a 3x3 matrix array");return[n.matrix]}default:throw new Error(`Unsupported transform type: ${r.params.type}`)}}function Vl(r){const e={};return Object.entries(r).forEach(([t,n])=>{if(typeof n=="string"&&Bl(n))try{e[t]=Ul(n)}catch(o){console.warn(`Failed to parse function string for ${t}: ${n}`,o),e[t]=()=>0}else e[t]=n}),e}function Wl(r){if(!r||typeof r!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!r.id||typeof r.id!="string"||r.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(r.transforms)?r.transforms.forEach((t,n)=>{(!t.id||typeof t.id!="string")&&e.push(`Transform at index ${n} must have a valid id`),(!t.type||typeof t.type!="string")&&e.push(`Transform at index ${n} must have a valid type`),(!t.params||typeof t.params!="object")&&e.push(`Transform at index ${n} must have valid params`),Array.isArray(t.targetShapes)?t.targetShapes.length===0&&e.push("targetShapes must not be empty"):e.push(`Transform at index ${n} must have targetShapes array`)}):e.push("Config must have a transforms array"),{valid:e.length===0,errors:e.length>0?e:void 0}}const ro=vo.JSXGraph,ds=r=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!r.animation,animationId:r.animation?.id,hasControl:!!r.animation?.control,controlConfig:r.animation?.control,animationProgress:r.animationProgress});const e=b.useRef(null),[t,n]=b.useState(null),[,o]=b.useState({}),[s,i]=b.useState(!1),a=b.useRef({}),d=b.useRef({}),l=b.useRef(null),c=b.useRef({}),u=b.useCallback((m,h)=>{r.onShapeChange},[r.onShapeChange]),y=b.useCallback(m=>{r.onSelectionChange&&r.onSelectionChange(m?[m]:[])},[r.onSelectionChange]);return b.useEffect(()=>{if(e.current){try{const m=r.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",m),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const h=ro.initBoard(e.current,{boundingbox:m,axis:r.showAxis??!0,grid:r.showGrid??!0,showNavigation:!1,pan:{enabled:r.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",h.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",m),console.warn(" * 实际边界框:",h.getBoundingBox()),console.warn(" * 实际显示范围:",{left:h.getBoundingBox()[0],top:h.getBoundingBox()[1],right:h.getBoundingBox()[2],bottom:h.getBoundingBox()[3]})},100),n(h)}catch(m){console.error("JSXGraph initialization failed:",m)}return()=>{t&&ro.freeBoard(t)}}},[]),b.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!t,hasAnimation:!!r.animation,hasControl:!!r.animation?.control,animationId:r.animation?.id,controlType:r.animation?.control?.type,controlPosition:r.animation?.control?.position,controlRange:r.animation?.control?.range}),!t||!r.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!t+", control="+!!r.animation?.control),l.current){try{l.current.remove&&l.current.remove()}catch(h){console.warn("Failed to remove control:",h)}l.current=null}return}const m=r.animation.control;console.warn("✨ Creating Control Component:",{type:m.type,config:m,position:m.position,range:m.range});try{if(m.type==="slider"){const h=m.position[0]+(m.length||5);console.warn("📐 Slider creation parameters:",{startPoint:m.position,endPoint:[h,m.position[1]],values:[m.range[0],m.initial||0,m.range[1]],label:m.label,snapWidth:m.snapWidth||.01});const g=t.create("slider",[m.position,[h,m.position[1]],[m.range[0],m.initial||0,m.range[1]]],{name:m.label||"control",snapWidth:m.snapWidth||.01,withLabel:m.showLabel!==void 0?m.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});l.current=g,console.warn("✅ Slider created:",{id:g.id,name:g.name,initialValue:g.Value(),startPoint:m.position,endPoint:[h,m.position[1]],boundingBox:t.getBoundingBox(),visProp:g.visProp});const p=t.objectsList.map(C=>({id:C.id,type:C.elType,name:C.name,visible:C.visProp?.visible})),x=p.find(C=>C.id===g.id);if(console.warn("📊 Slider in board.objectsList:",!!x,x),console.warn("📊 All board objects count:",p.length),r.onAnimationChange){let C=!1;g.on("drag",()=>{if(C)return;C=!0;const E=(g.Value()-m.range[0])/(m.range[1]-m.range[0]);r.onAnimationChange?.(E),C=!1})}}else if(m.type==="glider"){const h=t.select(m.line,!0);if(h){const g=t.create("glider",[m.initial||0,0,h],{name:m.label||"control",snapWidth:m.snapWidth||.01});if(l.current=g,console.warn("✅ Glider created:",{id:g.id,name:g.name}),r.onAnimationChange){let p=!1;g.on("drag",()=>{if(p)return;p=!0;const x=g.Value();r.onAnimationChange?.(x),p=!1})}}else console.warn(`Reference line not found for glider: ${m.line}`)}}catch(h){console.error("Failed to create control component:",h)}return()=>{if(l.current){try{l.current.remove()}catch(h){console.warn("Failed to remove control on cleanup:",h)}l.current=null}}},[t,r.animation?.control]),b.useEffect(()=>{if(!t||!r.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:r.animation.id,transformCount:r.animation.transforms.length}),Object.values(a.current).forEach(g=>{try{g&&g.remove&&g.remove()}catch(p){console.warn("Failed to remove transform:",p)}}),a.current={};const m={},h=r.animationProgress??0;r.animation.transforms.forEach(g=>{try{let p,x;const C=g.usesControl||!1;if(l.current&&C){p=Fr(g,h,l.current),console.warn(`🔧 Creating transform ${g.id} (with dynamic params):`,{type:g.type,paramsTypes:p.map(E=>typeof E),targetShapes:g.targetShapes,controlValue:l.current.Value()}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});const S=()=>{if(!l.current)return;t.update();const E=l.current.Value();if(console.warn(`🎯 Slider drag - transform ${g.id} auto-updated (controlValue: ${E})`),r.onAnimationChange){const _=r.animation?.control?.range||[0,1],j=(E-_[0])/(_[1]-_[0]);r.onAnimationChange(j)}};l.current.on("drag",S),c.current[g.id]=S,console.warn(`🔗 Slider listener attached for transform ${g.id} (auto-update mode)`)}else p=Fr(g,h),console.warn(`🔧 Creating transform ${g.id} (with progress ${h}):`,{type:g.type,params:p,targetShapes:g.targetShapes}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});m[g.id]=x,console.warn(`📝 Transform ${g.id} created:`,{type:g.type,paramsTypes:p.map(S=>typeof S),transformMethods:Object.keys(x).filter(S=>typeof x[S]=="function")})}catch(p){console.error(`Failed to create transform ${g.id}:`,p)}}),a.current=m}catch(m){console.error("Transform setup failed:",m)}},[t,r.animation]),b.useEffect(()=>{if(!s||!t||!r.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${s}, board=${!!t}, animation=${!!r.animation}`);return}if(console.warn("✅ Attempting to bind transforms to shapes..."),console.warn(` Available shapes: ${Object.keys(d.current).length}`),console.warn(` Available transforms: ${Object.keys(a.current).length}`),Object.keys(d.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(([m,h])=>{const g=r.animation?.transforms.find(x=>x.id===m);if(!g)return;console.warn(`🔍 Binding transform ${m} (type: ${g.type}) to shapes:`,g.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(d.current));const p=g.targetShapes.map(x=>{const C=d.current[x];return C?console.warn(`✅ Found shape ${x}:`,C):(console.warn(`❌ Shape not found for transform binding: ${x}`),console.warn(" Available IDs:",Object.keys(d.current))),C}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",p.length),p.length>0)try{console.warn(`🔗 Attempting to bind transform ${m} to ${p.length} shapes`),h.bindTo(p),console.warn(`✅ Successfully bound transform ${m} to ${p.length} shapes`),console.warn(" Transform object:",h),console.warn(" Target elements:",p.map(x=>({id:x.id,name:x.name,type:x.elementClass})))}catch(x){console.error(`❌ Failed to bind transform ${m}:`,x),console.error(" Transform:",h),console.error(" TargetElements:",p)}else console.warn(`⚠️ No valid target elements for transform ${m}`)}),t.update(),console.warn("✅ All transforms bound and board updated")},[s,t,r.animation]),b.useEffect(()=>{if(!t||Object.keys(a.current).length===0)return;const m=r.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${m}`);try{Object.entries(a.current).forEach(([h,g])=>{const p=r.animation?.transforms.find(C=>C.id===h);if(!p)return;const x=Fr(p,m);console.warn(`🔄 Attempting to update transform ${h} with params:`,x),g.update?(console.warn(" Using transform.update(params)"),g.update(x)):g.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),g.setMatrix(t,p.type,x)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(g).filter(C=>typeof g[C]=="function")))}),t.update()}catch(h){console.error("Transform update failed:",h)}},[t,r.animationProgress]),b.useEffect(()=>{if(t)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:r.shapes.length,shapes:r.shapes.map(g=>({id:g.id,type:g.type,hasVertices:"vertices"in g,verticesCount:"vertices"in g&&g.vertices?g.vertices.length:"undefined",hasPosition:"position"in g,hasGeometryRef:"geometryRef"in g,geometryRef:"geometryRef"in g?g.geometryRef:void 0}))}),t.suspendUpdate(),[...t.objectsList].forEach(g=>{t.removeObject(g)});const h={};d.current={},r.shapes.forEach(g=>{if(g.type==="point")try{const p=Pr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create point shape ${g.id}:`,p)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",t.objectsList.map(g=>({id:g.id,name:g.name,type:g.elementClass}))),r.shapes.forEach(g=>{if(g.type==="line"||g.type==="circle"||g.type==="polygon")try{const p=Pr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create shape ${g.id}:`,p)}}),console.warn("📝 Starting phase 3: creating text labels"),r.shapes.forEach(g=>{if(g.type==="text")try{const p=Pr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create text ${g.id}:`,p)}}),o(h),d.current=h,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(h).length} shapes created`),t.unsuspendUpdate()}catch(m){console.error("Shape rendering failed:",m)}},[t,r.shapes,r.mode,u,y]),b.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),l.current&&Object.entries(c.current).forEach(([m,h])=>{try{l.current.off("drag",h),console.warn(` Removed drag listener for transform ${m}`)}catch(g){console.warn(`Failed to remove drag listener for ${m}:`,g)}}),c.current={},Object.values(a.current).forEach(m=>{try{m&&m.remove&&m.remove()}catch(h){console.warn("Failed to remove transform during cleanup:",h)}}),a.current={},d.current={},i(!1),console.warn("✅ Cleanup complete")},[]),f.jsx("div",{ref:e,className:"w-full h-full"})};function Pr(r,e,t,n,o){const s=t==="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 l,c;if(e.position.x!==void 0&&e.position.y!==void 0)l=e.position.x,c=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)l=e.position[0],c=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const u=r.create("point",[l,c],{id:e.id,name:e.name||"",withLabel:e.withLabel??!!e.name,fixed:!s,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:u.id,pointName:u.name,hasIdProperty:"id"in u}),s&&(r.on("drag",()=>{n(e.id,{x:u.X(),y:u.Y()})}),r.on("down",()=>{o(e.id)})),u}catch(l){return console.error(`Failed to create point ${e.id}:`,l),null}case"line":const i=er(e.start,r),a=er(e.end,r);if(i&&a)try{const l=r.create("line",[i,a],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",dash:e.dash??0,fixed:!s,visible:e.visible??!0,straightFirst:!1,straightLast:!1});return s&&r.on("down",()=>{o(e.id)}),l}catch(l){return console.error(`Failed to create line ${e.id}:`,l),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 d=er(e.center,r);if(d){let l;if(e.through){const c=er(e.through,r);c&&(l=r.create("circle",[d,c],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!s,visible:e.visible??!0}))}else e.radius!==void 0&&(l=r.create("circle",[d,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:!s,visible:e.visible??!0}));return l&&s&&r.on("down",()=>{o(e.id)}),l}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 l=e.vertices.map((c,u)=>{const y=e.verticesConfig?e.verticesConfig[u]:null;return ql(c,r,y)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,l),console.warn(`🔧 Polygon ${e.id} vertices types:`,l.map(c=>({type:typeof c,isArray:Array.isArray(c),value:c}))),l.every(c=>c!==null)){const c={strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"lightblue",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!s,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 y={};e.verticesConfig.withLabel!==void 0?y.withLabel=e.verticesConfig.withLabel:y.withLabel=!0;const m={};let h=!1;e.verticesConfig.offset&&(m.offset=e.verticesConfig.offset,h=!0),e.verticesConfig.fontSize&&(m.fontSize=e.verticesConfig.fontSize,h=!0),e.verticesConfig.color&&(m.color=e.verticesConfig.color,h=!0),e.verticesConfig.anchorX&&(m.anchorX=e.verticesConfig.anchorX,h=!0),e.verticesConfig.anchorY&&(m.anchorY=e.verticesConfig.anchorY,h=!0),h&&(y.label=m),c.vertices=y,console.warn("🔧 Using JSXGraph vertices config:",y)}else c.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",c);const u=r.create("polygon",l,c);return console.warn("🔧 Polygon created:",u),console.warn("🔧 Polygon vertices:",u.vertices),console.warn("🔧 Polygon vertices names:",u.vertices?u.vertices.map(y=>y.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",u.vertices?u.vertices.map(y=>y.hasLabel?y.label:"no label"):"no vertices"),s&&r.on("down",()=>{o(e.id)}),u}else console.warn(`Cannot create polygon ${e.id}: some vertices are missing`,{vertices:e.vertices,resolvedVertices:l})}catch(l){console.error(`Failed to create polygon ${e.id}:`,l)}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)}),r.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(l){console.error(`Failed to create text ${e.id}:`,l)}break}return null}function er(r,e){if(Array.isArray(r)&&r.length>=2)return r;if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return[r.x,r.y];if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const n=e.objects[r.$ref];if(n)return n}const t=e.objectsList.find(n=>n.id===r.$ref);if(t)return console.warn(`✅ Found referenced point ${r.$ref}:`,t),t;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(t){console.warn(`Failed to resolve point reference ${r.$ref}:`,t)}}return null}function ql(r,e,t){if(Array.isArray(r)&&r.length>=2){if(t&&t.name){const n=e.create("point",r,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,r),n}return r}if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r){const n=[r.x,r.y];if(t&&t.name){const o=e.create("point",n,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,n),o}return n}if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const o=e.objects[r.$ref];if(o)return t&&t.name&&o.setName&&(o.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),o}const n=e.objectsList.find(o=>o.id===r.$ref);if(n)return console.warn(`✅ Found referenced point ${r.$ref}:`,n),t&&t.name&&n.setName&&(n.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),n;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${r.$ref}:`,n)}}return null}function mn(r,e={}){const{padding:t=.2,margin:n=1,minSize:o=4}=e,s=[];if(r.forEach(w=>{switch(w.type){case"point":s.push(w.position);break;case"line":const P=ht(w.start,r),$=ht(w.end,r);P&&s.push(P),$&&s.push($);break;case"circle":const O=ht(w.center,r);if(O&&(s.push(O),w.radius!==void 0&&s.push({x:O.x+w.radius,y:O.y},{x:O.x-w.radius,y:O.y},{x:O.x,y:O.y+w.radius},{x:O.x,y:O.y-w.radius})),w.through){const I=ht(w.through,r);I&&s.push(I)}break;case"polygon":w.vertices.forEach(I=>{const G=ht(I,r);G&&s.push(G)});break;case"text":s.push(w.position);const Y=w.content.length*(w.fontSize||14)/20,q=(w.fontSize||14)/10;s.push({x:w.position.x+Y,y:w.position.y},{x:w.position.x-Y,y:w.position.y},{x:w.position.x,y:w.position.y+q},{x:w.position.x,y:w.position.y-q});break}}),s.length===0)return{boundingBox:[-o,o,o,-o],center:{x:0,y:0},width:o*2,height:o*2};const i=Math.min(...s.map(w=>w.x)),a=Math.max(...s.map(w=>w.x)),d=Math.min(...s.map(w=>w.y)),l=Math.max(...s.map(w=>w.y)),c=(i+a)/2,u=(d+l)/2;let y=Math.max(a-i,o),m=Math.max(l-d,o);const h=800/500,g=y/m;Math.abs(g-h)>.1&&(g>h?m=y/h:y=m*h);const p=y*(1+t)+n*2,x=m*(1+t)+n*2,C=c-p/2,S=u+x/2,E=c+p/2,_=u-x/2,j=[C,S,E,_];if(process.env.NODE_ENV==="development"){const P=s.map($=>({x:$.x,y:$.y,insideX:$.x>=C&&$.x<=E,insideY:$.y<=S&&$.y>=_,inside:$.x>=C&&$.x<=E&&$.y<=S&&$.y>=_})).filter($=>!$.inside);P.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:j,outsidePoints:P.slice(0,5),totalOutside:P.length})}return{boundingBox:j,center:{x:c,y:u},width:p,height:x}}function ht(r,e=[]){if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return{x:r.x,y:r.y};if("$ref"in r){const t=e.find(n=>n.id===r.$ref&&n.type==="point");if(t)return t.position}}return null}function Yl(r,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const t=[];if(r.forEach(o=>{switch(o.type){case"point":t.push({x:o.position.x,y:o.position.y,source:`point:${o.id}`});break;case"text":t.push({x:o.position.x,y:o.position.y,source:`text:${o.id}`});const s=o.content.length*(o.fontSize||14)/20,i=(o.fontSize||14)/10;t.push({x:o.position.x+s,y:o.position.y,source:`text:${o.id}:right`},{x:o.position.x-s,y:o.position.y,source:`text:${o.id}:left`},{x:o.position.x,y:o.position.y+i,source:`text:${o.id}:top`},{x:o.position.x,y:o.position.y-i,source:`text:${o.id}:bottom`});break;case"polygon":o.vertices.forEach((a,d)=>{const l=ht(a,r);l&&t.push({x:l.x,y:l.y,source:`polygon:${o.id}:vertex${d}`})});break}}),console.log("📊 收集到的坐标点:",t),t.length>0){const o=Math.min(...t.map(d=>d.x)),s=Math.max(...t.map(d=>d.x)),i=Math.min(...t.map(d=>d.y)),a=Math.max(...t.map(d=>d.y));console.log("📐 原始包围盒:",{minX:o,maxX:s,minY:i,maxY:a,width:s-o,height:a-i})}const n=mn(r,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",n),console.groupEnd(),n}const Tr=r=>{const{shapes:e,mode:t,onShapeChange:n,onSelectionChange:o,width:s=600,height:i=400,showGrid:a=!0,showAxis:d=!0,className:l="",boundingBox:c,autoBoundingBox:u=!0,boundingBoxOptions:y,animation:m,animationProgress:h,onAnimationChange:g,showAnimationControls:p}=r,x=b.useMemo(()=>{if(c)return c;if(u&&e.length>0)try{process.env.NODE_ENV==="development"&&Yl(e,"MathGraph Auto BoundingBox");const S=mn(e,y);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",S.boundingBox),console.log(" - Center:",S.center),console.log(" - Width:",S.width),console.log(" - Height:",S.height),console.log(" - Options used:",y),S.boundingBox}catch(S){return console.warn("Failed to calculate auto bounding box, using default:",S),[-10,10,10,-10]}return[-10,10,10,-10]},[c,u,e,y]),C=b.useMemo(()=>({width:typeof s=="number"?`${s}px`:s,height:typeof i=="number"?`${i}px`:i}),[s,i]);return f.jsx(Ll,{children:f.jsx("div",{className:`border border-gray-200 rounded-lg bg-white shadow-sm overflow-hidden ${l}`,style:C,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:f.jsx(ds,{shapes:e,mode:t,onShapeChange:n,onSelectionChange:o,boundingBox:x,showGrid:a,showAxis:d,animation:m,animationProgress:h,onAnimationChange:g})})})},fs=({shapes:r,width:e,height:t,showGrid:n=!0,showAxis:o=!0,boundingBox:s,autoBoundingBox:i,onShapeChange:a,className:d="",animation:l,animationProgress:c,showAnimationControls:u,onAnimationChange:y})=>{const m=b.useRef(null),[h,g]=b.useState({width:600,height:400});b.useEffect(()=>{const x=()=>{if(m.current){const{clientWidth:S,clientHeight:E}=m.current;S>0&&E>0&&g({width:S,height:E})}};x(),window.addEventListener("resize",x);const C=new ResizeObserver(x);return m.current&&C.observe(m.current),()=>{window.removeEventListener("resize",x),C.disconnect()}},[]);const p={width:e?typeof e=="string"?e:`${e}px`:"100%",height:t?typeof t=="string"?t:`${t}px`:"100%"};return f.jsx("div",{ref:m,className:`mathcard-v2-graph ${d}`,style:p,children:f.jsx(Tr,{shapes:r,width:h.width,height:h.height,showGrid:n,showAxis:o,boundingBox:s,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:l,animationProgress:c,showAnimationControls:u,onAnimationChange:y})})},hn=({config:r,onTransformChange:e,onTransformComplete:t,onError:n,layoutDensity:o,boardHeight:s,boardWidth:i,className:a=""})=>{const d=o??r.ui?.layoutDensity??"default",l=s??r.ui?.boardHeight??300,c=i??r.ui?.boardWidth??400,u=h=>{e?.(h)},y=()=>{t?.()},m=h=>{n?.(h)};return console.error("🔍 GeometryTransformContent: config =",{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,shapesAnimatedLength:r.shapes?.animated?.length,shapesStaticLength:r.shapes?.static?.length,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,boardConfigKeys:r.boardConfig?Object.keys(r.boardConfig):[],boardConfigBoundingBox:r.boardConfig?.boundingBox,boardConfigOriginX:r.boardConfig?.originX,boardConfigOriginY:r.boardConfig?.originY,configKeys:Object.keys(r)}),f.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:f.jsx(Xo,{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,onTransformChange:u,onTransformComplete:y,onError:m,layoutDensity:d,boardHeight:l,boardWidth:c,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})},Hl=({headers:r,values:e,colors:t={}})=>{const{headerBg:n="#f1f5f9",valueBg:o="#ffffff",borderColor:s="#e2e8f0"}=t;return r.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):f.jsxs("div",{className:"place-value-chart",style:{display:"inline-block",border:`1px solid ${s}`,borderRadius:"8px",overflow:"hidden",fontFamily:"system-ui, sans-serif",fontSize:"14px",lineHeight:"1.4"},children:[f.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${s}`},children:r.map((i,a)=>f.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:n,fontWeight:"600",textAlign:"center",borderRight:a<r.length-1?`1px solid ${s}`:"none",color:"#1e293b"},children:i},a))}),f.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>f.jsx("div",{style:{flex:1,padding:"12px",backgroundColor:o,textAlign:"center",borderRight:a<e.length-1?`1px solid ${s}`:"none",color:"#0f172a",fontSize:"16px",fontWeight:"500"},children:i},a))})]})},us=({content:r,onInteraction:e})=>{const t=(n,o)=>{if(n.enabled===!1)return null;const s=`${n.type}-${o}`,i=a=>{e?.(s,a)};switch(n.type){case"text":return f.jsx(ls,{content:n.content,style:n.style,onInteraction:i},s);case"formula":const a=n;return f.jsx(cs,{parts:a.parts||[],displayMode:a.displayMode,style:n.style},s);case"graph":const d=n;return f.jsx(fs,{shapes:d.shapes||[],width:d.width,height:d.height,showGrid:d.showGrid,showAxis:d.showAxis,boundingBox:d.boardConfig?.boundingBox,autoBoundingBox:!d.boardConfig?.boundingBox,animation:d.animation,animationProgress:d.animationProgress,showAnimationControls:d.showAnimationControls,onAnimationChange:d.onAnimationChange},s);case"hundredGrid":const l=n;return f.jsx(ns,{...l.props},s);case"placeValueChart":const c=n;return f.jsx(Hl,{...c.props},s);case"geometryTransform":const u=n;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:u.metadata,config:u.metadata?.config,hasConfig:!!u.metadata?.config,configKeys:u.metadata?.config?Object.keys(u.metadata.config):[],configShapes:u.metadata?.config?.shapes,configShapesAnimatedLength:u.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:u.metadata?.config?.shapes?.static?.length,configBase:u.metadata?.config?.base,configHeight:u.metadata?.config?.height,configUnit:u.metadata?.config?.unit,configTransform:u.metadata?.config?.transform}),f.jsx(hn,{config:u.metadata.config,onTransformChange:y=>i({type:"transformChange",progress:y}),onTransformComplete:()=>i({type:"transformComplete"}),onError:y=>i({type:"error",error:y})},s);default:return f.jsx("div",{onClick:()=>i({type:"click"}),children:n.content},s)}};return f.jsx(f.Fragment,{children:r.map(t)})},Re=({data:r,scene:e="question",layout:t={type:"card"},renderer:n={mode:"default"},theme:o="light",onContentInteraction:s,className:i="",children:a})=>{const d=os(r,e),l={data:d,scene:e,layout:d.layout||t,renderer:d.renderer||n,theme:o,onContentInteraction:s},c=d.layout||t,u=(()=>{switch(c.type){case"grid":return is;case"flow":return as;default:return ss}})(),y=(()=>{const m={className:i,theme:o,"data-testid":"mathcard-v2-container"};switch(c.type){case"grid":return{...m,columns:c.columns||2,gap:c.gap||"16px",responsive:c.responsive!==!1};case"flow":return{...m,direction:c.direction||"vertical",gap:c.gap||"16px",wrap:c.wrap!==!1};default:return{...m,padding:c.padding||"24px",shadow:c.shadow!==!1,border:c.border!==!1}}})();return f.jsx(Dl.Provider,{value:l,children:f.jsx(u,{...y,children:a||f.jsx(us,{content:d.content,layout:d.layout||t,onInteraction:s})})})};Re.CardLayout=ss;Re.GridLayout=is;Re.FlowLayout=as;Re.TextContent=ls;Re.FormulaContent=cs;Re.GraphContent=fs;Re.GeometryTransformContent=hn;Re.ContentRenderer=us;const ms=r=>{const{ixlConfig:e,enableIXLStyle:t,isMobile:n}=r,o=b.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),s=b.useMemo(()=>{if(e.tagColor)return e.tagColor;const c={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return c[e.type]||c.remember},[e.tagColor,e.type]),i=b.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=b.useMemo(()=>{if(!t)return{};const c={backgroundColor:s,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return n?Object.assign(c,{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(c,{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)"}),c},[t,s,i,n]),d=b.useMemo(()=>!t||n?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[t,n]);return{ixlClassName:b.useMemo(()=>{if(!t)return"";const c=["ixl-styled"];return c.push(`ixl-type-${e.type}`),n?c.push("ixl-mobile-layout"):c.push("ixl-desktop-layout"),c.join(" ")},[t,e.type,n]),tagStyle:a,contentStyle:d,tagText:o,tagColor:s,tagTextColor:i}},Kl=(r,e)=>{let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>{r(...n)},e)}},hs=(r={})=>{const e=typeof r=="number"?r:r.breakpoint||768,t=typeof r=="number"?!0:r.enabled!==!1,[n,o]=b.useState(()=>typeof window<"u"?window.innerWidth:1024),[s,i]=b.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=b.useRef(new Set),d=b.useCallback(()=>{if(typeof window>"u")return;const y=window.innerWidth,m=y<e;o(y),i(m),a.current.forEach(h=>{try{h()}catch(g){console.error("Error in resize listener:",g)}})},[e]),l=b.useCallback(Kl(d,150),[d]);b.useEffect(()=>{if(!(!t||typeof window>"u"))return d(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l)}},[t,l,d]);const c=b.useCallback(y=>(a.current.add(y),()=>{a.current.delete(y)}),[]),u=b.useCallback(y=>{a.current.delete(y)},[]);return{isMobile:s,viewportWidth:n,addResizeListener:c,removeResizeListener:u}},wt=({cardProps:r,ixlConfig:e,enableIXLStyle:t=!0,wrapperMode:n="mathcard",mobileBreakpoint:o=768,className:s="",style:i,children:a,onResponsiveChange:d})=>{const l=hs(o),c=ms({ixlConfig:e,enableIXLStyle:t,isMobile:l.isMobile});b.useEffect(()=>{d?.(l.isMobile)},[l.isMobile,d]);const u=b.useMemo(()=>{const h=["ixl-style-card-container"];return t&&h.push(c.ixlClassName),s&&h.push(s),l.isMobile?h.push("ixl-mobile"):h.push("ixl-desktop"),h.join(" ")},[t,c.ixlClassName,s,l.isMobile]),y=b.useMemo(()=>{const h={...i};return t&&!l.isMobile?{...h,paddingLeft:c.contentStyle.paddingLeft}:h},[t,l.isMobile,c.contentStyle,i]),m=b.useMemo(()=>{if(n!=="mathcard"||!r)return"";const h=[r.className||""];return t&&h.push("ixl-adjusted"),h.filter(Boolean).join(" ")},[n,r?.className,t]);return f.jsxs("div",{className:u,style:y,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":t,"data-responsive-mode":l.isMobile?"mobile":"desktop",children:[t&&e.showTag!==!1&&f.jsx("div",{className:"ixl-tag",style:c.tagStyle,"data-testid":"ixl-tag",children:f.jsx("span",{className:"ixl-tag-text",children:c.tagText})}),n==="mathcard"&&r?f.jsx(Re,{...r,className:m}):a]})};wt.displayName="IXLStyleCard";const Xl={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},Jl={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},Zl={remember:"速记",review:"回顾",solve:"解答"},Ql=({grades:r,onGradeSelect:e,selectedGrade:t})=>f.jsxs("div",{className:"grade-navigation",children:[f.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),f.jsx("div",{className:"grade-navigation__grid",children:r.map(n=>f.jsxs("div",{className:`grade-card ${t===n.id?"grade-card--selected":""}`,style:{borderLeftColor:n.color},onClick:()=>e?.(n.id),children:[f.jsx("div",{className:"grade-card__level",children:n.level}),f.jsx("div",{className:"grade-card__name",children:n.name}),f.jsx("div",{className:"grade-card__description",children:n.description})]},n.id))})]}),gs=({abilities:r,width:e=400,height:t=400})=>{const n=()=>r.length===0?"":r.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*r.indexOf(i)/r.length,d=i.score/i.maxScore*40+10,l=50+d*Math.sin(a),c=50-d*Math.cos(a);return`${l},${c}`}).join(" "),o=i=>{const a=Math.PI*2*i/Math.max(r.length,1),d=50+40*Math.sin(a),l=50-40*Math.cos(a);return{x2:d,y2:l}},s=i=>{const a=Math.PI*2*i/Math.max(r.length,1),d=50+45*Math.sin(a),l=50-45*Math.cos(a);let c="middle";return a>Math.PI*.25&&a<Math.PI*.75&&(c="start"),a>Math.PI*1.25&&a<Math.PI*1.75&&(c="end"),{x:d,y:l,textAnchor:c}};return f.jsxs("svg",{"data-testid":"radar-chart",width:e,height:t,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[f.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),r.map((i,a)=>{const{x2:d,y2:l}=o(a);return f.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:d,y2:l,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),r.length>2&&f.jsx("polygon",{"data-testid":"radar-polygon",points:n(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),r.map((i,a)=>{let d,l;if(i.svgPoint)d=i.svgPoint.x,l=i.svgPoint.y;else{const c=Math.PI*2*a/r.length,u=i.score/i.maxScore*40+10;d=50+u*Math.sin(c),l=50-u*Math.cos(c)}return f.jsx("circle",{"data-testid":"data-point",cx:d,cy:l,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),r.map((i,a)=>{const{x:d,y:l,textAnchor:c}=s(a);return f.jsx("text",{x:d,y:l,textAnchor:c,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},no={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 ec{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),no):(await le.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 no}}static async submitFeedback(e){try{await le.post(`${this.API_BASE_URL}/feedback`,e)}catch(t){throw console.error("Failed to submit feedback:",t),new Error("提交反馈失败")}}}const tc=Ut.create((r,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){r({loading:!0,error:null});try{const t=await ec.fetchRadarAbilityData();r({data:t,loading:!1})}catch(t){const n=t instanceof Error?t.message:"获取数据失败";r({error:n,loading:!1})}}},setData:t=>{r({data:t,error:null,loading:!1})},setError:t=>{r({error:t,loading:!1})},reset:()=>{r({data:null,loading:!1,error:null})}})),ps=({ability:r})=>{const e=r.score/r.maxScore*100;return f.jsxs("div",{className:"ability-progress-bar-item","data-ability":r.name,"data-testid":"progress-bar-container",children:[f.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[f.jsx("span",{className:"text-gray-700 font-medium",children:r.name}),f.jsxs("span",{className:"text-gray-600",children:[r.score,"/",r.maxScore]})]}),f.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:f.jsx("div",{className:`${r.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":r.score,"aria-valuemin":0,"aria-valuemax":r.maxScore,"aria-label":`${r.name} progress: ${r.score} out of ${r.maxScore}`})})]})},ys=({generalRecommendation:r})=>f.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),f.jsxs("div",{className:"ml-3",children:[f.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),f.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:r})]})]})}),bs=({ability:r,customLinkTexts:e={}})=>{const t=n=>{const o={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[n]||o[n]||"开始挑战"};return f.jsx(ke.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":r.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:f.jsx(ke.CardBody,{className:"p-5",children:f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[r.name,": 专项提高"]}),f.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:r.recommendation}),f.jsx(ke.Button,{as:"a",href:r.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:f.jsx(Vr.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${r.name}专项提高页面`,children:t(r.name)})]})})})},rc="_dashboardLayout_10wqn_5",nc="_upperSection_10wqn_19",oc="_lowerSection_10wqn_33",sc="_radarChartArea_10wqn_51",tr={dashboardLayout:rc,upperSection:nc,lowerSection:oc,radarChartArea:sc},ic=()=>{const{data:r,loading:e,error:t,fetchData:n}=tc();return b.useEffect(()=>{n()},[n]),e?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),f.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):t?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[f.jsx("div",{className:"text-red-500 mb-4",children:f.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),f.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),f.jsx("p",{className:"text-gray-600 mb-4",children:t}),f.jsx("button",{onClick:n,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:"重试"})]}):r?f.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:[f.jsxs("div",{className:"flex justify-between items-center mb-6",children:[f.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),f.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${r.overallRating}`,children:["综合评级: ",r.overallRating]})]}),f.jsxs("div",{className:tr.dashboardLayout,children:[f.jsxs("div",{className:tr.upperSection,children:[f.jsx("div",{className:tr.radarChartArea,children:f.jsx(gs,{abilities:r.abilities})}),f.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:r.abilities.map(o=>f.jsx(ps,{ability:o},o.name))})]}),f.jsxs("div",{className:tr.lowerSection,children:[f.jsx(ys,{generalRecommendation:r.generalRecommendation}),f.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:r.abilities.map(o=>f.jsx(bs,{ability:o},o.name))})]})]})]}):f.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:f.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},Ft={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},ac={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},lc={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Yt={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},cc=[{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")}],dc="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",de={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:""}]}]}]},fc=cc,uc=Yt;class mc{baseURL;token;constructor(e="/api/v1",t=dc){this.baseURL=e,this.token=t}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,t={}){const n=await fetch(e,{...t,headers:{...this.getAuthHeaders(),...t.headers}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return n}async getCourseData(e){return(await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}`)).json()}async getUserGradeUnitsNav(e){const t=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(t)).json()}async getUnitProgress(e,t){const n=t?`${this.baseURL}/content/courses/${e}/units/${t}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(n)).json()}async batchUpdateLessonProgress(e,t){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(t)})).json()}async updateLessonProgress(e,t,n,o){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${t}/lessons/${n}/progress`,{method:"POST",body:JSON.stringify({status:o})})}setToken(e){this.token=e}getToken(){return this.token}}const rr=new mc;class Ye extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="DataSourceError"}}class hc{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},rr.setToken(this.config.token)}async getUserGradeUnitsNav(e,t){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.withRetry(()=>rr.getUserGradeUnitsNav(e))}catch(n){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",n),new Ye(`获取年级单元导航数据失败: ${n instanceof Error?n.message:"未知错误"}`,"GET_USER_GRADE_UNITS_NAV_FAILED",n instanceof Error?n: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(t){throw console.error("[ApiDataSource] 获取用户个人信息失败:",t),new Ye(`获取用户个人信息失败: ${t instanceof Error?t.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",t instanceof Error?t: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 Ye(`获取探索菜单数据失败: ${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(()=>rr.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(t){throw console.error("[ApiDataSource] 更新课时进度失败:",t),new Ye(`更新课时进度失败: ${t instanceof Error?t.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",t instanceof Error?t:void 0)}}async batchUpdateLessonProgress(e,t){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,t),await this.withRetry(()=>rr.batchUpdateLessonProgress(e,t))}catch(n){throw console.error("[ApiDataSource] 批量更新课时进度失败:",n),new Ye(`批量更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async withRetry(e){let t;for(let n=1;n<=this.config.retryCount;n++)try{return await e()}catch(o){t=o instanceof Error?o:new Error(String(o)),n<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${n}次重试...`,t.message),await this.delay(this.config.retryDelay))}throw t}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}}class gc{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,t){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${t}`),new Ye("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${t}`),{userId:t,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:de.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:de.units.map((o,s)=>({unitId:o.id,title:o.title,description:o.description,moduleCategory:o.moduleCategory,estimatedDuration:o.estimatedDuration,totalLessons:o.lessons.length,completedLessons:s<2?Math.floor(o.lessons.length*.5):0,progressPercentage:s<2?50:0,status:s<2?"in-progress":"not-started",lastAccessed:s<2?new Date().toISOString():void 0,isActive:s===0,route:`/math/grade-5/unit/${o.id}`,icon:Ft[o.moduleCategory]||Ft.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:获取用户个人信息失败","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 Ye("模拟数据源:获取探索菜单数据失败","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 Ye("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,t){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,t),{success:!0,results:t.map(o=>({lessonId:o.lessonId,success:!0,status:o.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 de}getLessonsData(){const e={};return de.units.forEach(t=>{e[t.id]=t.lessons.map(n=>({id:n.id,title:n.title,duration:n.duration,knowledgeItems:n.knowledgeItems.map(o=>({...o,progress:0}))}))}),e}}class pc{static instances=new Map;static createDataSource(e){const{type:t,config:n,customDataSourceClass:o}=e,s=this.getInstanceKey(t,n);if(this.instances.has(s))return this.instances.get(s);let i;switch(t){case"api":i=new hc(n);break;case"mock":i=new gc(n);break;case"custom":if(!o)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new o(n);break;default:throw new Error(`不支持的数据源类型: ${t}`)}return this.instances.set(s,i),console.log(`[DataSourceFactory] 创建数据源: type=${t}, name=${n.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 t=!1,n=!1,o=!1;try{typeof process<"u"&&process.env?(t=process.env.NODE_ENV==="development",n=process.env.NODE_ENV==="test",o=process.env.REACT_APP_USE_MOCK==="true"):(t=!0,o=!0)}catch(s){console.warn("无法检测环境变量,使用默认配置:",s),t=!0,o=!0}return t||n||o?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,t){return`${e}:${t.name}:${JSON.stringify(t)}`}}function yc(){return pc.createDefaultDataSource()}function bc(r={}){const{dataSource:e=yc(),fallbackStrategy:t="mock",errorHandling:n={},performance:o={},theme:s={},debug:i=!1,enableDevTools:a=!1}=r;return{dataSource:e,fallbackStrategy:t,errorHandling:{showUserFriendlyErrors:!0,logErrors:!0,autoRetry:!0,maxRetries:3,retryDelay:1e3,...n},performance:{enableVirtualization:!0,lazyLoadImages:!0,debounceSearch:300,enableCaching:!0,cacheTTL:3e5,...o},theme:{primaryColor:"#1865f2",borderRadius:"8px",spacing:"16px",fontSize:"14px",enableDarkMode:!1,...s},debug:i,enableDevTools:a}}function xc(r,e){return{...r,...e,errorHandling:{...r.errorHandling,...e.errorHandling},performance:{...r.performance,...e.performance},theme:{...r.theme,...e.theme}}}const xs=b.createContext(null),vs=()=>{const r=b.useContext(xs);if(!r)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return r},_s=({children:r,config:e})=>{const[t,n]=b.useState(()=>bc(e)),[o,s]=b.useState(null),[i,a]=b.useState([]),[d,l]=b.useState(null),[c,u]=b.useState({}),[y,m]=b.useState(!1),[h,g]=b.useState(null),[p,x]=b.useState(null),[C,S]=b.useState([]),E=b.useCallback(async($,O)=>{m(!0),g(null);try{process.env.NODE_ENV!=="test"&&await new Promise(I=>setTimeout(I,100));const Y=await t.dataSource.getUserGradeUnitsNav($,O);l(Y);const q={};de.units.forEach(I=>{q[I.id]=I.lessons.map(G=>({id:G.id,title:G.title,duration:G.duration,knowledgeItems:G.knowledgeItems.map(H=>({...H,progress:0}))}))}),console.log("Lessons data loaded:",q),u(q);try{const I=await t.dataSource.getUserProfile(O);s(I)}catch(I){console.warn("获取用户信息失败,使用默认数据:",I),s({id:O,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const I=await t.dataSource.getExploreMenu();a(I)}catch(I){console.warn("获取探索菜单失败,使用默认数据:",I),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(Y){if(console.error("数据加载错误:",Y),t.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const q={userId:O,courseId:$,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:de.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:de.units.map((G,H)=>({unitId:G.id,title:G.title,description:G.description,moduleCategory:G.moduleCategory,estimatedDuration:G.estimatedDuration,totalLessons:G.lessons.length,completedLessons:H<2?Math.floor(G.lessons.length*.5):0,progressPercentage:H<2?50:0,status:H<2?"in-progress":"not-started",lastAccessed:H<2?new Date().toISOString():void 0,isActive:H===0,route:`/math/grade-5/unit/${G.id}`,icon:Ft[G.moduleCategory]||Ft.Default}))};l(q);const I={};de.units.forEach(G=>{I[G.id]=G.lessons.map(H=>({id:H.id,title:H.title,duration:H.duration,knowledgeItems:H.knowledgeItems.map(M=>({...M,progress:0}))}))}),u(I),s({id:O,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else g(Y instanceof Error?Y.message:"数据加载失败"),l(null)}finally{m(!1)}},[t]),_=b.useCallback($=>{S(O=>O.includes($)?O.filter(Y=>Y!==$):[...O,$])},[]),j=b.useCallback($=>{x($)},[]),w=b.useCallback($=>{n(O=>xc(O,$))},[]);b.useEffect(()=>{if(console.log("unitsData state updated:",d),console.log("unitsData?.units:",d?.units),console.log("unitsData?.units?.length:",d?.units?.length),d&&d.units.length>0){console.log("Looking for active unit...");const $=d.units.find(Y=>Y.isActive);console.log("Found active unit:",$);const O=$?.unitId||d.units[0].unitId;console.log("Setting default active unit:",O),x(O),console.log("Default active unit set after state update:",O)}else console.log("No units data available for setting default active unit")},[d]);const P={userInfo:o,exploreMenu:i,unitsData:d,lessons:c,loading:y,error:h,activeUnitId:p,activeLessonIds:C,config:t,theme:t.theme,enableVirtualization:t.performance?.enableVirtualization,setLoading:m,setError:g,setActiveUnit:j,toggleLesson:_,loadPageData:E,updateConfig:w};return f.jsx(xs.Provider,{value:P,children:r})},vc=({gradeId:r,userId:e,onLearnAction:t,className:n,userInfo:o,exploreMenu:s})=>{const{userInfo:i,exploreMenu:a,unitsData:d,lessons:l,loading:c,error:u,activeUnitId:y,activeLessonIds:m,setActiveUnit:h,toggleLesson:g,loadPageData:p}=vs(),x=o??i,C=s??a;b.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",r,"userId:",e),p(r,e)},[r,e,p]),b.useEffect(()=>{console.log("activeUnitId from context:",y),console.log("lessons from context:",l);const _=d?.units?.find(w=>w.unitId===y)||null,j=_&&y&&l[y]?{id:_.unitId,title:_.title,description:_.description,estimatedDuration:_.estimatedDuration,totalLessons:_.totalLessons,moduleCategory:_.moduleCategory,lessons:l[y]}:null;console.log("activeUnit computed:",j)},[y,l,d]);const S=d?.units?.find(_=>_.unitId===y)||null,E=S&&y&&l[y]?{id:S.unitId,title:S.title,description:S.description,estimatedDuration:S.estimatedDuration,totalLessons:S.totalLessons,moduleCategory:S.moduleCategory,lessons:l[y]}:null;return c?f.jsx("div",{className:`grade-unit-browser-page loading ${n||""}`,"data-testid":"grade-unit-browser-page",children:f.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):u?f.jsxs("div",{className:`grade-unit-browser-page error ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"error-message","data-testid":"error-message",children:u}),f.jsx("button",{onClick:()=>p(r,e),className:"retry-button",children:"重试"})]}):f.jsxs("div",{className:`grade-unit-browser-page ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"header-area",children:f.jsx(Yo,{userData:x||void 0,exploreItems:C})}),f.jsx("div",{className:"sidebar-area",children:f.jsx(Ao,{data:d,activeUnitId:y,onUnitSelect:h,loading:c})}),f.jsx("div",{className:"content-area",children:f.jsx(wo,{unit:E,activeLessonIds:m,onToggleLesson:g,onLearnAction:t||(()=>{}),loading:c})})]})},_c=r=>f.jsx(_s,{config:r.config,children:f.jsx(vc,{...r})}),wc=(r,e,t=.1)=>{if(!r.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const n=parseFloat(r);if(isNaN(n))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(n<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const s=Math.abs(n-e)<=t;return{isValid:!0,isCorrect:s,errorMessage:s?void 0:"答案不正确,请再试一次"}},Ac=()=>Ut.create((r,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:t=>{r({problemData:t,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:t=>{r({userAnswer:t,validationError:null})},submitAnswer:t=>{const n=e();if(!n.problemData){r({validationError:"问题数据未加载,请刷新页面重试"});return}const o=n.problemData.answer_info?.value??n.problemData.answer.value,s=Number(o),i=n.problemData.answer_info?.tolerance??.1,a=wc(t,s,i);if(!a.isValid){r({userAnswer:t,validationError:a.errorMessage||"答案格式错误"});return}r({userAnswer:t,isCorrect:a.isCorrect,showAnswerForm:!1,validationError:null,currentScene:a.isCorrect?"success":"explanation"})},nextQuestion:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),et=Ac(),gn=()=>et(r=>r.currentScene),pn=()=>et(r=>r.userAnswer),Rc=()=>et(r=>r.isCorrect),yn=()=>et(r=>r.showAnswerForm),ws=()=>et(r=>r.validationError),Sc=()=>et(r=>r.problemData),bn=()=>et(on.useShallow(r=>({updateUserAnswer:r.updateUserAnswer,submitAnswer:r.submitAnswer,nextQuestion:r.nextQuestion,resetSession:r.resetSession,setProblemData:r.setProblemData}))),Cc=b.createContext(null),Ht=()=>{const r=b.useContext(Cc);if(!r)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return r},Ec=()=>{const r=Ht(),e=b.useCallback(t=>t.currentScene,[]);return r(e)},Tc=()=>{const r=Ht(),e=b.useCallback(t=>t.userAnswer,[]);return r(e)},Nc=()=>{const r=Ht(),e=b.useCallback(t=>t.showAnswerForm,[]);return r(e)},$c=()=>{const r=Ht(),e=b.useCallback(t=>t.validationError,[]);return r(e)},kc=()=>Ht()(on.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),xn=()=>{try{return Ec()}catch{return gn()}},vn=()=>{try{return Tc()}catch{return pn()}},_n=()=>{try{return Nc()}catch{return yn()}},wn=()=>{try{return $c()}catch{return ws()}},An=()=>{try{return kc()}catch{return bn()}},St=({problemData:r,userAnswer:e,showAnswerForm:t,onAnswerSubmit:n,onAnswerChange:o,validationError:s})=>{const i=d=>{d.preventDefault(),n(e)},a=d=>{o(d)};return f.jsx("div",{className:"question-scene-container",children:f.jsxs("div",{className:"question-scene-card",children:[f.jsx("div",{className:"question-display-area",children:f.jsx(Re,{data:{id:r.id,grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1}})}),t&&f.jsxs("div",{className:"answer-form-container",children:[f.jsxs("form",{onSubmit:i,className:"answer-form",children:[f.jsx("label",{className:"answer-label",children:"答案"}),f.jsx("input",{type:"number",value:e,onChange:d=>a(d.target.value),className:`answer-input ${s?"error":"normal"}`,placeholder:"?",required:!0}),f.jsx("span",{className:"answer-unit",children:r.basicInfo.answerUnit||r.basicInfo.areaUnit}),f.jsx(xt,{type:"submit",size:"lg",className:"submit-button",children:"提交答案"})]}),s&&f.jsxs("div",{className:"validation-error",children:[f.jsx("span",{children:"⚠️"}),f.jsx("span",{children:s})]})]})]})})},As=({problemData:r,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",r),console.log("🔍 RememberModule scenes.remember:",r?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",r?.scenes?.remember?.content);const n=(()=>{const s=r.scenes?.review?.items;if(s&&Array.isArray(s)&&s.length>0)return console.log("🔍 RememberModule 使用 review.items"),s;const i=r.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=r.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const d=r.scenes?.remember?.content;return d&&Array.isArray(d)&&d.length>0?(console.log("🔍 RememberModule 使用 remember.content"),d):(console.log("🔍 RememberModule 未找到任何内容"),[])})();if(n.length===0){const s=f.jsx("div",{className:"remember-module-content",children:f.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?f.jsx(wt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})}const o=f.jsx("div",{className:"remember-module-content",children:n.map((s,i)=>{const{type:a,content:d,style:l,parts:c}=s;switch(a){case"text":return f.jsx("p",{className:"remember-module-text-block",style:l,children:d},i);case"formula":return f.jsx("div",{className:"remember-module-formula-block",children:f.jsx(Re,{data:{id:`formula-${i}`,grade:r.grade,unit:r.unit,content:[{type:"formula",content:d,parts:c||[d]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return f.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?f.jsx(wt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})},Rn=({problemData:r,userAnswer:e,enableIXLStyle:t=!0})=>{const n=f.jsxs("div",{className:"review-module-content",children:[f.jsx("p",{className:"review-module-question",children:r.basicInfo.question}),f.jsx("div",{className:"review-module-graph",children:f.jsx(Re,{data:{id:"review-problem",grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:t?"ixl-adjusted":""})}),f.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",f.jsx("span",{className:"review-module-user-answer-value",children:e})]})]});return t?f.jsx(wt,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:n}):f.jsxs("div",{className:"review-module-container",children:[f.jsx("h4",{className:"review-module-title",children:"复习"}),n]})},Oc=r=>[{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)"}][r%3],jc=({step:r,problemData:e,stepNumber:t})=>{const{title:n,description:o,chartConfig:s}=r.content,i=!!s,a=Oc(t-1),d=[{type:"text",content:o.replace(/<br>/g,`
19
- `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return f.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[f.jsxs("h3",{className:"explanation-step-title",children:[f.jsx("span",{className:"explanation-step-number",children:t}),f.jsx("span",{children:n})]}),f.jsxs("div",{className:"explanation-step-content",children:[f.jsx(Re,{data:{id:`${r.id}-description`,grade:e.grade,unit:e.unit,content:d},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&f.jsx("div",{className:"explanation-step-chart-container",children:s.type==="geometryTransform"&&(s.config||s.metadata?.config)?f.jsx(hn,{config:s.config||s.metadata?.config,onTransformChange:l=>console.log("Transform progress:",l),onTransformComplete:()=>console.log("Transform complete"),onError:l=>console.error("Geometry transform error:",l)}):f.jsx(Tr,{shapes:s.shapes||[],width:400,height:300,boundingBox:s.boundingBox||[-10,10,10,-10],showGrid:s.showGrid||!1,showAxis:s.showAxis||!1,mode:"view",className:"mx-auto"})})]})]})};function Mc(r){return r.steps!==void 0}function Ic(r){if(Mc(r))return r;if(Array.isArray(r)){if(r.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=r[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=r.map(o=>({id:o.id,type:o.type,title:o.content.title||"",description:o.content.description||"",chartConfig:o.content.chartConfig,videoUrl:o.content.videoUrl,commonErrors:o.content.commonErrors,difficulty:o.content.difficulty}));return{steps:n,total_steps:n.length,strategy:"step_by_step",estimated_time:n.length*30}}else return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}const Sn=({problemData:r,enableIXLStyle:e=!0})=>{const[t,n]=b.useState(!1),o=r?.scenes?.solve?.items||r?.scenes?.solve?.content,s=Array.isArray(o)&&o.length>0,i=b.useMemo(()=>Ic(r.explanation),[r.explanation]),a=i.steps.length>0,d=b.useMemo(()=>a?i.steps.map(c=>({...c,content:{title:c.title,description:c.description,chartConfig:c.chartConfig?{...c.chartConfig,boundingBox:c.chartConfig.type==="graph"&&Array.isArray(c.chartConfig.boundingBox)&&c.chartConfig.boundingBox.length===4?[c.chartConfig.boundingBox[0],c.chartConfig.boundingBox[1],c.chartConfig.boundingBox[2],c.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[a,i.steps]),l=f.jsxs("div",{className:"solve-module-content",children:[s?f.jsxs(f.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",o),o?.forEach?.((c,u)=>{c.type==="geometryTransform"&&console.log(`🔍 SolveModule: geometryTransform block [${u}] =`,{type:c.type,hasMetadata:!!c.metadata,metadata:c.metadata,hasConfig:!!c.config,config:c.config,hasShapes:!!c.shapes,shapes:c.shapes,hasTransform:!!c.transform,transform:c.transform})}),f.jsx(Re,{data:{id:"solve-steps",grade:r.grade,unit:r.unit,content:o},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):f.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),f.jsx("div",{className:"solve-module-button-container",children:f.jsx("button",{type:"button",onClick:()=>n(c=>!c),className:"solve-module-button",children:t?"收起详细解题步骤":"查看详细解题步骤"})}),t&&f.jsxs("div",{className:"solve-module-detailed-container",children:[f.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),a?f.jsx("div",{className:"solve-module-detailed-list",children:d.map((c,u)=>f.jsx(jc,{step:c,problemData:r,stepNumber:u+1},c.id))}):f.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?f.jsx(wt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:l}):f.jsxs("div",{className:"solve-module-container",children:[f.jsx("h4",{className:"solve-module-title",children:"解题"}),l]})},Kt=({problemData:r,userAnswer:e,onNextQuestion:t})=>(console.log("🔍 ExplanationScene problemData:",r),console.log("🔍 ExplanationScene scenes.remember:",r?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",r?.scenes?.remember?.content),f.jsxs("div",{children:[f.jsx("div",{className:"explanation-error-banner",children:f.jsxs("div",{className:"explanation-inner-container",children:[f.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),f.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[f.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),f.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[f.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),f.jsx("div",{className:"correct-answer-value-container",children:f.jsx("span",{className:"correct-answer-value",children:f.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r.answer?.value??"--"})})})]})]}),f.jsx("div",{className:"explanation-button-container",children:f.jsx(xt,{onClick:t,size:"lg",className:"explanation-next-button",children:"明白了"})})]})}),f.jsxs("div",{className:"explanation-content-area",children:[f.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),f.jsx(Rn,{problemData:r,userAnswer:e}),f.jsx(As,{problemData:r}),f.jsx(Sn,{problemData:r})]}),f.jsx("div",{className:"explanation-bottom-area",children:f.jsx(xt,{onClick:t,size:"md",children:"明白了"})})]})),Ct=({problemData:r,onNextQuestion:e})=>f.jsxs("div",{className:"success-scene-container",children:[f.jsx("h3",{className:"success-message-title",children:"正确!"}),f.jsx("p",{className:"success-message-description",children:"你做得很好!"}),f.jsx("div",{className:"concept-review-container",children:f.jsx(Re,{data:{id:"review-concepts",grade:r.grade,unit:r.unit,content:r.scenes?.review?.items||r.scenes?.review?.content||r.scenes?.remember?.items||r.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),f.jsx(xt,{onClick:e,size:"lg",className:"next-button",children:"下一题"})]}),Dr={MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"},Fc={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},Pc={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},ee={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"},B={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 me extends Error{code;details;constructor(e,t,n){super(t),this.name="AdapterError",this.code=e,this.details=n}}const fr={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"}},oo={[B.INVALID_INPUT]:"输入数据无效",[B.MISSING_REQUIRED_FIELD]:"缺少必需字段",[B.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[B.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[B.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[B.STYLE_REF_NOT_FOUND]:"样式引用未找到",[B.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[B.BOARD_REF_NOT_FOUND]:"画板引用未找到",[B.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[B.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[B.TRANSFORMATION_FAILED]:"数据转换失败",[B.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},ot={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Lr={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"]},Rs=["question","solve","review","remember"],ie={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_]*)$/},ye={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},Ss={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.8rem",heading_normal:"1.2rem",body:"1rem",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}}},Cs={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_primary",fontSize:"$fonts.heading_large",fontWeight:"bold"},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"}}},Es={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:"左三角形模板"}}},Ts={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"}}},Ns={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:"缩放变换"}}},pt={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:"垂直滑块动画"}}},$s={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:"扩展画板配置(带网格和坐标轴)"}}},at={designTokens:Ss.design_tokens,stylePresets:Cs.style_presets,geometryPresets:Es.geometry_presets,layoutPresets:Ts.layout_presets,transformDefinitions:Ns.transform_definitions,animationDefinitions:pt.slider_definitions,animationConfigs:pt.slider_definitions,boardDefinitions:$s.board_definitions};function ks(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!pt,sliderDefinitionsKeys:pt.slider_definitions?Object.keys(pt.slider_definitions):[]});const r=pt.slider_definitions;return{designTokens:Ss.design_tokens,stylePresets:Cs.style_presets,geometryPresets:Es.geometry_presets,layoutPresets:Ts.layout_presets,transformDefinitions:Ns.transform_definitions,animationDefinitions:r,animationConfigs:r,boardDefinitions:$s.board_definitions}}class Pe{static canResolve(e){return ie.DESIGN_TOKEN.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,t.designTokens)}static resolvePath(e,t){const n=e.split(".");let o=t;for(const s of n){if(o==null)throw new Error(`设计令牌路径不存在: ${e} (在 ${s} 处中断)`);if(typeof o!="object")throw new Error(`设计令牌路径无效: ${e} (${s} 不是对象)`);o=o[s]}if(o===void 0)throw new Error(`设计令牌未找到: ${e}`);return o}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`设计令牌解析失败: ${o}`,s)}return n}static extractDesignTokenRefs(e){const t=[],n=o=>{typeof o=="string"?this.canResolve(o)&&t.push(o):Array.isArray(o)?o.forEach(n):typeof o=="object"&&o!==null&&Object.values(o).forEach(n)};return n(e),t}static replaceDesignTokenRefs(e,t,n){const o=s=>{if(typeof s=="string"){if(this.canResolve(s))try{return this.resolve(s,t)}catch(c){if(n)return n(s);throw c}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,d=0;const l=[];for(;(a=i.exec(s))!==null;){a.index>d&&l.push(s.substring(d,a.index));const c=a[0];try{const u=this.resolve(c,t);l.push(String(u))}catch{n?l.push(String(n(c))):l.push(c)}d=a.index+c.length}return d<s.length&&l.push(s.substring(d)),l.length>1?l.join(""):s}else{if(Array.isArray(s))return s.map(o);if(typeof s=="object"&&s!==null){const i={};for(const[a,d]of Object.entries(s))i[a]=o(d);return i}}return s};return o(e)}}function Dc(){return{type:ee.DESIGN_TOKEN,canResolve:Pe.canResolve.bind(Pe),resolve:Pe.resolve.bind(Pe)}}class Be{static canResolve(e,t){if(typeof e!="string"||e.length===0)return!1;if(ie.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(s=>s.test(e)))return!0;if(t&&t.geometryPresets){let s;const i=e.match(ie.GEOMETRY_REF);return i?s=i[1]:s=e,s in t.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,t){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!t.geometryPresets,pointFound:!!t.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(t.geometryPresets&&t.geometryPresets[n]){const o=t.geometryPresets[n];if(o.position)return console.error(`✅ 解析顶点引用 ${n}: 使用 position`,o.position),[o.position.x,o.position.y];if("x"in o&&"y"in o)return console.error(`✅ 解析顶点引用 ${n}: 使用 x/y`,{x:o.x,y:o.y}),[o.x,o.y]}return console.warn(`无法解析顶点引用: ${n}`),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,t){if(!this.canResolve(e,t))throw new Error(`无法解析的几何引用: ${e}`);let n;const o=e.match(ie.GEOMETRY_REF);o?n=o[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(t.geometryPresets||{}));const s=t.geometryPresets[n];if(!s)throw console.error(`❌ Geometry preset not found: ${n} in`,t.geometryPresets),new Error(`几何预设未找到: ${n}`);console.error("✅ Geometry resolved:",{name:n,type:s.type,hasVertices:"vertices"in s,verticesCount:s.vertices?s.vertices.length:0,hasEndpoints:"endpoints"in s,endpoints:s.endpoints,endpointsIsArray:Array.isArray(s.endpoints),endpointsLength:s.endpoints?s.endpoints.length:0,geometryKeys:Object.keys(s)});const i={...s};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,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(d){return console.warn("顶点引用解析失败:",d),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,d)=>({index:d,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,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(d){return console.warn("端点引用解析失败:",d),a}})),i}static validate(e,t){if(!this.canResolve(e,t))return!1;let n;const o=e.match(ie.GEOMETRY_REF);return o?n=o[1]:n=e,n in t.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,t){const n=this.resolve(e,t);if(n.styleRef&&t.stylePresets[n.styleRef]){const o=t.stylePresets[n.styleRef];return{...n,style:{...o}}}return n}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`几何引用解析失败: ${o}`,s)}return n}static extractGeometryRefs(e){const t=[],n=o=>{if(!(!o||typeof o!="object")){o.geometryRef&&typeof o.geometryRef=="string"&&t.push(o.geometryRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.geometryRef&&typeof s.geometryRef=="string"&&t.push(s.geometryRef)});for(const s of Object.values(o))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return n(e),[...new Set(t)]}}function Lc(){return{type:ee.GEOMETRY_REF,canResolve:Be.canResolve.bind(Be),resolve:Be.resolve.bind(Be),validate:Be.validate.bind(Be)}}class Se{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.TRANSFORM_REF.test(e)?!0:["left_rotation","right_rotation","translation"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const o=e.match(ie.TRANSFORM_REF);if(o?n=o[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n])return{...t.transformDefinitions[n]};const s={left_rotation:{type:"rotation",angle:-90,origin:[0,0]},right_rotation:{type:"rotation",angle:90,origin:[0,0]},translation:{type:"translation",dx:0,dy:0}};if(s[n])return{...s[n]};throw new Error(`变换定义未找到: ${n}`)}static validate(e,t){if(!this.canResolve(e))return!1;let n;const o=e.match(ie.TRANSFORM_REF);return o?n=o[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n]?!0:["left_rotation","right_rotation","translation"].includes(n)}static applyTransform(e,t){if(!t||!e)return e;const n={...e};switch(t.type){case"rotation":n.vertices=this.applyRotation(e.vertices,t.angle,t.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,t.dx,t.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,t.factor,t.origin);break;default:console.warn(`未知的变换类型: ${t.type}`)}return n}static applyRotation(e,t,n){if(!e||!Array.isArray(e))return e;const[o,s]=n,i=t*Math.PI/180,a=Math.cos(i),d=Math.sin(i);return e.map(([l,c])=>{const u=l-o,y=c-s;return[o+u*a-y*d,s+u*d+y*a]})}static applyTranslation(e,t,n){return!e||!Array.isArray(e)?e:e.map(([o,s])=>[o+t,s+n])}static applyScale(e,t,n){if(!e||!Array.isArray(e))return e;const[o,s]=n;return e.map(([i,a])=>{const d=i-o,l=a-s;return[o+d*t,s+l*t]})}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`变换引用解析失败: ${o}`,s)}return n}static extractTransformRefs(e){const t=[],n=o=>{if(!(!o||typeof o!="object")){o.transformRef&&typeof o.transformRef=="string"&&t.push(o.transformRef),Array.isArray(o.transformations)&&o.transformations.forEach(s=>{s.transformRef&&typeof s.transformRef=="string"&&t.push(s.transformRef)});for(const s of Object.values(o))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return n(e),[...new Set(t)]}}function Uc(){return{type:ee.TRANSFORM_REF,canResolve:Se.canResolve.bind(Se),resolve:Se.resolve.bind(Se),validate:Se.validate.bind(Se)}}class we{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.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,t){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const o=e.match(ie.STYLE_REF);o?n=o[1]:n=e;const s=t.stylePresets[n];if(!s)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(s,t)}static resolveStylePreset(e,t){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(Pe.canResolve(s))try{n[o]=Pe.resolve(s,t)}catch(i){console.warn(`样式中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveStylePreset(s,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const o=e.match(ie.STYLE_REF);return o?n=o[1]:n=e,n in t.stylePresets}static applyStyle(e,t){if(!e||!t)return e;const n={...e};return n.style=n.style?{...n.style,...t}:{...t},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(s=>{t[s]!==void 0&&(n[s]=t[s])}),n}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`样式引用解析失败: ${o}`,s)}return n}static extractStyleRefs(e){const t=[],n=o=>{if(!(!o||typeof o!="object")){o.styleRef&&typeof o.styleRef=="string"&&t.push(o.styleRef),o.style&&typeof o.style=="object"&&o.style.styleRef&&typeof o.style.styleRef=="string"&&t.push(o.style.styleRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.styleRef&&typeof s.styleRef=="string"&&t.push(s.styleRef),s.style&&s.style.styleRef&&typeof s.style.styleRef=="string"&&t.push(s.style.styleRef)});for(const s of Object.values(o))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return n(e),[...new Set(t)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Gc(){return{type:ee.STYLE_REF,canResolve:we.canResolve.bind(we),resolve:we.resolve.bind(we),validate:we.validate.bind(we)}}class Ve{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const o=e.match(ie.LAYOUT_REF);if(o?n=o[1]:n=e,t.layoutPresets&&t.layoutPresets[n]){const i=t.layoutPresets[n];return this.resolveLayoutPreset(i,t)}const s={card:{type:"card",padding:"20px",theme:"light"},vertical:{type:"vertical",spacing:"15px",alignment:"start"},horizontal:{type:"horizontal",spacing:"15px",alignment:"center"}};if(s[n])return{...s[n]};throw new Error(`布局预设未找到: ${n}`)}static resolveLayoutPreset(e,t){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(Pe.canResolve(s))try{n[o]=Pe.resolve(s,t)}catch(i){console.warn(`布局中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveLayoutPreset(s,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const o=e.match(ie.LAYOUT_REF);return o?n=o[1]:n=e,t.layoutPresets&&t.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,t){if(!e||!t)return e;const n={...e};return n.layout?n.layout={...n.layout,...t}:n.layout={...t},n}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`布局引用解析失败: ${o}`,s)}return n}static extractLayoutRefs(e){const t=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&t.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const o of Object.values(n.layout))typeof o=="string"&&this.isLayoutRef(o)&&t.push(o);return[...new Set(t)]}static isLayoutRef(e){return ie.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function zc(){return{type:ee.LAYOUT_REF,canResolve:Ve.canResolve.bind(Ve),resolve:Ve.resolve.bind(Ve),validate:Ve.validate.bind(Ve)}}class st{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.ANIMATION_REF.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new me(B.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(ie.ANIMATION_REF);if(!n)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const o=n[1],s=t.animationConfigs?.[o];if(!s)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${o}`);return this.resolveAnimationConfig(o,s,t)}static resolveAnimationConfig(e,t,n){if(!t.transforms||!Array.isArray(t.transforms))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const o=t.transforms.map((a,d)=>{if(!a.id)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${d}] 缺少 id 字段`);if(!a.type)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${d}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${d}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${d}] targetShapes 不能为空`);a.targetShapes.forEach((u,y)=>{if(typeof u!="string"||u.trim()==="")throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${d}].targetShapes[${y}] 必须是有效的字符串 ID`)});const l=Vl(a.params),c=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:c}}),s={id:e,control:t.control,transforms:o,visualEffects:t.visualEffects||[],progressControl:t.progressControl},i=Wl(s);if(!i.valid)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
13
+ Received: ${JSON.stringify(n)}`)}case"shear":{const n=r.params,s=ye(n.shearX,e),o=ye(n.shearY,e);return[s,o]}case"generic":{const n=r.params;return[ye(n.a,e),ye(n.b,e),ye(n.c,e),ye(n.d,e),ye(n.e,e),ye(n.f,e),ye(n.g,e),ye(n.h,e),ye(n.i,e)]}case"matrix":{const n=r.params;if(!Array.isArray(n.matrix)||n.matrix.length!==3||!n.matrix.every(s=>Array.isArray(s)&&s.length===3))throw new Error("Matrix transform requires a 3x3 matrix array");return[n.matrix]}default:throw new Error(`Unsupported transform type: ${r.params.type}`)}}function Il(r){const e={};return Object.entries(r).forEach(([t,n])=>{if(typeof n=="string"&&Ml(n))try{e[t]=kl(n)}catch(s){console.warn(`Failed to parse function string for ${t}: ${n}`,s),e[t]=()=>0}else e[t]=n}),e}function Fl(r){if(!r||typeof r!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!r.id||typeof r.id!="string"||r.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(r.transforms)?r.transforms.forEach((t,n)=>{(!t.id||typeof t.id!="string")&&e.push(`Transform at index ${n} must have a valid id`),(!t.type||typeof t.type!="string")&&e.push(`Transform at index ${n} must have a valid type`),(!t.params||typeof t.params!="object")&&e.push(`Transform at index ${n} must have valid params`),Array.isArray(t.targetShapes)?t.targetShapes.length===0&&e.push("targetShapes must not be empty"):e.push(`Transform at index ${n} must have targetShapes array`)}):e.push("Config must have a transforms array"),{valid:e.length===0,errors:e.length>0?e:void 0}}const Xn=ms.JSXGraph,no=r=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!r.animation,animationId:r.animation?.id,hasControl:!!r.animation?.control,controlConfig:r.animation?.control,animationProgress:r.animationProgress});const e=b.useRef(null),[t,n]=b.useState(null),[,s]=b.useState({}),[o,i]=b.useState(!1),a=b.useRef({}),c=b.useRef({}),l=b.useRef(null),d=b.useRef({}),u=b.useCallback((m,h)=>{r.onShapeChange},[r.onShapeChange]),y=b.useCallback(m=>{r.onSelectionChange&&r.onSelectionChange(m?[m]:[])},[r.onSelectionChange]);return b.useEffect(()=>{if(e.current){try{const m=r.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",m),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const h=Xn.initBoard(e.current,{boundingbox:m,axis:r.showAxis??!0,grid:r.showGrid??!0,showNavigation:!1,pan:{enabled:r.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",h.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",m),console.warn(" * 实际边界框:",h.getBoundingBox()),console.warn(" * 实际显示范围:",{left:h.getBoundingBox()[0],top:h.getBoundingBox()[1],right:h.getBoundingBox()[2],bottom:h.getBoundingBox()[3]})},100),n(h)}catch(m){console.error("JSXGraph initialization failed:",m)}return()=>{t&&Xn.freeBoard(t)}}},[]),b.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!t,hasAnimation:!!r.animation,hasControl:!!r.animation?.control,animationId:r.animation?.id,controlType:r.animation?.control?.type,controlPosition:r.animation?.control?.position,controlRange:r.animation?.control?.range}),!t||!r.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!t+", control="+!!r.animation?.control),l.current){try{l.current.remove&&l.current.remove()}catch(h){console.warn("Failed to remove control:",h)}l.current=null}return}const m=r.animation.control;console.warn("✨ Creating Control Component:",{type:m.type,config:m,position:m.position,range:m.range});try{if(m.type==="slider"){const h=m.position[0]+(m.length||5);console.warn("📐 Slider creation parameters:",{startPoint:m.position,endPoint:[h,m.position[1]],values:[m.range[0],m.initial||0,m.range[1]],label:m.label,snapWidth:m.snapWidth||.01});const g=t.create("slider",[m.position,[h,m.position[1]],[m.range[0],m.initial||0,m.range[1]]],{name:m.label||"control",snapWidth:m.snapWidth||.01,withLabel:m.showLabel!==void 0?m.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});l.current=g,console.warn("✅ Slider created:",{id:g.id,name:g.name,initialValue:g.Value(),startPoint:m.position,endPoint:[h,m.position[1]],boundingBox:t.getBoundingBox(),visProp:g.visProp});const p=t.objectsList.map(S=>({id:S.id,type:S.elType,name:S.name,visible:S.visProp?.visible})),x=p.find(S=>S.id===g.id);if(console.warn("📊 Slider in board.objectsList:",!!x,x),console.warn("📊 All board objects count:",p.length),r.onAnimationChange){let S=!1;g.on("drag",()=>{if(S)return;S=!0;const C=(g.Value()-m.range[0])/(m.range[1]-m.range[0]);r.onAnimationChange?.(C),S=!1})}}else if(m.type==="glider"){const h=t.select(m.line,!0);if(h){const g=t.create("glider",[m.initial||0,0,h],{name:m.label||"control",snapWidth:m.snapWidth||.01});if(l.current=g,console.warn("✅ Glider created:",{id:g.id,name:g.name}),r.onAnimationChange){let p=!1;g.on("drag",()=>{if(p)return;p=!0;const x=g.Value();r.onAnimationChange?.(x),p=!1})}}else console.warn(`Reference line not found for glider: ${m.line}`)}}catch(h){console.error("Failed to create control component:",h)}return()=>{if(l.current){try{l.current.remove()}catch(h){console.warn("Failed to remove control on cleanup:",h)}l.current=null}}},[t,r.animation?.control]),b.useEffect(()=>{if(!t||!r.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:r.animation.id,transformCount:r.animation.transforms.length}),Object.values(a.current).forEach(g=>{try{g&&g.remove&&g.remove()}catch(p){console.warn("Failed to remove transform:",p)}}),a.current={};const m={},h=r.animationProgress??0;r.animation.transforms.forEach(g=>{try{let p,x;const S=g.usesControl||!1;if(l.current&&S){p=Or(g,h,l.current),console.warn(`🔧 Creating transform ${g.id} (with dynamic params):`,{type:g.type,paramsTypes:p.map(C=>typeof C),targetShapes:g.targetShapes,controlValue:l.current.Value()}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});const R=()=>{if(!l.current)return;t.update();const C=l.current.Value();if(console.warn(`🎯 Slider drag - transform ${g.id} auto-updated (controlValue: ${C})`),r.onAnimationChange){const _=r.animation?.control?.range||[0,1],O=(C-_[0])/(_[1]-_[0]);r.onAnimationChange(O)}};l.current.on("drag",R),d.current[g.id]=R,console.warn(`🔗 Slider listener attached for transform ${g.id} (auto-update mode)`)}else p=Or(g,h),console.warn(`🔧 Creating transform ${g.id} (with progress ${h}):`,{type:g.type,params:p,targetShapes:g.targetShapes}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});m[g.id]=x,console.warn(`📝 Transform ${g.id} created:`,{type:g.type,paramsTypes:p.map(R=>typeof R),transformMethods:Object.keys(x).filter(R=>typeof x[R]=="function")})}catch(p){console.error(`Failed to create transform ${g.id}:`,p)}}),a.current=m}catch(m){console.error("Transform setup failed:",m)}},[t,r.animation]),b.useEffect(()=>{if(!o||!t||!r.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${o}, board=${!!t}, animation=${!!r.animation}`);return}if(console.warn("✅ Attempting to bind transforms to shapes..."),console.warn(` Available shapes: ${Object.keys(c.current).length}`),console.warn(` Available transforms: ${Object.keys(a.current).length}`),Object.keys(c.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(([m,h])=>{const g=r.animation?.transforms.find(x=>x.id===m);if(!g)return;console.warn(`🔍 Binding transform ${m} (type: ${g.type}) to shapes:`,g.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(c.current));const p=g.targetShapes.map(x=>{const S=c.current[x];return S?console.warn(`✅ Found shape ${x}:`,S):(console.warn(`❌ Shape not found for transform binding: ${x}`),console.warn(" Available IDs:",Object.keys(c.current))),S}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",p.length),p.length>0)try{console.warn(`🔗 Attempting to bind transform ${m} to ${p.length} shapes`),h.bindTo(p),console.warn(`✅ Successfully bound transform ${m} to ${p.length} shapes`),console.warn(" Transform object:",h),console.warn(" Target elements:",p.map(x=>({id:x.id,name:x.name,type:x.elementClass})))}catch(x){console.error(`❌ Failed to bind transform ${m}:`,x),console.error(" Transform:",h),console.error(" TargetElements:",p)}else console.warn(`⚠️ No valid target elements for transform ${m}`)}),t.update(),console.warn("✅ All transforms bound and board updated")},[o,t,r.animation]),b.useEffect(()=>{if(!t||Object.keys(a.current).length===0)return;const m=r.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${m}`);try{Object.entries(a.current).forEach(([h,g])=>{const p=r.animation?.transforms.find(S=>S.id===h);if(!p)return;const x=Or(p,m);console.warn(`🔄 Attempting to update transform ${h} with params:`,x),g.update?(console.warn(" Using transform.update(params)"),g.update(x)):g.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),g.setMatrix(t,p.type,x)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(g).filter(S=>typeof g[S]=="function")))}),t.update()}catch(h){console.error("Transform update failed:",h)}},[t,r.animationProgress]),b.useEffect(()=>{if(t)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:r.shapes.length,shapes:r.shapes.map(g=>({id:g.id,type:g.type,hasVertices:"vertices"in g,verticesCount:"vertices"in g&&g.vertices?g.vertices.length:"undefined",hasPosition:"position"in g,hasGeometryRef:"geometryRef"in g,geometryRef:"geometryRef"in g?g.geometryRef:void 0}))}),t.suspendUpdate(),[...t.objectsList].forEach(g=>{t.removeObject(g)});const h={};c.current={},r.shapes.forEach(g=>{if(g.type==="point")try{const p=jr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create point shape ${g.id}:`,p)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",t.objectsList.map(g=>({id:g.id,name:g.name,type:g.elementClass}))),r.shapes.forEach(g=>{if(g.type==="line"||g.type==="circle"||g.type==="polygon")try{const p=jr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create shape ${g.id}:`,p)}}),console.warn("📝 Starting phase 3: creating text labels"),r.shapes.forEach(g=>{if(g.type==="text")try{const p=jr(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create text ${g.id}:`,p)}}),s(h),c.current=h,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(h).length} shapes created`),t.unsuspendUpdate()}catch(m){console.error("Shape rendering failed:",m)}},[t,r.shapes,r.mode,u,y]),b.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),l.current&&Object.entries(d.current).forEach(([m,h])=>{try{l.current.off("drag",h),console.warn(` Removed drag listener for transform ${m}`)}catch(g){console.warn(`Failed to remove drag listener for ${m}:`,g)}}),d.current={},Object.values(a.current).forEach(m=>{try{m&&m.remove&&m.remove()}catch(h){console.warn("Failed to remove transform during cleanup:",h)}}),a.current={},c.current={},i(!1),console.warn("✅ Cleanup complete")},[]),f.jsx("div",{ref:e,className:"w-full h-full"})};function jr(r,e,t,n,s){const o=t==="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 l,d;if(e.position.x!==void 0&&e.position.y!==void 0)l=e.position.x,d=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)l=e.position[0],d=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const u=r.create("point",[l,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:u.id,pointName:u.name,hasIdProperty:"id"in u}),o&&(r.on("drag",()=>{n(e.id,{x:u.X(),y:u.Y()})}),r.on("down",()=>{s(e.id)})),u}catch(l){return console.error(`Failed to create point ${e.id}:`,l),null}case"line":const i=Kt(e.start,r),a=Kt(e.end,r);if(i&&a)try{const l=r.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&&r.on("down",()=>{s(e.id)}),l}catch(l){return console.error(`Failed to create line ${e.id}:`,l),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 c=Kt(e.center,r);if(c){let l;if(e.through){const d=Kt(e.through,r);d&&(l=r.create("circle",[c,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&&(l=r.create("circle",[c,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 l&&o&&r.on("down",()=>{s(e.id)}),l}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 l=e.vertices.map((d,u)=>{const y=e.verticesConfig?e.verticesConfig[u]:null;return Pl(d,r,y)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,l),console.warn(`🔧 Polygon ${e.id} vertices types:`,l.map(d=>({type:typeof d,isArray:Array.isArray(d),value:d}))),l.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 y={};e.verticesConfig.withLabel!==void 0?y.withLabel=e.verticesConfig.withLabel:y.withLabel=!0;const m={};let h=!1;e.verticesConfig.offset&&(m.offset=e.verticesConfig.offset,h=!0),e.verticesConfig.fontSize&&(m.fontSize=e.verticesConfig.fontSize,h=!0),e.verticesConfig.color&&(m.color=e.verticesConfig.color,h=!0),e.verticesConfig.anchorX&&(m.anchorX=e.verticesConfig.anchorX,h=!0),e.verticesConfig.anchorY&&(m.anchorY=e.verticesConfig.anchorY,h=!0),h&&(y.label=m),d.vertices=y,console.warn("🔧 Using JSXGraph vertices config:",y)}else d.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",d);const u=r.create("polygon",l,d);return console.warn("🔧 Polygon created:",u),console.warn("🔧 Polygon vertices:",u.vertices),console.warn("🔧 Polygon vertices names:",u.vertices?u.vertices.map(y=>y.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",u.vertices?u.vertices.map(y=>y.hasLabel?y.label:"no label"):"no vertices"),o&&r.on("down",()=>{s(e.id)}),u}else console.warn(`Cannot create polygon ${e.id}: some vertices are missing`,{vertices:e.vertices,resolvedVertices:l})}catch(l){console.error(`Failed to create polygon ${e.id}:`,l)}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)}),r.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(l){console.error(`Failed to create text ${e.id}:`,l)}break}return null}function Kt(r,e){if(Array.isArray(r)&&r.length>=2)return r;if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return[r.x,r.y];if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const n=e.objects[r.$ref];if(n)return n}const t=e.objectsList.find(n=>n.id===r.$ref);if(t)return console.warn(`✅ Found referenced point ${r.$ref}:`,t),t;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(t){console.warn(`Failed to resolve point reference ${r.$ref}:`,t)}}return null}function Pl(r,e,t){if(Array.isArray(r)&&r.length>=2){if(t&&t.name){const n=e.create("point",r,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,r),n}return r}if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r){const n=[r.x,r.y];if(t&&t.name){const s=e.create("point",n,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,n),s}return n}if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const s=e.objects[r.$ref];if(s)return t&&t.name&&s.setName&&(s.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),s}const n=e.objectsList.find(s=>s.id===r.$ref);if(n)return console.warn(`✅ Found referenced point ${r.$ref}:`,n),t&&t.name&&n.setName&&(n.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),n;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${r.$ref}:`,n)}}return null}function cn(r,e={}){const{padding:t=.2,margin:n=1,minSize:s=4}=e,o=[];if(r.forEach(w=>{switch(w.type){case"point":o.push(w.position);break;case"line":const F=ft(w.start,r),$=ft(w.end,r);F&&o.push(F),$&&o.push($);break;case"circle":const k=ft(w.center,r);if(k&&(o.push(k),w.radius!==void 0&&o.push({x:k.x+w.radius,y:k.y},{x:k.x-w.radius,y:k.y},{x:k.x,y:k.y+w.radius},{x:k.x,y:k.y-w.radius})),w.through){const M=ft(w.through,r);M&&o.push(M)}break;case"polygon":w.vertices.forEach(M=>{const L=ft(M,r);L&&o.push(L)});break;case"text":o.push(w.position);const B=w.content.length*(w.fontSize||14)/20,W=(w.fontSize||14)/10;o.push({x:w.position.x+B,y:w.position.y},{x:w.position.x-B,y:w.position.y},{x:w.position.x,y:w.position.y+W},{x:w.position.x,y:w.position.y-W});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(w=>w.x)),a=Math.max(...o.map(w=>w.x)),c=Math.min(...o.map(w=>w.y)),l=Math.max(...o.map(w=>w.y)),d=(i+a)/2,u=(c+l)/2;let y=Math.max(a-i,s),m=Math.max(l-c,s);const h=800/500,g=y/m;Math.abs(g-h)>.1&&(g>h?m=y/h:y=m*h);const p=y*(1+t)+n*2,x=m*(1+t)+n*2,S=d-p/2,R=u+x/2,C=d+p/2,_=u-x/2,O=[S,R,C,_];if(process.env.NODE_ENV==="development"){const F=o.map($=>({x:$.x,y:$.y,insideX:$.x>=S&&$.x<=C,insideY:$.y<=R&&$.y>=_,inside:$.x>=S&&$.x<=C&&$.y<=R&&$.y>=_})).filter($=>!$.inside);F.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:O,outsidePoints:F.slice(0,5),totalOutside:F.length})}return{boundingBox:O,center:{x:d,y:u},width:p,height:x}}function ft(r,e=[]){if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return{x:r.x,y:r.y};if("$ref"in r){const t=e.find(n=>n.id===r.$ref&&n.type==="point");if(t)return t.position}}return null}function Dl(r,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const t=[];if(r.forEach(s=>{switch(s.type){case"point":t.push({x:s.position.x,y:s.position.y,source:`point:${s.id}`});break;case"text":t.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;t.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,c)=>{const l=ft(a,r);l&&t.push({x:l.x,y:l.y,source:`polygon:${s.id}:vertex${c}`})});break}}),console.log("📊 收集到的坐标点:",t),t.length>0){const s=Math.min(...t.map(c=>c.x)),o=Math.max(...t.map(c=>c.x)),i=Math.min(...t.map(c=>c.y)),a=Math.max(...t.map(c=>c.y));console.log("📐 原始包围盒:",{minX:s,maxX:o,minY:i,maxY:a,width:o-s,height:a-i})}const n=cn(r,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",n),console.groupEnd(),n}const Ar=r=>{const{shapes:e,mode:t,onShapeChange:n,onSelectionChange:s,width:o=600,height:i=400,showGrid:a=!0,showAxis:c=!0,className:l="",boundingBox:d,autoBoundingBox:u=!0,boundingBoxOptions:y,animation:m,animationProgress:h,onAnimationChange:g,showAnimationControls:p}=r,x=b.useMemo(()=>{if(d)return d;if(u&&e.length>0)try{process.env.NODE_ENV==="development"&&Dl(e,"MathGraph Auto BoundingBox");const R=cn(e,y);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",R.boundingBox),console.log(" - Center:",R.center),console.log(" - Width:",R.width),console.log(" - Height:",R.height),console.log(" - Options used:",y),R.boundingBox}catch(R){return console.warn("Failed to calculate auto bounding box, using default:",R),[-10,10,10,-10]}return[-10,10,10,-10]},[d,u,e,y]),S=b.useMemo(()=>({width:typeof o=="number"?`${o}px`:o,height:typeof i=="number"?`${i}px`:i}),[o,i]);return f.jsx($l,{children:f.jsx("div",{className:`border border-gray-200 rounded-lg bg-white shadow-sm overflow-hidden ${l}`,style:S,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:f.jsx(no,{shapes:e,mode:t,onShapeChange:n,onSelectionChange:s,boundingBox:x,showGrid:a,showAxis:c,animation:m,animationProgress:h,onAnimationChange:g})})})},so=({shapes:r,width:e,height:t,showGrid:n=!0,showAxis:s=!0,boundingBox:o,autoBoundingBox:i,onShapeChange:a,className:c="",animation:l,animationProgress:d,showAnimationControls:u,onAnimationChange:y})=>{const m=b.useRef(null),[h,g]=b.useState({width:600,height:400});b.useEffect(()=>{const x=()=>{if(m.current){const{clientWidth:R,clientHeight:C}=m.current;R>0&&C>0&&g({width:R,height:C})}};x(),window.addEventListener("resize",x);const S=new ResizeObserver(x);return m.current&&S.observe(m.current),()=>{window.removeEventListener("resize",x),S.disconnect()}},[]);const p={width:e?typeof e=="string"?e:`${e}px`:"100%",height:t?typeof t=="string"?t:`${t}px`:"100%"};return f.jsx("div",{ref:m,className:`mathcard-v2-graph ${c}`,style:p,children:f.jsx(Ar,{shapes:r,width:h.width,height:h.height,showGrid:n,showAxis:s,boundingBox:o,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:l,animationProgress:d,showAnimationControls:u,onAnimationChange:y})})},dn=({config:r,onTransformChange:e,onTransformComplete:t,onError:n,layoutDensity:s,boardHeight:o,boardWidth:i,className:a=""})=>{const c=s??r.ui?.layoutDensity??"default",l=o??r.ui?.boardHeight??300,d=i??r.ui?.boardWidth??400,u=h=>{e?.(h)},y=()=>{t?.()},m=h=>{n?.(h)};return console.error("🔍 GeometryTransformContent: config =",{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,shapesAnimatedLength:r.shapes?.animated?.length,shapesStaticLength:r.shapes?.static?.length,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,boardConfigKeys:r.boardConfig?Object.keys(r.boardConfig):[],boardConfigBoundingBox:r.boardConfig?.boundingBox,boardConfigOriginX:r.boardConfig?.originX,boardConfigOriginY:r.boardConfig?.originY,configKeys:Object.keys(r)}),f.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:f.jsx(Bs,{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,onTransformChange:u,onTransformComplete:y,onError:m,layoutDensity:c,boardHeight:l,boardWidth:d,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})},Ll=({headers:r,values:e,colors:t={}})=>{const{headerBg:n="#f1f5f9",valueBg:s="#ffffff",borderColor:o="#e2e8f0"}=t;return r.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):f.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:[f.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${o}`},children:r.map((i,a)=>f.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:n,fontWeight:"600",textAlign:"center",borderRight:a<r.length-1?`1px solid ${o}`:"none",color:"#1e293b"},children:i},a))}),f.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>f.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))})]})},oo=({content:r,onInteraction:e})=>{const t=(n,s)=>{if(n.enabled===!1)return null;const o=`${n.type}-${s}`,i=a=>{e?.(o,a)};switch(n.type){case"text":return f.jsx(to,{content:n.content,style:n.style,onInteraction:i},o);case"formula":const a=n;return f.jsx(ro,{parts:a.parts||[],displayMode:a.displayMode,style:n.style},o);case"graph":const c=n;return f.jsx(so,{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},o);case"hundredGrid":const l=n;return f.jsx(Xs,{...l.props},o);case"placeValueChart":const d=n;return f.jsx(Ll,{...d.props},o);case"geometryTransform":const u=n;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:u.metadata,config:u.metadata?.config,hasConfig:!!u.metadata?.config,configKeys:u.metadata?.config?Object.keys(u.metadata.config):[],configShapes:u.metadata?.config?.shapes,configShapesAnimatedLength:u.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:u.metadata?.config?.shapes?.static?.length,configBase:u.metadata?.config?.base,configHeight:u.metadata?.config?.height,configUnit:u.metadata?.config?.unit,configTransform:u.metadata?.config?.transform}),f.jsx(dn,{config:u.metadata.config,onTransformChange:y=>i({type:"transformChange",progress:y}),onTransformComplete:()=>i({type:"transformComplete"}),onError:y=>i({type:"error",error:y})},o);default:return f.jsx("div",{onClick:()=>i({type:"click"}),children:n.content},o)}};return f.jsx(f.Fragment,{children:r.map(t)})},_e=({data:r,scene:e="question",layout:t={type:"card"},renderer:n={mode:"default"},theme:s="light",onContentInteraction:o,className:i="",children:a})=>{const c=Js(r,e),l={data:c,scene:e,layout:c.layout||t,renderer:c.renderer||n,theme:s,onContentInteraction:o},d=c.layout||t,u=(()=>{switch(d.type){case"grid":return Qs;case"flow":return eo;default:return Zs}})(),y=(()=>{const m={className:i,theme:s,"data-testid":"mathcard-v2-container"};switch(d.type){case"grid":return{...m,columns:d.columns||2,gap:d.gap||"16px",responsive:d.responsive!==!1};case"flow":return{...m,direction:d.direction||"vertical",gap:d.gap||"16px",wrap:d.wrap!==!1};default:return{...m,padding:d.padding||"24px",shadow:d.shadow!==!1,border:d.border!==!1}}})();return f.jsx(Nl.Provider,{value:l,children:f.jsx(u,{...y,children:a||f.jsx(oo,{content:c.content,layout:c.layout||t,onInteraction:o})})})};_e.CardLayout=Zs;_e.GridLayout=Qs;_e.FlowLayout=eo;_e.TextContent=to;_e.FormulaContent=ro;_e.GraphContent=so;_e.GeometryTransformContent=dn;_e.ContentRenderer=oo;const io=r=>{const{ixlConfig:e,enableIXLStyle:t,isMobile:n}=r,s=b.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),o=b.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=b.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=b.useMemo(()=>{if(!t)return{};const d={backgroundColor:o,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return n?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},[t,o,i,n]),c=b.useMemo(()=>!t||n?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[t,n]);return{ixlClassName:b.useMemo(()=>{if(!t)return"";const d=["ixl-styled"];return d.push(`ixl-type-${e.type}`),n?d.push("ixl-mobile-layout"):d.push("ixl-desktop-layout"),d.join(" ")},[t,e.type,n]),tagStyle:a,contentStyle:c,tagText:s,tagColor:o,tagTextColor:i}},Ul=(r,e)=>{let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>{r(...n)},e)}},ao=(r={})=>{const e=typeof r=="number"?r:r.breakpoint||768,t=typeof r=="number"?!0:r.enabled!==!1,[n,s]=b.useState(()=>typeof window<"u"?window.innerWidth:1024),[o,i]=b.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=b.useRef(new Set),c=b.useCallback(()=>{if(typeof window>"u")return;const y=window.innerWidth,m=y<e;s(y),i(m),a.current.forEach(h=>{try{h()}catch(g){console.error("Error in resize listener:",g)}})},[e]),l=b.useCallback(Ul(c,150),[c]);b.useEffect(()=>{if(!(!t||typeof window>"u"))return c(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l)}},[t,l,c]);const d=b.useCallback(y=>(a.current.add(y),()=>{a.current.delete(y)}),[]),u=b.useCallback(y=>{a.current.delete(y)},[]);return{isMobile:o,viewportWidth:n,addResizeListener:d,removeResizeListener:u}},xt=({cardProps:r,ixlConfig:e,enableIXLStyle:t=!0,wrapperMode:n="mathcard",mobileBreakpoint:s=768,className:o="",style:i,children:a,onResponsiveChange:c})=>{const l=ao(s),d=io({ixlConfig:e,enableIXLStyle:t,isMobile:l.isMobile});b.useEffect(()=>{c?.(l.isMobile)},[l.isMobile,c]);const u=b.useMemo(()=>{const h=["ixl-style-card-container"];return t&&h.push(d.ixlClassName),o&&h.push(o),l.isMobile?h.push("ixl-mobile"):h.push("ixl-desktop"),h.join(" ")},[t,d.ixlClassName,o,l.isMobile]),y=b.useMemo(()=>{const h={...i};return t&&!l.isMobile?{...h,paddingLeft:d.contentStyle.paddingLeft}:h},[t,l.isMobile,d.contentStyle,i]),m=b.useMemo(()=>{if(n!=="mathcard"||!r)return"";const h=[r.className||""];return t&&h.push("ixl-adjusted"),h.filter(Boolean).join(" ")},[n,r?.className,t]);return f.jsxs("div",{className:u,style:y,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":t,"data-responsive-mode":l.isMobile?"mobile":"desktop",children:[t&&e.showTag!==!1&&f.jsx("div",{className:"ixl-tag",style:d.tagStyle,"data-testid":"ixl-tag",children:f.jsx("span",{className:"ixl-tag-text",children:d.tagText})}),n==="mathcard"&&r?f.jsx(_e,{...r,className:m}):a]})};xt.displayName="IXLStyleCard";const Gl={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},zl={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},Bl={remember:"速记",review:"回顾",solve:"解答"},Vl=({grades:r,onGradeSelect:e,selectedGrade:t})=>f.jsxs("div",{className:"grade-navigation",children:[f.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),f.jsx("div",{className:"grade-navigation__grid",children:r.map(n=>f.jsxs("div",{className:`grade-card ${t===n.id?"grade-card--selected":""}`,style:{borderLeftColor:n.color},onClick:()=>e?.(n.id),children:[f.jsx("div",{className:"grade-card__level",children:n.level}),f.jsx("div",{className:"grade-card__name",children:n.name}),f.jsx("div",{className:"grade-card__description",children:n.description})]},n.id))})]}),lo=({abilities:r,width:e=400,height:t=400})=>{const n=()=>r.length===0?"":r.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*r.indexOf(i)/r.length,c=i.score/i.maxScore*40+10,l=50+c*Math.sin(a),d=50-c*Math.cos(a);return`${l},${d}`}).join(" "),s=i=>{const a=Math.PI*2*i/Math.max(r.length,1),c=50+40*Math.sin(a),l=50-40*Math.cos(a);return{x2:c,y2:l}},o=i=>{const a=Math.PI*2*i/Math.max(r.length,1),c=50+45*Math.sin(a),l=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:c,y:l,textAnchor:d}};return f.jsxs("svg",{"data-testid":"radar-chart",width:e,height:t,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[f.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),r.map((i,a)=>{const{x2:c,y2:l}=s(a);return f.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:c,y2:l,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),r.length>2&&f.jsx("polygon",{"data-testid":"radar-polygon",points:n(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),r.map((i,a)=>{let c,l;if(i.svgPoint)c=i.svgPoint.x,l=i.svgPoint.y;else{const d=Math.PI*2*a/r.length,u=i.score/i.maxScore*40+10;c=50+u*Math.sin(d),l=50-u*Math.cos(d)}return f.jsx("circle",{"data-testid":"data-point",cx:c,cy:l,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),r.map((i,a)=>{const{x:c,y:l,textAnchor:d}=o(a);return f.jsx("text",{x:c,y:l,textAnchor:d,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},Jn={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 ql{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),Jn):(await re.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 Jn}}static async submitFeedback(e){try{await re.post(`${this.API_BASE_URL}/feedback`,e)}catch(t){throw console.error("Failed to submit feedback:",t),new Error("提交反馈失败")}}}const Wl=Ft.create((r,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){r({loading:!0,error:null});try{const t=await ql.fetchRadarAbilityData();r({data:t,loading:!1})}catch(t){const n=t instanceof Error?t.message:"获取数据失败";r({error:n,loading:!1})}}},setData:t=>{r({data:t,error:null,loading:!1})},setError:t=>{r({error:t,loading:!1})},reset:()=>{r({data:null,loading:!1,error:null})}})),co=({ability:r})=>{const e=r.score/r.maxScore*100;return f.jsxs("div",{className:"ability-progress-bar-item","data-ability":r.name,"data-testid":"progress-bar-container",children:[f.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[f.jsx("span",{className:"text-gray-700 font-medium",children:r.name}),f.jsxs("span",{className:"text-gray-600",children:[r.score,"/",r.maxScore]})]}),f.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:f.jsx("div",{className:`${r.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":r.score,"aria-valuemin":0,"aria-valuemax":r.maxScore,"aria-label":`${r.name} progress: ${r.score} out of ${r.maxScore}`})})]})},fo=({generalRecommendation:r})=>f.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),f.jsxs("div",{className:"ml-3",children:[f.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),f.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:r})]})]})}),uo=({ability:r,customLinkTexts:e={}})=>{const t=n=>{const s={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[n]||s[n]||"开始挑战"};return f.jsx(Ne.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":r.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:f.jsx(Ne.CardBody,{className:"p-5",children:f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[r.name,": 专项提高"]}),f.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:r.recommendation}),f.jsx(Ne.Button,{as:"a",href:r.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:f.jsx(Ur.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${r.name}专项提高页面`,children:t(r.name)})]})})})},Hl="_dashboardLayout_10wqn_5",Yl="_upperSection_10wqn_19",Kl="_lowerSection_10wqn_33",Xl="_radarChartArea_10wqn_51",Xt={dashboardLayout:Hl,upperSection:Yl,lowerSection:Kl,radarChartArea:Xl},Jl=()=>{const{data:r,loading:e,error:t,fetchData:n}=Wl();return b.useEffect(()=>{n()},[n]),e?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),f.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):t?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[f.jsx("div",{className:"text-red-500 mb-4",children:f.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),f.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),f.jsx("p",{className:"text-gray-600 mb-4",children:t}),f.jsx("button",{onClick:n,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:"重试"})]}):r?f.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:[f.jsxs("div",{className:"flex justify-between items-center mb-6",children:[f.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),f.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${r.overallRating}`,children:["综合评级: ",r.overallRating]})]}),f.jsxs("div",{className:Xt.dashboardLayout,children:[f.jsxs("div",{className:Xt.upperSection,children:[f.jsx("div",{className:Xt.radarChartArea,children:f.jsx(lo,{abilities:r.abilities})}),f.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:r.abilities.map(s=>f.jsx(co,{ability:s},s.name))})]}),f.jsxs("div",{className:Xt.lowerSection,children:[f.jsx(fo,{generalRecommendation:r.generalRecommendation}),f.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:r.abilities.map(s=>f.jsx(uo,{ability:s},s.name))})]})]})]}):f.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:f.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},Ot={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},Zl={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},Ql={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Bt={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},ec=[{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")}],tc="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",se={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:""}]}]}]},rc=ec,nc=Bt;class sc{baseURL;token;constructor(e="/api/v1",t=tc){this.baseURL=e,this.token=t}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,t={}){const n=await fetch(e,{...t,headers:{...this.getAuthHeaders(),...t.headers}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return n}async getCourseData(e){return(await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}`)).json()}async getUserGradeUnitsNav(e){const t=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(t)).json()}async getUnitProgress(e,t){const n=t?`${this.baseURL}/content/courses/${e}/units/${t}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(n)).json()}async batchUpdateLessonProgress(e,t){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(t)})).json()}async updateLessonProgress(e,t,n,s){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${t}/lessons/${n}/progress`,{method:"POST",body:JSON.stringify({status:s})})}setToken(e){this.token=e}getToken(){return this.token}}const Jt=new sc;class ze extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="DataSourceError"}}class oc{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},Jt.setToken(this.config.token)}async getUserGradeUnitsNav(e,t){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.withRetry(()=>Jt.getUserGradeUnitsNav(e))}catch(n){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",n),new ze(`获取年级单元导航数据失败: ${n instanceof Error?n.message:"未知错误"}`,"GET_USER_GRADE_UNITS_NAV_FAILED",n instanceof Error?n: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(t){throw console.error("[ApiDataSource] 获取用户个人信息失败:",t),new ze(`获取用户个人信息失败: ${t instanceof Error?t.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",t instanceof Error?t: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 ze(`获取探索菜单数据失败: ${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(()=>Jt.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(t){throw console.error("[ApiDataSource] 更新课时进度失败:",t),new ze(`更新课时进度失败: ${t instanceof Error?t.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",t instanceof Error?t:void 0)}}async batchUpdateLessonProgress(e,t){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,t),await this.withRetry(()=>Jt.batchUpdateLessonProgress(e,t))}catch(n){throw console.error("[ApiDataSource] 批量更新课时进度失败:",n),new ze(`批量更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async withRetry(e){let t;for(let n=1;n<=this.config.retryCount;n++)try{return await e()}catch(s){t=s instanceof Error?s:new Error(String(s)),n<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${n}次重试...`,t.message),await this.delay(this.config.retryDelay))}throw t}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}}class ic{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,t){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${t}`),new ze("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${t}`),{userId:t,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:se.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:se.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:Ot[s.moduleCategory]||Ot.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new ze("模拟数据源:获取用户个人信息失败","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 ze("模拟数据源:获取探索菜单数据失败","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 ze("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,t){if(await this.simulateDelay(),this.shouldSimulateError())throw new ze("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,t),{success:!0,results:t.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 se}getLessonsData(){const e={};return se.units.forEach(t=>{e[t.id]=t.lessons.map(n=>({id:n.id,title:n.title,duration:n.duration,knowledgeItems:n.knowledgeItems.map(s=>({...s,progress:0}))}))}),e}}class ac{static instances=new Map;static createDataSource(e){const{type:t,config:n,customDataSourceClass:s}=e,o=this.getInstanceKey(t,n);if(this.instances.has(o))return this.instances.get(o);let i;switch(t){case"api":i=new oc(n);break;case"mock":i=new ic(n);break;case"custom":if(!s)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new s(n);break;default:throw new Error(`不支持的数据源类型: ${t}`)}return this.instances.set(o,i),console.log(`[DataSourceFactory] 创建数据源: type=${t}, name=${n.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 t=!1,n=!1,s=!1;try{typeof process<"u"&&process.env?(t=process.env.NODE_ENV==="development",n=process.env.NODE_ENV==="test",s=process.env.REACT_APP_USE_MOCK==="true"):(t=!0,s=!0)}catch(o){console.warn("无法检测环境变量,使用默认配置:",o),t=!0,s=!0}return t||n||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,t){return`${e}:${t.name}:${JSON.stringify(t)}`}}function lc(){return ac.createDefaultDataSource()}function cc(r={}){const{dataSource:e=lc(),fallbackStrategy:t="mock",errorHandling:n={},performance:s={},theme:o={},debug:i=!1,enableDevTools:a=!1}=r;return{dataSource:e,fallbackStrategy:t,errorHandling:{showUserFriendlyErrors:!0,logErrors:!0,autoRetry:!0,maxRetries:3,retryDelay:1e3,...n},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 dc(r,e){return{...r,...e,errorHandling:{...r.errorHandling,...e.errorHandling},performance:{...r.performance,...e.performance},theme:{...r.theme,...e.theme}}}const mo=b.createContext(null),ho=()=>{const r=b.useContext(mo);if(!r)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return r},go=({children:r,config:e})=>{const[t,n]=b.useState(()=>cc(e)),[s,o]=b.useState(null),[i,a]=b.useState([]),[c,l]=b.useState(null),[d,u]=b.useState({}),[y,m]=b.useState(!1),[h,g]=b.useState(null),[p,x]=b.useState(null),[S,R]=b.useState([]),C=b.useCallback(async($,k)=>{m(!0),g(null);try{process.env.NODE_ENV!=="test"&&await new Promise(M=>setTimeout(M,100));const B=await t.dataSource.getUserGradeUnitsNav($,k);l(B);const W={};se.units.forEach(M=>{W[M.id]=M.lessons.map(L=>({id:L.id,title:L.title,duration:L.duration,knowledgeItems:L.knowledgeItems.map(J=>({...J,progress:0}))}))}),console.log("Lessons data loaded:",W),u(W);try{const M=await t.dataSource.getUserProfile(k);o(M)}catch(M){console.warn("获取用户信息失败,使用默认数据:",M),o({id:k,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const M=await t.dataSource.getExploreMenu();a(M)}catch(M){console.warn("获取探索菜单失败,使用默认数据:",M),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(B){if(console.error("数据加载错误:",B),t.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const W={userId:k,courseId:$,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:se.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:se.units.map((L,J)=>({unitId:L.id,title:L.title,description:L.description,moduleCategory:L.moduleCategory,estimatedDuration:L.estimatedDuration,totalLessons:L.lessons.length,completedLessons:J<2?Math.floor(L.lessons.length*.5):0,progressPercentage:J<2?50:0,status:J<2?"in-progress":"not-started",lastAccessed:J<2?new Date().toISOString():void 0,isActive:J===0,route:`/math/grade-5/unit/${L.id}`,icon:Ot[L.moduleCategory]||Ot.Default}))};l(W);const M={};se.units.forEach(L=>{M[L.id]=L.lessons.map(J=>({id:J.id,title:J.title,duration:J.duration,knowledgeItems:J.knowledgeItems.map(j=>({...j,progress:0}))}))}),u(M),o({id:k,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else g(B instanceof Error?B.message:"数据加载失败"),l(null)}finally{m(!1)}},[t]),_=b.useCallback($=>{R(k=>k.includes($)?k.filter(B=>B!==$):[...k,$])},[]),O=b.useCallback($=>{x($)},[]),w=b.useCallback($=>{n(k=>dc(k,$))},[]);b.useEffect(()=>{if(console.log("unitsData state updated:",c),console.log("unitsData?.units:",c?.units),console.log("unitsData?.units?.length:",c?.units?.length),c&&c.units.length>0){console.log("Looking for active unit...");const $=c.units.find(B=>B.isActive);console.log("Found active unit:",$);const k=$?.unitId||c.units[0].unitId;console.log("Setting default active unit:",k),x(k),console.log("Default active unit set after state update:",k)}else console.log("No units data available for setting default active unit")},[c]);const F={userInfo:s,exploreMenu:i,unitsData:c,lessons:d,loading:y,error:h,activeUnitId:p,activeLessonIds:S,config:t,theme:t.theme,enableVirtualization:t.performance?.enableVirtualization,setLoading:m,setError:g,setActiveUnit:O,toggleLesson:_,loadPageData:C,updateConfig:w};return f.jsx(mo.Provider,{value:F,children:r})},fc=({gradeId:r,userId:e,onLearnAction:t,className:n,userInfo:s,exploreMenu:o})=>{const{userInfo:i,exploreMenu:a,unitsData:c,lessons:l,loading:d,error:u,activeUnitId:y,activeLessonIds:m,setActiveUnit:h,toggleLesson:g,loadPageData:p}=ho(),x=s??i,S=o??a;b.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",r,"userId:",e),p(r,e)},[r,e,p]),b.useEffect(()=>{console.log("activeUnitId from context:",y),console.log("lessons from context:",l);const _=c?.units?.find(w=>w.unitId===y)||null,O=_&&y&&l[y]?{id:_.unitId,title:_.title,description:_.description,estimatedDuration:_.estimatedDuration,totalLessons:_.totalLessons,moduleCategory:_.moduleCategory,lessons:l[y]}:null;console.log("activeUnit computed:",O)},[y,l,c]);const R=c?.units?.find(_=>_.unitId===y)||null,C=R&&y&&l[y]?{id:R.unitId,title:R.title,description:R.description,estimatedDuration:R.estimatedDuration,totalLessons:R.totalLessons,moduleCategory:R.moduleCategory,lessons:l[y]}:null;return d?f.jsx("div",{className:`grade-unit-browser-page loading ${n||""}`,"data-testid":"grade-unit-browser-page",children:f.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):u?f.jsxs("div",{className:`grade-unit-browser-page error ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"error-message","data-testid":"error-message",children:u}),f.jsx("button",{onClick:()=>p(r,e),className:"retry-button",children:"重试"})]}):f.jsxs("div",{className:`grade-unit-browser-page ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"header-area",children:f.jsx(Us,{userData:x||void 0,exploreItems:S})}),f.jsx("div",{className:"sidebar-area",children:f.jsx(ps,{data:c,activeUnitId:y,onUnitSelect:h,loading:d})}),f.jsx("div",{className:"content-area",children:f.jsx(gs,{unit:C,activeLessonIds:m,onToggleLesson:g,onLearnAction:t||(()=>{}),loading:d})})]})},uc=r=>f.jsx(go,{config:r.config,children:f.jsx(fc,{...r})}),mc=(r,e,t=.1)=>{if(!r.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const n=parseFloat(r);if(isNaN(n))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(n<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const o=Math.abs(n-e)<=t;return{isValid:!0,isCorrect:o,errorMessage:o?void 0:"答案不正确,请再试一次"}},hc=()=>Ft.create((r,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:t=>{r({problemData:t,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:t=>{r({userAnswer:t,validationError:null})},submitAnswer:t=>{const n=e();if(!n.problemData){r({validationError:"问题数据未加载,请刷新页面重试"});return}const s=n.problemData.answer_info?.value??n.problemData.answer.value,o=Number(s),i=n.problemData.answer_info?.tolerance??.1,a=mc(t,o,i);if(!a.isValid){r({userAnswer:t,validationError:a.errorMessage||"答案格式错误"});return}r({userAnswer:t,isCorrect:a.isCorrect,showAnswerForm:!1,validationError:null,currentScene:a.isCorrect?"success":"explanation"})},nextQuestion:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),Xe=hc(),fn=()=>Xe(r=>r.currentScene),un=()=>Xe(r=>r.userAnswer),gc=()=>Xe(r=>r.isCorrect),mn=()=>Xe(r=>r.showAnswerForm),po=()=>Xe(r=>r.validationError),pc=()=>Xe(r=>r.problemData),hn=()=>Xe(en.useShallow(r=>({updateUserAnswer:r.updateUserAnswer,submitAnswer:r.submitAnswer,nextQuestion:r.nextQuestion,resetSession:r.resetSession,setProblemData:r.setProblemData}))),yc=b.createContext(null),Vt=()=>{const r=b.useContext(yc);if(!r)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return r},bc=()=>{const r=Vt(),e=b.useCallback(t=>t.currentScene,[]);return r(e)},xc=()=>{const r=Vt(),e=b.useCallback(t=>t.userAnswer,[]);return r(e)},vc=()=>{const r=Vt(),e=b.useCallback(t=>t.showAnswerForm,[]);return r(e)},_c=()=>{const r=Vt(),e=b.useCallback(t=>t.validationError,[]);return r(e)},wc=()=>Vt()(en.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),gn=()=>{try{return bc()}catch{return fn()}},pn=()=>{try{return xc()}catch{return un()}},yn=()=>{try{return vc()}catch{return mn()}},bn=()=>{try{return _c()}catch{return po()}},xn=()=>{try{return wc()}catch{return hn()}},wt=({problemData:r,userAnswer:e,showAnswerForm:t,onAnswerSubmit:n,onAnswerChange:s,validationError:o})=>{const i=c=>{c.preventDefault(),n(e)},a=c=>{s(c)};return f.jsx("div",{className:"question-scene-container",children:f.jsxs("div",{className:"question-scene-card",children:[f.jsx("div",{className:"question-display-area",children:f.jsx(_e,{data:{id:r.id,grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1}})}),t&&f.jsxs("div",{className:"answer-form-container",children:[f.jsxs("form",{onSubmit:i,className:"answer-form",children:[f.jsx("label",{className:"answer-label",children:"答案"}),f.jsx("input",{type:"number",value:e,onChange:c=>a(c.target.value),className:`answer-input ${o?"error":"normal"}`,placeholder:"?",required:!0}),f.jsx("span",{className:"answer-unit",children:r.basicInfo.answerUnit||r.basicInfo.areaUnit}),f.jsx(pt,{type:"submit",size:"lg",className:"submit-button",children:"提交答案"})]}),o&&f.jsxs("div",{className:"validation-error",children:[f.jsx("span",{children:"⚠️"}),f.jsx("span",{children:o})]})]})]})})},yo=({problemData:r,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",r),console.log("🔍 RememberModule scenes.remember:",r?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",r?.scenes?.remember?.content);const n=(()=>{const o=r.scenes?.review?.items;if(o&&Array.isArray(o)&&o.length>0)return console.log("🔍 RememberModule 使用 review.items"),o;const i=r.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=r.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const c=r.scenes?.remember?.content;return c&&Array.isArray(c)&&c.length>0?(console.log("🔍 RememberModule 使用 remember.content"),c):(console.log("🔍 RememberModule 未找到任何内容"),[])})();if(n.length===0){const o=f.jsx("div",{className:"remember-module-content",children:f.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})}const s=f.jsx("div",{className:"remember-module-content",children:n.map((o,i)=>{const{type:a,content:c,style:l,parts:d}=o;switch(a){case"text":return f.jsx("p",{className:"remember-module-text-block",style:l,children:c},i);case"formula":return f.jsx("div",{className:"remember-module-formula-block",children:f.jsx(_e,{data:{id:`formula-${i}`,grade:r.grade,unit:r.unit,content:[{type:"formula",content:c,parts:d||[c]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return f.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})},vn=({problemData:r,userAnswer:e,enableIXLStyle:t=!0})=>{const n=f.jsxs("div",{className:"review-module-content",children:[f.jsx("p",{className:"review-module-question",children:r.basicInfo.question}),f.jsx("div",{className:"review-module-graph",children:f.jsx(_e,{data:{id:"review-problem",grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:t?"ixl-adjusted":""})}),f.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",f.jsx("span",{className:"review-module-user-answer-value",children:e})]})]});return t?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:n}):f.jsxs("div",{className:"review-module-container",children:[f.jsx("h4",{className:"review-module-title",children:"复习"}),n]})},Ac=r=>[{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)"}][r%3],Rc=({step:r,problemData:e,stepNumber:t})=>{const{title:n,description:s,chartConfig:o}=r.content,i=!!o,a=Ac(t-1),c=[{type:"text",content:s.replace(/<br>/g,`
14
+ `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return f.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[f.jsxs("h3",{className:"explanation-step-title",children:[f.jsx("span",{className:"explanation-step-number",children:t}),f.jsx("span",{children:n})]}),f.jsxs("div",{className:"explanation-step-content",children:[f.jsx(_e,{data:{id:`${r.id}-description`,grade:e.grade,unit:e.unit,content:c},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&f.jsx("div",{className:"explanation-step-chart-container",children:o.type==="geometryTransform"&&(o.config||o.metadata?.config)?f.jsx(dn,{config:o.config||o.metadata?.config,onTransformChange:l=>console.log("Transform progress:",l),onTransformComplete:()=>console.log("Transform complete"),onError:l=>console.error("Geometry transform error:",l)}):f.jsx(Ar,{shapes:o.shapes||[],width:400,height:300,boundingBox:o.boundingBox||[-10,10,10,-10],showGrid:o.showGrid||!1,showAxis:o.showAxis||!1,mode:"view",className:"mx-auto"})})]})]})};function Sc(r){return r.steps!==void 0}function Cc(r){if(Sc(r))return r;if(Array.isArray(r)){if(r.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=r[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=r.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:n,total_steps:n.length,strategy:"step_by_step",estimated_time:n.length*30}}else return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}const _n=({problemData:r,enableIXLStyle:e=!0})=>{const[t,n]=b.useState(!1),s=r?.scenes?.solve?.items||r?.scenes?.solve?.content,o=Array.isArray(s)&&s.length>0,i=b.useMemo(()=>Cc(r.explanation),[r.explanation]),a=i.steps.length>0,c=b.useMemo(()=>a?i.steps.map(d=>({...d,content:{title:d.title,description:d.description,chartConfig:d.chartConfig?{...d.chartConfig,boundingBox:d.chartConfig.type==="graph"&&Array.isArray(d.chartConfig.boundingBox)&&d.chartConfig.boundingBox.length===4?[d.chartConfig.boundingBox[0],d.chartConfig.boundingBox[1],d.chartConfig.boundingBox[2],d.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[a,i.steps]),l=f.jsxs("div",{className:"solve-module-content",children:[o?f.jsxs(f.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",s),s?.forEach?.((d,u)=>{d.type==="geometryTransform"&&console.log(`🔍 SolveModule: geometryTransform block [${u}] =`,{type:d.type,hasMetadata:!!d.metadata,metadata:d.metadata,hasConfig:!!d.config,config:d.config,hasShapes:!!d.shapes,shapes:d.shapes,hasTransform:!!d.transform,transform:d.transform})}),f.jsx(_e,{data:{id:"solve-steps",grade:r.grade,unit:r.unit,content:s},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):f.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),f.jsx("div",{className:"solve-module-button-container",children:f.jsx("button",{type:"button",onClick:()=>n(d=>!d),className:"solve-module-button",children:t?"收起详细解题步骤":"查看详细解题步骤"})}),t&&f.jsxs("div",{className:"solve-module-detailed-container",children:[f.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),a?f.jsx("div",{className:"solve-module-detailed-list",children:c.map((d,u)=>f.jsx(Rc,{step:d,problemData:r,stepNumber:u+1},d.id))}):f.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:l}):f.jsxs("div",{className:"solve-module-container",children:[f.jsx("h4",{className:"solve-module-title",children:"解题"}),l]})},qt=({problemData:r,userAnswer:e,onNextQuestion:t})=>(console.log("🔍 ExplanationScene problemData:",r),console.log("🔍 ExplanationScene scenes.remember:",r?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",r?.scenes?.remember?.content),f.jsxs("div",{children:[f.jsx("div",{className:"explanation-error-banner",children:f.jsxs("div",{className:"explanation-inner-container",children:[f.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),f.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[f.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),f.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[f.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),f.jsx("div",{className:"correct-answer-value-container",children:f.jsx("span",{className:"correct-answer-value",children:f.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r.answer?.value??"--"})})})]})]}),f.jsx("div",{className:"explanation-button-container",children:f.jsx(pt,{onClick:t,size:"lg",className:"explanation-next-button",children:"明白了"})})]})}),f.jsxs("div",{className:"explanation-content-area",children:[f.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),f.jsx(vn,{problemData:r,userAnswer:e}),f.jsx(yo,{problemData:r}),f.jsx(_n,{problemData:r})]}),f.jsx("div",{className:"explanation-bottom-area",children:f.jsx(pt,{onClick:t,size:"md",children:"明白了"})})]})),At=({problemData:r,onNextQuestion:e})=>f.jsxs("div",{className:"success-scene-container",children:[f.jsx("h3",{className:"success-message-title",children:"正确!"}),f.jsx("p",{className:"success-message-description",children:"你做得很好!"}),f.jsx("div",{className:"concept-review-container",children:f.jsx(_e,{data:{id:"review-concepts",grade:r.grade,unit:r.unit,content:r.scenes?.review?.items||r.scenes?.review?.content||r.scenes?.remember?.items||r.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),f.jsx(pt,{onClick:e,size:"lg",className:"next-button",children:"下一题"})]}),Mr={MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"},Ec={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},Tc={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},X={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"},G={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 le extends Error{code;details;constructor(e,t,n){super(t),this.name="AdapterError",this.code=e,this.details=n}}const ir={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"}},Zn={[G.INVALID_INPUT]:"输入数据无效",[G.MISSING_REQUIRED_FIELD]:"缺少必需字段",[G.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[G.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[G.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[G.STYLE_REF_NOT_FOUND]:"样式引用未找到",[G.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[G.BOARD_REF_NOT_FOUND]:"画板引用未找到",[G.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[G.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[G.TRANSFORMATION_FAILED]:"数据转换失败",[G.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},tt={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Ir={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"]},bo=["question","solve","review","remember"],ee={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_]*)$/},ue={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},xo={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.8rem",heading_normal:"1.2rem",body:"1rem",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}}},vo={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_primary",fontSize:"$fonts.heading_large",fontWeight:"bold"},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"}}},_o={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:"左三角形模板"}}},wo={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"}}},Ao={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:"缩放变换"}}},mt={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:"垂直滑块动画"}}},Ro={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:"扩展画板配置(带网格和坐标轴)"}}},st={designTokens:xo.design_tokens,stylePresets:vo.style_presets,geometryPresets:_o.geometry_presets,layoutPresets:wo.layout_presets,transformDefinitions:Ao.transform_definitions,animationDefinitions:mt.slider_definitions,animationConfigs:mt.slider_definitions,boardDefinitions:Ro.board_definitions};function So(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!mt,sliderDefinitionsKeys:mt.slider_definitions?Object.keys(mt.slider_definitions):[]});const r=mt.slider_definitions;return{designTokens:xo.design_tokens,stylePresets:vo.style_presets,geometryPresets:_o.geometry_presets,layoutPresets:wo.layout_presets,transformDefinitions:Ao.transform_definitions,animationDefinitions:r,animationConfigs:r,boardDefinitions:Ro.board_definitions}}class Me{static canResolve(e){return ee.DESIGN_TOKEN.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,t.designTokens)}static resolvePath(e,t){const n=e.split(".");let s=t;for(const o of n){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,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`设计令牌解析失败: ${s}`,o)}return n}static extractDesignTokenRefs(e){const t=[],n=s=>{typeof s=="string"?this.canResolve(s)&&t.push(s):Array.isArray(s)?s.forEach(n):typeof s=="object"&&s!==null&&Object.values(s).forEach(n)};return n(e),t}static replaceDesignTokenRefs(e,t,n){const s=o=>{if(typeof o=="string"){if(this.canResolve(o))try{return this.resolve(o,t)}catch(d){if(n)return n(o);throw d}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,c=0;const l=[];for(;(a=i.exec(o))!==null;){a.index>c&&l.push(o.substring(c,a.index));const d=a[0];try{const u=this.resolve(d,t);l.push(String(u))}catch{n?l.push(String(n(d))):l.push(d)}c=a.index+d.length}return c<o.length&&l.push(o.substring(c)),l.length>1?l.join(""):o}else{if(Array.isArray(o))return o.map(s);if(typeof o=="object"&&o!==null){const i={};for(const[a,c]of Object.entries(o))i[a]=s(c);return i}}return o};return s(e)}}function Nc(){return{type:X.DESIGN_TOKEN,canResolve:Me.canResolve.bind(Me),resolve:Me.resolve.bind(Me)}}class De{static canResolve(e,t){if(typeof e!="string"||e.length===0)return!1;if(ee.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(t&&t.geometryPresets){let o;const i=e.match(ee.GEOMETRY_REF);return i?o=i[1]:o=e,o in t.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,t){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!t.geometryPresets,pointFound:!!t.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return console.error(`✅ 解析顶点引用 ${n}: 使用 position`,s.position),[s.position.x,s.position.y];if("x"in s&&"y"in s)return console.error(`✅ 解析顶点引用 ${n}: 使用 x/y`,{x:s.x,y:s.y}),[s.x,s.y]}return console.warn(`无法解析顶点引用: ${n}`),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,t){if(!this.canResolve(e,t))throw new Error(`无法解析的几何引用: ${e}`);let n;const s=e.match(ee.GEOMETRY_REF);s?n=s[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(t.geometryPresets||{}));const o=t.geometryPresets[n];if(!o)throw console.error(`❌ Geometry preset not found: ${n} in`,t.geometryPresets),new Error(`几何预设未找到: ${n}`);console.error("✅ Geometry resolved:",{name:n,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,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("顶点引用解析失败:",c),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,c)=>({index:c,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,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("端点引用解析失败:",c),a}})),i}static validate(e,t){if(!this.canResolve(e,t))return!1;let n;const s=e.match(ee.GEOMETRY_REF);return s?n=s[1]:n=e,n in t.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,t){const n=this.resolve(e,t);if(n.styleRef&&t.stylePresets[n.styleRef]){const s=t.stylePresets[n.styleRef];return{...n,style:{...s}}}return n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`几何引用解析失败: ${s}`,o)}return n}static extractGeometryRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.geometryRef&&typeof s.geometryRef=="string"&&t.push(s.geometryRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.geometryRef&&typeof o.geometryRef=="string"&&t.push(o.geometryRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function $c(){return{type:X.GEOMETRY_REF,canResolve:De.canResolve.bind(De),resolve:De.resolve.bind(De),validate:De.validate.bind(De)}}class we{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.TRANSFORM_REF.test(e)?!0:["left_rotation","right_rotation","translation"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const s=e.match(ee.TRANSFORM_REF);if(s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n])return{...t.transformDefinitions[n]};const o={left_rotation:{type:"rotation",angle:-90,origin:[0,0]},right_rotation:{type:"rotation",angle:90,origin:[0,0]},translation:{type:"translation",dx:0,dy:0}};if(o[n])return{...o[n]};throw new Error(`变换定义未找到: ${n}`)}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ee.TRANSFORM_REF);return s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n]?!0:["left_rotation","right_rotation","translation"].includes(n)}static applyTransform(e,t){if(!t||!e)return e;const n={...e};switch(t.type){case"rotation":n.vertices=this.applyRotation(e.vertices,t.angle,t.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,t.dx,t.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,t.factor,t.origin);break;default:console.warn(`未知的变换类型: ${t.type}`)}return n}static applyRotation(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n,i=t*Math.PI/180,a=Math.cos(i),c=Math.sin(i);return e.map(([l,d])=>{const u=l-s,y=d-o;return[s+u*a-y*c,o+u*c+y*a]})}static applyTranslation(e,t,n){return!e||!Array.isArray(e)?e:e.map(([s,o])=>[s+t,o+n])}static applyScale(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n;return e.map(([i,a])=>{const c=i-s,l=a-o;return[s+c*t,o+l*t]})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`变换引用解析失败: ${s}`,o)}return n}static extractTransformRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.transformRef&&typeof s.transformRef=="string"&&t.push(s.transformRef),Array.isArray(s.transformations)&&s.transformations.forEach(o=>{o.transformRef&&typeof o.transformRef=="string"&&t.push(o.transformRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function kc(){return{type:X.TRANSFORM_REF,canResolve:we.canResolve.bind(we),resolve:we.resolve.bind(we),validate:we.validate.bind(we)}}class xe{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.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,t){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const s=e.match(ee.STYLE_REF);s?n=s[1]:n=e;const o=t.stylePresets[n];if(!o)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(o,t)}static resolveStylePreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Me.canResolve(o))try{n[s]=Me.resolve(o,t)}catch(i){console.warn(`样式中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveStylePreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ee.STYLE_REF);return s?n=s[1]:n=e,n in t.stylePresets}static applyStyle(e,t){if(!e||!t)return e;const n={...e};return n.style=n.style?{...n.style,...t}:{...t},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(o=>{t[o]!==void 0&&(n[o]=t[o])}),n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`样式引用解析失败: ${s}`,o)}return n}static extractStyleRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.styleRef&&typeof s.styleRef=="string"&&t.push(s.styleRef),s.style&&typeof s.style=="object"&&s.style.styleRef&&typeof s.style.styleRef=="string"&&t.push(s.style.styleRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.styleRef&&typeof o.styleRef=="string"&&t.push(o.styleRef),o.style&&o.style.styleRef&&typeof o.style.styleRef=="string"&&t.push(o.style.styleRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Oc(){return{type:X.STYLE_REF,canResolve:xe.canResolve.bind(xe),resolve:xe.resolve.bind(xe),validate:xe.validate.bind(xe)}}class Le{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const s=e.match(ee.LAYOUT_REF);if(s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]){const i=t.layoutPresets[n];return this.resolveLayoutPreset(i,t)}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[n])return{...o[n]};throw new Error(`布局预设未找到: ${n}`)}static resolveLayoutPreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Me.canResolve(o))try{n[s]=Me.resolve(o,t)}catch(i){console.warn(`布局中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveLayoutPreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ee.LAYOUT_REF);return s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,t){if(!e||!t)return e;const n={...e};return n.layout?n.layout={...n.layout,...t}:n.layout={...t},n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`布局引用解析失败: ${s}`,o)}return n}static extractLayoutRefs(e){const t=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&t.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const s of Object.values(n.layout))typeof s=="string"&&this.isLayoutRef(s)&&t.push(s);return[...new Set(t)]}static isLayoutRef(e){return ee.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function jc(){return{type:X.LAYOUT_REF,canResolve:Le.canResolve.bind(Le),resolve:Le.resolve.bind(Le),validate:Le.validate.bind(Le)}}class rt{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.ANIMATION_REF.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new le(G.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(ee.ANIMATION_REF);if(!n)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const s=n[1],o=t.animationConfigs?.[s];if(!o)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${s}`);return this.resolveAnimationConfig(s,o,t)}static resolveAnimationConfig(e,t,n){if(!t.transforms||!Array.isArray(t.transforms))throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const s=t.transforms.map((a,c)=>{if(!a.id)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 id 字段`);if(!a.type)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] targetShapes 不能为空`);a.targetShapes.forEach((u,y)=>{if(typeof u!="string"||u.trim()==="")throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}].targetShapes[${y}] 必须是有效的字符串 ID`)});const l=Il(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:d}}),o={id:e,control:t.control,transforms:s,visualEffects:t.visualEffects||[],progressControl:t.progressControl},i=Fl(o);if(!i.valid)throw new le(G.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
20
15
  ${i.errors?.join(`
21
- `)}`);return s}static validate(e,t){if(!this.canResolve(e))return!1;let n;const o=e.match(ie.ANIMATION_REF);return o?n=o[1]:n=e,n in(t.animationConfigs||{})}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`动画引用解析失败: ${o}`,s)}return n}static extractAnimationRefs(e){const t=[],n=o=>{if(!(!o||typeof o!="object")){o.animationRef&&typeof o.animationRef=="string"&&t.push(o.animationRef),o.chartConfig?.animationRef&&typeof o.chartConfig.animationRef=="string"&&t.push(o.chartConfig.animationRef);for(const s of Object.values(o))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return n(e),[...new Set(t)]}}function Bc(){return{type:ee.ANIMATION_REF,canResolve:st.canResolve.bind(st),resolve:st.resolve.bind(st),validate:st.validate.bind(st)}}class Ze{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!t,contextKeys:Object.keys(t||{}),animationDefinitionsKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[],animationConfigsKeys:t.animationConfigs?Object.keys(t.animationConfigs):[]}),!this.canResolve(e))throw new me(B.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(ie.SLIDER_REF),o=n?n[1]:e;let s=t.animationDefinitions?.[o];return!s&&t.animationConfigs&&(s=t.animationConfigs[o]),!s&&at?.animationDefinitions&&(s=at.animationDefinitions[o]),!s&&at?.animationConfigs&&(s=at.animationConfigs[o]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:o,hasRawConfig:!!s,rawConfig:s,animationDefinitions:t.animationDefinitions,animationConfigs:t.animationConfigs,hasGlobalContext:!!at}),s?this.validateAndTransformConfig(o,s):(console.warn(`⚠️ 滑块配置未找到: ${o},使用默认配置`),{...Vc,id:o})}static validateAndTransformConfig(e,t){if(!t.slider)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=t,o=["position","length","orientation","min","max","step"];for(const s of o)if(!(s in n))throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${s} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:n.position,length:n.length,orientation:n.orientation,min:n.min,max:n.max,step:n.step},progressIndicator:t.progressIndicator,duration:t.duration,easing:t.easing,description:t.description}}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.SLIDER_REF),o=n?n[1]:e;return o in(t.animationDefinitions||{})||o in(t.animationConfigs||{}),!0}static batchResolve(e,t){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,t)}catch(s){console.warn(`滑块引用解析失败: ${o}`,s)}return n}static extractSliderRefs(e){const t=[],n=o=>{if(!(!o||typeof o!="object")){o.sliderRef&&typeof o.sliderRef=="string"&&t.push(o.sliderRef),o.chartConfig?.sliderRef&&typeof o.chartConfig.sliderRef=="string"&&t.push(o.chartConfig.sliderRef);for(const s of Object.values(o))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return n(e),[...new Set(t)]}}const Vc={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 Wc(){return{type:ee.SLIDER_REF,canResolve:Ze.canResolve.bind(Ze),resolve:Ze.resolve.bind(Ze),validate:Ze.validate.bind(Ze)}}class it{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const o=e.match(ie.GEOMETRY_TRANSFORM_REF),s=o?o[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${s}`,{hasGeometryTransformConfigs:!!t.geometryTransformConfigs,configKeys:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});const i=t.geometryTransformConfigs?.[s];if(!i)throw new me(B.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${s}`,{reference:e,configId:s,availableConfigs:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,t){const n={...e};for(const[o,s]of Object.entries(t))s!==void 0&&(n[o]=s);return t.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},t.shapes.static&&(n.shapes.static=t.shapes.static),t.shapes.animated&&(n.shapes.animated=t.shapes.animated)),t.transform&&(n.transform={...n.transform,...t.transform}),n}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.GEOMETRY_TRANSFORM_REF),o=n?n[1]:e;return!!t.geometryTransformConfigs?.[o]}static batchResolve(e,t,n){const o={};for(const s of e)if(this.canResolve(s)&&this.validate(s,t))try{const i=n?.[s];o[s]=this.resolve(s,t,i)}catch(i){console.warn(`几何变换引用解析失败: ${s}`,i)}return o}static extractFromContentBlock(e){return!e||typeof e!="object"?null:e.geometryTransformRef&&typeof e.geometryTransformRef=="string"?e.geometryTransformRef:null}static extractFromContentBlocks(e){const t=[];for(const n of e){const o=this.extractFromContentBlock(n);o&&t.push(o)}return[...new Set(t)]}}function qc(){return{type:ee.GEOMETRY_TRANSFORM_REF,canResolve:it.canResolve.bind(it),resolve:it.resolve.bind(it),validate:it.validate.bind(it)}}const Ur={geometryRef:ee.GEOMETRY_REF,styleRef:ee.STYLE_REF,layoutRef:ee.LAYOUT_REF,boardRef:ee.BOARD_REF,animationRef:ee.ANIMATION_REF,transformRef:ee.TRANSFORM_REF,appearanceRef:ee.STYLE_REF,geometryTransformRef:ee.GEOMETRY_TRANSFORM_REF,sliderRef:ee.SLIDER_REF,$ref:ee.GEOMETRY_REF};class Yc{static extractRefs(e){const t=[],n=new Set,o=s=>{if(!(!s||typeof s!="object"))for(const[i,a]of Object.entries(s)){if(i in Ur){if(typeof a=="string"){const d=Ur[i],l=`${i}:${a}`;n.has(l)||(n.add(l),t.push({ref:a,type:d,path:i,value:a,fieldName:i,combined:l}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(l=>{const c=`$ref:${l}`;n.has(c)||(n.add(c),t.push({ref:l,type:ee.GEOMETRY_REF,path:"$ref",value:l,fieldName:"$ref",combined:c}))});continue}if(Array.isArray(a)){a.forEach(d=>o(d));continue}typeof a=="object"&&o(a)}};return o(e),t}static extractDesignTokens(e){const t=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let o;for(;(o=n.exec(e))!==null;)t.push(o[0]);return t}static calculateStats(e){const t=this.extractRefs(e).map(s=>s.ref),n={},o=s=>{if(!(!s||typeof s!="object"))for(const[i,a]of Object.entries(s))i in Ur?n[i]=(n[i]||0)+1:typeof a=="object"&&o(a)};return o(e),{totalRefs:t.length,uniqueRefs:new Set(t).size,fieldCounts:n}}}class gt{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(Dc()),this.register(Lc()),this.register(Uc()),this.register(Gc()),this.register(zc()),this.register(Bc()),this.register(Wc()),this.register(qc())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(t=>t.type===e)}getResolverForRef(e){return this.resolvers.find(t=>t.canResolve(e))}resolve(e,t){if(typeof e!="string"){const o=this.getResolverByType(e.type);if(!o)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return o.resolve(e.value,t)}catch(s){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${s}`)}}const n=this.resolvers.filter(o=>o.canResolve(e));if(n.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const o of n)try{return o.resolve(e,t)}catch(s){console.debug(`解析器 ${o.type} 解析 ${e} 失败:`,s);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,t){const n={};for(const o of e)try{const s=this.resolve(o,t),i=typeof o=="string"?o:o.combined;n[i]=s}catch(s){const i=typeof o=="string"?o:o.combined;console.warn(`引用解析失败: ${i}`,s)}return n}extractAllRefsEnhanced(e){try{return Yc.extractRefs(e)}catch(t){return console.warn("ReferenceExtractor 提取失败:",t),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const t=[],n=o=>{if(!(!o||typeof o!="object"))for(const[s,i]of Object.entries(o))if(s.endsWith("Ref")&&typeof i=="string")t.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&&t.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(t)]}validate(e,t){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,t);try{return n.resolve(e,t),!0}catch{return!1}}}function Os(){return new gt}class nr{static transform(e,t,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error("🔄 GraphTransformer.transform START for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:o,strictMode:s,contextGeometryKeys:Object.keys(t.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:o,strictMode:s}),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:ye.GRAPH};if(!o)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,t),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,d)=>(console.error(` 🎯 处理shape[${d}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,t,{strictMode:s})))),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style=a}catch(a){if(s)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}`,d=st.resolve(a,t);console.warn(" 动画配置解析结果:",{animationId:d.id,transformCount:d.transforms.length,hasControl:!!d.control,controlConfig:d.control,hasVisualEffects:!!d.visualEffects,visualEffectsCount:d.visualEffects?.length||0}),i.animation=d,i.transformDefinitions&&(console.warn(" 清理旧的 transformDefinitions(被 animation 替代)"),delete i.transformDefinitions)}catch(a){if(s)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(s)throw a;return console.warn("图形转换失败:",a),i}}static transformShape(e,t,n={}){const{strictMode:o=!1}=n;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(t.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 s={...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(s.geometryRef){console.warn(`🔄 GraphTransformer processing geometryRef: ${s.geometryRef} for shape ${s.id}`,{shapeId:s.id,shapeType:s.type,geometryRef:s.geometryRef,contextHasGeometryPresets:!!t.geometryPresets,geometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});try{const i=Be.resolve(s.geometryRef,t);console.warn(` Geometry resolved for ${s.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=s.type,d=s.content,l={...s};Object.assign(s,i),s.id=e.id,a!==void 0&&(s.type=a),d!==void 0&&(s.content=d),console.warn(` After merge for ${s.id}:`,{type:s.type,vertices:s.vertices,verticesIsArray:Array.isArray(s.vertices),verticesLength:s.vertices?s.vertices.length:"undefined",position:s.position,endpoints:s.endpoints,endpointsIsArray:Array.isArray(s.endpoints),transformedShapeKeys:Object.keys(s)});const c=s.type;let u=!1;const y=t.geometryPresets[s.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:s.geometryRef,originalGeometryExists:!!y,originalGeometryType:y?.type,originalGeometryKeys:y?Object.keys(y):[],hasVertices:y&&"vertices"in y,verticesIsArray:y&&Array.isArray(y.vertices),verticesLength:y?.vertices?.length,contextGeometryPresetsKeys:Object.keys(t.geometryPresets||{})}),y&&y.vertices&&Array.isArray(y.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:y.vertices,hasWithLabel:"withLabel"in y,withLabel:y.withLabel,hasLabel:"label"in y,label:y.label}),s.verticesConfig||(s.verticesConfig={}),y.vertices.forEach((m,h)=>{if(console.warn(`🔍 DEBUG: 检查顶点${h}:`,{vertex:m,isObject:m&&typeof m=="object",hasDollarRef:m&&typeof m=="object"&&"$ref"in m,refName:m?.$ref}),m&&typeof m=="object"&&"$ref"in m){const g=m.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${g},检查context.geometryPresets`),t.geometryPresets&&t.geometryPresets[g]){const p=t.geometryPresets[g];console.warn(`🔍 DEBUG: 找到点定义 ${g}:`,p),p.name?(s.verticesConfig[h]||(s.verticesConfig[h]={}),s.verticesConfig[h].name=p.name,console.warn(`✅ 从原始几何定义提取顶点${h}名字: ${p.name}`)):console.warn(`⚠️ 点定义 ${g} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${g}`)}else console.warn(`⚠️ 顶点${h}不是$ref对象`)}),y.withLabel!==void 0&&(s.verticesConfig.withLabel=y.withLabel),y.label&&typeof y.label=="object"){const m=y.label;m.offset&&Array.isArray(m.offset)&&m.offset.length>=2&&(s.verticesConfig.offset=m.offset),m.fontSize!==void 0&&(s.verticesConfig.fontSize=m.fontSize),m.color&&(s.verticesConfig.color=m.color),m.anchorX&&(s.verticesConfig.anchorX=m.anchorX),m.anchorY&&(s.verticesConfig.anchorY=m.anchorY)}console.warn("✅ 构建的verticesConfig:",s.verticesConfig)}if(c==="segment"||c==="line"?u="endpoints"in s&&Array.isArray(s.endpoints):c==="point"?u="position"in s&&s.position!==void 0:c==="polygon"||c==="triangle"||c==="rectangle"||c==="parallelogram"?u="vertices"in s&&Array.isArray(s.vertices):u="vertices"in s&&Array.isArray(s.vertices)||"endpoints"in s&&Array.isArray(s.endpoints)||"position"in s&&s.position!==void 0,u||(console.error(`❌ ERROR: After geometryRef merge, shape ${s.id} (type: ${c}) has no valid geometry properties!`),console.error(" geometry keys:",Object.keys(i)),console.error(" geometry.type:",i.type),console.error(" transformedShape keys:",Object.keys(s))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const m=we.resolve(i.styleRef,t);console.error(" 几何样式解析结果:",m),s.style=m}}catch(i){if(o)throw i;console.error(`❌ 图形几何解析失败: ${s.geometryRef}`,i),console.error(` shape id: ${s.id}, type: ${s.type}`),console.error(" context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):"undefined")}delete s.geometryRef}if(s.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${s.styleRef}, shape id: ${s.id}`);try{const i=we.resolve(s.styleRef,t);console.error(" 形状样式解析成功:",i);const{id:a,...d}=i;s={...s,...d,style:{...s.style,...i}}}catch(i){if(o)throw i;console.warn(`图形元素样式解析失败: ${s.styleRef}`,i),delete s.style}delete s.styleRef}if(Array.isArray(s.transformations)&&(s.transformations=s.transformations.map(i=>this.transformTransform(i,t,{strictMode:o}))),s.label&&typeof s.label=="object"&&(s.label=this.transformLabel(s.label,t)),console.warn(`🔍 Checking segment conversion for ${s.id}:`,{type:s.type,hasEndpoints:"endpoints"in s,endpoints:s.endpoints,endpointsIsArray:Array.isArray(s.endpoints),endpointsLength:s.endpoints?s.endpoints.length:0,shapeKeys:Object.keys(s)}),s=this.convertShapeCoordinates(s,t),s.type==="segment"&&Array.isArray(s.endpoints)&&s.endpoints.length>=2){console.warn(`🔄 Converting segment to line for ${s.id}:`,{originalType:s.type,endpoints:s.endpoints}),s.type="line";const i=this.resolvePointReference(s.endpoints[0],t),a=this.resolvePointReference(s.endpoints[1],t);Array.isArray(i)&&i.length>=2?s.start={x:i[0],y:i[1]}:i&&typeof i=="object"&&"x"in i&&"y"in i?s.start=i:s.start=s.endpoints[0],Array.isArray(a)&&a.length>=2?s.end={x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?s.end=a:s.end=s.endpoints[1],delete s.endpoints}return console.warn(`✅ GraphTransformer finished transforming shape ${s.id} (${s.type}):`,{id:s.id,type:s.type,hasVertices:"vertices"in s,vertices:s.vertices,verticesIsArray:Array.isArray(s.vertices),verticesLength:s.vertices?s.vertices.length:0,hasVerticesConfig:"verticesConfig"in s,verticesConfig:s.verticesConfig,verticesConfigKeys:s.verticesConfig?Object.keys(s.verticesConfig):[],hasPosition:"position"in s,position:s.position,hasStart:"start"in s,start:s.start,hasEnd:"end"in s,end:s.end,hasEndpoints:"endpoints"in s,endpoints:s.endpoints,hasGeometryRef:"geometryRef"in s,geometryRef:s.geometryRef,keys:Object.keys(s)}),s}catch(i){if(o)throw i;return console.warn("图形元素转换失败:",i),s}}static resolvePointReference(e,t){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(t&&t.geometryPresets&&t.geometryPresets[n]){const o=t.geometryPresets[n];if(o.position)return o.position;if("x"in o&&"y"in o)return o}return e}if("geometryRef"in e){const n=e.geometryRef;if(t&&t.geometryPresets&&t.geometryPresets[n]){const o=t.geometryPresets[n];if(o.position)return o.position;if("x"in o&&"y"in o)return o}return e}return e}static convertShapeCoordinates(e,t){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 n={...e};if(n.position){if(Array.isArray(n.position)&&n.position.length>=2)console.warn(`🔄 Converting position array to object for ${n.id}:`,{shapeId:n.id,positionArray:n.position,convertedTo:{x:n.position[0],y:n.position[1]}}),n.position={x:n.position[0],y:n.position[1]};else if(typeof n.position=="object"){const o=this.resolvePointReference(n.position,t);o&&typeof o=="object"&&(n.position=o)}}if(Array.isArray(n.vertices)){const o=n.verticesConfig?{...n.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!n.verticesConfig,existingKeys:n.verticesConfig?Object.keys(n.verticesConfig):[],verticesConfigKeys:Object.keys(o)}),n.vertices=n.vertices.map((s,i)=>{const a=this.resolvePointReference(s,t);let d=null;if(s&&typeof s=="object"&&"$ref"in s){const l=s.$ref;t&&t.geometryPresets&&t.geometryPresets[l]&&(d=t.geometryPresets[l],console.warn(`📌 Found point definition for ${l} at vertex ${i}:`,{hasWithLabel:"withLabel"in d,withLabel:d.withLabel,hasLabel:"label"in d,labelKeys:d.label?Object.keys(d.label):"none"}),d.name&&(o[i]||(o[i]={}),o[i].name=d.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:(s&&typeof s=="object"&&("$ref"in s||"geometryRef"in s),s)}),n.withLabel!==void 0||n.label){const s={withLabel:n.withLabel!==void 0?n.withLabel:!0};if(n.label&&typeof n.label=="object"){const a=n.label;a.offset&&Array.isArray(a.offset)&&a.offset.length>=2&&(s.offset=a.offset),a.fontSize!==void 0&&(s.fontSize=a.fontSize),a.color&&(s.color=a.color),a.anchorX&&(s.anchorX=a.anchorX),a.anchorY&&(s.anchorY=a.anchorY)}const i={...s};for(const a in o)isNaN(Number(a))||(i[a]||(i[a]={}),Object.assign(i[a],o[a]));n.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${n.id}:`,i)}else Object.keys(o).length>0&&(n.verticesConfig=o,console.warn(`✅ Added verticesConfig for polygon ${n.id}:`,o))}if(Array.isArray(n.endpoints)&&(n.endpoints=n.endpoints.map(o=>{const s=this.resolvePointReference(o,t);return Array.isArray(s)&&s.length>=2?{x:s[0],y:s[1]}:s&&typeof s=="object"&&"x"in s&&"y"in s?s:(o&&typeof o=="object"&&("$ref"in o||"geometryRef"in o),o)})),Array.isArray(n.center)&&n.center.length>=2)n.center={x:n.center[0],y:n.center[1]};else if(n.center&&typeof n.center=="object"){const o=this.resolvePointReference(n.center,t);o&&typeof o=="object"&&(n.center=o)}if(n.start){if(Array.isArray(n.start)&&n.start.length>=2)n.start={x:n.start[0],y:n.start[1]};else if(typeof n.start=="object"){const o=this.resolvePointReference(n.start,t);o&&typeof o=="object"&&(n.start=o)}}if(n.end){if(Array.isArray(n.end)&&n.end.length>=2)n.end={x:n.end[0],y:n.end[1]};else if(typeof n.end=="object"){const o=this.resolvePointReference(n.end,t);o&&typeof o=="object"&&(n.end=o)}}for(const[o,s]of Object.entries(n))Array.isArray(s)?n[o]=s.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,t):i):s&&typeof s=="object"&&(n[o]=this.convertShapeCoordinates(s,t));return n}static transformTransform(e,t,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Se.resolve(s.transformRef,t);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformLabel(e,t){const n={...e};if(n.styleRef){try{const o=we.resolve(n.styleRef,t);n.style=o}catch(o){console.warn(`标签样式解析失败: ${n.styleRef}`,o)}delete n.styleRef}return n}static resolveBoardConfig(e,t){if(t.boardDefinitions&&t.boardDefinitions[e])return t.boardDefinitions[e];const n={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 n[e]||n.default}static validate(e){const t=[];return e?(e.type!==ye.GRAPH&&t.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&t.push("图形内容块 shapes 数组不能为空"):t.push("图形内容块缺少 shapes 数组"),t):(t.push("图形内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(o=>o.type===ye.GRAPH).map(o=>this.transform(o,t,n))}}function Hc(){return{type:ye.GRAPH,transform:nr.transform.bind(nr),validate:nr.validate.bind(nr)}}class or{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const t={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:t,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:t.static.length,animatedLength:t.animated.length}),t}static transform(e,t,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(o){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const c=it.resolve(e.geometryTransformRef,t,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",c),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(c||{}));const u={type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:c}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",u.metadata.config),u.metadata.config&&typeof u.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),u.metadata.config=this.transformConfig(u.metadata.config,t,{strictMode:s})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",u),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",u.metadata.config),u}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(c){if(s)throw c;console.error("❌ 几何变换引用解析失败:",c),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",t.geometryTransformConfigs)}}const i=e.base||e.config?.base||t.basicInfo?.base||0,a=e.height||e.config?.height||t.basicInfo?.height||0,d=e.unit||e.config?.unit||t.basicInfo?.baseUnit||"cm",l={...e,type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:d,...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:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete l.config,delete l.base,delete l.height,delete l.unit,delete l.shapes,delete l.transform,delete l.animation,delete l.boardConfig,!o)return l;try{if(l.geometryRef){try{const c=Be.resolve(l.geometryRef,t);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,c),c.styleRef){const u=we.resolve(c.styleRef,t);l.metadata.config.style=u}}catch(c){if(s)throw c;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,c)}delete l.geometryRef}if(l.transformRef){try{const c=Se.resolve(l.transformRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,c)}catch(c){if(s)throw c;console.warn(`几何变换变换解析失败: ${l.transformRef}`,c)}delete l.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!l.metadata,hasConfig:!!l.metadata?.config,configType:l.metadata?.config?typeof l.metadata.config:"undefined",configIsObject:l.metadata?.config?typeof l.metadata.config=="object":!1,configKeys:l.metadata?.config?Object.keys(l.metadata.config):[]}),l.metadata?.config&&typeof l.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),l.metadata.config=this.transformConfig(l.metadata.config,t,{strictMode:s}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const c=we.resolve(l.styleRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=c}catch(c){if(s)throw c;console.warn(`几何变换样式解析失败: ${l.styleRef}`,c)}delete l.styleRef}if(l.animationRef){try{const c=this.resolveAnimationConfig(l.animationRef,t,{strictMode:s});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...c,...l.metadata.config.animation||{}}}catch(c){if(s)throw c;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,c)}delete l.animationRef}if(l.sliderRef){try{const c=Ze.resolve(l.sliderRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...c,...l.metadata.config.animation||{}}}catch(c){if(s)throw c;console.warn(`顶层滑块引用解析失败: ${l.sliderRef}`,c)}delete l.sliderRef}if(l.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:l.boardRef,hasMetadataConfig:!!l.metadata?.config,currentBoardConfig:l.metadata?.config?.boardConfig});try{const c=this.resolveBoardConfig(l.boardRef,t,{strictMode:s});console.error("🔍 解析后的 boardConfig:",c),l.metadata.config||(l.metadata.config={}),l.metadata.config.boardConfig={...c,...l.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",l.metadata.config.boardConfig)}catch(c){if(s)throw c;console.warn(`顶层画板引用解析失败: ${l.boardRef}`,c)}delete l.boardRef}if(l.metadata?.config?.boardConfig&&typeof l.metadata.config.boardConfig=="object"){const c=l.metadata.config.boardConfig;(!c.boundingBox||!Array.isArray(c.boundingBox)||c.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),c.boundingBox=[0,7,10,0],c.originX=c.originX??2,c.originY=c.originY??2,c.keepAspectRatio=c.keepAspectRatio??!0,c.showGrid=c.showGrid??!1,c.showAxis=c.showAxis??!1,c.description=c.description||"默认画板配置")}return console.error("🔍 GeometryTransformTransformer.transform: 最终转换结果 =",{type:l.type,metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasTransform:!!l.metadata?.config?.transform,transform:l.metadata?.config?.transform,hasAnimation:!!l.metadata?.config?.animation,animation:l.metadata?.config?.animation,hasBoardConfig:!!l.metadata?.config?.boardConfig,boardConfig:l.metadata?.config?.boardConfig}),l}catch(c){if(s)throw c;return console.warn("几何变换转换失败:",c),l}}static transformConfig(e,t,n={}){const{strictMode:o=!1}=n,s={...e},i={};if(s.shapes&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 shapes"),console.error(" transformedConfig.shapes:",s.shapes),s.shapes.static&&(console.error(` 处理 static shapes (${s.shapes.static.length}):`),s.shapes.static=s.shapes.static.map((a,d)=>{console.error(` 处理 static shape[${d}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:o});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 static shape[${d}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l})),s.shapes.animated&&(console.error(` 处理 animated shapes (${s.shapes.animated.length}):`),s.shapes.animated=s.shapes.animated.map((a,d)=>{console.error(` 处理 animated shape[${d}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:o});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 animated shape[${d}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l}))),s.transform){if(s.transform.transformRef)try{const a=Se.resolve(s.transform.transformRef,t);s.transform={...a,...s.transform,transformRef:void 0},console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transform 对象中的 transformRef",{originalTransformRef:s.transform.transformRef,resolvedTransform:a,mergedTransform:s.transform})}catch(a){if(o)throw a;console.warn(`Transform ref解析失败: ${s.transform.transformRef}`,a)}s.transform=this.normalizeTransformConfig(s.transform,i),Array.isArray(s.transform.transforms)&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transforms 数组",{transformsLength:s.transform.transforms.length,transforms:s.transform.transforms}),s.transform.transforms=s.transform.transforms.map((a,d)=>{if(console.error(`🔍 处理 transform[${d}]:`,{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[${d}] 是字符串格式`),a.startsWith("transformRef:")){const l=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${l}`);try{const c=Se.resolve(l,t);console.error(`🔍 transform[${d}] 解析成功:`,c);const u=this.normalizeTransformConfig(c,i);return console.error(`🔍 transform[${d}] 标准化后:`,u),u}catch(c){if(o)throw c;return console.warn(`Transform ref解析失败: ${l}`,c),a}}try{const l=Se.resolve(a,t);return this.normalizeTransformConfig(l,i)}catch(l){if(o)throw l;return console.warn(`Transform ref解析失败: ${a}`,l),a}}else if(a&&typeof a=="object"&&a.transformRef){const l=a.transformRef;console.error(`🔍 transform[${d}] 是对象格式,refName=${l}`);try{const c=Se.resolve(l,t);console.error(`🔍 transform[${d}] 解析成功:`,c);const u={...c,...a,transformRef:void 0};console.error(`🔍 transform[${d}] 合并后:`,u);const y=this.normalizeTransformConfig(u,i);return console.error(`🔍 transform[${d}] 标准化后:`,y),y}catch(c){if(o)throw c;return console.warn(`Transform ref解析失败: ${l}`,c),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${d}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${d}] 未处理,返回原始值:`,a),a}))}if(s.geometry&&typeof s.geometry=="object"&&(s.geometry=this.transformGeometry(s.geometry,t,{strictMode:o})),Array.isArray(s.transformations)&&(s.transformations=s.transformations.map(a=>{if(a.transformRef)try{const d=Se.resolve(a.transformRef,t);return{...a,...d,transformRef:void 0}}catch(d){if(o)throw d;return console.warn(`Transformations解析失败: ${a.transformRef}`,d),a}return a})),s.style&&typeof s.style=="object"&&(s.style=this.transformStyle(s.style,t,{strictMode:o})),s.animationRef){try{const a=this.resolveAnimationConfig(s.animationRef,t,{strictMode:o});s.animation={...a,...s.animation||{}}}catch(a){if(o)throw a;console.warn(`动画引用解析失败: ${s.animationRef}`,a)}delete s.animationRef}if(s.sliderRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 sliderRef",{sliderRef:s.sliderRef,hasAnimationDefinitions:!!t.animationDefinitions,animationDefinitionKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[]});try{const a={...at,...t,animationDefinitions:t.animationDefinitions||at.animationDefinitions},d=Ze.resolve(s.sliderRef,a);s.animation={...d,...s.animation||{}}}catch(a){if(o)throw a;console.warn(`滑块引用解析失败: ${s.sliderRef}`,a)}delete s.sliderRef}if(s.boardRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 config 中的 boardRef",{boardRef:s.boardRef,currentBoardConfig:s.boardConfig});try{const a=this.resolveBoardConfig(s.boardRef,t,{strictMode:o});console.error("🔍 解析后的 boardConfig (config):",a),s.boardConfig={...a,...s.boardConfig||{}},console.error("🔍 设置后的 transformedConfig.boardConfig:",s.boardConfig)}catch(a){if(o)throw a;console.warn(`画板引用解析失败: ${s.boardRef}`,a)}delete s.boardRef}return s}static normalizeTransformConfig(e,t){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:t?Object.keys(t):[],geometryRefToShapeId:t});const n={...e};switch(!n.type&&n.config&&n.config.type&&(n.type=n.config.type),n.type){case"rotation":if(n.config){if(n.rotation={...n.config},n.rotation.center&&typeof n.rotation.center=="object"){const o=n.rotation.center;"x"in o&&"y"in o&&(n.rotation.center=[o.x,o.y])}delete n.config}break;case"translation":n.config&&(n.translation={...n.config},delete n.config);break;case"scale":if(n.config){if(n.scale={...n.config},n.scale.center&&typeof n.scale.center=="object"){const o=n.scale.center;"x"in o&&"y"in o&&(n.scale.center=[o.x,o.y])}delete n.config}break;case"composite":n.config&&Array.isArray(n.config.transforms)&&(n.composite=n.config.transforms.map(o=>this.normalizeTransformConfig(o,t)),delete n.config);break;default:if(n.config){const{type:o,...s}=n.config;Object.assign(n,s),delete n.config}}if(n.targetGroup&&t){const o=n.targetGroup;let s;if(t[o])s=t[o],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:o,mapped:s,type:"exact"});else{const i=Object.keys(t).find(a=>{if(a.startsWith(o+"_")||a===o||a.includes(o))return!0;const d=a.split("_"),l=o.split("_");return d.some(c=>l.includes(c))});i&&(s=t[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:o,geometryRef:i,mapped:s,type:"heuristic"}))}s?n.targetGroup=s:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:o,geometryRefToShapeId:t,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!n.targetGroup&&(n.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:n,hasRotation:!!n.rotation,hasTranslation:!!n.translation,hasScale:!!n.scale,hasComposite:!!n.composite}),n}static transformShape(e,t,n={}){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:!!t.geometryPresets,contextGeometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",s.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",t.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=Be.resolve(s.geometryRef,t);console.error("🔍 transformShape: geometry 解析结果:",i),Object.assign(s,i),console.error("🔍 transformShape: 合并后的 shape:",s),s.vertices&&Array.isArray(s.vertices)&&console.error("🔍 transformShape: 顶点数据:",{count:s.vertices.length,sample:s.vertices.slice(0,3).map((a,d)=>({index:d,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})}catch(i){if(console.error("🔍 transformShape: geometryRef 解析错误:",i),o)throw i;console.warn(`Shape geometryRef解析失败: ${s.geometryRef}`,i)}delete s.geometryRef,console.error("🔍 transformShape: 删除 geometryRef 后的 shape:",s)}if(s.styleRef){try{const i=we.resolve(s.styleRef,t);s.style=i}catch(i){if(o)throw i;console.warn(`Shape styleRef解析失败: ${s.styleRef}`,i)}delete s.styleRef}if(s.metadata||(s.metadata={}),!s.metadata.id&&s.id&&(s.metadata.id=s.id),s.withLabel!==void 0&&(s.metadata.showLabel=s.withLabel,delete s.withLabel),s.label&&(typeof s.label=="object"?s.metadata.label=s.label.text||s.metadata.id||"":typeof s.label=="string"&&(s.metadata.label=s.label),delete s.label),s.metadata.showLabel&&!s.metadata.label&&s.metadata.id&&(s.metadata.label=s.metadata.id),s.metadata.id){const i=s.metadata.id.toLowerCase();i.includes("left")?s.metadata.rotationGroup="left":i.includes("right")?s.metadata.rotationGroup="right":s.metadata.rotationGroup=s.metadata.id}if(s.type==="point"&&s.position){console.error("🔍 transformShape: 转换point为circle:",{shapeId:s.metadata?.id,position:s.position,originalType:s.type});const i=s.position.x,a=s.position.y,d=.1;s.type="circle",s.vertices=[[i,a],[i+d,a]],delete s.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:s.type,vertices:s.vertices})}return s}static transformGeometry(e,t,n={}){const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){try{const i=Be.resolve(s.geometryRef,t);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`几何对象解析失败: ${s.geometryRef}`,i)}delete s.geometryRef}return s}static transformTransform(e,t,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Se.resolve(s.transformRef,t);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换对象解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformStyle(e,t,n={}){const{strictMode:o=!1}=n,s={...e};if(s.styleRef){try{const i=we.resolve(s.styleRef,t);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`样式对象解析失败: ${s.styleRef}`,i)}delete s.styleRef}return s}static resolveAnimationConfig(e,t,n={}){const{strictMode:o=!1}=n;if(!e||typeof e!="string"){if(o)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const s=e.replace("animationRef:","");if(t.animationDefinitions&&t.animationDefinitions[s])return{...t.animationDefinitions[s]};if(o)throw new Error(`动画引用未找到: ${s}`);const i=this.getFallbackAnimationConfig(s);return console.warn(`动画引用未在上下文中找到,使用回退配置: ${s}`),i}catch(s){if(o)throw s;return console.warn(`动画配置解析失败: ${e}`,s),{}}}static resolveBoardConfig(e,t,n={}){const{strictMode:o=!1}=n;if(!e||typeof e!="string"){if(o)throw new Error(`无效的画板引用: ${e}`);return console.warn(`无效的画板引用: ${e}`),{}}try{const s=e.replace("boardRef:","");if(console.error("🔍 GeometryTransformTransformer.resolveBoardConfig:",{boardRef:e,refName:s,hasContextBoardDefinitions:!!t.boardDefinitions,contextBoardDefinitionKeys:t.boardDefinitions?Object.keys(t.boardDefinitions):[],hasRefInContext:t.boardDefinitions&&!!t.boardDefinitions[s]}),t.boardDefinitions&&t.boardDefinitions[s]){const a={...t.boardDefinitions[s]};return console.error("🔍 从上下文获取画板配置:",a),a}if(o)throw new Error(`画板引用未找到: ${s}`);const i=this.getFallbackBoardConfig(s);return console.warn(`画板引用未在上下文中找到,使用回退配置: ${s}`),console.error("🔍 使用回退画板配置:",i),i}catch(s){if(o)throw s;return console.warn(`画板配置解析失败: ${e}`,s),{}}}static getFallbackAnimationConfig(e){const t={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 t[e]||t.slider_horizontal}static getFallbackBoardConfig(e){const t={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 t[e]||t.default}static validate(e){const t=[];return e?(e.type!==ye.GEOMETRY_TRANSFORM&&t.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||t.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&t.push("几何变换内容块缺少 geometry 或 geometryRef"),t):(t.push("几何变换内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(o=>o.type===ye.GEOMETRY_TRANSFORM).map(o=>this.transform(o,t,n))}}function Kc(){return{type:ye.GEOMETRY_TRANSFORM,transform:or.transform.bind(or),validate:or.validate.bind(or)}}class Qe{static transformText(e,t,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${o}`);const i={...e,type:ye.TEXT};if(!o)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,t,{strictMode:s})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:s})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=we.resolve(i.styleRef,t);console.error(" StyleRefResolver解析结果:",a),i.style={...i.style,...a},console.error(" 合并后style:",i.style)}catch(a){if(s)throw a;console.warn(`文本样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(s)throw a;return console.warn("文本转换失败:",a),i}}static transformFormula(e,t,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n,i={...e,type:ye.FORMULA};if(!o)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:s})),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style={...i.style,...a}}catch(a){if(s)throw a;console.warn(`公式样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(s)throw a;return console.warn("公式转换失败:",a),i}}static resolveTextContent(e,t,n={}){const{strictMode:o=!1}=n;if(console.error(`📝 TextTransformer.resolveTextContent START: text="${e}", hasDesignTokens=${e.includes("$")}`),!e.includes("$"))return console.error(` resolveTextContent END (no design tokens): "${e}"`),e;let s=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 d=i[0],l=i[1];console.error(` 发现设计令牌: ${d}, path=${l}`);try{const c=Pe.resolve(d,t);console.error(` 解析结果: ${d} -> ${c}`),s=s.replace(d,String(c))}catch(c){if(o)throw c;console.warn(`文本中的设计令牌解析失败: ${d}`,c)}}return console.error(` resolveTextContent END: original="${e}", resolved="${s}"`),s}static resolveStyle(e,t,n={}){const{strictMode:o=!1}=n;try{return Pe.replaceDesignTokenRefs(e,t,s=>{if(o)throw new Error(`设计令牌未找到: ${s}`);return console.warn(`设计令牌未找到: ${s}`),s})}catch(s){if(o)throw s;return console.warn("样式解析失败:",s),e}}static validateText(e){const t=[];return e?(e.type!==ye.TEXT&&t.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("文本内容块缺少 content 字段"),t):(t.push("文本内容块不能为空"),t)}static validateFormula(e){const t=[];return e?(e.type!==ye.FORMULA&&t.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("公式内容块缺少 content 字段"),t):(t.push("公式内容块不能为空"),t)}static batchTransformText(e,t,n={}){return e.filter(o=>o.type===ye.TEXT).map(o=>this.transformText(o,t,n))}static batchTransformFormula(e,t,n={}){return e.filter(o=>o.type===ye.FORMULA).map(o=>this.transformFormula(o,t,n))}}function Xc(){return{type:ye.TEXT,transform:Qe.transformText.bind(Qe),validate:Qe.validateText.bind(Qe)}}function Jc(){return{type:ye.FORMULA,transform:Qe.transformFormula.bind(Qe),validate:Qe.validateFormula.bind(Qe)}}class Zc{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(Hc()),this.register(Kc()),this.register(Xc()),this.register(Jc())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,t,n={}){if(!e||!e.type)throw new Error("内容块缺少 type 字段");const o=this.getTransformer(e.type);return o?(console.error(`🔄 TransformerRegistry.transform: type="${e.type}", transformer.type="${o.type}", enableReferenceResolution=${n.enableReferenceResolution}`),o.transform(e,t,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,t,n={}){return e.map(o=>this.transform(o,t,n))}transformScene(e,t,n={}){const o=e.items||e.content;if(!e||!Array.isArray(o))return{items:[],layout:e?.layout};const s=this.batchTransform(o,t,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,t,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=Ve.resolve(e.layout,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:s,layout:i}}resolveLayoutReferences(e,t,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return Ve.resolve(e,t)}catch(o){if(n.strictMode)throw o;return console.warn(`布局引用解析失败: ${e}`,o),e}if(typeof e=="object"){if(e.layoutRef&&typeof e.layoutRef=="string")try{const s=`layoutRef:${e.layoutRef}`,i=Ve.resolve(s,t),{layoutRef:a,...d}=e;return{...i,...d}}catch(s){if(n.strictMode)throw s;console.warn(`布局引用解析失败: ${e.layoutRef}`,s)}const o=Array.isArray(e)?[]:{};for(const[s,i]of Object.entries(e))if(typeof i=="string"&&i.startsWith("layoutRef:"))try{o[s]=Ve.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),o[s]=i}else if(typeof i=="string"&&i.startsWith("$"))try{o[s]=Pe.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${s}=${i}`,a),o[s]=i}else i&&typeof i=="object"?o[s]=this.resolveLayoutReferences(i,t,n):o[s]=i;return o}return e}transformScenes(e,t,n={}){const o={};for(const[s,i]of Object.entries(e))o[s]=this.transformScene(i,t,n);return o}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const t=this.getTransformer(e.type);return!t||!t.validate?[]:t.validate(e)}batchValidate(e){return e.map(t=>({block:t,errors:this.validate(t)}))}}function js(){return new Zc}class Zr{static validate(e,t={}){const{strictMode:n=!1,skipOptionalFields:o=!1}=t,s=[],i=[];return!e||typeof e!="object"?(s.push("输入数据必须是对象"),{isValid:!1,errors:s,warnings:i}):(this.validateRequiredFields(e,s,i,{skipOptionalFields:o}),this.validateFieldTypes(e,s,i),this.validateScenes(e,s,i),this.validateBasicInfo(e,s,i),this.validateAnswerInfo(e,s,i),n&&this.validateStrictMode(e,s,i),{isValid:s.length===0,errors:s,warnings:i})}static validateRequiredFields(e,t,n,o){const{skipOptionalFields:s}=o;for(const i of Lr.RAW_DATA)e[i]===void 0&&t.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Lr.BASIC_INFO)e.basic_info[i]===void 0&&t.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Lr.ANSWER_INFO)e.answer_info[i]===void 0&&t.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,t,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&t.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&t.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&t.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&t.push(`${a} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||t.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${s} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||t.push(`场景 ${s} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${s} 的 layout 应为对象类型`),Rs.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,t,n){if(!e.basic_info||typeof e.basic_info!="object")return;const o=e.basic_info;["base","height","length","width","score"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="number"&&t.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&t.push(`basic_info.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&t.push("basic_info.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&t.push("basic_info.context 应为对象类型"),o.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(o.shape)&&n.push(`未知的形状类型: ${o.shape}`)}static validateAnswerInfo(e,t,n){if(!e.answer_info||typeof e.answer_info!="object")return;const o=e.answer_info;typeof o.value!="number"&&t.push("answer_info.value 应为数字类型"),typeof o.unit!="string"&&t.push("answer_info.unit 应为字符串类型"),typeof o.explanation_text!="string"&&t.push("answer_info.explanation_text 应为字符串类型"),o.value!==void 0&&(o.value<0&&n.push("answer_info.value 为负数,可能不正确"),o.value>1e4&&n.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,t,n){if(e.schema_version||n.push("建议添加 schema_version 字段"),e.config_version||n.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&n.push("knowledge_points 数组为空"),e.scenes)for(const[o,s]of Object.entries(e.scenes)){const i=s;i.content&&i.content.length===0&&n.push(`场景 ${o} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of t)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,t={}){const{strictMode:n=!1,removeInvalidFields:o=!1}=t,s=this.validate(e,{strictMode:n});let i=e;return o&&!s.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(d=>{d in i&&delete i[d]})),{data:i,errors:s.errors,warnings:s.warnings}}}class Qr{static validate(e,t={}){const{strictMode:n=!1,checkSceneContent:o=!0}=t,s=[],i=[];return!e||typeof e!="object"?(s.push("输出数据必须是对象"),{isValid:!1,errors:s,warnings:i}):(this.validateRequiredFields(e,s,i),this.validateFieldTypes(e,s,i),o&&this.validateScenes(e,s,i),this.validateBasicInfo(e,s,i),this.validateAnswer(e,s,i),this.validateExplanation(e,s,i),n&&this.validateStrictMode(e,s,i),{isValid:s.length===0,errors:s,warnings:i})}static validateRequiredFields(e,t,n){const o=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const s of o)e[s]===void 0&&t.push(`缺少必需字段: ${s}`)}static validateFieldTypes(e,t,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&t.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&t.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&t.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&t.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&t.push(`${i} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||t.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${s} 应为对象类型`);continue}const a=i,d=a.items||a.content;Array.isArray(d)?d.length===0&&n.push(`场景 ${s} 的内容数组为空`):t.push(`场景 ${s} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${s} 的 layout 应为对象类型`),Rs.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,t,n){if(!e.basicInfo||typeof e.basicInfo!="object"){t.push("basicInfo 应为对象类型");return}const o=e.basicInfo;(o.question===void 0||typeof o.question!="string")&&t.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="number"&&t.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&t.push(`basicInfo.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&t.push("basicInfo.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&t.push("basicInfo.context 应为对象类型")}static validateAnswer(e,t,n){if(!e.answer||typeof e.answer!="object"){t.push("answer 应为对象类型");return}const o=e.answer;typeof o.value!="number"&&t.push("answer.value 应为数字类型"),typeof o.unit!="string"&&t.push("answer.unit 应为字符串类型"),typeof o.explanation!="string"&&t.push("answer.explanation 应为字符串类型"),o.value!==void 0&&(o.value<0&&n.push("answer.value 为负数,可能不正确"),o.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,t,n){if(e.explanation===void 0){t.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){t.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((o,s)=>{(!o||typeof o!="object")&&t.push(`explanation[${s}] 应为对象类型`)})):e.explanation.steps===void 0?t.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||t.push("explanation.steps 应为数组类型")}static validateStrictMode(e,t,n){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||n.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&n.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&n.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&n.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const o=e.metadata;(!o.topic||typeof o.topic!="string")&&n.push("metadata.topic 应为字符串类型"),(!o.skill||typeof o.skill!="string")&&n.push("metadata.skill 应为字符串类型"),(!o.tags||!Array.isArray(o.tags))&&n.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["id","title","basicInfo","scenes","answer"];for(const n of t)if(e[n]===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 ft{static validateInput(e,t={}){const{isValid:n,errors:o,warnings:s}=Zr.validate(e,t);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateOutput(e,t={}){const{isValid:n,errors:o,warnings:s}=Qr.validate(e,t);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateComplete(e,t,n={}){const{inputStrictMode:o=!1,outputStrictMode:s=!1}=n,i=this.validateInput(e,{strictMode:o}),a=this.validateOutput(t,{strictMode:s}),d=[...i.errors,...a.errors],l=[...i.warnings,...a.warnings],c={isValid:i.isValid&&a.isValid,errors:d,warnings:l};return{input:i,output:a,overall:c}}static quickValidateInput(e){return Zr.quickValidate(e)}static quickValidateOutput(e){return Qr.quickValidate(e)}static validateAndReport(e,t,n={}){const o=t==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${t.toUpperCase()} 验证结果`),console.log(`有效性: ${o.isValid?"✅ 通过":"❌ 失败"}`),o.errors.length>0&&(console.group("❌ 错误:"),o.errors.forEach(s=>console.log(` - ${s}`)),console.groupEnd()),o.warnings.length>0&&(console.group("⚠️ 警告:"),o.warnings.forEach(s=>console.log(` - ${s}`)),console.groupEnd()),console.groupEnd()}}class en{static extractAllReferences(e){const t=[],n=o=>{typeof o=="string"?t.push(o):Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return n(e),[...new Set(t)]}static categorizeReferences(e,t){const n={[ee.DESIGN_TOKEN]:[],[ee.STYLE_REF]:[],[ee.GEOMETRY_REF]:[],[ee.TRANSFORM_REF]:[],[ee.LAYOUT_REF]:[]},o=new gt;for(const s of e){const i=o.getResolverForRef(s);i&&n[i.type].push(s)}return n}static batchResolveReferences(e,t,n={}){const{strictMode:o=!1,onMissing:s}=n,i=new gt,a={};for(const d of e){const l=i.getResolverForRef(d);if(l)try{a[d]=l.resolve(d,t)}catch(c){if(o)throw c;console.warn(`引用解析失败: ${d}`,c),s&&(a[d]=s(d))}}return a}static replaceReferences(e,t,n={}){const{strictMode:o=!1,onMissing:s,maxDepth:i=10}=n,a=new gt,d=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"]),l=(c,u=0,y)=>{if(u>i)return console.warn(`引用替换达到最大深度: ${i}`),c;if(typeof c=="string"){if(y&&d.has(y))return console.warn(`🛡️ 跳过保留字段 "${y}" 的通用解析: "${c}"`),c;if(!(c.startsWith("$")||c.includes("Ref:")))return c;const h=a.getResolverForRef(c);if(h)try{return h.resolve(c,t)}catch(g){if(o)throw g;return console.warn(`引用解析失败: ${c}`,g),s?s(c):c}return c}else{if(Array.isArray(c))return c.map(m=>l(m,u+1,void 0));if(c&&typeof c=="object"){const m={};for(const[h,g]of Object.entries(c))m[h]=l(g,u+1,h);return m}}return c};return l(e)}static calculateReferenceStats(e,t){const n=new gt,o={total:e.length,resolved:0,failed:0,byType:{}};Object.values(ee).forEach(s=>{o.byType[s]={total:0,resolved:0,failed:0}}),console.log("🔍 calculateReferenceStats: 开始处理引用,总数=",e.length);for(const s of e){console.log("🔍 处理引用:",s);const i=n.getResolverForRef(s);if(i){const a=i.type;o.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const d=i.resolve(s,t);console.log(`🔍 引用解析成功: ${s} =>`,d),o.resolved++,o.byType[a].resolved++}catch(d){console.error(`🔍 引用解析失败: ${s}`,d),o.failed++,o.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${s}`)}return o}static checkReferenceExists(e,t){const o=new gt().getResolverForRef(e);if(!o)return!1;if(o.validate)return o.validate(e,t);try{return o.resolve(e,t),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const t=e.match(/^(\w+):(\w+)$/);return t?[t[1],t[2]]:[e]}static createReference(e,t){switch(e){case ee.DESIGN_TOKEN:return`$${t.join(".")}`;case ee.STYLE_REF:return`styleRef:${t[0]}`;case ee.GEOMETRY_REF:return`geometryRef:${t[0]}`;case ee.TRANSFORM_REF:return`transformRef:${t[0]}`;case ee.LAYOUT_REF:return`layoutRef:${t[0]}`;default:return t.join(":")}}static flattenNestedReferences(e){const t=[],n=(o,s=[])=>{if(typeof o=="string")t.push(`${s.join(".")}=${o}`);else if(Array.isArray(o))o.forEach((i,a)=>{n(i,[...s,`[${a}]`])});else if(o&&typeof o=="object")for(const[i,a]of Object.entries(o))n(a,[...s,i])};return n(e),t}}class Ms{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 t=this.marks.get(e);if(!t){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),o=n-t.startTime;t.endTime=n,t.duration=o,this.updateStats(e,o)}updateStats(e,t){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=t;break;case"transformation":this.stats.transformationTime=t;break;case"validation":this.stats.validationTime=t;break;case"total":this.stats.totalTime=t;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>ot.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${ot.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>ot.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${ot.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>ot.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${ot.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>ot.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 Qc{static deepMerge(e,t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return Array.isArray(e)?e.map((o,s)=>s<t.length?this.deepMerge(o,t[s]):o):[...t];const n={...e};for(const[o,s]of Object.entries(t))s!==void 0&&(o in n&&typeof n[o]=="object"&&typeof s=="object"?n[o]=this.deepMerge(n[o],s):n[o]=s);return n}static deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t||typeof e!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((s,i)=>this.deepEqual(s,t[i]));const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(s=>s in t?this.deepEqual(e[s],t[s]):!1)}static safeGet(e,t,n=void 0){const o=Array.isArray(t)?t:t.split(".");let s=e;for(const i of o){if(s==null||typeof s!="object")return n;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(s)){const d=parseInt(a[1],10);s=s[d]}else s=s[i]}return s!==void 0?s:n}static safeSet(e,t,n){const o=Array.isArray(t)?t:t.split("."),s=Array.isArray(e)?[...e]:{...e};let i=s;for(let l=0;l<o.length-1;l++){const c=o[l],u=c.match(/^\[(\d+)\]$/);if(u&&Array.isArray(i)){const y=parseInt(u[1],10);i[y]===void 0&&(i[y]={}),i=i[y]}else{if(i[c]===void 0){const m=o[l+1].match(/^\[(\d+)\]$/);i[c]=m?[]:{}}i=i[c]}}const a=o[o.length-1],d=a.match(/^\[(\d+)\]$/);if(d&&Array.isArray(i)){const l=parseInt(d[1],10);i[l]=n}else i[a]=n;return s}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,t){let n=0;return(...o)=>{const s=Date.now();s-n>=t&&(n=s,e(...o))}}static debounce(e,t){let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>e(...o),t)}}static formatBytes(e,t=2){if(e===0)return"0 Bytes";const n=1024,o=t<0?0:t,s=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/Math.pow(n,i)).toFixed(o))+" "+s[i]}static estimateObjectSize(e){const t=new Set,n=o=>t.has(o)?0:typeof o=="string"?o.length*2:typeof o=="number"?8:typeof o=="boolean"?4:o==null?0:Array.isArray(o)?(t.add(o),o.reduce((s,i)=>s+n(i),0)):typeof o=="object"?(t.add(o),Object.values(o).reduce((s,i)=>s+n(i),0)):0;return n(e)}}class ed{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...Pc,...e},this.referenceContext=ks(),this.resolverRegistry=Os(),this.transformerRegistry=js(),this.performanceMonitor=new Ms}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 t=this.validateInput(e);if(!t.isValid&&this.config.strictMode)throw new me(B.INVALID_INPUT,oo[B.INVALID_INPUT],{errors:t.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const n=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let o=n;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),o=this.resolveReferences(n),this.performanceMonitor.markEnd("reference-resolution")),this.performanceMonitor.markStart("scene-transformation"),!this.referenceContext.basicInfo&&o.basicInfo&&(this.referenceContext.basicInfo=o.basicInfo);const s=this.transformScenes(o);this.performanceMonitor.markEnd("scene-transformation"),this.performanceMonitor.markStart("output-validation");const i=this.validateOutput(s);if(!i.isValid&&this.config.strictMode)throw new me(B.OUTPUT_VALIDATION_FAILED,oo[B.OUTPUT_VALIDATION_FAILED],{errors:i.errors});this.performanceMonitor.markEnd("output-validation"),this.performanceMonitor.markEnd("total"),console.error("🔧 adapt: transformedData before buildResult:",s),console.error("🔧 adapt: transformedData.basicInfo:",s.basicInfo),console.error("🔧 adapt: transformedData.basicInfo?.answerUnit:",s.basicInfo?.answerUnit);const a=this.buildResult(s,{inputValidation:t,outputValidation:i,inputWarnings:t.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(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}validateInput(e){return ft.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(([t,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${t}:`,{id:n.id,type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),shapeKeys:Object.keys(n)});const o=this.convertGeometryShapeCoordinates(n);console.error(` 📍 ${t}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[t]=o}}),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(([t,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=o}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(t=>{t&&t.content&&Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="graph"&&n.shapes&&this.extractPointCoordinatesFromShapes(n.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(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${t}:`,{id:n.id,strategy:n.strategy,hasBase:"base"in n,hasHeight:"height"in n,hasShapes:"shapes"in n,hasTransform:"transform"in n}),this.referenceContext.geometryTransformConfigs[t]=n)}),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(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${t}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[t]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;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});const t={...e};t.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(console.error(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,o)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(console.error(` Endpoint ${o} is not array:`,n),n)),t.type==="segment"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&console.error(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,o]of Object.entries(t))Array.isArray(o)?t[n]=o.map(s=>s&&typeof s=="object"&&"$ref"in s?s:typeof s=="object"?this.convertGeometryShapeCoordinates(s):s):o&&typeof o=="object"&&("$ref"in o?t[n]=o:t[n]=this.convertGeometryShapeCoordinates(o));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(t))Array.isArray(o)?t[n]=o.map(s=>typeof s=="object"?this.convertTransformDefinitionCoordinates(s):s):o&&typeof o=="object"&&(t[n]=this.convertTransformDefinitionCoordinates(o));return t}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(t=>{if(t&&t.type==="point"&&t.position&&Array.isArray(t.position)&&t.position.length>=2){const n=t.id||`point_${t.position[0]}_${t.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:t.position[0],y:t.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);const t={id:e.math_prob_id||Qc.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(s=>{e[s]!==void 0&&(t[s]=e[s])}),console.error("🔧 transformBaseData: inputData.basic_info =",e.basic_info);const o=this.transformBasicInfo(e.basic_info);return console.error("🔧 transformBaseData: basicInfo after transform =",o),console.error("🔧 transformBaseData: basicInfo.answerUnit =",o?.answerUnit),this.referenceContext.basicInfo=o,t.basicInfo=o,console.error("🔧 transformBaseData: transformed.basicInfo set =",t.basicInfo),t.explanation=this.transformExplanation(e.explanation),t}parseGrade(e){const t=e.match(/g(\d+)/);return t?parseInt(t[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 t={...e};return console.error("🔄 transformBasicInfo: transformed copy:",t),t.question===void 0&&t.content!==void 0&&(t.question=t.content),t.question===void 0&&(t.question=""),console.error("🔄 transformBasicInfo: returning:",t),t}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const t={};return["question","solve","review"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];t[s]={...i,items:a},i.content!==void 0&&delete t[s].content}else t[s]={items:[]}}),["remember"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];t[s]={...i,items:a},i.content!==void 0&&delete t[s].content}}),t}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 t=e.steps.map((n,o)=>(console.error(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(t)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={type:n,...t};console.error(" contentBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&(console.error(" shapes count:",o.shapes.length),o.shapes.length>0&&console.error(" first shape:",o.shapes[0])),console.error("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.error("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]);const s=this.transformerRegistry.transform(o,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});console.error(" transformedBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&console.error(" transformed shapes count:",s.shapes.length);let i;if(n==="geometryTransform"&&s.metadata&&s.metadata.config)i=s,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(n==="graph"&&s.boardConfig){const{boardConfig:a,...d}=s;i={...d,...a},console.error(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...s};return{...e,chartConfig:i}}catch(o){if(console.error("❌ 转换解释步骤中的 chartConfig 失败:",o),this.config.strictMode)throw o;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 t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),en.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),t}validateOutput(e){return ft.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const o=this.performanceMonitor.getStats(),s=this.performanceMonitor.checkPerformance(),i=[...t.inputValidation.warnings.map(c=>({code:B.INVALID_INPUT,message:`输入验证警告: ${c}`,suggestion:"检查输入数据格式"})),...t.outputValidation.warnings.map(c=>({code:B.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${c}`,suggestion:"检查数据转换逻辑"})),...s.warnings.map(c=>({code:B.TRANSFORMATION_FAILED,message:`性能警告: ${c}`,suggestion:"优化数据转换性能"}))],a=n||e,d=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=en.calculateReferenceStats(d,this.referenceContext);return{data:e,warnings:i,performance:o,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,t){const n={...fr,id:e?.math_prob_id||fr.id,title:e?.title||fr.title},o={code:B.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:n,warnings:[o],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class Xt{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...Fc,...e},this.referenceContext=ks(),this.resolverRegistry=Os(),this.transformerRegistry=js(),this.performanceMonitor=new Ms,this.syncAdapter=new ed(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 t=e,n=this.syncAdapter.adapt(t);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:n.data.id,hasBasicInfo:!!n.data.basicInfo,warningCount:n.warnings.length,referenceStats:n.referenceStats}),n}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}_validateInput(e){return ft.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(([t,n])=>{if(n&&typeof n=="object"){const o=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[t]=o}}),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(([t,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=o}}))}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 t=e.steps.map((n,o)=>(this.config.enableLogging&&console.log(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(t))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={...t,type:n};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&(console.log(" shapes count:",o.shapes.length),o.shapes.length>0&&console.log(" first shape:",o.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 s=this.transformerRegistry.transform(o,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});this.config.enableLogging&&(console.log(" transformedBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&console.log(" transformed shapes count:",s.shapes.length));let i;if(n==="geometryTransform"&&s.metadata&&s.metadata.config)i=s,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(n==="graph"&&s.boardConfig){const{boardConfig:a,...d}=s;i={...d,...a},this.config.enableLogging&&console.log(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...s};return{...e,chartConfig:i}}catch(o){if(this.config.enableLogging&&console.error("❌ 转换解释步骤中的 chartConfig 失败:",o),this.config.strictMode)throw o;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 t={...e};t.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,o)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(this.config.enableLogging&&console.log(` Endpoint ${o} is not array:`,n),n)),t.type==="line"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&this.config.enableLogging&&console.log(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,o]of Object.entries(t))Array.isArray(o)?t[n]=o.map(s=>s&&typeof s=="object"&&"$ref"in s?s:typeof s=="object"?this.convertGeometryShapeCoordinates(s):s):o&&typeof o=="object"&&("$ref"in o?t[n]=o:t[n]=this.convertGeometryShapeCoordinates(o));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(t))Array.isArray(o)?t[n]=o.map(s=>typeof s=="object"&&s!==null?"id"in s&&"type"in s&&"config"in s?this.convertTransformDefinitionCoordinates(s):this.deepClone(s):s):o&&typeof o=="object"&&("id"in o&&"type"in o&&"config"in o?t[n]=this.convertTransformDefinitionCoordinates(o):t[n]=this.deepClone(o));return t}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const t={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=t.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),t}_resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),en.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),t}_validateOutput(e){return ft.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const o=this.performanceMonitor.getStats(),s=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(t.inputWarnings||[]).map(a=>({code:Dr.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(t.outputWarnings||[]).map(a=>({code:Dr.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?o:void 0,referenceStats:s}}createFallbackResult(e,t){return{data:{...fr,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:Dr.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t instanceof Error?t.message:t}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new Xt(e)}}function ut(r,e){return new Xt(e).adapt(r)}async function Cn(r,e){return Promise.resolve(ut(r,e))}function Is(r,e){const t=typeof r=="function"?r():r;return ut(t,e)}async function Fs(r,e){const t=typeof r=="function"?await r():r instanceof Promise?await r:r;return ut(t,e)}function Ps(r){return new Xt(r)}function Ds(r){const e=new Xt(r);return{adapt:t=>Promise.resolve(e.adapt(t))}}function td(r,e="input"){return e==="input"?ft.validateInput(r):ft.validateOutput(r)}function rd(r,e,t=100){const n=[];for(let d=0;d<t;d++){const l=performance.now();r.adapt(e);const c=performance.now();n.push(c-l)}const o=n.reduce((d,l)=>d+l,0)/t,s=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:o,minTime:s,maxTime:i,memoryUsage:a}}const nd={adapt:(r,e)=>ut(r,e),adaptAsync:(r,e)=>Cn(r,e),create:r=>Ps(r)},od="4.0.0",Ls="4.0.0";function sd(r="4.0.0"){return Ls>=r}function Us(r){return r?.schema_version==="4.0.0"||r?.schema_version?.startsWith("4.")}function id(r){return Us(r)&&(r.geometry_shapes||r.transform_definitions||r.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(r.basic_info.shape))}class Gr extends Error{constructor(e,t,n,o){super(`Failed to generate config for ${t}: ${e}`),this.shapeType=t,this.options=n,this.innerError=o,this.name="ConfigGenerationError"}}function ad(r){const e=[],t=[];if(r.shapes||e.push(U("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),r.transform||e.push(U("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),r.strategy||e.push(U("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:io(e),timestamp:new Date().toISOString()};r.shapes&&e.push(...ld(r.shapes));let n=!1;if(r.shapes?.animated){for(const o of r.shapes.animated)if(o.transform){n=!0;break}}return r.transform?e.push(...cd(r.transform)):n||e.push(U("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...dd(r)),e.push(...fd(r)),e.push(...ud(r)),e.length>0&&t.push(...io(e)),{isValid:e.length===0,errors:e,fixes:t,timestamp:new Date().toISOString()}}function Gs(r){if(!r||typeof r!="object"||!r.type||typeof r.type!="string"||!["rotation","translation","scale","composite"].includes(r.type))return!1;switch(r.type){case"rotation":if(!r.config||typeof r.config!="object")return!1;const t=r.config.center;if(t!=="auto"&&(!Array.isArray(t)||t.length!==2)||typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number"||r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical")return!1;break;case"translation":if(!r.config||typeof r.config!="object")return!1;const n=r.config.direction;if(Array.isArray(n)){if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="number")return!1}else if(typeof n=="string"){if(n!=="horizontal"&&n!=="vertical")return!1}else return!1;if(typeof r.config.distance!="number"||r.config.distance<=0)return!1;break;case"scale":if(!r.config||typeof r.config!="object")return!1;const o=r.config.center;if(o!=="centroid"&&(!Array.isArray(o)||o.length!==2)||typeof r.config.startScale!="number"||typeof r.config.endScale!="number"||typeof r.config.uniform!="boolean")return!1;break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))return!1;for(const s of r.transforms)if(!Gs(s))return!1;if(r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel")return!1;break}return!0}function zs(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,r,{type:"rotation"})),t;(!r.type||typeof r.type!="string")&&t.push(U("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,r.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(r.type&&!n.includes(r.type)&&t.push(U("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${r.type}`,`${e}.type`,r.type,"rotation")),r.type){case"rotation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,r.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const o=r.config.center;o!=="auto"&&(!Array.isArray(o)||o.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,r.config.center,[0,0])),(typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,r.config,{startAngle:0,endAngle:Math.PI})),r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,r.config.direction,"clockwise"))}break;case"translation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,r.config,{direction:"horizontal",distance:1}));else{const o=r.config.direction;Array.isArray(o)?o.length!==2?t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,o,[1,0])):(typeof o[0]!="number"||typeof o[1]!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,o,[1,0])):typeof o=="string"?o!=="horizontal"&&o!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,o,"horizontal")):t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,o,"horizontal")),(typeof r.config.distance!="number"||r.config.distance<=0)&&t.push(U("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,r.config.distance,1))}break;case"scale":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,r.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const o=r.config.center;o!=="centroid"&&(!Array.isArray(o)||o.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,r.config.center,"centroid")),(typeof r.config.startScale!="number"||typeof r.config.endScale!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,r.config,{startScale:1,endScale:2})),typeof r.config.uniform!="boolean"&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,r.config.uniform,!0))}break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))t.push(U("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,r.transforms,[]));else for(let o=0;o<r.transforms.length;o++){const s=zs(r.transforms[o],`${e}.transforms[${o}]`);t.push(...s)}r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel"&&t.push(U("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,r.executionMode,"sequential"));break}return t}function U(r,e,t,n,o){let s=o;if(o===void 0)switch(r){case"INVALID_TRIANGLE_TYPE":s="right_triangle";break;case"INVALID_BASE_VALUE":case"INVALID_HEIGHT_VALUE":s=1;break;case"INVALID_ORIGIN":s=0;break;case"MISSING_SHAPES":s={static:[],animated:[]};break;case"MISSING_TRANSFORM":s={type:"rotation"};break;case"STRATEGY_MISMATCH":s="single_rotation";break;case"UNIT_MISMATCH":s="in";break;default:s=void 0}return{code:r,message:e,path:t,value:n,suggestedValue:s}}function ld(r){const e=[];if(!r||typeof r!="object")return e.push(U("MISSING_SHAPES","形状定义无效或缺失","$.shapes",r)),e;if(!Array.isArray(r.static))e.push(U("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",r.static));else for(let t=0;t<r.static.length;t++){const n=r.static[t],o=so(n,`$.shapes.static[${t}]`);e.push(...o)}if(!Array.isArray(r.animated))e.push(U("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",r.animated));else for(let t=0;t<r.animated.length;t++){const n=r.animated[t],o=so(n,`$.shapes.animated[${t}]`);e.push(...o)}return e}function so(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,r)),t;if((!r.type||typeof r.type!="string")&&t.push(U("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,r.type)),!Array.isArray(r.vertices))t.push(U("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,r.vertices));else if(r.vertices.length===0)t.push(U("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,r.vertices));else for(let n=0;n<r.vertices.length;n++){const o=r.vertices[n];!Array.isArray(o)||o.length!==2?t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,o)):(typeof o[0]!="number"||typeof o[1]!="number")&&t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,o))}if(r.transform!==void 0){const n=zs(r.transform,`${e}.transform`);t.push(...n)}return t}function cd(r){const e=[];if(!r)return e.push(U("MISSING_TRANSFORM","变换配置缺失","$.transform",r)),e;const t=Array.isArray(r),n=t?r:[r],o="$.transform";for(let s=0;s<n.length;s++){const i=n[s],a=t?`${o}[${s}]`:o;Gs(i)||e.push(U("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function dd(r){const e=[];if(!r.strategy)return e;const{strategy:t}=r;let n=0;if(r.transform&&(Array.isArray(r.transform)?n+=r.transform.length:typeof r.transform=="object"&&(r.transform&&typeof r.transform=="object"&&"transforms"in r.transform?n+=r.transform.transforms.length:n+=1)),r.shapes?.animated)for(const s of r.shapes.animated)s.transform&&(n+=1);return t.includes("single")&&n!==1&&e.push(U("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",t,n===0?"single_rotation":"double_rotation")),t.includes("double")&&n!==2&&e.push(U("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",t,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(t)||e.push(U("STRATEGY_MISMATCH",`无效的策略名称: ${t}`,"$.strategy",t,"single_rotation")),e}function fd(r){const e=[];if(r.unit&&typeof r.unit!="string"&&e.push(U("UNIT_MISMATCH","单位必须是字符串","$.unit",r.unit,"in")),r.baseUnit&&typeof r.baseUnit!="string"&&e.push(U("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",r.baseUnit,r.unit||"in")),r.heightUnit&&typeof r.heightUnit!="string"&&e.push(U("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",r.heightUnit,r.unit||"in")),r.unit&&r.baseUnit&&r.baseUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`底边单位 (${r.baseUnit}) 与主单位 (${r.unit}) 不一致`,"$.baseUnit",r.baseUnit,r.unit)),r.unit&&r.heightUnit&&r.heightUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`高度单位 (${r.heightUnit}) 与主单位 (${r.unit}) 不一致`,"$.heightUnit",r.heightUnit,r.unit)),r.unit&&r.boardConfig&&r.boardConfig.boundingBox){const[t,n,o,s]=r.boardConfig.boundingBox,i=o-t,a=n-s,d=r.unit==="cm"?50:20;(i>d*5||a>d*5)&&e.push(U("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${r.unit})不匹配`,"$.boardConfig.boundingBox",r.boardConfig.boundingBox,void 0))}return e}function ud(r){const e=[];if(r.shapes&&r.boardConfig&&r.boardConfig.boundingBox){const t=r.boardConfig.boundingBox,[n,o,s,i]=t,a=[...r.shapes.static||[],...r.shapes.animated||[]];for(let d=0;d<a.length;d++){const l=a[d];if(l&&l.vertices)for(let c=0;c<l.vertices.length;c++){const u=l.vertices[c];if(Array.isArray(u)&&u.length===2){const[y,m]=u;(y<n||y>s||m<i||m>o)&&e.push(U("GEOMETRY_INCONSISTENCY",`形状 ${d} 的顶点 ${c} (${y}, ${m}) 超出画板边界`,`$.shapes.${d<(r.shapes.static?.length||0)?"static":"animated"}[${d}].vertices[${c}]`,u,[Math.max(n,Math.min(y,s)),Math.max(i,Math.min(m,o))]))}}}}if(r.metadata&&r.metadata.base&&r.metadata.height){const t=.5*r.metadata.base*r.metadata.height;if(r.shapes?.static?.[0]?.vertices){const n=r.shapes.static[0].vertices;if(n.length===3){const[o,s]=n[0],[i,a]=n[1],[d,l]=n[2],c=.5*Math.abs((i-o)*(l-s)-(d-o)*(a-s));Math.abs(c-t)>.01&&e.push(U("GEOMETRY_INCONSISTENCY",`计算面积 (${c.toFixed(2)}) 与预期面积 (${t.toFixed(2)}) 不一致`,"$.metadata",{base:r.metadata.base,height:r.metadata.height,calculatedArea:c,expectedArea:t}))}}}return e}function io(r){const e=[];for(const t of r)switch(t.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:t.path,value:t.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${t.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将底边长度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将高度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:t.path,value:t.suggestedValue||0,description:`将原点坐标修复为: ${t.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:t.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:t.suggestedValue!==void 0&&e.push({action:"replace",path:t.path,value:t.suggestedValue,description:`修复 ${t.code} 错误`,isSafe:!1})}return e}function ao(r){if(!md(r))throw new Gr("Invalid parallelogram config options","parallelogram",r);const{base:e,height:t,unit:n="in",layoutDensity:o="compact",theme:s="light"}=r,i=r.originX??0,a=r.originY??0,d=r.skew??e/3;try{const l=hd(e,t,d,i,a,s),c=gd(e),u=pd(o),y=yd(e,t,d,i,a);return{ui:{layoutDensity:o},base:e,height:t,unit:n,shapes:l,transform:c,animation:u,boardConfig:y,strategy:"cut_and_paste",theme:s,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:t,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){if(l instanceof Gr)throw l;const c=l instanceof Error?l.message:String(l);throw new Gr(c,"parallelogram",r,l instanceof Error?l:void 0)}}function md(r){if(!r||typeof r!="object")return!1;const e=["base","height"];for(const t of e)if(!(t in r))return!1;return!(typeof r.base!="number"||r.base<=0||typeof r.height!="number"||r.height<=0||r.skew!==void 0&&(typeof r.skew!="number"||r.skew<0)||r.originX!==void 0&&(typeof r.originX!="number"||!isFinite(r.originX))||r.originY!==void 0&&(typeof r.originY!="number"||!isFinite(r.originY)))}function hd(r,e,t,n,o,s){const a=s==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},d=[[n+t,o],[n+r,o],[n+r+t,o+e],[n+t,o+e]],l=[[n,o],[n+t,o],[n+t,o+e]];return{static:[{type:"trapezoid",vertices:d,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:l,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function gd(r){return{type:"translation",config:{direction:[1,0],distance:r}}}function pd(r){return{slider:{position:r==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function yd(r,e,t,n,o){const s=Math.min(n,n+t,n+r,n+r+t),i=Math.max(n,n+t,n+r,n+r+t),a=Math.min(o,o+e),d=Math.max(o,o+e),l=3;return{boundingBox:[s-l,d+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function bd(r){return{id:r.id||r.math_prob_id,title:r.title||"",grade:r.grade||5,unit:r.unit||r.unit_name||"",lesson:r.lesson||r.lesson_name||"",skill:r.skill||r.skill_description||"",objective:r.objective||"",knowledgePoints:Array.isArray(r.knowledge_points)?r.knowledge_points:Array.isArray(r.knowledgePoints)?r.knowledgePoints:[],difficulty:r.difficulty||1,description:r.description||"",metadata:r.metadata||{topic:"",skill:"",tags:[]},math_prob_id:r.math_prob_id,grade_id:r.grade_id,unit_id:r.unit_id,lesson_id:r.lesson_id,module_id:r.module_id,skill_item_id:r.skill_item_id,skill_id:r.skill_id,created_at:r.created_at,updated_at:r.updated_at,layout:r.layout||{type:"card",padding:"20px",theme:"light"}}}function xd(r){const e=r||{};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 vd(r,e,t){return{value:r,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:t}}function _d(r){return r?{value:r.value,unit:r.unit,explanation:r.explanation_text||r.explanation||"正确答案"}:null}function wd(r){return r.answer?r.answer:r.answer_info?_d(r.answer_info):null}function Ad(){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 Rd(){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 Sd(r){return Array.isArray(r)||r&&r.steps?r:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Bs(r){const e=bd(r),t=xd(r.basic_info||r.basicInfo),n=["平行四边形面积公式 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:n,difficulty:e.difficulty||1,description:e.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:e.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...t,question:t.question||"计算下面平行四边形的面积:",answerUnit:t.answerUnit||"平方英寸",shape:t.shape||"parallelogram",base:t.base||9,height:t.height||6,baseUnit:t.baseUnit||"in",heightUnit:t.heightUnit||"in",variables:t.variables||{b:9,h:6,unit:"in"},context:t.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:Td(r.scenes||Ad(),"parallelogram",t),explanation:Sd(r.explanation||Rd()),answer:wd(r)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:r.answer_info||vd(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:r.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function Cd(r){return r?.config&&typeof r.config=="object"}function Ed(r){if(r.shapes?.static&&r.shapes?.animated)return console.log("🔍 JSON config already in system format"),r;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!r.transform,type:yt(r.transform),distance:Xe(r.transform),direction:ur(r.transform)});try{const e={...r};if(r.shapes&&typeof r.shapes=="object"){const n=[],o=[];if(r.shapes.trapezoid){const s=r.shapes.trapezoid;Array.isArray(s)?n.push(...s.map(i=>({...i,metadata:{...i.metadata,isStatic:!0}}))):typeof s=="object"&&n.push({...s,metadata:{...s.metadata,isStatic:!0}})}if(r.shapes.triangle){const s=r.shapes.triangle;Array.isArray(s)?o.push(...s.map(i=>({...i,metadata:{...i.metadata,isMovable:!0}}))):typeof s=="object"&&o.push({...s,metadata:{...s.metadata,isMovable:!0}})}(n.length===0||o.length===0)&&Object.entries(r.shapes).forEach(([s,i])=>{const a=s.toLowerCase();a.includes("static")||a.includes("original")||a.includes("trapezoid")?Array.isArray(i)?n.push(...i):i&&typeof i=="object"&&n.push(i):(a.includes("animated")||a.includes("movable")||a.includes("triangle"))&&(Array.isArray(i)?o.push(...i):i&&typeof i=="object"&&o.push(i))}),e.shapes={static:n,animated:o}}!e.base&&r.base&&(e.base=r.base),!e.height&&r.height&&(e.height=r.height),!e.unit&&r.unit&&(e.unit=r.unit);const t=yt(r.transform);return r.transform&&t==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:t,translation:r.transform.translation,distance:Xe(r.transform),direction:ur(r.transform)}),r.transform.translation&&(e.transform={type:"translation",translation:r.transform.translation},console.log("✅ Set converted.transform with distance:",Xe(r.transform)))):r.transform?console.log("⚠️ JSON has transform but not translation type:",yt(r.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&&r.boardConfig&&(e.boardConfig=r.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:yt(e.transform),distance:Xe(e.transform),direction:ur(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),r}}function Xe(r){if(!r)return"N/A";const e=Array.isArray(r)?r[0]:r;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function ur(r){if(!r)return;const e=Array.isArray(r)?r[0]:r;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function yt(r){return r&&(Array.isArray(r)?r[0]:r)?.type||"N/A"}function Td(r,e,t){if(r?.solve?.content){const n=r.solve.content.map(o=>{if(o.type==="geometryTransform"){if(Cd(o))try{const i=Ed(o.config),a=ad(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",Xe(i.transform)),console.log("📐 JSON base:",i.base,"height:",i.height),{...o,metadata:{...o.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:yt(i.transform),distance:Xe(i.transform),strategy:i.strategy,theme:i.theme})}catch(i){console.warn("Failed to process JSON-provided parallelogram config:",i)}let s;try{const i=t?.base||9,a=t?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),s=ao({base:i,height:a,unit:t?.baseUnit||t?.unit||"in",originX:t?.originX,originY:t?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",Xe(s.transform))}catch(i){console.warn("Failed to generate dynamic parallelogram config:",i),console.log("🔄 Using fallback dynamic config with base: 9, height: 6"),s=ao({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",Xe(s.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:yt(s.transform),direction:ur(s.transform),distance:Xe(s.transform)}),{...o,metadata:{...o.metadata,config:s,source:"generated"}}}return o});return{...r,solve:{...r.solve,content:n}}}return r}const Nd="4.0.0",$d="1.0.0",kd="mp-10506-0002-0002-G01-0001",Od="锐角三角形面积练习",jd="通过双旋转策略练习锐角三角形面积公式 A=½bh",Md="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",Id=1,Fd="g5",Pd="三角形面积计算",Dd=1050602,Ld="锐角三角形的面积",Ud=105060201,Gd=1002,zd="已知锐角三角形的底和高,求三角形面积",Bd="s-105-06-0002",Vd=1002,Wd=2,qd=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Yd={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Hd={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}},Kd={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"}},Xd={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},Jd={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"What is the area of the triangle?",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"}]}},Zd={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"}}]}}]},Qd={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²"]},ef="2026-01-20T20:34:00Z",tf="2026-01-20T20:34:00Z",rf={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"}},nf={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right"}},of={schema_version:Nd,config_version:$d,math_prob_id:kd,title:Od,description:jd,objective:Md,difficulty:Id,grade_id:Fd,unit_name:Pd,unit_id:Dd,lesson_name:Ld,lesson_id:Ud,module_id:Gd,skill_description:zd,skill_item_id:Bd,skill_id:Vd,score:Wd,knowledge_points:qd,metadata:Yd,basic_info:Hd,geometry_shapes:Kd,layout:Xd,scenes:Jd,explanation:Zd,answer_info:Qd,created_at:ef,updated_at:tf,geometry_transform_configs:rf,transform_definitions:nf},sf="mp-10506-0001-0001-G01-0001",af="平行四边形面积公式推导",lf="通过割补变换演示理解平行四边形面积公式 A=bh",cf="理解平行四边形面积公式 A=bh",df=1,ff="g5",uf="多边形的面积",mf=1050601,hf="平行四边形的面积",gf=105060101,pf=1002,yf="已知平行四边形的底和高,求平行四边形面积",bf="s-105-06-0001",xf=1001,vf=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],_f={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},wf={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}},Af={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},Rf={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"}}}},Sf={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:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},Cf={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 平方英寸"}]},Ef="2024-01-15T10:30:00Z",Tf="2024-01-15T10:30:00Z",Nf={math_prob_id:sf,title:af,description:lf,objective:cf,difficulty:df,grade_id:ff,unit_name:uf,unit_id:mf,lesson_name:hf,lesson_id:gf,module_id:pf,skill_description:yf,skill_item_id:bf,skill_id:xf,knowledge_points:vf,metadata:_f,basic_info:wf,layout:Af,scenes:Rf,explanation:Sf,answer_info:Cf,created_at:Ef,updated_at:Tf},$f={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function kf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
16
+ `)}`);return o}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ee.ANIMATION_REF);return s?n=s[1]:n=e,n in(t.animationConfigs||{})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`动画引用解析失败: ${s}`,o)}return n}static extractAnimationRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.animationRef&&typeof s.animationRef=="string"&&t.push(s.animationRef),s.chartConfig?.animationRef&&typeof s.chartConfig.animationRef=="string"&&t.push(s.chartConfig.animationRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Mc(){return{type:X.ANIMATION_REF,canResolve:rt.canResolve.bind(rt),resolve:rt.resolve.bind(rt),validate:rt.validate.bind(rt)}}class Ye{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!t,contextKeys:Object.keys(t||{}),animationDefinitionsKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[],animationConfigsKeys:t.animationConfigs?Object.keys(t.animationConfigs):[]}),!this.canResolve(e))throw new le(G.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(ee.SLIDER_REF),s=n?n[1]:e;let o=t.animationDefinitions?.[s];return!o&&t.animationConfigs&&(o=t.animationConfigs[s]),!o&&st?.animationDefinitions&&(o=st.animationDefinitions[s]),!o&&st?.animationConfigs&&(o=st.animationConfigs[s]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:s,hasRawConfig:!!o,rawConfig:o,animationDefinitions:t.animationDefinitions,animationConfigs:t.animationConfigs,hasGlobalContext:!!st}),o?this.validateAndTransformConfig(s,o):(console.warn(`⚠️ 滑块配置未找到: ${s},使用默认配置`),{...Ic,id:s})}static validateAndTransformConfig(e,t){if(!t.slider)throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=t,s=["position","length","orientation","min","max","step"];for(const o of s)if(!(o in n))throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${o} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new le(G.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:n.position,length:n.length,orientation:n.orientation,min:n.min,max:n.max,step:n.step},progressIndicator:t.progressIndicator,duration:t.duration,easing:t.easing,description:t.description}}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ee.SLIDER_REF),s=n?n[1]:e;return s in(t.animationDefinitions||{})||s in(t.animationConfigs||{}),!0}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`滑块引用解析失败: ${s}`,o)}return n}static extractSliderRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.sliderRef&&typeof s.sliderRef=="string"&&t.push(s.sliderRef),s.chartConfig?.sliderRef&&typeof s.chartConfig.sliderRef=="string"&&t.push(s.chartConfig.sliderRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}const Ic={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 Fc(){return{type:X.SLIDER_REF,canResolve:Ye.canResolve.bind(Ye),resolve:Ye.resolve.bind(Ye),validate:Ye.validate.bind(Ye)}}class nt{static canResolve(e){return typeof e!="string"||e.length===0?!1:ee.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const s=e.match(ee.GEOMETRY_TRANSFORM_REF),o=s?s[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${o}`,{hasGeometryTransformConfigs:!!t.geometryTransformConfigs,configKeys:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});const i=t.geometryTransformConfigs?.[o];if(!i)throw new le(G.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${o}`,{reference:e,configId:o,availableConfigs:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,t){const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(n[s]=o);return t.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},t.shapes.static&&(n.shapes.static=t.shapes.static),t.shapes.animated&&(n.shapes.animated=t.shapes.animated)),t.transform&&(n.transform={...n.transform,...t.transform}),n}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ee.GEOMETRY_TRANSFORM_REF),s=n?n[1]:e;return!!t.geometryTransformConfigs?.[s]}static batchResolve(e,t,n){const s={};for(const o of e)if(this.canResolve(o)&&this.validate(o,t))try{const i=n?.[o];s[o]=this.resolve(o,t,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 t=[];for(const n of e){const s=this.extractFromContentBlock(n);s&&t.push(s)}return[...new Set(t)]}}function Pc(){return{type:X.GEOMETRY_TRANSFORM_REF,canResolve:nt.canResolve.bind(nt),resolve:nt.resolve.bind(nt),validate:nt.validate.bind(nt)}}const Fr={geometryRef:X.GEOMETRY_REF,styleRef:X.STYLE_REF,layoutRef:X.LAYOUT_REF,boardRef:X.BOARD_REF,animationRef:X.ANIMATION_REF,transformRef:X.TRANSFORM_REF,appearanceRef:X.STYLE_REF,geometryTransformRef:X.GEOMETRY_TRANSFORM_REF,sliderRef:X.SLIDER_REF,$ref:X.GEOMETRY_REF};class Dc{static extractRefs(e){const t=[],n=new Set,s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o)){if(i in Fr){if(typeof a=="string"){const c=Fr[i],l=`${i}:${a}`;n.has(l)||(n.add(l),t.push({ref:a,type:c,path:i,value:a,fieldName:i,combined:l}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(l=>{const d=`$ref:${l}`;n.has(d)||(n.add(d),t.push({ref:l,type:X.GEOMETRY_REF,path:"$ref",value:l,fieldName:"$ref",combined:d}))});continue}if(Array.isArray(a)){a.forEach(c=>s(c));continue}typeof a=="object"&&s(a)}};return s(e),t}static extractDesignTokens(e){const t=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let s;for(;(s=n.exec(e))!==null;)t.push(s[0]);return t}static calculateStats(e){const t=this.extractRefs(e).map(o=>o.ref),n={},s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o))i in Fr?n[i]=(n[i]||0)+1:typeof a=="object"&&s(a)};return s(e),{totalRefs:t.length,uniqueRefs:new Set(t).size,fieldCounts:n}}}class ut{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(Nc()),this.register($c()),this.register(kc()),this.register(Oc()),this.register(jc()),this.register(Mc()),this.register(Fc()),this.register(Pc())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(t=>t.type===e)}getResolverForRef(e){return this.resolvers.find(t=>t.canResolve(e))}resolve(e,t){if(typeof e!="string"){const s=this.getResolverByType(e.type);if(!s)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return s.resolve(e.value,t)}catch(o){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${o}`)}}const n=this.resolvers.filter(s=>s.canResolve(e));if(n.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const s of n)try{return s.resolve(e,t)}catch(o){console.debug(`解析器 ${s.type} 解析 ${e} 失败:`,o);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,t){const n={};for(const s of e)try{const o=this.resolve(s,t),i=typeof s=="string"?s:s.combined;n[i]=o}catch(o){const i=typeof s=="string"?s:s.combined;console.warn(`引用解析失败: ${i}`,o)}return n}extractAllRefsEnhanced(e){try{return Dc.extractRefs(e)}catch(t){return console.warn("ReferenceExtractor 提取失败:",t),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const t=[],n=s=>{if(!(!s||typeof s!="object"))for(const[o,i]of Object.entries(s))if(o.endsWith("Ref")&&typeof i=="string")t.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&&t.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(t)]}validate(e,t){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,t);try{return n.resolve(e,t),!0}catch{return!1}}}function Co(){return new ut}class Zt{static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;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(t.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:ue.GRAPH};if(!s)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,t),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,c)=>(console.error(` 🎯 处理shape[${c}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,t,{strictMode:o})))),i.styleRef){try{const a=xe.resolve(i.styleRef,t);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}`,c=rt.resolve(a,t);console.warn(" 动画配置解析结果:",{animationId:c.id,transformCount:c.transforms.length,hasControl:!!c.control,controlConfig:c.control,hasVisualEffects:!!c.visualEffects,visualEffectsCount:c.visualEffects?.length||0}),i.animation=c,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,t,n={}){const{strictMode:s=!1}=n;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(t.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:!!t.geometryPresets,geometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});try{const i=De.resolve(o.geometryRef,t);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,c=o.content,l={...o};Object.assign(o,i),o.id=e.id,a!==void 0&&(o.type=a),c!==void 0&&(o.content=c),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 u=!1;const y=t.geometryPresets[o.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:o.geometryRef,originalGeometryExists:!!y,originalGeometryType:y?.type,originalGeometryKeys:y?Object.keys(y):[],hasVertices:y&&"vertices"in y,verticesIsArray:y&&Array.isArray(y.vertices),verticesLength:y?.vertices?.length,contextGeometryPresetsKeys:Object.keys(t.geometryPresets||{})}),y&&y.vertices&&Array.isArray(y.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:y.vertices,hasWithLabel:"withLabel"in y,withLabel:y.withLabel,hasLabel:"label"in y,label:y.label}),o.verticesConfig||(o.verticesConfig={}),y.vertices.forEach((m,h)=>{if(console.warn(`🔍 DEBUG: 检查顶点${h}:`,{vertex:m,isObject:m&&typeof m=="object",hasDollarRef:m&&typeof m=="object"&&"$ref"in m,refName:m?.$ref}),m&&typeof m=="object"&&"$ref"in m){const g=m.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${g},检查context.geometryPresets`),t.geometryPresets&&t.geometryPresets[g]){const p=t.geometryPresets[g];console.warn(`🔍 DEBUG: 找到点定义 ${g}:`,p),p.name?(o.verticesConfig[h]||(o.verticesConfig[h]={}),o.verticesConfig[h].name=p.name,console.warn(`✅ 从原始几何定义提取顶点${h}名字: ${p.name}`)):console.warn(`⚠️ 点定义 ${g} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${g}`)}else console.warn(`⚠️ 顶点${h}不是$ref对象`)}),y.withLabel!==void 0&&(o.verticesConfig.withLabel=y.withLabel),y.label&&typeof y.label=="object"){const m=y.label;m.offset&&Array.isArray(m.offset)&&m.offset.length>=2&&(o.verticesConfig.offset=m.offset),m.fontSize!==void 0&&(o.verticesConfig.fontSize=m.fontSize),m.color&&(o.verticesConfig.color=m.color),m.anchorX&&(o.verticesConfig.anchorX=m.anchorX),m.anchorY&&(o.verticesConfig.anchorY=m.anchorY)}console.warn("✅ 构建的verticesConfig:",o.verticesConfig)}if(d==="segment"||d==="line"?u="endpoints"in o&&Array.isArray(o.endpoints):d==="point"?u="position"in o&&o.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?u="vertices"in o&&Array.isArray(o.vertices):u="vertices"in o&&Array.isArray(o.vertices)||"endpoints"in o&&Array.isArray(o.endpoints)||"position"in o&&o.position!==void 0,u||(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 m=xe.resolve(i.styleRef,t);console.error(" 几何样式解析结果:",m),o.style=m}}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:",t.geometryPresets?Object.keys(t.geometryPresets):"undefined")}delete o.geometryRef}if(o.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${o.styleRef}, shape id: ${o.id}`);try{const i=xe.resolve(o.styleRef,t);console.error(" 形状样式解析成功:",i);const{id:a,...c}=i;o={...o,...c,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,t,{strictMode:s}))),o.label&&typeof o.label=="object"&&(o.label=this.transformLabel(o.label,t)),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,t),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],t),a=this.resolvePointReference(o.endpoints[1],t);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,t){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}if("geometryRef"in e){const n=e.geometryRef;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}return e}static convertShapeCoordinates(e,t){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 n={...e};if(n.position){if(Array.isArray(n.position)&&n.position.length>=2)console.warn(`🔄 Converting position array to object for ${n.id}:`,{shapeId:n.id,positionArray:n.position,convertedTo:{x:n.position[0],y:n.position[1]}}),n.position={x:n.position[0],y:n.position[1]};else if(typeof n.position=="object"){const s=this.resolvePointReference(n.position,t);s&&typeof s=="object"&&(n.position=s)}}if(Array.isArray(n.vertices)){const s=n.verticesConfig?{...n.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!n.verticesConfig,existingKeys:n.verticesConfig?Object.keys(n.verticesConfig):[],verticesConfigKeys:Object.keys(s)}),n.vertices=n.vertices.map((o,i)=>{const a=this.resolvePointReference(o,t);let c=null;if(o&&typeof o=="object"&&"$ref"in o){const l=o.$ref;t&&t.geometryPresets&&t.geometryPresets[l]&&(c=t.geometryPresets[l],console.warn(`📌 Found point definition for ${l} at vertex ${i}:`,{hasWithLabel:"withLabel"in c,withLabel:c.withLabel,hasLabel:"label"in c,labelKeys:c.label?Object.keys(c.label):"none"}),c.name&&(s[i]||(s[i]={}),s[i].name=c.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)}),n.withLabel!==void 0||n.label){const o={withLabel:n.withLabel!==void 0?n.withLabel:!0};if(n.label&&typeof n.label=="object"){const a=n.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]));n.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${n.id}:`,i)}else Object.keys(s).length>0&&(n.verticesConfig=s,console.warn(`✅ Added verticesConfig for polygon ${n.id}:`,s))}if(Array.isArray(n.endpoints)&&(n.endpoints=n.endpoints.map(s=>{const o=this.resolvePointReference(s,t);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(n.center)&&n.center.length>=2)n.center={x:n.center[0],y:n.center[1]};else if(n.center&&typeof n.center=="object"){const s=this.resolvePointReference(n.center,t);s&&typeof s=="object"&&(n.center=s)}if(n.start){if(Array.isArray(n.start)&&n.start.length>=2)n.start={x:n.start[0],y:n.start[1]};else if(typeof n.start=="object"){const s=this.resolvePointReference(n.start,t);s&&typeof s=="object"&&(n.start=s)}}if(n.end){if(Array.isArray(n.end)&&n.end.length>=2)n.end={x:n.end[0],y:n.end[1]};else if(typeof n.end=="object"){const s=this.resolvePointReference(n.end,t);s&&typeof s=="object"&&(n.end=s)}}for(const[s,o]of Object.entries(n))Array.isArray(o)?n[s]=o.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,t):i):o&&typeof o=="object"&&(n[s]=this.convertShapeCoordinates(o,t));return n}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=we.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformLabel(e,t){const n={...e};if(n.styleRef){try{const s=xe.resolve(n.styleRef,t);n.style=s}catch(s){console.warn(`标签样式解析失败: ${n.styleRef}`,s)}delete n.styleRef}return n}static resolveBoardConfig(e,t){if(t.boardDefinitions&&t.boardDefinitions[e])return t.boardDefinitions[e];const n={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 n[e]||n.default}static validate(e){const t=[];return e?(e.type!==ue.GRAPH&&t.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&t.push("图形内容块 shapes 数组不能为空"):t.push("图形内容块缺少 shapes 数组"),t):(t.push("图形内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ue.GRAPH).map(s=>this.transform(s,t,n))}}function Lc(){return{type:ue.GRAPH,transform:Zt.transform.bind(Zt),validate:Zt.validate.bind(Zt)}}class Qt{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const t={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:t,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:t.static.length,animatedLength:t.animated.length}),t}static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(s){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const d=nt.resolve(e.geometryTransformRef,t,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const u={type:ue.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",u.metadata.config),u.metadata.config&&typeof u.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),u.metadata.config=this.transformConfig(u.metadata.config,t,{strictMode:o})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",u),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",u.metadata.config),u}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:ue.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:",t.geometryTransformConfigs)}}const i=e.base||e.config?.base||t.basicInfo?.base||0,a=e.height||e.config?.height||t.basicInfo?.height||0,c=e.unit||e.config?.unit||t.basicInfo?.baseUnit||"cm",l={...e,type:ue.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:c,...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:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete l.config,delete l.base,delete l.height,delete l.unit,delete l.shapes,delete l.transform,delete l.animation,delete l.boardConfig,!s)return l;try{if(l.geometryRef){try{const d=De.resolve(l.geometryRef,t);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,d),d.styleRef){const u=xe.resolve(d.styleRef,t);l.metadata.config.style=u}}catch(d){if(o)throw d;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,d)}delete l.geometryRef}if(l.transformRef){try{const d=we.resolve(l.transformRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,d)}catch(d){if(o)throw d;console.warn(`几何变换变换解析失败: ${l.transformRef}`,d)}delete l.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!l.metadata,hasConfig:!!l.metadata?.config,configType:l.metadata?.config?typeof l.metadata.config:"undefined",configIsObject:l.metadata?.config?typeof l.metadata.config=="object":!1,configKeys:l.metadata?.config?Object.keys(l.metadata.config):[]}),l.metadata?.config&&typeof l.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),l.metadata.config=this.transformConfig(l.metadata.config,t,{strictMode:o}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const d=xe.resolve(l.styleRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=d}catch(d){if(o)throw d;console.warn(`几何变换样式解析失败: ${l.styleRef}`,d)}delete l.styleRef}if(l.animationRef){try{const d=this.resolveAnimationConfig(l.animationRef,t,{strictMode:o});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,d)}delete l.animationRef}if(l.sliderRef){try{const d=Ye.resolve(l.sliderRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层滑块引用解析失败: ${l.sliderRef}`,d)}delete l.sliderRef}if(l.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:l.boardRef,hasMetadataConfig:!!l.metadata?.config,currentBoardConfig:l.metadata?.config?.boardConfig});try{const d=this.resolveBoardConfig(l.boardRef,t,{strictMode:o});console.error("🔍 解析后的 boardConfig:",d),l.metadata.config||(l.metadata.config={}),l.metadata.config.boardConfig={...d,...l.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",l.metadata.config.boardConfig)}catch(d){if(o)throw d;console.warn(`顶层画板引用解析失败: ${l.boardRef}`,d)}delete l.boardRef}if(l.metadata?.config?.boardConfig&&typeof l.metadata.config.boardConfig=="object"){const d=l.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:l.type,metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasTransform:!!l.metadata?.config?.transform,transform:l.metadata?.config?.transform,hasAnimation:!!l.metadata?.config?.animation,animation:l.metadata?.config?.animation,hasBoardConfig:!!l.metadata?.config?.boardConfig,boardConfig:l.metadata?.config?.boardConfig}),l}catch(d){if(o)throw d;return console.warn("几何变换转换失败:",d),l}}static transformConfig(e,t,n={}){const{strictMode:s=!1}=n,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,c)=>{console.error(` 处理 static shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 static shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l})),o.shapes.animated&&(console.error(` 处理 animated shapes (${o.shapes.animated.length}):`),o.shapes.animated=o.shapes.animated.map((a,c)=>{console.error(` 处理 animated shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 animated shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l}))),o.transform){if(o.transform.transformRef)try{const a=we.resolve(o.transform.transformRef,t);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,c)=>{if(console.error(`🔍 处理 transform[${c}]:`,{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[${c}] 是字符串格式`),a.startsWith("transformRef:")){const l=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${l}`);try{const d=we.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${c}] 标准化后:`,u),u}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}try{const l=we.resolve(a,t);return this.normalizeTransformConfig(l,i)}catch(l){if(s)throw l;return console.warn(`Transform ref解析失败: ${a}`,l),a}}else if(a&&typeof a=="object"&&a.transformRef){const l=a.transformRef;console.error(`🔍 transform[${c}] 是对象格式,refName=${l}`);try{const d=we.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u={...d,...a,transformRef:void 0};console.error(`🔍 transform[${c}] 合并后:`,u);const y=this.normalizeTransformConfig(u,i);return console.error(`🔍 transform[${c}] 标准化后:`,y),y}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${c}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${c}] 未处理,返回原始值:`,a),a}))}if(o.geometry&&typeof o.geometry=="object"&&(o.geometry=this.transformGeometry(o.geometry,t,{strictMode:s})),Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(a=>{if(a.transformRef)try{const c=we.resolve(a.transformRef,t);return{...a,...c,transformRef:void 0}}catch(c){if(s)throw c;return console.warn(`Transformations解析失败: ${a.transformRef}`,c),a}return a})),o.style&&typeof o.style=="object"&&(o.style=this.transformStyle(o.style,t,{strictMode:s})),o.animationRef){try{const a=this.resolveAnimationConfig(o.animationRef,t,{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:!!t.animationDefinitions,animationDefinitionKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[]});try{const a={...st,...t,animationDefinitions:t.animationDefinitions||st.animationDefinitions},c=Ye.resolve(o.sliderRef,a);o.animation={...c,...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,t,{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,t){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:t?Object.keys(t):[],geometryRefToShapeId:t});const n={...e};switch(!n.type&&n.config&&n.config.type&&(n.type=n.config.type),n.type){case"rotation":if(n.config){if(n.rotation={...n.config},n.rotation.center&&typeof n.rotation.center=="object"){const s=n.rotation.center;"x"in s&&"y"in s&&(n.rotation.center=[s.x,s.y])}delete n.config}break;case"translation":n.config&&(n.translation={...n.config},delete n.config);break;case"scale":if(n.config){if(n.scale={...n.config},n.scale.center&&typeof n.scale.center=="object"){const s=n.scale.center;"x"in s&&"y"in s&&(n.scale.center=[s.x,s.y])}delete n.config}break;case"composite":n.config&&Array.isArray(n.config.transforms)&&(n.composite=n.config.transforms.map(s=>this.normalizeTransformConfig(s,t)),delete n.config);break;default:if(n.config){const{type:s,...o}=n.config;Object.assign(n,o),delete n.config}}if(n.targetGroup&&t){const s=n.targetGroup;let o;if(t[s])o=t[s],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:s,mapped:o,type:"exact"});else{const i=Object.keys(t).find(a=>{if(a.startsWith(s+"_")||a===s||a.includes(s))return!0;const c=a.split("_"),l=s.split("_");return c.some(d=>l.includes(d))});i&&(o=t[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:s,geometryRef:i,mapped:o,type:"heuristic"}))}o?n.targetGroup=o:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:s,geometryRefToShapeId:t,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!n.targetGroup&&(n.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:n,hasRotation:!!n.rotation,hasTranslation:!!n.translation,hasScale:!!n.scale,hasComposite:!!n.composite}),n}static transformShape(e,t,n={}){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:!!t.geometryPresets,contextGeometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",o.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",t.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=De.resolve(o.geometryRef,t);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,c)=>({index:c,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=xe.resolve(o.styleRef,t);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){const i=o.metadata.id.toLowerCase();i.includes("left")?o.metadata.rotationGroup="left":i.includes("right")?o.metadata.rotationGroup="right":o.metadata.rotationGroup=o.metadata.id}if(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,c=.1;o.type="circle",o.vertices=[[i,a],[i+c,a]],delete o.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:o.type,vertices:o.vertices})}return o}static transformGeometry(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){try{const i=De.resolve(o.geometryRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`几何对象解析失败: ${o.geometryRef}`,i)}delete o.geometryRef}return o}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=we.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换对象解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformStyle(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.styleRef){try{const i=xe.resolve(o.styleRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`样式对象解析失败: ${o.styleRef}`,i)}delete o.styleRef}return o}static resolveAnimationConfig(e,t,n={}){const{strictMode:s=!1}=n;if(!e||typeof e!="string"){if(s)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const o=e.replace("animationRef:","");if(t.animationDefinitions&&t.animationDefinitions[o])return{...t.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,t,n={}){const{strictMode:s=!1}=n;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:!!t.boardDefinitions,contextBoardDefinitionKeys:t.boardDefinitions?Object.keys(t.boardDefinitions):[],hasRefInContext:t.boardDefinitions&&!!t.boardDefinitions[o]}),t.boardDefinitions&&t.boardDefinitions[o]){const a={...t.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 t={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 t[e]||t.slider_horizontal}static getFallbackBoardConfig(e){const t={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 t[e]||t.default}static validate(e){const t=[];return e?(e.type!==ue.GEOMETRY_TRANSFORM&&t.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||t.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&t.push("几何变换内容块缺少 geometry 或 geometryRef"),t):(t.push("几何变换内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ue.GEOMETRY_TRANSFORM).map(s=>this.transform(s,t,n))}}function Uc(){return{type:ue.GEOMETRY_TRANSFORM,transform:Qt.transform.bind(Qt),validate:Qt.validate.bind(Qt)}}class Ke{static transformText(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${s}`);const i={...e,type:ue.TEXT};if(!s)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,t,{strictMode:o})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=xe.resolve(i.styleRef,t);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,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n,i={...e,type:ue.FORMULA};if(!s)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){try{const a=xe.resolve(i.styleRef,t);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,t,n={}){const{strictMode:s=!1}=n;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 c=i[0],l=i[1];console.error(` 发现设计令牌: ${c}, path=${l}`);try{const d=Me.resolve(c,t);console.error(` 解析结果: ${c} -> ${d}`),o=o.replace(c,String(d))}catch(d){if(s)throw d;console.warn(`文本中的设计令牌解析失败: ${c}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${o}"`),o}static resolveStyle(e,t,n={}){const{strictMode:s=!1}=n;try{return Me.replaceDesignTokenRefs(e,t,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 t=[];return e?(e.type!==ue.TEXT&&t.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("文本内容块缺少 content 字段"),t):(t.push("文本内容块不能为空"),t)}static validateFormula(e){const t=[];return e?(e.type!==ue.FORMULA&&t.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("公式内容块缺少 content 字段"),t):(t.push("公式内容块不能为空"),t)}static batchTransformText(e,t,n={}){return e.filter(s=>s.type===ue.TEXT).map(s=>this.transformText(s,t,n))}static batchTransformFormula(e,t,n={}){return e.filter(s=>s.type===ue.FORMULA).map(s=>this.transformFormula(s,t,n))}}function Gc(){return{type:ue.TEXT,transform:Ke.transformText.bind(Ke),validate:Ke.validateText.bind(Ke)}}function zc(){return{type:ue.FORMULA,transform:Ke.transformFormula.bind(Ke),validate:Ke.validateFormula.bind(Ke)}}class Bc{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(Lc()),this.register(Uc()),this.register(Gc()),this.register(zc())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,t,n={}){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=${n.enableReferenceResolution}`),s.transform(e,t,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,t,n={}){return e.map(s=>this.transform(s,t,n))}transformScene(e,t,n={}){const s=e.items||e.content;if(!e||!Array.isArray(s))return{items:[],layout:e?.layout};const o=this.batchTransform(s,t,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,t,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=Le.resolve(e.layout,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:o,layout:i}}resolveLayoutReferences(e,t,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return Le.resolve(e,t)}catch(s){if(n.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=Le.resolve(o,t),{layoutRef:a,...c}=e;return{...i,...c}}catch(o){if(n.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]=Le.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),s[o]=i}else if(typeof i=="string"&&i.startsWith("$"))try{s[o]=Me.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${o}=${i}`,a),s[o]=i}else i&&typeof i=="object"?s[o]=this.resolveLayoutReferences(i,t,n):s[o]=i;return s}return e}transformScenes(e,t,n={}){const s={};for(const[o,i]of Object.entries(e))s[o]=this.transformScene(i,t,n);return s}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const t=this.getTransformer(e.type);return!t||!t.validate?[]:t.validate(e)}batchValidate(e){return e.map(t=>({block:t,errors:this.validate(t)}))}}function Eo(){return new Bc}class Yr{static validate(e,t={}){const{strictMode:n=!1,skipOptionalFields:s=!1}=t,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),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n,s){const{skipOptionalFields:o}=s;for(const i of Ir.RAW_DATA)e[i]===void 0&&t.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Ir.BASIC_INFO)e.basic_info[i]===void 0&&t.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Ir.ANSWER_INFO)e.answer_info[i]===void 0&&t.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,t,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&t.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&t.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&t.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&t.push(`${a} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||t.push(`场景 ${o} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),bo.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){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"&&t.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basic_info.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basic_info.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basic_info.context 应为对象类型"),s.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(s.shape)&&n.push(`未知的形状类型: ${s.shape}`)}static validateAnswerInfo(e,t,n){if(!e.answer_info||typeof e.answer_info!="object")return;const s=e.answer_info;typeof s.value!="number"&&t.push("answer_info.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer_info.unit 应为字符串类型"),typeof s.explanation_text!="string"&&t.push("answer_info.explanation_text 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer_info.value 为负数,可能不正确"),s.value>1e4&&n.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,t,n){if(e.schema_version||n.push("建议添加 schema_version 字段"),e.config_version||n.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&n.push("knowledge_points 数组为空"),e.scenes)for(const[s,o]of Object.entries(e.scenes)){const i=o;i.content&&i.content.length===0&&n.push(`场景 ${s} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of t)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,t={}){const{strictMode:n=!1,removeInvalidFields:s=!1}=t,o=this.validate(e,{strictMode:n});let i=e;return s&&!o.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(c=>{c in i&&delete i[c]})),{data:i,errors:o.errors,warnings:o.warnings}}}class Kr{static validate(e,t={}){const{strictMode:n=!1,checkSceneContent:s=!0}=t,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),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n){const s=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const o of s)e[o]===void 0&&t.push(`缺少必需字段: ${o}`)}static validateFieldTypes(e,t,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&t.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&t.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&t.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&t.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&t.push(`${i} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i,c=a.items||a.content;Array.isArray(c)?c.length===0&&n.push(`场景 ${o} 的内容数组为空`):t.push(`场景 ${o} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),bo.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){if(!e.basicInfo||typeof e.basicInfo!="object"){t.push("basicInfo 应为对象类型");return}const s=e.basicInfo;(s.question===void 0||typeof s.question!="string")&&t.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&t.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basicInfo.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basicInfo.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basicInfo.context 应为对象类型")}static validateAnswer(e,t,n){if(!e.answer||typeof e.answer!="object"){t.push("answer 应为对象类型");return}const s=e.answer;typeof s.value!="number"&&t.push("answer.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer.unit 应为字符串类型"),typeof s.explanation!="string"&&t.push("answer.explanation 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer.value 为负数,可能不正确"),s.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,t,n){if(e.explanation===void 0){t.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){t.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((s,o)=>{(!s||typeof s!="object")&&t.push(`explanation[${o}] 应为对象类型`)})):e.explanation.steps===void 0?t.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||t.push("explanation.steps 应为数组类型")}static validateStrictMode(e,t,n){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||n.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&n.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&n.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&n.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const s=e.metadata;(!s.topic||typeof s.topic!="string")&&n.push("metadata.topic 应为字符串类型"),(!s.skill||typeof s.skill!="string")&&n.push("metadata.skill 应为字符串类型"),(!s.tags||!Array.isArray(s.tags))&&n.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["id","title","basicInfo","scenes","answer"];for(const n of t)if(e[n]===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 lt{static validateInput(e,t={}){const{isValid:n,errors:s,warnings:o}=Yr.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateOutput(e,t={}){const{isValid:n,errors:s,warnings:o}=Kr.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateComplete(e,t,n={}){const{inputStrictMode:s=!1,outputStrictMode:o=!1}=n,i=this.validateInput(e,{strictMode:s}),a=this.validateOutput(t,{strictMode:o}),c=[...i.errors,...a.errors],l=[...i.warnings,...a.warnings],d={isValid:i.isValid&&a.isValid,errors:c,warnings:l};return{input:i,output:a,overall:d}}static quickValidateInput(e){return Yr.quickValidate(e)}static quickValidateOutput(e){return Kr.quickValidate(e)}static validateAndReport(e,t,n={}){const s=t==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${t.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 Xr{static extractAllReferences(e){const t=[],n=s=>{typeof s=="string"?t.push(s):Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&Object.values(s).forEach(n)};return n(e),[...new Set(t)]}static categorizeReferences(e,t){const n={[X.DESIGN_TOKEN]:[],[X.STYLE_REF]:[],[X.GEOMETRY_REF]:[],[X.TRANSFORM_REF]:[],[X.LAYOUT_REF]:[]},s=new ut;for(const o of e){const i=s.getResolverForRef(o);i&&n[i.type].push(o)}return n}static batchResolveReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o}=n,i=new ut,a={};for(const c of e){const l=i.getResolverForRef(c);if(l)try{a[c]=l.resolve(c,t)}catch(d){if(s)throw d;console.warn(`引用解析失败: ${c}`,d),o&&(a[c]=o(c))}}return a}static replaceReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o,maxDepth:i=10}=n,a=new ut,c=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"]),l=(d,u=0,y)=>{if(u>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(y&&c.has(y))return console.warn(`🛡️ 跳过保留字段 "${y}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const h=a.getResolverForRef(d);if(h)try{return h.resolve(d,t)}catch(g){if(s)throw g;return console.warn(`引用解析失败: ${d}`,g),o?o(d):d}return d}else{if(Array.isArray(d))return d.map(m=>l(m,u+1,void 0));if(d&&typeof d=="object"){const m={};for(const[h,g]of Object.entries(d))m[h]=l(g,u+1,h);return m}}return d};return l(e)}static calculateReferenceStats(e,t){const n=new ut,s={total:e.length,resolved:0,failed:0,byType:{}};Object.values(X).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=n.getResolverForRef(o);if(i){const a=i.type;s.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const c=i.resolve(o,t);console.log(`🔍 引用解析成功: ${o} =>`,c),s.resolved++,s.byType[a].resolved++}catch(c){console.error(`🔍 引用解析失败: ${o}`,c),s.failed++,s.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${o}`)}return s}static checkReferenceExists(e,t){const s=new ut().getResolverForRef(e);if(!s)return!1;if(s.validate)return s.validate(e,t);try{return s.resolve(e,t),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const t=e.match(/^(\w+):(\w+)$/);return t?[t[1],t[2]]:[e]}static createReference(e,t){switch(e){case X.DESIGN_TOKEN:return`$${t.join(".")}`;case X.STYLE_REF:return`styleRef:${t[0]}`;case X.GEOMETRY_REF:return`geometryRef:${t[0]}`;case X.TRANSFORM_REF:return`transformRef:${t[0]}`;case X.LAYOUT_REF:return`layoutRef:${t[0]}`;default:return t.join(":")}}static flattenNestedReferences(e){const t=[],n=(s,o=[])=>{if(typeof s=="string")t.push(`${o.join(".")}=${s}`);else if(Array.isArray(s))s.forEach((i,a)=>{n(i,[...o,`[${a}]`])});else if(s&&typeof s=="object")for(const[i,a]of Object.entries(s))n(a,[...o,i])};return n(e),t}}class To{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 t=this.marks.get(e);if(!t){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),s=n-t.startTime;t.endTime=n,t.duration=s,this.updateStats(e,s)}updateStats(e,t){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=t;break;case"transformation":this.stats.transformationTime=t;break;case"validation":this.stats.validationTime=t;break;case"total":this.stats.totalTime=t;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>tt.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${tt.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>tt.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${tt.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>tt.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${tt.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>tt.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 Vc{static deepMerge(e,t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return Array.isArray(e)?e.map((s,o)=>o<t.length?this.deepMerge(s,t[o]):s):[...t];const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(s in n&&typeof n[s]=="object"&&typeof o=="object"?n[s]=this.deepMerge(n[s],o):n[s]=o);return n}static deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t||typeof e!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((o,i)=>this.deepEqual(o,t[i]));const n=Object.keys(e),s=Object.keys(t);return n.length!==s.length?!1:n.every(o=>o in t?this.deepEqual(e[o],t[o]):!1)}static safeGet(e,t,n=void 0){const s=Array.isArray(t)?t:t.split(".");let o=e;for(const i of s){if(o==null||typeof o!="object")return n;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(o)){const c=parseInt(a[1],10);o=o[c]}else o=o[i]}return o!==void 0?o:n}static safeSet(e,t,n){const s=Array.isArray(t)?t:t.split("."),o=Array.isArray(e)?[...e]:{...e};let i=o;for(let l=0;l<s.length-1;l++){const d=s[l],u=d.match(/^\[(\d+)\]$/);if(u&&Array.isArray(i)){const y=parseInt(u[1],10);i[y]===void 0&&(i[y]={}),i=i[y]}else{if(i[d]===void 0){const m=s[l+1].match(/^\[(\d+)\]$/);i[d]=m?[]:{}}i=i[d]}}const a=s[s.length-1],c=a.match(/^\[(\d+)\]$/);if(c&&Array.isArray(i)){const l=parseInt(c[1],10);i[l]=n}else i[a]=n;return o}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,t){let n=0;return(...s)=>{const o=Date.now();o-n>=t&&(n=o,e(...s))}}static debounce(e,t){let n;return(...s)=>{clearTimeout(n),n=setTimeout(()=>e(...s),t)}}static formatBytes(e,t=2){if(e===0)return"0 Bytes";const n=1024,s=t<0?0:t,o=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/Math.pow(n,i)).toFixed(s))+" "+o[i]}static estimateObjectSize(e){const t=new Set,n=s=>t.has(s)?0:typeof s=="string"?s.length*2:typeof s=="number"?8:typeof s=="boolean"?4:s==null?0:Array.isArray(s)?(t.add(s),s.reduce((o,i)=>o+n(i),0)):typeof s=="object"?(t.add(s),Object.values(s).reduce((o,i)=>o+n(i),0)):0;return n(e)}}class qc{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...Tc,...e},this.referenceContext=So(),this.resolverRegistry=Co(),this.transformerRegistry=Eo(),this.performanceMonitor=new To}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 t=this.validateInput(e);if(!t.isValid&&this.config.strictMode)throw new le(G.INVALID_INPUT,Zn[G.INVALID_INPUT],{errors:t.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const n=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let s=n;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),s=this.resolveReferences(n),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 le(G.OUTPUT_VALIDATION_FAILED,Zn[G.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:t,outputValidation:i,inputWarnings:t.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(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}validateInput(e){return lt.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(([t,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${t}:`,{id:n.id,type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),shapeKeys:Object.keys(n)});const s=this.convertGeometryShapeCoordinates(n);console.error(` 📍 ${t}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[t]=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(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=s}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(t=>{t&&t.content&&Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="graph"&&n.shapes&&this.extractPointCoordinatesFromShapes(n.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(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${t}:`,{id:n.id,strategy:n.strategy,hasBase:"base"in n,hasHeight:"height"in n,hasShapes:"shapes"in n,hasTransform:"transform"in n}),this.referenceContext.geometryTransformConfigs[t]=n)}),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(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${t}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[t]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;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});const t={...e};t.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(console.error(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(console.error(` Endpoint ${s} is not array:`,n),n)),t.type==="segment"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&console.error(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=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?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(t[n]=this.convertTransformDefinitionCoordinates(s));return t}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(t=>{if(t&&t.type==="point"&&t.position&&Array.isArray(t.position)&&t.position.length>=2){const n=t.id||`point_${t.position[0]}_${t.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:t.position[0],y:t.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);const t={id:e.math_prob_id||Vc.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&&(t[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,t.basicInfo=s,console.error("🔧 transformBaseData: transformed.basicInfo set =",t.basicInfo),t.explanation=this.transformExplanation(e.explanation),t}parseGrade(e){const t=e.match(/g(\d+)/);return t?parseInt(t[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 t={...e};return console.error("🔄 transformBasicInfo: transformed copy:",t),t.question===void 0&&t.content!==void 0&&(t.question=t.content),t.question===void 0&&(t.question=""),console.error("🔄 transformBasicInfo: returning:",t),t}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const t={};return["question","solve","review"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}else t[o]={items:[]}}),["remember"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}}),t}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 t=e.steps.map((n,s)=>(console.error(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(t)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={type:n,...t};console.error(" contentBlock keys:",Object.keys(s)),n==="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)),n==="graph"&&o.shapes&&console.error(" transformed shapes count:",o.shapes.length);let i;if(n==="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(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...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 t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Xr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),t}validateOutput(e){return lt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.performanceMonitor.checkPerformance(),i=[...t.inputValidation.warnings.map(d=>({code:G.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...t.outputValidation.warnings.map(d=>({code:G.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...o.warnings.map(d=>({code:G.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=n||e,c=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=Xr.calculateReferenceStats(c,this.referenceContext);return{data:e,warnings:i,performance:s,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,t){const n={...ir,id:e?.math_prob_id||ir.id,title:e?.title||ir.title},s={code:G.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:n,warnings:[s],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class Wt{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...Ec,...e},this.referenceContext=So(),this.resolverRegistry=Co(),this.transformerRegistry=Eo(),this.performanceMonitor=new To,this.syncAdapter=new qc(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 t=e,n=this.syncAdapter.adapt(t);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:n.data.id,hasBasicInfo:!!n.data.basicInfo,warningCount:n.warnings.length,referenceStats:n.referenceStats}),n}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}_validateInput(e){return lt.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(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[t]=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(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=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 t=e.steps.map((n,s)=>(this.config.enableLogging&&console.log(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(t))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={...t,type:n};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(s)),n==="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)),n==="graph"&&o.shapes&&console.log(" transformed shapes count:",o.shapes.length));let i;if(n==="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(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...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 t={...e};t.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(this.config.enableLogging&&console.log(` Endpoint ${s} is not array:`,n),n)),t.type==="line"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&this.config.enableLogging&&console.log(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=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?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=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?t[n]=this.convertTransformDefinitionCoordinates(s):t[n]=this.deepClone(s));return t}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const t={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=t.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),t}_resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Xr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),t}_validateOutput(e){return lt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(t.inputWarnings||[]).map(a=>({code:Mr.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(t.outputWarnings||[]).map(a=>({code:Mr.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?s:void 0,referenceStats:o}}createFallbackResult(e,t){return{data:{...ir,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:Mr.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t instanceof Error?t.message:t}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new Wt(e)}}function ct(r,e){return new Wt(e).adapt(r)}async function wn(r,e){return Promise.resolve(ct(r,e))}function No(r,e){const t=typeof r=="function"?r():r;return ct(t,e)}async function $o(r,e){const t=typeof r=="function"?await r():r instanceof Promise?await r:r;return ct(t,e)}function ko(r){return new Wt(r)}function Oo(r){const e=new Wt(r);return{adapt:t=>Promise.resolve(e.adapt(t))}}function Wc(r,e="input"){return e==="input"?lt.validateInput(r):lt.validateOutput(r)}function Hc(r,e,t=100){const n=[];for(let c=0;c<t;c++){const l=performance.now();r.adapt(e);const d=performance.now();n.push(d-l)}const s=n.reduce((c,l)=>c+l,0)/t,o=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:s,minTime:o,maxTime:i,memoryUsage:a}}const Yc={adapt:(r,e)=>ct(r,e),adaptAsync:(r,e)=>wn(r,e),create:r=>ko(r)},Kc="4.0.0",jo="4.0.0";function Xc(r="4.0.0"){return jo>=r}function Mo(r){return r?.schema_version==="4.0.0"||r?.schema_version?.startsWith("4.")}function Jc(r){return Mo(r)&&(r.geometry_shapes||r.transform_definitions||r.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(r.basic_info.shape))}class Pr extends Error{constructor(e,t,n,s){super(`Failed to generate config for ${t}: ${e}`),this.shapeType=t,this.options=n,this.innerError=s,this.name="ConfigGenerationError"}}function Zc(r){const e=[],t=[];if(r.shapes||e.push(D("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),r.transform||e.push(D("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),r.strategy||e.push(D("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:es(e),timestamp:new Date().toISOString()};r.shapes&&e.push(...Qc(r.shapes));let n=!1;if(r.shapes?.animated){for(const s of r.shapes.animated)if(s.transform){n=!0;break}}return r.transform?e.push(...ed(r.transform)):n||e.push(D("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...td(r)),e.push(...rd(r)),e.push(...nd(r)),e.length>0&&t.push(...es(e)),{isValid:e.length===0,errors:e,fixes:t,timestamp:new Date().toISOString()}}function Io(r){if(!r||typeof r!="object"||!r.type||typeof r.type!="string"||!["rotation","translation","scale","composite"].includes(r.type))return!1;switch(r.type){case"rotation":if(!r.config||typeof r.config!="object")return!1;const t=r.config.center;if(t!=="auto"&&(!Array.isArray(t)||t.length!==2)||typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number"||r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical")return!1;break;case"translation":if(!r.config||typeof r.config!="object")return!1;const n=r.config.direction;if(Array.isArray(n)){if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="number")return!1}else if(typeof n=="string"){if(n!=="horizontal"&&n!=="vertical")return!1}else return!1;if(typeof r.config.distance!="number"||r.config.distance<=0)return!1;break;case"scale":if(!r.config||typeof r.config!="object")return!1;const s=r.config.center;if(s!=="centroid"&&(!Array.isArray(s)||s.length!==2)||typeof r.config.startScale!="number"||typeof r.config.endScale!="number"||typeof r.config.uniform!="boolean")return!1;break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))return!1;for(const o of r.transforms)if(!Io(o))return!1;if(r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel")return!1;break}return!0}function Fo(r,e){const t=[];if(!r||typeof r!="object")return t.push(D("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,r,{type:"rotation"})),t;(!r.type||typeof r.type!="string")&&t.push(D("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,r.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(r.type&&!n.includes(r.type)&&t.push(D("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${r.type}`,`${e}.type`,r.type,"rotation")),r.type){case"rotation":if(!r.config||typeof r.config!="object")t.push(D("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,r.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const s=r.config.center;s!=="auto"&&(!Array.isArray(s)||s.length!==2)&&t.push(D("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,r.config.center,[0,0])),(typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number")&&t.push(D("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,r.config,{startAngle:0,endAngle:Math.PI})),r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical"&&t.push(D("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,r.config.direction,"clockwise"))}break;case"translation":if(!r.config||typeof r.config!="object")t.push(D("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,r.config,{direction:"horizontal",distance:1}));else{const s=r.config.direction;Array.isArray(s)?s.length!==2?t.push(D("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,s,[1,0])):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(D("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,s,[1,0])):typeof s=="string"?s!=="horizontal"&&s!=="vertical"&&t.push(D("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,s,"horizontal")):t.push(D("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,s,"horizontal")),(typeof r.config.distance!="number"||r.config.distance<=0)&&t.push(D("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,r.config.distance,1))}break;case"scale":if(!r.config||typeof r.config!="object")t.push(D("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,r.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const s=r.config.center;s!=="centroid"&&(!Array.isArray(s)||s.length!==2)&&t.push(D("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,r.config.center,"centroid")),(typeof r.config.startScale!="number"||typeof r.config.endScale!="number")&&t.push(D("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,r.config,{startScale:1,endScale:2})),typeof r.config.uniform!="boolean"&&t.push(D("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,r.config.uniform,!0))}break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))t.push(D("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,r.transforms,[]));else for(let s=0;s<r.transforms.length;s++){const o=Fo(r.transforms[s],`${e}.transforms[${s}]`);t.push(...o)}r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel"&&t.push(D("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,r.executionMode,"sequential"));break}return t}function D(r,e,t,n,s){let o=s;if(s===void 0)switch(r){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:r,message:e,path:t,value:n,suggestedValue:o}}function Qc(r){const e=[];if(!r||typeof r!="object")return e.push(D("MISSING_SHAPES","形状定义无效或缺失","$.shapes",r)),e;if(!Array.isArray(r.static))e.push(D("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",r.static));else for(let t=0;t<r.static.length;t++){const n=r.static[t],s=Qn(n,`$.shapes.static[${t}]`);e.push(...s)}if(!Array.isArray(r.animated))e.push(D("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",r.animated));else for(let t=0;t<r.animated.length;t++){const n=r.animated[t],s=Qn(n,`$.shapes.animated[${t}]`);e.push(...s)}return e}function Qn(r,e){const t=[];if(!r||typeof r!="object")return t.push(D("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,r)),t;if((!r.type||typeof r.type!="string")&&t.push(D("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,r.type)),!Array.isArray(r.vertices))t.push(D("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,r.vertices));else if(r.vertices.length===0)t.push(D("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,r.vertices));else for(let n=0;n<r.vertices.length;n++){const s=r.vertices[n];!Array.isArray(s)||s.length!==2?t.push(D("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,s)):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(D("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,s))}if(r.transform!==void 0){const n=Fo(r.transform,`${e}.transform`);t.push(...n)}return t}function ed(r){const e=[];if(!r)return e.push(D("MISSING_TRANSFORM","变换配置缺失","$.transform",r)),e;const t=Array.isArray(r),n=t?r:[r],s="$.transform";for(let o=0;o<n.length;o++){const i=n[o],a=t?`${s}[${o}]`:s;Io(i)||e.push(D("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function td(r){const e=[];if(!r.strategy)return e;const{strategy:t}=r;let n=0;if(r.transform&&(Array.isArray(r.transform)?n+=r.transform.length:typeof r.transform=="object"&&(r.transform&&typeof r.transform=="object"&&"transforms"in r.transform?n+=r.transform.transforms.length:n+=1)),r.shapes?.animated)for(const o of r.shapes.animated)o.transform&&(n+=1);return t.includes("single")&&n!==1&&e.push(D("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",t,n===0?"single_rotation":"double_rotation")),t.includes("double")&&n!==2&&e.push(D("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",t,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(t)||e.push(D("STRATEGY_MISMATCH",`无效的策略名称: ${t}`,"$.strategy",t,"single_rotation")),e}function rd(r){const e=[];if(r.unit&&typeof r.unit!="string"&&e.push(D("UNIT_MISMATCH","单位必须是字符串","$.unit",r.unit,"in")),r.baseUnit&&typeof r.baseUnit!="string"&&e.push(D("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",r.baseUnit,r.unit||"in")),r.heightUnit&&typeof r.heightUnit!="string"&&e.push(D("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",r.heightUnit,r.unit||"in")),r.unit&&r.baseUnit&&r.baseUnit!==r.unit&&e.push(D("UNIT_MISMATCH",`底边单位 (${r.baseUnit}) 与主单位 (${r.unit}) 不一致`,"$.baseUnit",r.baseUnit,r.unit)),r.unit&&r.heightUnit&&r.heightUnit!==r.unit&&e.push(D("UNIT_MISMATCH",`高度单位 (${r.heightUnit}) 与主单位 (${r.unit}) 不一致`,"$.heightUnit",r.heightUnit,r.unit)),r.unit&&r.boardConfig&&r.boardConfig.boundingBox){const[t,n,s,o]=r.boardConfig.boundingBox,i=s-t,a=n-o,c=r.unit==="cm"?50:20;(i>c*5||a>c*5)&&e.push(D("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${r.unit})不匹配`,"$.boardConfig.boundingBox",r.boardConfig.boundingBox,void 0))}return e}function nd(r){const e=[];if(r.shapes&&r.boardConfig&&r.boardConfig.boundingBox){const t=r.boardConfig.boundingBox,[n,s,o,i]=t,a=[...r.shapes.static||[],...r.shapes.animated||[]];for(let c=0;c<a.length;c++){const l=a[c];if(l&&l.vertices)for(let d=0;d<l.vertices.length;d++){const u=l.vertices[d];if(Array.isArray(u)&&u.length===2){const[y,m]=u;(y<n||y>o||m<i||m>s)&&e.push(D("GEOMETRY_INCONSISTENCY",`形状 ${c} 的顶点 ${d} (${y}, ${m}) 超出画板边界`,`$.shapes.${c<(r.shapes.static?.length||0)?"static":"animated"}[${c}].vertices[${d}]`,u,[Math.max(n,Math.min(y,o)),Math.max(i,Math.min(m,s))]))}}}}if(r.metadata&&r.metadata.base&&r.metadata.height){const t=.5*r.metadata.base*r.metadata.height;if(r.shapes?.static?.[0]?.vertices){const n=r.shapes.static[0].vertices;if(n.length===3){const[s,o]=n[0],[i,a]=n[1],[c,l]=n[2],d=.5*Math.abs((i-s)*(l-o)-(c-s)*(a-o));Math.abs(d-t)>.01&&e.push(D("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${t.toFixed(2)}) 不一致`,"$.metadata",{base:r.metadata.base,height:r.metadata.height,calculatedArea:d,expectedArea:t}))}}}return e}function es(r){const e=[];for(const t of r)switch(t.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:t.path,value:t.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${t.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将底边长度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将高度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:t.path,value:t.suggestedValue||0,description:`将原点坐标修复为: ${t.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:t.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:t.suggestedValue!==void 0&&e.push({action:"replace",path:t.path,value:t.suggestedValue,description:`修复 ${t.code} 错误`,isSafe:!1})}return e}function ts(r){if(!sd(r))throw new Pr("Invalid parallelogram config options","parallelogram",r);const{base:e,height:t,unit:n="in",layoutDensity:s="compact",theme:o="light"}=r,i=r.originX??0,a=r.originY??0,c=r.skew??e/3;try{const l=od(e,t,c,i,a,o),d=id(e),u=ad(s),y=ld(e,t,c,i,a);return{ui:{layoutDensity:s},base:e,height:t,unit:n,shapes:l,transform:d,animation:u,boardConfig:y,strategy:"cut_and_paste",theme:o,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:t,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){if(l instanceof Pr)throw l;const d=l instanceof Error?l.message:String(l);throw new Pr(d,"parallelogram",r,l instanceof Error?l:void 0)}}function sd(r){if(!r||typeof r!="object")return!1;const e=["base","height"];for(const t of e)if(!(t in r))return!1;return!(typeof r.base!="number"||r.base<=0||typeof r.height!="number"||r.height<=0||r.skew!==void 0&&(typeof r.skew!="number"||r.skew<0)||r.originX!==void 0&&(typeof r.originX!="number"||!isFinite(r.originX))||r.originY!==void 0&&(typeof r.originY!="number"||!isFinite(r.originY)))}function od(r,e,t,n,s,o){const a=o==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},c=[[n+t,s],[n+r,s],[n+r+t,s+e],[n+t,s+e]],l=[[n,s],[n+t,s],[n+t,s+e]];return{static:[{type:"trapezoid",vertices:c,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:l,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function id(r){return{type:"translation",config:{direction:[1,0],distance:r}}}function ad(r){return{slider:{position:r==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function ld(r,e,t,n,s){const o=Math.min(n,n+t,n+r,n+r+t),i=Math.max(n,n+t,n+r,n+r+t),a=Math.min(s,s+e),c=Math.max(s,s+e),l=3;return{boundingBox:[o-l,c+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function cd(r){return{id:r.id||r.math_prob_id,title:r.title||"",grade:r.grade||5,unit:r.unit||r.unit_name||"",lesson:r.lesson||r.lesson_name||"",skill:r.skill||r.skill_description||"",objective:r.objective||"",knowledgePoints:Array.isArray(r.knowledge_points)?r.knowledge_points:Array.isArray(r.knowledgePoints)?r.knowledgePoints:[],difficulty:r.difficulty||1,description:r.description||"",metadata:r.metadata||{topic:"",skill:"",tags:[]},math_prob_id:r.math_prob_id,grade_id:r.grade_id,unit_id:r.unit_id,lesson_id:r.lesson_id,module_id:r.module_id,skill_item_id:r.skill_item_id,skill_id:r.skill_id,created_at:r.created_at,updated_at:r.updated_at,layout:r.layout||{type:"card",padding:"20px",theme:"light"}}}function dd(r){const e=r||{};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 fd(r,e,t){return{value:r,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:t}}function ud(r){return r?{value:r.value,unit:r.unit,explanation:r.explanation_text||r.explanation||"正确答案"}:null}function md(r){return r.answer?r.answer:r.answer_info?ud(r.answer_info):null}function hd(){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 gd(){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 pd(r){return Array.isArray(r)||r&&r.steps?r:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Po(r){const e=cd(r),t=dd(r.basic_info||r.basicInfo),n=["平行四边形面积公式 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:n,difficulty:e.difficulty||1,description:e.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:e.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...t,question:t.question||"计算下面平行四边形的面积:",answerUnit:t.answerUnit||"平方英寸",shape:t.shape||"parallelogram",base:t.base||9,height:t.height||6,baseUnit:t.baseUnit||"in",heightUnit:t.heightUnit||"in",variables:t.variables||{b:9,h:6,unit:"in"},context:t.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:xd(r.scenes||hd(),"parallelogram",t),explanation:pd(r.explanation||gd()),answer:md(r)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:r.answer_info||fd(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:r.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function yd(r){return r?.config&&typeof r.config=="object"}function bd(r){if(r.shapes?.static&&r.shapes?.animated)return console.log("🔍 JSON config already in system format"),r;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!r.transform,type:ht(r.transform),distance:qe(r.transform),direction:ar(r.transform)});try{const e={...r};if(r.shapes&&typeof r.shapes=="object"){const n=[],s=[];if(r.shapes.trapezoid){const o=r.shapes.trapezoid;Array.isArray(o)?n.push(...o.map(i=>({...i,metadata:{...i.metadata,isStatic:!0}}))):typeof o=="object"&&n.push({...o,metadata:{...o.metadata,isStatic:!0}})}if(r.shapes.triangle){const o=r.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}})}(n.length===0||s.length===0)&&Object.entries(r.shapes).forEach(([o,i])=>{const a=o.toLowerCase();a.includes("static")||a.includes("original")||a.includes("trapezoid")?Array.isArray(i)?n.push(...i):i&&typeof i=="object"&&n.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:n,animated:s}}!e.base&&r.base&&(e.base=r.base),!e.height&&r.height&&(e.height=r.height),!e.unit&&r.unit&&(e.unit=r.unit);const t=ht(r.transform);return r.transform&&t==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:t,translation:r.transform.translation,distance:qe(r.transform),direction:ar(r.transform)}),r.transform.translation&&(e.transform={type:"translation",translation:r.transform.translation},console.log("✅ Set converted.transform with distance:",qe(r.transform)))):r.transform?console.log("⚠️ JSON has transform but not translation type:",ht(r.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&&r.boardConfig&&(e.boardConfig=r.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:ht(e.transform),distance:qe(e.transform),direction:ar(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),r}}function qe(r){if(!r)return"N/A";const e=Array.isArray(r)?r[0]:r;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function ar(r){if(!r)return;const e=Array.isArray(r)?r[0]:r;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function ht(r){return r&&(Array.isArray(r)?r[0]:r)?.type||"N/A"}function xd(r,e,t){if(r?.solve?.content){const n=r.solve.content.map(s=>{if(s.type==="geometryTransform"){if(yd(s))try{const i=bd(s.config),a=Zc(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",qe(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:ht(i.transform),distance:qe(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=t?.base||9,a=t?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),o=ts({base:i,height:a,unit:t?.baseUnit||t?.unit||"in",originX:t?.originX,originY:t?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",qe(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=ts({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",qe(o.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:ht(o.transform),direction:ar(o.transform),distance:qe(o.transform)}),{...s,metadata:{...s.metadata,config:o,source:"generated"}}}return s});return{...r,solve:{...r.solve,content:n}}}return r}const vd="4.0.0",_d="1.0.0",wd="mp-10506-0002-0002-G01-0001",Ad="锐角三角形面积练习",Rd="通过双旋转策略练习锐角三角形面积公式 A=½bh",Sd="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",Cd=1,Ed="g5",Td="三角形面积计算",Nd=1050602,$d="锐角三角形的面积",kd=105060201,Od=1002,jd="已知锐角三角形的底和高,求三角形面积",Md="s-105-06-0002",Id=1002,Fd=2,Pd=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Dd={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Ld={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}},Ud={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"}},Gd={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},zd={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"What is the area of the triangle?",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"}]}},Bd={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"}}]}}]},Vd={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²"]},qd="2026-01-20T20:34:00Z",Wd="2026-01-20T20:34:00Z",Hd={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"}},Yd={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right"}},Kd={schema_version:vd,config_version:_d,math_prob_id:wd,title:Ad,description:Rd,objective:Sd,difficulty:Cd,grade_id:Ed,unit_name:Td,unit_id:Nd,lesson_name:$d,lesson_id:kd,module_id:Od,skill_description:jd,skill_item_id:Md,skill_id:Id,score:Fd,knowledge_points:Pd,metadata:Dd,basic_info:Ld,geometry_shapes:Ud,layout:Gd,scenes:zd,explanation:Bd,answer_info:Vd,created_at:qd,updated_at:Wd,geometry_transform_configs:Hd,transform_definitions:Yd},Xd="mp-10506-0001-0001-G01-0001",Jd="平行四边形面积公式推导",Zd="通过割补变换演示理解平行四边形面积公式 A=bh",Qd="理解平行四边形面积公式 A=bh",ef=1,tf="g5",rf="多边形的面积",nf=1050601,sf="平行四边形的面积",of=105060101,af=1002,lf="已知平行四边形的底和高,求平行四边形面积",cf="s-105-06-0001",df=1001,ff=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],uf={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},mf={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}},hf={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},gf={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"}}}},pf={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:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},yf={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 平方英寸"}]},bf="2024-01-15T10:30:00Z",xf="2024-01-15T10:30:00Z",vf={math_prob_id:Xd,title:Jd,description:Zd,objective:Qd,difficulty:ef,grade_id:tf,unit_name:rf,unit_id:nf,lesson_name:sf,lesson_id:of,module_id:af,skill_description:lf,skill_item_id:cf,skill_id:df,knowledge_points:ff,metadata:uf,basic_info:mf,layout:hf,scenes:gf,explanation:pf,answer_info:yf,created_at:bf,updated_at:xf},_f={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function wf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
22
17
  函数 loadAcuteTriangleV2Data() 已弃用。
23
18
  组件库不再包含数据加载逻辑。
24
19
 
@@ -31,7 +26,7 @@ ${i.errors?.join(`
31
26
  ${new Error().stack?.split(`
32
27
  `).slice(2,6).join(`
33
28
  `)||"无法获取调用栈"}
34
- `);const r=ut(of,$f);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",r.data.id),r.data}async function Of(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
29
+ `);const r=ct(Kd,_f);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",r.data.id),r.data}async function Af(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
35
30
  函数 loadTriangleProblemData() 已弃用。
36
31
  组件库不再包含数据加载逻辑。
37
32
 
@@ -44,7 +39,7 @@ ${new Error().stack?.split(`
44
39
  ${new Error().stack?.split(`
45
40
  `).slice(2,6).join(`
46
41
  `)||"无法获取调用栈"}
47
- `),kf()}async function jf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
42
+ `),wf()}async function Rf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
48
43
  函数 loadParallelogramProblemData() 已弃用。
49
44
  组件库不再包含数据加载逻辑。
50
45
 
@@ -57,56 +52,56 @@ ${new Error().stack?.split(`
57
52
  ${new Error().stack?.split(`
58
53
  `).slice(2,6).join(`
59
54
  `)||"无法获取调用栈"}
60
- `);try{const r=Bs(Nf);return console.log("平行四边形数据加载成功 (传统适配器):",r.id),r}catch(r){return console.error("传统适配器失败:",r),Mf()}}function Mf(){return Bs({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const If=({className:r="",problemData:e})=>{const t=xn(),n=vn(),o=_n(),s=wn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:d,setProblemData:l}=An(),[c,u]=b.useState(!0),[y,m]=b.useState(null),[h,g]=b.useState(null),p=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(p){u(!1),m(null),g(null);return}(async()=>{try{u(!0),m(null);const S=await jf();g(S)}catch(S){const E=S instanceof Error?S.message:"数据加载失败";m(E),console.error("页面数据加载失败:",S)}finally{u(!1)}})()},[p]);const x=b.useMemo(()=>p||h,[p,h]);return b.useEffect(()=>{x&&l(x)},[x,l]),c?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),f.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):y?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),f.jsx("div",{className:"text-lg text-red-600 mb-4",children:y}),f.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(St,{problemData:x,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),t==="explanation"&&f.jsx(Kt,{problemData:x,userAnswer:n,onNextQuestion:d}),t==="success"&&f.jsx(Ct,{problemData:x,onNextQuestion:d})]})]}):f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),f.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},Ff=({className:r="",problemData:e})=>{const t=xn(),n=vn(),o=_n(),s=wn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:d,setProblemData:l}=An(),[c,u]=b.useState(!0),[y,m]=b.useState(null),[h,g]=b.useState(null),p=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(p){u(!1),m(null),g(null);return}(async()=>{try{u(!0),m(null);const S=await Of();g(S)}catch(S){const E=S instanceof Error?S.message:"数据加载失败";m(E),console.error("页面数据加载失败:",S)}finally{u(!1)}})()},[p]);const x=b.useMemo(()=>p||h,[p,h]);return b.useEffect(()=>{x&&l(x)},[x,l]),c?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),f.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):y?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),f.jsx("div",{className:"text-lg text-red-600 mb-4",children:y}),f.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(St,{problemData:x,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),t==="explanation"&&f.jsx(Kt,{problemData:x,userAnswer:n,onNextQuestion:d}),t==="success"&&f.jsx(Ct,{problemData:x,onNextQuestion:d})]})]}):f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),f.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Vs=b.createContext(void 0),Pf=()=>{const r=b.useContext(Vs);if(!r)throw new Error("useMathCardContext must be used within a MathCard component");return r},Ws=(r,e,t)=>r.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,t.join(", ")),Df=r=>r.type==="formula"?b.createElement(qt,{key:r.content,parts:[r.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):r.type==="image"?b.createElement("img",{src:r.content,alt:"content",className:"image",key:r.content}):b.createElement("span",{key:r.content},r.content),En=r=>r.map((e,t)=>b.createElement("div",{className:"content-block",key:t},Df(e))),Lf=r=>{const e=[];let t=0;const n=/\$\$?[^$]+\$\$?/g;let o;for(;(o=n.exec(r))!==null;){const s=o.index,i=o.index+o[0].length;if(s>t){const l=r.substring(t,s);l.trim()&&e.push({type:"text",content:l})}const d=o[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:d}),t=i}if(t<r.length){const s=r.substring(t);s.trim()&&e.push({type:"text",content:s})}return e},Uf=(r,e,t)=>{const n=Ws(r,e,t),o=Lf(n);return En(o)},Gf=r=>{const{type:e,content:t,style:n={}}=r,o={marginBottom:"8px",lineHeight:"1.6",...n};switch(e){case"instruction":return b.createElement("div",{key:r.id,style:{...o,fontWeight:"bold",color:"#4a6cf7"}},t);case"formula":const s=t.includes("\\\\")||t.includes("\\downarrow")||t.includes("\\quad");return b.createElement(qt,{key:r.id,parts:[t],children:null,displayMode:s,fontSize:"1.1em",color:"#333333"});case"conclusion":return b.createElement("div",{key:r.id,style:{...o,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},t);case"image":return b.createElement("div",{key:r.id,style:o},b.createElement("img",{src:t,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return b.createElement("div",{key:r.id,style:o},b.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},t));default:return b.createElement("div",{key:r.id,style:o},t)}},zf=(r,e,t)=>{const{type:n,content:o,style:s={}}=r,i={marginBottom:"8px",lineHeight:"1.6",...s};switch(n){case"instruction":return b.createElement("div",{key:r.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},o);case"formula":const a=o.includes("\\\\")||o.includes("\\downarrow")||o.includes("\\quad");return b.createElement(qt,{key:r.id,parts:[o],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const d=Ws(o,t,e);return b.createElement("div",{key:r.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},d);default:return b.createElement("div",{key:r.id,style:i},o)}},Bf=r=>r.map(Gf),Vf=(r,e,t)=>r.map(n=>zf(n,e,t)),qs=({scene:r,position:e="header",size:t="medium",color:n,bgColor:o,hidden:s=!1})=>{if(s)return null;const i={question:"题目作答",solve:"官方解析",review:"用户复习"},a=()=>{const d={display:"flex",alignItems:"center",justifyContent:"center",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px"},l={question:"#f97316",solve:"#4a6cf7",review:"#4ade80"};return d.background=o||l[r],d.color=n||"#ffffff",e==="header"?d.borderBottom="1px solid #e0e0e0":e==="sidebar"&&(d.borderRight="1px solid #e0e0e0",d.writingMode="vertical-rl",d.textOrientation="mixed"),Object.assign(d,{small:{fontSize:"12px",padding:"8px 12px"},medium:{fontSize:"14px",padding:"12px 16px"},large:{fontSize:"16px",padding:"16px 20px"}}[t]),d};return f.jsx("div",{style:a(),children:i[r]})},Ys=({question:r})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return f.jsx("div",{style:e,children:En(r)})},Hs=({problemType:r,options:e,value:t=[],onChange:n,placeholder:o="请输入答案"})=>{const s={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"},d=u=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:u?"#f97316":"transparent",color:u?"#ffffff":"inherit",borderColor:u?"#f97316":"#e0e0e0"}),l=u=>{if(n)if(r==="multiple-choice"){const y=t.includes(u)?t.filter(m=>m!==u):[...t,u];n(y)}else n([u])},c=u=>{n&&n([u.target.value])};return r==="multiple-choice"&&e?f.jsx("div",{style:s,children:f.jsx("div",{style:a,children:e.map(u=>f.jsx("div",{style:d(t.includes(u.id)),onClick:()=>l(u.id),children:En(u.content)},u.id))})}):f.jsx("div",{style:s,children:f.jsx("input",{type:"text",style:i,placeholder:o,value:t[0]||"",onChange:c})})},mr=({onClick:r,children:e,disabled:t=!1,loading:n=!1})=>{const o={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:t?"not-allowed":"pointer",opacity:t?.6:1};return f.jsx("button",{style:o,onClick:r,disabled:t||n,children:n?"提交中...":e})},Ks=({steps:r,title:e="解题步骤"})=>{const t={padding:"20px",borderTop:"1px solid #e0e0e0"},n={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4a6cf7"},o={display:"flex",flexDirection:"column",gap:"12px"},s={padding:"12px",borderLeft:"3px solid #4a6cf7",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return f.jsxs("div",{style:t,children:[f.jsx("div",{style:n,children:e}),f.jsx("div",{style:o,children:Bf(r).map((i,a)=>f.jsx("div",{style:s,children:i},r[a].id))})]})},Xs=({reviewContent:r,userAnswer:e,correctAnswer:t})=>{const n={padding:"20px",borderTop:"1px solid #e0e0e0"},o={fontSize:"18px",fontWeight:600,marginBottom:"16px",color:"#4ade80"},s={lineHeight:"1.6"},i={padding:"12px",background:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:"4px",marginBottom:"16px"},a={display:"flex",flexDirection:"column",gap:"12px"},d={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return f.jsxs("div",{style:n,children:[f.jsx("div",{style:o,children:"复习内容"}),f.jsxs("div",{style:s,children:[r.reviewTemplate&&f.jsx("div",{style:i,children:Uf(r.reviewTemplate,t,e)}),r.reviewExplanation&&f.jsx("div",{style:a,children:Vf(r.reviewExplanation,e,t).map((l,c)=>f.jsx("div",{style:d,children:l},r.reviewExplanation[c].id))})]})]})},Js=({type:r="skeleton"})=>{const e={padding:"20px"},t={height:"16px",background:"linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",backgroundSize:"200% 100%",animation:"loading 1.5s infinite",borderRadius:"4px",marginBottom:"12px"},n={display:"flex",justifyContent:"center",alignItems:"center",padding:"24px"},o={width:"40px",height:"40px",border:"4px solid #f0f0f0",borderTop:"4px solid #f97316",borderRadius:"50%",animation:"spin 1s linear infinite"};return r==="spinner"?f.jsx("div",{style:n,children:f.jsx("div",{style:o})}):f.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[f.jsx("div",{style:{...t,width:"80%"}}),f.jsx("div",{style:{...t,width:"60%"}}),f.jsx("div",{style:{...t,width:"70%"}})]})},xr=({error:r,onRetry:e})=>{const t={padding:"24px",textAlign:"center",color:"#ef4444"},n={marginBottom:"16px",fontSize:"16px"},o={padding:"12px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},s=typeof r=="string"?r:r.message;return f.jsxs("div",{style:t,children:[f.jsx("div",{style:n,children:s}),e&&f.jsx("button",{style:o,onClick:()=>e(r),children:"重试"})]})},Wf=({orientation:r="horizontal",size:e="medium"})=>{const t={background:"#e0e0e0"},n={small:"12px",medium:"16px",large:"20px"};return r==="horizontal"?(t.height="1px",t.width="100%",t.margin=`${n[e]} 0`):(t.width="1px",t.height="100%",t.margin=`0 ${n[e]}`),f.jsx("div",{style:t})},qf=({onSubmit:r,onNext:e,onRetry:t,onAnswerChange:n,value:o})=>{const{problemData:s,scene:i,submissionResult:a,config:d}=Pf();if(!s)return f.jsx(xr,{error:"No problem data provided"});const l=()=>{r&&r()},c=()=>{e&&e(s.problemId)},u=()=>{t&&t(s.problemId)},y=g=>{n&&n(g,s.problemType)},m={background:d?.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:d?.theme==="dark"?"#ffffff":"#333333",width:"100%",maxWidth:"800px"},h={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return f.jsxs("div",{style:m,"data-testid":"math-card","data-theme":d?.theme,children:[d?.showBanner!==!1&&f.jsx(qs,{scene:i,position:d?.bannerPosition,size:d?.bannerSize,color:d?.bannerCustomStyle?.color,bgColor:d?.bannerCustomStyle?.bgColor}),f.jsx(Ys,{question:s.question,problemType:s.problemType}),i==="question"&&f.jsxs(f.Fragment,{children:[f.jsx(Hs,{problemType:s.problemType,options:s.answer.options,value:o,onChange:y,placeholder:d?.inputPlaceholder}),f.jsx("div",{style:h,children:f.jsx(mr,{onClick:l,disabled:!r,children:d?.submitButtonText||"提交答案"})})]}),i==="solve"&&s.explanation&&f.jsx(Ks,{steps:s.explanation,title:"官方解析"}),i==="review"&&a&&s.reviewContent&&f.jsx(Xs,{reviewContent:s.reviewContent,userAnswer:a.userAnswer,correctAnswer:s.answer.correctAnswer}),(i==="solve"||i==="review")&&f.jsxs("div",{style:h,children:[e&&f.jsx(mr,{onClick:c,children:d?.nextButtonText||"下一题"}),t&&f.jsx(mr,{onClick:u,children:d?.retryButtonText||"重新作答"})]})]})},Ke=({problemData:r,scene:e,submissionResult:t,loading:n,error:o,config:s,children:i,onSubmit:a,onNext:d,onRetry:l,onErrorRetry:c,onAnswerChange:u,onHintToggle:y,value:m})=>{if(n)return f.jsx(Js,{type:"skeleton"});if(o)return f.jsx(xr,{error:o,onRetry:c});if(!r)return f.jsx(xr,{error:"No problem data provided"});const h={problemData:r,scene:e,submissionResult:t,config:s,value:m};return f.jsx(Vs.Provider,{value:h,children:i||f.jsx(qf,{onSubmit:a,onNext:d,onRetry:l,onAnswerChange:u,onHintToggle:y,value:m})})};Ke.Banner=qs;Ke.Question=Ys;Ke.AnswerInput=Hs;Ke.SubmitButton=mr;Ke.Explanation=Ks;Ke.ReviewContent=Xs;Ke.LoadingState=Js;Ke.ErrorState=xr;Ke.Divider=Wf;function Yf(r){if(r.sheet)return r.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===r)return document.styleSheets[e]}function Hf(r){var e=document.createElement("style");return e.setAttribute("data-emotion",r.key),r.nonce!==void 0&&e.setAttribute("nonce",r.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var Kf=(function(){function r(t){var n=this;this._insertTag=function(o){var s;n.tags.length===0?n.insertionPoint?s=n.insertionPoint.nextSibling:n.prepend?s=n.container.firstChild:s=n.before:s=n.tags[n.tags.length-1].nextSibling,n.container.insertBefore(o,s),n.tags.push(o)},this.isSpeedy=t.speedy===void 0?!0:t.speedy,this.tags=[],this.ctr=0,this.nonce=t.nonce,this.key=t.key,this.container=t.container,this.prepend=t.prepend,this.insertionPoint=t.insertionPoint,this.before=null}var e=r.prototype;return e.hydrate=function(n){n.forEach(this._insertTag)},e.insert=function(n){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(Hf(this));var o=this.tags[this.tags.length-1];if(this.isSpeedy){var s=Yf(o);try{s.insertRule(n,s.cssRules.length)}catch{}}else o.appendChild(document.createTextNode(n));this.ctr++},e.flush=function(){this.tags.forEach(function(n){var o;return(o=n.parentNode)==null?void 0:o.removeChild(n)}),this.tags=[],this.ctr=0},r})(),_e="-ms-",vr="-moz-",K="-webkit-",Zs="comm",Tn="rule",Nn="decl",Xf="@import",Qs="@keyframes",Jf="@layer",Zf=Math.abs,Nr=String.fromCharCode,Qf=Object.assign;function eu(r,e){return be(r,0)^45?(((e<<2^be(r,0))<<2^be(r,1))<<2^be(r,2))<<2^be(r,3):0}function ei(r){return r.trim()}function tu(r,e){return(r=e.exec(r))?r[0]:r}function X(r,e,t){return r.replace(e,t)}function tn(r,e){return r.indexOf(e)}function be(r,e){return r.charCodeAt(e)|0}function Pt(r,e,t){return r.slice(e,t)}function We(r){return r.length}function $n(r){return r.length}function sr(r,e){return e.push(r),r}function ru(r,e){return r.map(e).join("")}var $r=1,At=1,ti=0,Te=0,he=0,Et="";function kr(r,e,t,n,o,s,i){return{value:r,root:e,parent:t,type:n,props:o,children:s,line:$r,column:At,length:i,return:""}}function jt(r,e){return Qf(kr("",null,null,"",null,null,0),r,{length:-r.length},e)}function nu(){return he}function ou(){return he=Te>0?be(Et,--Te):0,At--,he===10&&(At=1,$r--),he}function Oe(){return he=Te<ti?be(Et,Te++):0,At++,he===10&&(At=1,$r++),he}function He(){return be(Et,Te)}function hr(){return Te}function Jt(r,e){return Pt(Et,r,e)}function Dt(r){switch(r){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 ri(r){return $r=At=1,ti=We(Et=r),Te=0,[]}function ni(r){return Et="",r}function gr(r){return ei(Jt(Te-1,rn(r===91?r+2:r===40?r+1:r)))}function su(r){for(;(he=He())&&he<33;)Oe();return Dt(r)>2||Dt(he)>3?"":" "}function iu(r,e){for(;--e&&Oe()&&!(he<48||he>102||he>57&&he<65||he>70&&he<97););return Jt(r,hr()+(e<6&&He()==32&&Oe()==32))}function rn(r){for(;Oe();)switch(he){case r:return Te;case 34:case 39:r!==34&&r!==39&&rn(he);break;case 40:r===41&&rn(r);break;case 92:Oe();break}return Te}function au(r,e){for(;Oe()&&r+he!==57;)if(r+he===84&&He()===47)break;return"/*"+Jt(e,Te-1)+"*"+Nr(r===47?r:Oe())}function lu(r){for(;!Dt(He());)Oe();return Jt(r,Te)}function cu(r){return ni(pr("",null,null,null,[""],r=ri(r),0,[0],r))}function pr(r,e,t,n,o,s,i,a,d){for(var l=0,c=0,u=i,y=0,m=0,h=0,g=1,p=1,x=1,C=0,S="",E=o,_=s,j=n,w=S;p;)switch(h=C,C=Oe()){case 40:if(h!=108&&be(w,u-1)==58){tn(w+=X(gr(C),"&","&\f"),"&\f")!=-1&&(x=-1);break}case 34:case 39:case 91:w+=gr(C);break;case 9:case 10:case 13:case 32:w+=su(h);break;case 92:w+=iu(hr()-1,7);continue;case 47:switch(He()){case 42:case 47:sr(du(au(Oe(),hr()),e,t),d);break;default:w+="/"}break;case 123*g:a[l++]=We(w)*x;case 125*g:case 59:case 0:switch(C){case 0:case 125:p=0;case 59+c:x==-1&&(w=X(w,/\f/g,"")),m>0&&We(w)-u&&sr(m>32?co(w+";",n,t,u-1):co(X(w," ","")+";",n,t,u-2),d);break;case 59:w+=";";default:if(sr(j=lo(w,e,t,l,c,o,a,S,E=[],_=[],u),s),C===123)if(c===0)pr(w,e,j,j,E,s,u,a,_);else switch(y===99&&be(w,3)===110?100:y){case 100:case 108:case 109:case 115:pr(r,j,j,n&&sr(lo(r,j,j,0,0,o,a,S,o,E=[],u),_),o,_,u,a,n?E:_);break;default:pr(w,j,j,j,[""],_,0,a,_)}}l=c=m=0,g=x=1,S=w="",u=i;break;case 58:u=1+We(w),m=h;default:if(g<1){if(C==123)--g;else if(C==125&&g++==0&&ou()==125)continue}switch(w+=Nr(C),C*g){case 38:x=c>0?1:(w+="\f",-1);break;case 44:a[l++]=(We(w)-1)*x,x=1;break;case 64:He()===45&&(w+=gr(Oe())),y=He(),c=u=We(S=w+=lu(hr())),C++;break;case 45:h===45&&We(w)==2&&(g=0)}}return s}function lo(r,e,t,n,o,s,i,a,d,l,c){for(var u=o-1,y=o===0?s:[""],m=$n(y),h=0,g=0,p=0;h<n;++h)for(var x=0,C=Pt(r,u+1,u=Zf(g=i[h])),S=r;x<m;++x)(S=ei(g>0?y[x]+" "+C:X(C,/&\f/g,y[x])))&&(d[p++]=S);return kr(r,e,t,o===0?Tn:a,d,l,c)}function du(r,e,t){return kr(r,e,t,Zs,Nr(nu()),Pt(r,2,-2),0)}function co(r,e,t,n){return kr(r,e,t,Nn,Pt(r,0,n),Pt(r,n+1,-1),n)}function bt(r,e){for(var t="",n=$n(r),o=0;o<n;o++)t+=e(r[o],o,r,e)||"";return t}function fu(r,e,t,n){switch(r.type){case Jf:if(r.children.length)break;case Xf:case Nn:return r.return=r.return||r.value;case Zs:return"";case Qs:return r.return=r.value+"{"+bt(r.children,n)+"}";case Tn:r.value=r.props.join(",")}return We(t=bt(r.children,n))?r.return=r.value+"{"+t+"}":""}function uu(r){var e=$n(r);return function(t,n,o,s){for(var i="",a=0;a<e;a++)i+=r[a](t,n,o,s)||"";return i}}function mu(r){return function(e){e.root||(e=e.return)&&r(e)}}function hu(r){var e=Object.create(null);return function(t){return e[t]===void 0&&(e[t]=r(t)),e[t]}}var gu=function(e,t,n){for(var o=0,s=0;o=s,s=He(),o===38&&s===12&&(t[n]=1),!Dt(s);)Oe();return Jt(e,Te)},pu=function(e,t){var n=-1,o=44;do switch(Dt(o)){case 0:o===38&&He()===12&&(t[n]=1),e[n]+=gu(Te-1,t,n);break;case 2:e[n]+=gr(o);break;case 4:if(o===44){e[++n]=He()===58?"&\f":"",t[n]=e[n].length;break}default:e[n]+=Nr(o)}while(o=Oe());return e},yu=function(e,t){return ni(pu(ri(e),t))},fo=new WeakMap,bu=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var t=e.value,n=e.parent,o=e.column===n.column&&e.line===n.line;n.type!=="rule";)if(n=n.parent,!n)return;if(!(e.props.length===1&&t.charCodeAt(0)!==58&&!fo.get(n))&&!o){fo.set(e,!0);for(var s=[],i=yu(t,s),a=n.props,d=0,l=0;d<i.length;d++)for(var c=0;c<a.length;c++,l++)e.props[l]=s[d]?i[d].replace(/&\f/g,a[c]):a[c]+" "+i[d]}}},xu=function(e){if(e.type==="decl"){var t=e.value;t.charCodeAt(0)===108&&t.charCodeAt(2)===98&&(e.return="",e.value="")}};function oi(r,e){switch(eu(r,e)){case 5103:return K+"print-"+r+r;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 K+r+r;case 5349:case 4246:case 4810:case 6968:case 2756:return K+r+vr+r+_e+r+r;case 6828:case 4268:return K+r+_e+r+r;case 6165:return K+r+_e+"flex-"+r+r;case 5187:return K+r+X(r,/(\w+).+(:[^]+)/,K+"box-$1$2"+_e+"flex-$1$2")+r;case 5443:return K+r+_e+"flex-item-"+X(r,/flex-|-self/,"")+r;case 4675:return K+r+_e+"flex-line-pack"+X(r,/align-content|flex-|-self/,"")+r;case 5548:return K+r+_e+X(r,"shrink","negative")+r;case 5292:return K+r+_e+X(r,"basis","preferred-size")+r;case 6060:return K+"box-"+X(r,"-grow","")+K+r+_e+X(r,"grow","positive")+r;case 4554:return K+X(r,/([^-])(transform)/g,"$1"+K+"$2")+r;case 6187:return X(X(X(r,/(zoom-|grab)/,K+"$1"),/(image-set)/,K+"$1"),r,"")+r;case 5495:case 3959:return X(r,/(image-set\([^]*)/,K+"$1$`$1");case 4968:return X(X(r,/(.+:)(flex-)?(.*)/,K+"box-pack:$3"+_e+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+K+r+r;case 4095:case 3583:case 4068:case 2532:return X(r,/(.+)-inline(.+)/,K+"$1$2")+r;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(We(r)-1-e>6)switch(be(r,e+1)){case 109:if(be(r,e+4)!==45)break;case 102:return X(r,/(.+:)(.+)-([^]+)/,"$1"+K+"$2-$3$1"+vr+(be(r,e+3)==108?"$3":"$2-$3"))+r;case 115:return~tn(r,"stretch")?oi(X(r,"stretch","fill-available"),e)+r:r}break;case 4949:if(be(r,e+1)!==115)break;case 6444:switch(be(r,We(r)-3-(~tn(r,"!important")&&10))){case 107:return X(r,":",":"+K)+r;case 101:return X(r,/(.+:)([^;!]+)(;|!.+)?/,"$1"+K+(be(r,14)===45?"inline-":"")+"box$3$1"+K+"$2$3$1"+_e+"$2box$3")+r}break;case 5936:switch(be(r,e+11)){case 114:return K+r+_e+X(r,/[svh]\w+-[tblr]{2}/,"tb")+r;case 108:return K+r+_e+X(r,/[svh]\w+-[tblr]{2}/,"tb-rl")+r;case 45:return K+r+_e+X(r,/[svh]\w+-[tblr]{2}/,"lr")+r}return K+r+_e+r+r}return r}var vu=function(e,t,n,o){if(e.length>-1&&!e.return)switch(e.type){case Nn:e.return=oi(e.value,e.length);break;case Qs:return bt([jt(e,{value:X(e.value,"@","@"+K)})],o);case Tn:if(e.length)return ru(e.props,function(s){switch(tu(s,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return bt([jt(e,{props:[X(s,/:(read-\w+)/,":"+vr+"$1")]})],o);case"::placeholder":return bt([jt(e,{props:[X(s,/:(plac\w+)/,":"+K+"input-$1")]}),jt(e,{props:[X(s,/:(plac\w+)/,":"+vr+"$1")]}),jt(e,{props:[X(s,/:(plac\w+)/,_e+"input-$1")]})],o)}return""})}},_u=[vu],wu=function(e){var t=e.key;if(t==="css"){var n=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(n,function(g){var p=g.getAttribute("data-emotion");p.indexOf(" ")!==-1&&(document.head.appendChild(g),g.setAttribute("data-s",""))})}var o=e.stylisPlugins||_u,s={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+t+' "]'),function(g){for(var p=g.getAttribute("data-emotion").split(" "),x=1;x<p.length;x++)s[p[x]]=!0;a.push(g)});var d,l=[bu,xu];{var c,u=[fu,mu(function(g){c.insert(g)})],y=uu(l.concat(o,u)),m=function(p){return bt(cu(p),y)};d=function(p,x,C,S){c=C,m(p?p+"{"+x.styles+"}":x.styles),S&&(h.inserted[x.name]=!0)}}var h={key:t,sheet:new Kf({key:t,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:s,registered:{},insert:d};return h.sheet.hydrate(a),h},ir={exports:{}},Z={};var uo;function Au(){if(uo)return Z;uo=1;var r=typeof Symbol=="function"&&Symbol.for,e=r?Symbol.for("react.element"):60103,t=r?Symbol.for("react.portal"):60106,n=r?Symbol.for("react.fragment"):60107,o=r?Symbol.for("react.strict_mode"):60108,s=r?Symbol.for("react.profiler"):60114,i=r?Symbol.for("react.provider"):60109,a=r?Symbol.for("react.context"):60110,d=r?Symbol.for("react.async_mode"):60111,l=r?Symbol.for("react.concurrent_mode"):60111,c=r?Symbol.for("react.forward_ref"):60112,u=r?Symbol.for("react.suspense"):60113,y=r?Symbol.for("react.suspense_list"):60120,m=r?Symbol.for("react.memo"):60115,h=r?Symbol.for("react.lazy"):60116,g=r?Symbol.for("react.block"):60121,p=r?Symbol.for("react.fundamental"):60117,x=r?Symbol.for("react.responder"):60118,C=r?Symbol.for("react.scope"):60119;function S(_){if(typeof _=="object"&&_!==null){var j=_.$$typeof;switch(j){case e:switch(_=_.type,_){case d:case l:case n:case s:case o:case u:return _;default:switch(_=_&&_.$$typeof,_){case a:case c:case h:case m:case i:return _;default:return j}}case t:return j}}}function E(_){return S(_)===l}return Z.AsyncMode=d,Z.ConcurrentMode=l,Z.ContextConsumer=a,Z.ContextProvider=i,Z.Element=e,Z.ForwardRef=c,Z.Fragment=n,Z.Lazy=h,Z.Memo=m,Z.Portal=t,Z.Profiler=s,Z.StrictMode=o,Z.Suspense=u,Z.isAsyncMode=function(_){return E(_)||S(_)===d},Z.isConcurrentMode=E,Z.isContextConsumer=function(_){return S(_)===a},Z.isContextProvider=function(_){return S(_)===i},Z.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},Z.isForwardRef=function(_){return S(_)===c},Z.isFragment=function(_){return S(_)===n},Z.isLazy=function(_){return S(_)===h},Z.isMemo=function(_){return S(_)===m},Z.isPortal=function(_){return S(_)===t},Z.isProfiler=function(_){return S(_)===s},Z.isStrictMode=function(_){return S(_)===o},Z.isSuspense=function(_){return S(_)===u},Z.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===n||_===l||_===s||_===o||_===u||_===y||typeof _=="object"&&_!==null&&(_.$$typeof===h||_.$$typeof===m||_.$$typeof===i||_.$$typeof===a||_.$$typeof===c||_.$$typeof===p||_.$$typeof===x||_.$$typeof===C||_.$$typeof===g)},Z.typeOf=S,Z}var Q={};var mo;function Ru(){return mo||(mo=1,process.env.NODE_ENV!=="production"&&(function(){var r=typeof Symbol=="function"&&Symbol.for,e=r?Symbol.for("react.element"):60103,t=r?Symbol.for("react.portal"):60106,n=r?Symbol.for("react.fragment"):60107,o=r?Symbol.for("react.strict_mode"):60108,s=r?Symbol.for("react.profiler"):60114,i=r?Symbol.for("react.provider"):60109,a=r?Symbol.for("react.context"):60110,d=r?Symbol.for("react.async_mode"):60111,l=r?Symbol.for("react.concurrent_mode"):60111,c=r?Symbol.for("react.forward_ref"):60112,u=r?Symbol.for("react.suspense"):60113,y=r?Symbol.for("react.suspense_list"):60120,m=r?Symbol.for("react.memo"):60115,h=r?Symbol.for("react.lazy"):60116,g=r?Symbol.for("react.block"):60121,p=r?Symbol.for("react.fundamental"):60117,x=r?Symbol.for("react.responder"):60118,C=r?Symbol.for("react.scope"):60119;function S(R){return typeof R=="string"||typeof R=="function"||R===n||R===l||R===s||R===o||R===u||R===y||typeof R=="object"&&R!==null&&(R.$$typeof===h||R.$$typeof===m||R.$$typeof===i||R.$$typeof===a||R.$$typeof===c||R.$$typeof===p||R.$$typeof===x||R.$$typeof===C||R.$$typeof===g)}function E(R){if(typeof R=="object"&&R!==null){var J=R.$$typeof;switch(J){case e:var re=R.type;switch(re){case d:case l:case n:case s:case o:case u:return re;default:var D=re&&re.$$typeof;switch(D){case a:case c:case h:case m:case i:return D;default:return J}}case t:return J}}}var _=d,j=l,w=a,P=i,$=e,O=c,Y=n,q=h,I=m,G=t,H=s,M=o,ge=u,se=!1;function W(R){return se||(se=!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.")),fe(R)||E(R)===d}function fe(R){return E(R)===l}function A(R){return E(R)===a}function F(R){return E(R)===i}function V(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function te(R){return E(R)===c}function je(R){return E(R)===n}function Le(R){return E(R)===h}function oe(R){return E(R)===m}function Ue(R){return E(R)===t}function mt(R){return E(R)===s}function k(R){return E(R)===o}function T(R){return E(R)===u}Q.AsyncMode=_,Q.ConcurrentMode=j,Q.ContextConsumer=w,Q.ContextProvider=P,Q.Element=$,Q.ForwardRef=O,Q.Fragment=Y,Q.Lazy=q,Q.Memo=I,Q.Portal=G,Q.Profiler=H,Q.StrictMode=M,Q.Suspense=ge,Q.isAsyncMode=W,Q.isConcurrentMode=fe,Q.isContextConsumer=A,Q.isContextProvider=F,Q.isElement=V,Q.isForwardRef=te,Q.isFragment=je,Q.isLazy=Le,Q.isMemo=oe,Q.isPortal=Ue,Q.isProfiler=mt,Q.isStrictMode=k,Q.isSuspense=T,Q.isValidElementType=S,Q.typeOf=E})()),Q}var ho;function Su(){return ho||(ho=1,process.env.NODE_ENV==="production"?ir.exports=Au():ir.exports=Ru()),ir.exports}var zr,go;function Cu(){if(go)return zr;go=1;var r=Su(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},t={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},n={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},o={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},s={};s[r.ForwardRef]=n,s[r.Memo]=o;function i(h){return r.isMemo(h)?o:s[h.$$typeof]||e}var a=Object.defineProperty,d=Object.getOwnPropertyNames,l=Object.getOwnPropertySymbols,c=Object.getOwnPropertyDescriptor,u=Object.getPrototypeOf,y=Object.prototype;function m(h,g,p){if(typeof g!="string"){if(y){var x=u(g);x&&x!==y&&m(h,x,p)}var C=d(g);l&&(C=C.concat(l(g)));for(var S=i(h),E=i(g),_=0;_<C.length;++_){var j=C[_];if(!t[j]&&!(p&&p[j])&&!(E&&E[j])&&!(S&&S[j])){var w=c(g,j);try{a(h,j,w)}catch{}}}}return h}return zr=m,zr}Cu();var Eu=!0;function Tu(r,e,t){var n="";return t.split(" ").forEach(function(o){r[o]!==void 0?e.push(r[o]+";"):o&&(n+=o+" ")}),n}var si=function(e,t,n){var o=e.key+"-"+t.name;(n===!1||Eu===!1)&&e.registered[o]===void 0&&(e.registered[o]=t.styles)},Nu=function(e,t,n){si(e,t,n);var o=e.key+"-"+t.name;if(e.inserted[t.name]===void 0){var s=t;do e.insert(t===s?"."+o:"",s,e.sheet,!0),s=s.next;while(s!==void 0)}};function $u(r){for(var e=0,t,n=0,o=r.length;o>=4;++n,o-=4)t=r.charCodeAt(n)&255|(r.charCodeAt(++n)&255)<<8|(r.charCodeAt(++n)&255)<<16|(r.charCodeAt(++n)&255)<<24,t=(t&65535)*1540483477+((t>>>16)*59797<<16),t^=t>>>24,e=(t&65535)*1540483477+((t>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(o){case 3:e^=(r.charCodeAt(n+2)&255)<<16;case 2:e^=(r.charCodeAt(n+1)&255)<<8;case 1:e^=r.charCodeAt(n)&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 ku={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},Ou=/[A-Z]|^ms/g,ju=/_EMO_([^_]+?)_([^]*?)_EMO_/g,ii=function(e){return e.charCodeAt(1)===45},po=function(e){return e!=null&&typeof e!="boolean"},Br=hu(function(r){return ii(r)?r:r.replace(Ou,"-$&").toLowerCase()}),yo=function(e,t){switch(e){case"animation":case"animationName":if(typeof t=="string")return t.replace(ju,function(n,o,s){return qe={name:o,styles:s,next:qe},o})}return ku[e]!==1&&!ii(e)&&typeof t=="number"&&t!==0?t+"px":t};function Lt(r,e,t){if(t==null)return"";var n=t;if(n.__emotion_styles!==void 0)return n;switch(typeof t){case"boolean":return"";case"object":{var o=t;if(o.anim===1)return qe={name:o.name,styles:o.styles,next:qe},o.name;var s=t;if(s.styles!==void 0){var i=s.next;if(i!==void 0)for(;i!==void 0;)qe={name:i.name,styles:i.styles,next:qe},i=i.next;var a=s.styles+";";return a}return Mu(r,e,t)}case"function":{if(r!==void 0){var d=qe,l=t(r);return qe=d,Lt(r,e,l)}break}}var c=t;return c}function Mu(r,e,t){var n="";if(Array.isArray(t))for(var o=0;o<t.length;o++)n+=Lt(r,e,t[o])+";";else for(var s in t){var i=t[s];if(typeof i!="object"){var a=i;po(a)&&(n+=Br(s)+":"+yo(s,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var d=0;d<i.length;d++)po(i[d])&&(n+=Br(s)+":"+yo(s,i[d])+";");else{var l=Lt(r,e,i);switch(s){case"animation":case"animationName":{n+=Br(s)+":"+l+";";break}default:n+=s+"{"+l+"}"}}}return n}var bo=/label:\s*([^\s;{]+)\s*(;|$)/g,qe;function ai(r,e,t){if(r.length===1&&typeof r[0]=="object"&&r[0]!==null&&r[0].styles!==void 0)return r[0];var n=!0,o="";qe=void 0;var s=r[0];if(s==null||s.raw===void 0)n=!1,o+=Lt(t,e,s);else{var i=s;o+=i[0]}for(var a=1;a<r.length;a++)if(o+=Lt(t,e,r[a]),n){var d=s;o+=d[a]}bo.lastIndex=0;for(var l="",c;(c=bo.exec(o))!==null;)l+="-"+c[1];var u=$u(o)+l;return{name:u,styles:o,next:qe}}var Iu=function(e){return e()},Fu=Fe.useInsertionEffect?Fe.useInsertionEffect:!1,Pu=Fu||Iu,li=Fe.createContext(typeof HTMLElement<"u"?wu({key:"css"}):null);li.Provider;var Du=function(e){return b.forwardRef(function(t,n){var o=b.useContext(li);return e(t,o,n)})},Lu=Fe.createContext({}),kn={}.hasOwnProperty,nn="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",Uu=function(e,t){var n={};for(var o in t)kn.call(t,o)&&(n[o]=t[o]);return n[nn]=e,n},Gu=function(e){var t=e.cache,n=e.serialized,o=e.isStringTag;return si(t,n,o),Pu(function(){return Nu(t,n,o)}),null},zu=Du(function(r,e,t){var n=r.css;typeof n=="string"&&e.registered[n]!==void 0&&(n=e.registered[n]);var o=r[nn],s=[n],i="";typeof r.className=="string"?i=Tu(e.registered,s,r.className):r.className!=null&&(i=r.className+" ");var a=ai(s,void 0,Fe.useContext(Lu));i+=e.key+"-"+a.name;var d={};for(var l in r)kn.call(r,l)&&l!=="css"&&l!==nn&&(d[l]=r[l]);return d.className=i,t&&(d.ref=t),Fe.createElement(Fe.Fragment,null,Fe.createElement(Gu,{cache:e,serialized:a,isStringTag:typeof o=="string"}),Fe.createElement(o,d))}),Bu=zu,xo=function(e,t){var n=arguments;if(t==null||!kn.call(t,"css"))return Fe.createElement.apply(void 0,n);var o=n.length,s=new Array(o);s[0]=Bu,s[1]=Uu(e,t);for(var i=2;i<o;i++)s[i]=n[i];return Fe.createElement.apply(null,s)};(function(r){var e;e||(e=r.JSX||(r.JSX={}))})(xo||(xo={}));function ae(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return ai(e)}const N={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)"}};ae`
61
- background: ${N.colors.background.card};
62
- border-radius: ${N.borderRadius.card};
63
- box-shadow: ${N.shadows.card};
64
- font-family: ${N.typography.fontFamily};
65
- font-size: ${N.typography.fontSizeBase};
55
+ `);try{const r=Po(vf);return console.log("平行四边形数据加载成功 (传统适配器):",r.id),r}catch(r){return console.error("传统适配器失败:",r),Sf()}}function Sf(){return Po({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const Cf=({className:r="",problemData:e})=>{const t=gn(),n=pn(),s=yn(),o=bn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=xn(),[d,u]=b.useState(!0),[y,m]=b.useState(null),[h,g]=b.useState(null),p=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(p){u(!1),m(null),g(null);return}(async()=>{try{u(!0),m(null);const R=await Rf();g(R)}catch(R){const C=R instanceof Error?R.message:"数据加载失败";m(C),console.error("页面数据加载失败:",R)}finally{u(!1)}})()},[p]);const x=b.useMemo(()=>p||h,[p,h]);return b.useEffect(()=>{x&&l(x)},[x,l]),d?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),f.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):y?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),f.jsx("div",{className:"text-lg text-red-600 mb-4",children:y}),f.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(wt,{problemData:x,userAnswer:n,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),t==="explanation"&&f.jsx(qt,{problemData:x,userAnswer:n,onNextQuestion:c}),t==="success"&&f.jsx(At,{problemData:x,onNextQuestion:c})]})]}):f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),f.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},Ef=({className:r="",problemData:e})=>{const t=gn(),n=pn(),s=yn(),o=bn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=xn(),[d,u]=b.useState(!0),[y,m]=b.useState(null),[h,g]=b.useState(null),p=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(p){u(!1),m(null),g(null);return}(async()=>{try{u(!0),m(null);const R=await Af();g(R)}catch(R){const C=R instanceof Error?R.message:"数据加载失败";m(C),console.error("页面数据加载失败:",R)}finally{u(!1)}})()},[p]);const x=b.useMemo(()=>p||h,[p,h]);return b.useEffect(()=>{x&&l(x)},[x,l]),d?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),f.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):y?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),f.jsx("div",{className:"text-lg text-red-600 mb-4",children:y}),f.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(wt,{problemData:x,userAnswer:n,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),t==="explanation"&&f.jsx(qt,{problemData:x,userAnswer:n,onNextQuestion:c}),t==="success"&&f.jsx(At,{problemData:x,onNextQuestion:c})]})]}):f.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),f.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Do=b.createContext(void 0),Tf=()=>{const r=b.useContext(Do);if(!r)throw new Error("useMathCardContext must be used within a MathCard component");return r},Lo=(r,e,t)=>r.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,t.join(", ")),Nf=r=>r.type==="formula"?b.createElement(zt,{key:r.content,parts:[r.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):r.type==="image"?b.createElement("img",{src:r.content,alt:"content",className:"image",key:r.content}):b.createElement("span",{key:r.content},r.content),An=r=>r.map((e,t)=>b.createElement("div",{className:"content-block",key:t},Nf(e))),$f=r=>{const e=[];let t=0;const n=/\$\$?[^$]+\$\$?/g;let s;for(;(s=n.exec(r))!==null;){const o=s.index,i=s.index+s[0].length;if(o>t){const l=r.substring(t,o);l.trim()&&e.push({type:"text",content:l})}const c=s[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:c}),t=i}if(t<r.length){const o=r.substring(t);o.trim()&&e.push({type:"text",content:o})}return e},kf=(r,e,t)=>{const n=Lo(r,e,t),s=$f(n);return An(s)},Of=r=>{const{type:e,content:t,style:n={}}=r,s={marginBottom:"8px",lineHeight:"1.6",...n};switch(e){case"instruction":return b.createElement("div",{key:r.id,style:{...s,fontWeight:"bold",color:"#4a6cf7"}},t);case"formula":const o=t.includes("\\\\")||t.includes("\\downarrow")||t.includes("\\quad");return b.createElement(zt,{key:r.id,parts:[t],children:null,displayMode:o,fontSize:"1.1em",color:"#333333"});case"conclusion":return b.createElement("div",{key:r.id,style:{...s,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},t);case"image":return b.createElement("div",{key:r.id,style:s},b.createElement("img",{src:t,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return b.createElement("div",{key:r.id,style:s},b.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},t));default:return b.createElement("div",{key:r.id,style:s},t)}},jf=(r,e,t)=>{const{type:n,content:s,style:o={}}=r,i={marginBottom:"8px",lineHeight:"1.6",...o};switch(n){case"instruction":return b.createElement("div",{key:r.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},s);case"formula":const a=s.includes("\\\\")||s.includes("\\downarrow")||s.includes("\\quad");return b.createElement(zt,{key:r.id,parts:[s],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const c=Lo(s,t,e);return b.createElement("div",{key:r.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},c);default:return b.createElement("div",{key:r.id,style:i},s)}},Mf=r=>r.map(Of),If=(r,e,t)=>r.map(n=>jf(n,e,t)),Uo=({scene:r,position:e="header",size:t="medium",color:n,bgColor:s,hidden:o=!1})=>{if(o)return null;const i={question:"题目作答",solve:"官方解析",review:"用户复习"},a=()=>{const c={display:"flex",alignItems:"center",justifyContent:"center",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px"},l={question:"#f97316",solve:"#4a6cf7",review:"#4ade80"};return c.background=s||l[r],c.color=n||"#ffffff",e==="header"?c.borderBottom="1px solid #e0e0e0":e==="sidebar"&&(c.borderRight="1px solid #e0e0e0",c.writingMode="vertical-rl",c.textOrientation="mixed"),Object.assign(c,{small:{fontSize:"12px",padding:"8px 12px"},medium:{fontSize:"14px",padding:"12px 16px"},large:{fontSize:"16px",padding:"16px 20px"}}[t]),c};return f.jsx("div",{style:a(),children:i[r]})},Go=({question:r})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return f.jsx("div",{style:e,children:An(r)})},zo=({problemType:r,options:e,value:t=[],onChange:n,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"},c=u=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:u?"#f97316":"transparent",color:u?"#ffffff":"inherit",borderColor:u?"#f97316":"#e0e0e0"}),l=u=>{if(n)if(r==="multiple-choice"){const y=t.includes(u)?t.filter(m=>m!==u):[...t,u];n(y)}else n([u])},d=u=>{n&&n([u.target.value])};return r==="multiple-choice"&&e?f.jsx("div",{style:o,children:f.jsx("div",{style:a,children:e.map(u=>f.jsx("div",{style:c(t.includes(u.id)),onClick:()=>l(u.id),children:An(u.content)},u.id))})}):f.jsx("div",{style:o,children:f.jsx("input",{type:"text",style:i,placeholder:s,value:t[0]||"",onChange:d})})},lr=({onClick:r,children:e,disabled:t=!1,loading:n=!1})=>{const s={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:t?"not-allowed":"pointer",opacity:t?.6:1};return f.jsx("button",{style:s,onClick:r,disabled:t||n,children:n?"提交中...":e})},Bo=({steps:r,title:e="解题步骤"})=>{const t={padding:"20px",borderTop:"1px solid #e0e0e0"},n={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 f.jsxs("div",{style:t,children:[f.jsx("div",{style:n,children:e}),f.jsx("div",{style:s,children:Mf(r).map((i,a)=>f.jsx("div",{style:o,children:i},r[a].id))})]})},Vo=({reviewContent:r,userAnswer:e,correctAnswer:t})=>{const n={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"},c={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return f.jsxs("div",{style:n,children:[f.jsx("div",{style:s,children:"复习内容"}),f.jsxs("div",{style:o,children:[r.reviewTemplate&&f.jsx("div",{style:i,children:kf(r.reviewTemplate,t,e)}),r.reviewExplanation&&f.jsx("div",{style:a,children:If(r.reviewExplanation,e,t).map((l,d)=>f.jsx("div",{style:c,children:l},r.reviewExplanation[d].id))})]})]})},qo=({type:r="skeleton"})=>{const e={padding:"20px"},t={height:"16px",background:"linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",backgroundSize:"200% 100%",animation:"loading 1.5s infinite",borderRadius:"4px",marginBottom:"12px"},n={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 r==="spinner"?f.jsx("div",{style:n,children:f.jsx("div",{style:s})}):f.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[f.jsx("div",{style:{...t,width:"80%"}}),f.jsx("div",{style:{...t,width:"60%"}}),f.jsx("div",{style:{...t,width:"70%"}})]})},hr=({error:r,onRetry:e})=>{const t={padding:"24px",textAlign:"center",color:"#ef4444"},n={marginBottom:"16px",fontSize:"16px"},s={padding:"12px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"14px"},o=typeof r=="string"?r:r.message;return f.jsxs("div",{style:t,children:[f.jsx("div",{style:n,children:o}),e&&f.jsx("button",{style:s,onClick:()=>e(r),children:"重试"})]})},Ff=({orientation:r="horizontal",size:e="medium"})=>{const t={background:"#e0e0e0"},n={small:"12px",medium:"16px",large:"20px"};return r==="horizontal"?(t.height="1px",t.width="100%",t.margin=`${n[e]} 0`):(t.width="1px",t.height="100%",t.margin=`0 ${n[e]}`),f.jsx("div",{style:t})},Pf=({onSubmit:r,onNext:e,onRetry:t,onAnswerChange:n,value:s})=>{const{problemData:o,scene:i,submissionResult:a,config:c}=Tf();if(!o)return f.jsx(hr,{error:"No problem data provided"});const l=()=>{r&&r()},d=()=>{e&&e(o.problemId)},u=()=>{t&&t(o.problemId)},y=g=>{n&&n(g,o.problemType)},m={background:c?.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:c?.theme==="dark"?"#ffffff":"#333333",width:"100%",maxWidth:"800px"},h={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return f.jsxs("div",{style:m,"data-testid":"math-card","data-theme":c?.theme,children:[c?.showBanner!==!1&&f.jsx(Uo,{scene:i,position:c?.bannerPosition,size:c?.bannerSize,color:c?.bannerCustomStyle?.color,bgColor:c?.bannerCustomStyle?.bgColor}),f.jsx(Go,{question:o.question,problemType:o.problemType}),i==="question"&&f.jsxs(f.Fragment,{children:[f.jsx(zo,{problemType:o.problemType,options:o.answer.options,value:s,onChange:y,placeholder:c?.inputPlaceholder}),f.jsx("div",{style:h,children:f.jsx(lr,{onClick:l,disabled:!r,children:c?.submitButtonText||"提交答案"})})]}),i==="solve"&&o.explanation&&f.jsx(Bo,{steps:o.explanation,title:"官方解析"}),i==="review"&&a&&o.reviewContent&&f.jsx(Vo,{reviewContent:o.reviewContent,userAnswer:a.userAnswer,correctAnswer:o.answer.correctAnswer}),(i==="solve"||i==="review")&&f.jsxs("div",{style:h,children:[e&&f.jsx(lr,{onClick:d,children:c?.nextButtonText||"下一题"}),t&&f.jsx(lr,{onClick:u,children:c?.retryButtonText||"重新作答"})]})]})},Ve=({problemData:r,scene:e,submissionResult:t,loading:n,error:s,config:o,children:i,onSubmit:a,onNext:c,onRetry:l,onErrorRetry:d,onAnswerChange:u,onHintToggle:y,value:m})=>{if(n)return f.jsx(qo,{type:"skeleton"});if(s)return f.jsx(hr,{error:s,onRetry:d});if(!r)return f.jsx(hr,{error:"No problem data provided"});const h={problemData:r,scene:e,submissionResult:t,config:o,value:m};return f.jsx(Do.Provider,{value:h,children:i||f.jsx(Pf,{onSubmit:a,onNext:c,onRetry:l,onAnswerChange:u,onHintToggle:y,value:m})})};Ve.Banner=Uo;Ve.Question=Go;Ve.AnswerInput=zo;Ve.SubmitButton=lr;Ve.Explanation=Bo;Ve.ReviewContent=Vo;Ve.LoadingState=qo;Ve.ErrorState=hr;Ve.Divider=Ff;function Df(r){if(r.sheet)return r.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===r)return document.styleSheets[e]}function Lf(r){var e=document.createElement("style");return e.setAttribute("data-emotion",r.key),r.nonce!==void 0&&e.setAttribute("nonce",r.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var Uf=(function(){function r(t){var n=this;this._insertTag=function(s){var o;n.tags.length===0?n.insertionPoint?o=n.insertionPoint.nextSibling:n.prepend?o=n.container.firstChild:o=n.before:o=n.tags[n.tags.length-1].nextSibling,n.container.insertBefore(s,o),n.tags.push(s)},this.isSpeedy=t.speedy===void 0?!0:t.speedy,this.tags=[],this.ctr=0,this.nonce=t.nonce,this.key=t.key,this.container=t.container,this.prepend=t.prepend,this.insertionPoint=t.insertionPoint,this.before=null}var e=r.prototype;return e.hydrate=function(n){n.forEach(this._insertTag)},e.insert=function(n){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(Lf(this));var s=this.tags[this.tags.length-1];if(this.isSpeedy){var o=Df(s);try{o.insertRule(n,o.cssRules.length)}catch{}}else s.appendChild(document.createTextNode(n));this.ctr++},e.flush=function(){this.tags.forEach(function(n){var s;return(s=n.parentNode)==null?void 0:s.removeChild(n)}),this.tags=[],this.ctr=0},r})(),be="-ms-",gr="-moz-",V="-webkit-",Wo="comm",Rn="rule",Sn="decl",Gf="@import",Ho="@keyframes",zf="@layer",Bf=Math.abs,Rr=String.fromCharCode,Vf=Object.assign;function qf(r,e){return me(r,0)^45?(((e<<2^me(r,0))<<2^me(r,1))<<2^me(r,2))<<2^me(r,3):0}function Yo(r){return r.trim()}function Wf(r,e){return(r=e.exec(r))?r[0]:r}function q(r,e,t){return r.replace(e,t)}function Jr(r,e){return r.indexOf(e)}function me(r,e){return r.charCodeAt(e)|0}function jt(r,e,t){return r.slice(e,t)}function Ue(r){return r.length}function Cn(r){return r.length}function er(r,e){return e.push(r),r}function Hf(r,e){return r.map(e).join("")}var Sr=1,vt=1,Ko=0,Se=0,ce=0,Rt="";function Cr(r,e,t,n,s,o,i){return{value:r,root:e,parent:t,type:n,props:s,children:o,line:Sr,column:vt,length:i,return:""}}function Nt(r,e){return Vf(Cr("",null,null,"",null,null,0),r,{length:-r.length},e)}function Yf(){return ce}function Kf(){return ce=Se>0?me(Rt,--Se):0,vt--,ce===10&&(vt=1,Sr--),ce}function $e(){return ce=Se<Ko?me(Rt,Se++):0,vt++,ce===10&&(vt=1,Sr++),ce}function Be(){return me(Rt,Se)}function cr(){return Se}function Ht(r,e){return jt(Rt,r,e)}function Mt(r){switch(r){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 Xo(r){return Sr=vt=1,Ko=Ue(Rt=r),Se=0,[]}function Jo(r){return Rt="",r}function dr(r){return Yo(Ht(Se-1,Zr(r===91?r+2:r===40?r+1:r)))}function Xf(r){for(;(ce=Be())&&ce<33;)$e();return Mt(r)>2||Mt(ce)>3?"":" "}function Jf(r,e){for(;--e&&$e()&&!(ce<48||ce>102||ce>57&&ce<65||ce>70&&ce<97););return Ht(r,cr()+(e<6&&Be()==32&&$e()==32))}function Zr(r){for(;$e();)switch(ce){case r:return Se;case 34:case 39:r!==34&&r!==39&&Zr(ce);break;case 40:r===41&&Zr(r);break;case 92:$e();break}return Se}function Zf(r,e){for(;$e()&&r+ce!==57;)if(r+ce===84&&Be()===47)break;return"/*"+Ht(e,Se-1)+"*"+Rr(r===47?r:$e())}function Qf(r){for(;!Mt(Be());)$e();return Ht(r,Se)}function eu(r){return Jo(fr("",null,null,null,[""],r=Xo(r),0,[0],r))}function fr(r,e,t,n,s,o,i,a,c){for(var l=0,d=0,u=i,y=0,m=0,h=0,g=1,p=1,x=1,S=0,R="",C=s,_=o,O=n,w=R;p;)switch(h=S,S=$e()){case 40:if(h!=108&&me(w,u-1)==58){Jr(w+=q(dr(S),"&","&\f"),"&\f")!=-1&&(x=-1);break}case 34:case 39:case 91:w+=dr(S);break;case 9:case 10:case 13:case 32:w+=Xf(h);break;case 92:w+=Jf(cr()-1,7);continue;case 47:switch(Be()){case 42:case 47:er(tu(Zf($e(),cr()),e,t),c);break;default:w+="/"}break;case 123*g:a[l++]=Ue(w)*x;case 125*g:case 59:case 0:switch(S){case 0:case 125:p=0;case 59+d:x==-1&&(w=q(w,/\f/g,"")),m>0&&Ue(w)-u&&er(m>32?ns(w+";",n,t,u-1):ns(q(w," ","")+";",n,t,u-2),c);break;case 59:w+=";";default:if(er(O=rs(w,e,t,l,d,s,a,R,C=[],_=[],u),o),S===123)if(d===0)fr(w,e,O,O,C,o,u,a,_);else switch(y===99&&me(w,3)===110?100:y){case 100:case 108:case 109:case 115:fr(r,O,O,n&&er(rs(r,O,O,0,0,s,a,R,s,C=[],u),_),s,_,u,a,n?C:_);break;default:fr(w,O,O,O,[""],_,0,a,_)}}l=d=m=0,g=x=1,R=w="",u=i;break;case 58:u=1+Ue(w),m=h;default:if(g<1){if(S==123)--g;else if(S==125&&g++==0&&Kf()==125)continue}switch(w+=Rr(S),S*g){case 38:x=d>0?1:(w+="\f",-1);break;case 44:a[l++]=(Ue(w)-1)*x,x=1;break;case 64:Be()===45&&(w+=dr($e())),y=Be(),d=u=Ue(R=w+=Qf(cr())),S++;break;case 45:h===45&&Ue(w)==2&&(g=0)}}return o}function rs(r,e,t,n,s,o,i,a,c,l,d){for(var u=s-1,y=s===0?o:[""],m=Cn(y),h=0,g=0,p=0;h<n;++h)for(var x=0,S=jt(r,u+1,u=Bf(g=i[h])),R=r;x<m;++x)(R=Yo(g>0?y[x]+" "+S:q(S,/&\f/g,y[x])))&&(c[p++]=R);return Cr(r,e,t,s===0?Rn:a,c,l,d)}function tu(r,e,t){return Cr(r,e,t,Wo,Rr(Yf()),jt(r,2,-2),0)}function ns(r,e,t,n){return Cr(r,e,t,Sn,jt(r,0,n),jt(r,n+1,-1),n)}function gt(r,e){for(var t="",n=Cn(r),s=0;s<n;s++)t+=e(r[s],s,r,e)||"";return t}function ru(r,e,t,n){switch(r.type){case zf:if(r.children.length)break;case Gf:case Sn:return r.return=r.return||r.value;case Wo:return"";case Ho:return r.return=r.value+"{"+gt(r.children,n)+"}";case Rn:r.value=r.props.join(",")}return Ue(t=gt(r.children,n))?r.return=r.value+"{"+t+"}":""}function nu(r){var e=Cn(r);return function(t,n,s,o){for(var i="",a=0;a<e;a++)i+=r[a](t,n,s,o)||"";return i}}function su(r){return function(e){e.root||(e=e.return)&&r(e)}}function ou(r){var e=Object.create(null);return function(t){return e[t]===void 0&&(e[t]=r(t)),e[t]}}var iu=function(e,t,n){for(var s=0,o=0;s=o,o=Be(),s===38&&o===12&&(t[n]=1),!Mt(o);)$e();return Ht(e,Se)},au=function(e,t){var n=-1,s=44;do switch(Mt(s)){case 0:s===38&&Be()===12&&(t[n]=1),e[n]+=iu(Se-1,t,n);break;case 2:e[n]+=dr(s);break;case 4:if(s===44){e[++n]=Be()===58?"&\f":"",t[n]=e[n].length;break}default:e[n]+=Rr(s)}while(s=$e());return e},lu=function(e,t){return Jo(au(Xo(e),t))},ss=new WeakMap,cu=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var t=e.value,n=e.parent,s=e.column===n.column&&e.line===n.line;n.type!=="rule";)if(n=n.parent,!n)return;if(!(e.props.length===1&&t.charCodeAt(0)!==58&&!ss.get(n))&&!s){ss.set(e,!0);for(var o=[],i=lu(t,o),a=n.props,c=0,l=0;c<i.length;c++)for(var d=0;d<a.length;d++,l++)e.props[l]=o[c]?i[c].replace(/&\f/g,a[d]):a[d]+" "+i[c]}}},du=function(e){if(e.type==="decl"){var t=e.value;t.charCodeAt(0)===108&&t.charCodeAt(2)===98&&(e.return="",e.value="")}};function Zo(r,e){switch(qf(r,e)){case 5103:return V+"print-"+r+r;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 V+r+r;case 5349:case 4246:case 4810:case 6968:case 2756:return V+r+gr+r+be+r+r;case 6828:case 4268:return V+r+be+r+r;case 6165:return V+r+be+"flex-"+r+r;case 5187:return V+r+q(r,/(\w+).+(:[^]+)/,V+"box-$1$2"+be+"flex-$1$2")+r;case 5443:return V+r+be+"flex-item-"+q(r,/flex-|-self/,"")+r;case 4675:return V+r+be+"flex-line-pack"+q(r,/align-content|flex-|-self/,"")+r;case 5548:return V+r+be+q(r,"shrink","negative")+r;case 5292:return V+r+be+q(r,"basis","preferred-size")+r;case 6060:return V+"box-"+q(r,"-grow","")+V+r+be+q(r,"grow","positive")+r;case 4554:return V+q(r,/([^-])(transform)/g,"$1"+V+"$2")+r;case 6187:return q(q(q(r,/(zoom-|grab)/,V+"$1"),/(image-set)/,V+"$1"),r,"")+r;case 5495:case 3959:return q(r,/(image-set\([^]*)/,V+"$1$`$1");case 4968:return q(q(r,/(.+:)(flex-)?(.*)/,V+"box-pack:$3"+be+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+V+r+r;case 4095:case 3583:case 4068:case 2532:return q(r,/(.+)-inline(.+)/,V+"$1$2")+r;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(Ue(r)-1-e>6)switch(me(r,e+1)){case 109:if(me(r,e+4)!==45)break;case 102:return q(r,/(.+:)(.+)-([^]+)/,"$1"+V+"$2-$3$1"+gr+(me(r,e+3)==108?"$3":"$2-$3"))+r;case 115:return~Jr(r,"stretch")?Zo(q(r,"stretch","fill-available"),e)+r:r}break;case 4949:if(me(r,e+1)!==115)break;case 6444:switch(me(r,Ue(r)-3-(~Jr(r,"!important")&&10))){case 107:return q(r,":",":"+V)+r;case 101:return q(r,/(.+:)([^;!]+)(;|!.+)?/,"$1"+V+(me(r,14)===45?"inline-":"")+"box$3$1"+V+"$2$3$1"+be+"$2box$3")+r}break;case 5936:switch(me(r,e+11)){case 114:return V+r+be+q(r,/[svh]\w+-[tblr]{2}/,"tb")+r;case 108:return V+r+be+q(r,/[svh]\w+-[tblr]{2}/,"tb-rl")+r;case 45:return V+r+be+q(r,/[svh]\w+-[tblr]{2}/,"lr")+r}return V+r+be+r+r}return r}var fu=function(e,t,n,s){if(e.length>-1&&!e.return)switch(e.type){case Sn:e.return=Zo(e.value,e.length);break;case Ho:return gt([Nt(e,{value:q(e.value,"@","@"+V)})],s);case Rn:if(e.length)return Hf(e.props,function(o){switch(Wf(o,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return gt([Nt(e,{props:[q(o,/:(read-\w+)/,":"+gr+"$1")]})],s);case"::placeholder":return gt([Nt(e,{props:[q(o,/:(plac\w+)/,":"+V+"input-$1")]}),Nt(e,{props:[q(o,/:(plac\w+)/,":"+gr+"$1")]}),Nt(e,{props:[q(o,/:(plac\w+)/,be+"input-$1")]})],s)}return""})}},uu=[fu],mu=function(e){var t=e.key;if(t==="css"){var n=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(n,function(g){var p=g.getAttribute("data-emotion");p.indexOf(" ")!==-1&&(document.head.appendChild(g),g.setAttribute("data-s",""))})}var s=e.stylisPlugins||uu,o={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+t+' "]'),function(g){for(var p=g.getAttribute("data-emotion").split(" "),x=1;x<p.length;x++)o[p[x]]=!0;a.push(g)});var c,l=[cu,du];{var d,u=[ru,su(function(g){d.insert(g)})],y=nu(l.concat(s,u)),m=function(p){return gt(eu(p),y)};c=function(p,x,S,R){d=S,m(p?p+"{"+x.styles+"}":x.styles),R&&(h.inserted[x.name]=!0)}}var h={key:t,sheet:new Uf({key:t,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:o,registered:{},insert:c};return h.sheet.hydrate(a),h},tr={exports:{}},Y={};var os;function hu(){if(os)return Y;os=1;var r=typeof Symbol=="function"&&Symbol.for,e=r?Symbol.for("react.element"):60103,t=r?Symbol.for("react.portal"):60106,n=r?Symbol.for("react.fragment"):60107,s=r?Symbol.for("react.strict_mode"):60108,o=r?Symbol.for("react.profiler"):60114,i=r?Symbol.for("react.provider"):60109,a=r?Symbol.for("react.context"):60110,c=r?Symbol.for("react.async_mode"):60111,l=r?Symbol.for("react.concurrent_mode"):60111,d=r?Symbol.for("react.forward_ref"):60112,u=r?Symbol.for("react.suspense"):60113,y=r?Symbol.for("react.suspense_list"):60120,m=r?Symbol.for("react.memo"):60115,h=r?Symbol.for("react.lazy"):60116,g=r?Symbol.for("react.block"):60121,p=r?Symbol.for("react.fundamental"):60117,x=r?Symbol.for("react.responder"):60118,S=r?Symbol.for("react.scope"):60119;function R(_){if(typeof _=="object"&&_!==null){var O=_.$$typeof;switch(O){case e:switch(_=_.type,_){case c:case l:case n:case o:case s:case u:return _;default:switch(_=_&&_.$$typeof,_){case a:case d:case h:case m:case i:return _;default:return O}}case t:return O}}}function C(_){return R(_)===l}return Y.AsyncMode=c,Y.ConcurrentMode=l,Y.ContextConsumer=a,Y.ContextProvider=i,Y.Element=e,Y.ForwardRef=d,Y.Fragment=n,Y.Lazy=h,Y.Memo=m,Y.Portal=t,Y.Profiler=o,Y.StrictMode=s,Y.Suspense=u,Y.isAsyncMode=function(_){return C(_)||R(_)===c},Y.isConcurrentMode=C,Y.isContextConsumer=function(_){return R(_)===a},Y.isContextProvider=function(_){return R(_)===i},Y.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},Y.isForwardRef=function(_){return R(_)===d},Y.isFragment=function(_){return R(_)===n},Y.isLazy=function(_){return R(_)===h},Y.isMemo=function(_){return R(_)===m},Y.isPortal=function(_){return R(_)===t},Y.isProfiler=function(_){return R(_)===o},Y.isStrictMode=function(_){return R(_)===s},Y.isSuspense=function(_){return R(_)===u},Y.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===n||_===l||_===o||_===s||_===u||_===y||typeof _=="object"&&_!==null&&(_.$$typeof===h||_.$$typeof===m||_.$$typeof===i||_.$$typeof===a||_.$$typeof===d||_.$$typeof===p||_.$$typeof===x||_.$$typeof===S||_.$$typeof===g)},Y.typeOf=R,Y}var K={};var is;function gu(){return is||(is=1,process.env.NODE_ENV!=="production"&&(function(){var r=typeof Symbol=="function"&&Symbol.for,e=r?Symbol.for("react.element"):60103,t=r?Symbol.for("react.portal"):60106,n=r?Symbol.for("react.fragment"):60107,s=r?Symbol.for("react.strict_mode"):60108,o=r?Symbol.for("react.profiler"):60114,i=r?Symbol.for("react.provider"):60109,a=r?Symbol.for("react.context"):60110,c=r?Symbol.for("react.async_mode"):60111,l=r?Symbol.for("react.concurrent_mode"):60111,d=r?Symbol.for("react.forward_ref"):60112,u=r?Symbol.for("react.suspense"):60113,y=r?Symbol.for("react.suspense_list"):60120,m=r?Symbol.for("react.memo"):60115,h=r?Symbol.for("react.lazy"):60116,g=r?Symbol.for("react.block"):60121,p=r?Symbol.for("react.fundamental"):60117,x=r?Symbol.for("react.responder"):60118,S=r?Symbol.for("react.scope"):60119;function R(A){return typeof A=="string"||typeof A=="function"||A===n||A===l||A===o||A===s||A===u||A===y||typeof A=="object"&&A!==null&&(A.$$typeof===h||A.$$typeof===m||A.$$typeof===i||A.$$typeof===a||A.$$typeof===d||A.$$typeof===p||A.$$typeof===x||A.$$typeof===S||A.$$typeof===g)}function C(A){if(typeof A=="object"&&A!==null){var H=A.$$typeof;switch(H){case e:var Z=A.type;switch(Z){case c:case l:case n:case o:case s:case u:return Z;default:var I=Z&&Z.$$typeof;switch(I){case a:case d:case h:case m:case i:return I;default:return H}}case t:return H}}}var _=c,O=l,w=a,F=i,$=e,k=d,B=n,W=h,M=m,L=t,J=o,j=s,he=u,oe=!1;function z(A){return oe||(oe=!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.")),de(A)||C(A)===c}function de(A){return C(A)===l}function ae(A){return C(A)===a}function ge(A){return C(A)===i}function Ce(A){return typeof A=="object"&&A!==null&&A.$$typeof===e}function We(A){return C(A)===d}function Je(A){return C(A)===n}function dt(A){return C(A)===h}function Ct(A){return C(A)===m}function Er(A){return C(A)===t}function $n(A){return C(A)===o}function N(A){return C(A)===s}function E(A){return C(A)===u}K.AsyncMode=_,K.ConcurrentMode=O,K.ContextConsumer=w,K.ContextProvider=F,K.Element=$,K.ForwardRef=k,K.Fragment=B,K.Lazy=W,K.Memo=M,K.Portal=L,K.Profiler=J,K.StrictMode=j,K.Suspense=he,K.isAsyncMode=z,K.isConcurrentMode=de,K.isContextConsumer=ae,K.isContextProvider=ge,K.isElement=Ce,K.isForwardRef=We,K.isFragment=Je,K.isLazy=dt,K.isMemo=Ct,K.isPortal=Er,K.isProfiler=$n,K.isStrictMode=N,K.isSuspense=E,K.isValidElementType=R,K.typeOf=C})()),K}var as;function pu(){return as||(as=1,process.env.NODE_ENV==="production"?tr.exports=hu():tr.exports=gu()),tr.exports}var Dr,ls;function yu(){if(ls)return Dr;ls=1;var r=pu(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},t={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},n={$$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[r.ForwardRef]=n,o[r.Memo]=s;function i(h){return r.isMemo(h)?s:o[h.$$typeof]||e}var a=Object.defineProperty,c=Object.getOwnPropertyNames,l=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,u=Object.getPrototypeOf,y=Object.prototype;function m(h,g,p){if(typeof g!="string"){if(y){var x=u(g);x&&x!==y&&m(h,x,p)}var S=c(g);l&&(S=S.concat(l(g)));for(var R=i(h),C=i(g),_=0;_<S.length;++_){var O=S[_];if(!t[O]&&!(p&&p[O])&&!(C&&C[O])&&!(R&&R[O])){var w=d(g,O);try{a(h,O,w)}catch{}}}}return h}return Dr=m,Dr}yu();var bu=!0;function xu(r,e,t){var n="";return t.split(" ").forEach(function(s){r[s]!==void 0?e.push(r[s]+";"):s&&(n+=s+" ")}),n}var Qo=function(e,t,n){var s=e.key+"-"+t.name;(n===!1||bu===!1)&&e.registered[s]===void 0&&(e.registered[s]=t.styles)},vu=function(e,t,n){Qo(e,t,n);var s=e.key+"-"+t.name;if(e.inserted[t.name]===void 0){var o=t;do e.insert(t===o?"."+s:"",o,e.sheet,!0),o=o.next;while(o!==void 0)}};function _u(r){for(var e=0,t,n=0,s=r.length;s>=4;++n,s-=4)t=r.charCodeAt(n)&255|(r.charCodeAt(++n)&255)<<8|(r.charCodeAt(++n)&255)<<16|(r.charCodeAt(++n)&255)<<24,t=(t&65535)*1540483477+((t>>>16)*59797<<16),t^=t>>>24,e=(t&65535)*1540483477+((t>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(s){case 3:e^=(r.charCodeAt(n+2)&255)<<16;case 2:e^=(r.charCodeAt(n+1)&255)<<8;case 1:e^=r.charCodeAt(n)&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 wu={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},Au=/[A-Z]|^ms/g,Ru=/_EMO_([^_]+?)_([^]*?)_EMO_/g,ei=function(e){return e.charCodeAt(1)===45},cs=function(e){return e!=null&&typeof e!="boolean"},Lr=ou(function(r){return ei(r)?r:r.replace(Au,"-$&").toLowerCase()}),ds=function(e,t){switch(e){case"animation":case"animationName":if(typeof t=="string")return t.replace(Ru,function(n,s,o){return Ge={name:s,styles:o,next:Ge},s})}return wu[e]!==1&&!ei(e)&&typeof t=="number"&&t!==0?t+"px":t};function It(r,e,t){if(t==null)return"";var n=t;if(n.__emotion_styles!==void 0)return n;switch(typeof t){case"boolean":return"";case"object":{var s=t;if(s.anim===1)return Ge={name:s.name,styles:s.styles,next:Ge},s.name;var o=t;if(o.styles!==void 0){var i=o.next;if(i!==void 0)for(;i!==void 0;)Ge={name:i.name,styles:i.styles,next:Ge},i=i.next;var a=o.styles+";";return a}return Su(r,e,t)}case"function":{if(r!==void 0){var c=Ge,l=t(r);return Ge=c,It(r,e,l)}break}}var d=t;return d}function Su(r,e,t){var n="";if(Array.isArray(t))for(var s=0;s<t.length;s++)n+=It(r,e,t[s])+";";else for(var o in t){var i=t[o];if(typeof i!="object"){var a=i;cs(a)&&(n+=Lr(o)+":"+ds(o,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var c=0;c<i.length;c++)cs(i[c])&&(n+=Lr(o)+":"+ds(o,i[c])+";");else{var l=It(r,e,i);switch(o){case"animation":case"animationName":{n+=Lr(o)+":"+l+";";break}default:n+=o+"{"+l+"}"}}}return n}var fs=/label:\s*([^\s;{]+)\s*(;|$)/g,Ge;function ti(r,e,t){if(r.length===1&&typeof r[0]=="object"&&r[0]!==null&&r[0].styles!==void 0)return r[0];var n=!0,s="";Ge=void 0;var o=r[0];if(o==null||o.raw===void 0)n=!1,s+=It(t,e,o);else{var i=o;s+=i[0]}for(var a=1;a<r.length;a++)if(s+=It(t,e,r[a]),n){var c=o;s+=c[a]}fs.lastIndex=0;for(var l="",d;(d=fs.exec(s))!==null;)l+="-"+d[1];var u=_u(s)+l;return{name:u,styles:s,next:Ge}}var Cu=function(e){return e()},Eu=je.useInsertionEffect?je.useInsertionEffect:!1,Tu=Eu||Cu,ri=je.createContext(typeof HTMLElement<"u"?mu({key:"css"}):null);ri.Provider;var Nu=function(e){return b.forwardRef(function(t,n){var s=b.useContext(ri);return e(t,s,n)})},$u=je.createContext({}),En={}.hasOwnProperty,Qr="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",ku=function(e,t){var n={};for(var s in t)En.call(t,s)&&(n[s]=t[s]);return n[Qr]=e,n},Ou=function(e){var t=e.cache,n=e.serialized,s=e.isStringTag;return Qo(t,n,s),Tu(function(){return vu(t,n,s)}),null},ju=Nu(function(r,e,t){var n=r.css;typeof n=="string"&&e.registered[n]!==void 0&&(n=e.registered[n]);var s=r[Qr],o=[n],i="";typeof r.className=="string"?i=xu(e.registered,o,r.className):r.className!=null&&(i=r.className+" ");var a=ti(o,void 0,je.useContext($u));i+=e.key+"-"+a.name;var c={};for(var l in r)En.call(r,l)&&l!=="css"&&l!==Qr&&(c[l]=r[l]);return c.className=i,t&&(c.ref=t),je.createElement(je.Fragment,null,je.createElement(Ou,{cache:e,serialized:a,isStringTag:typeof s=="string"}),je.createElement(s,c))}),Mu=ju,us=function(e,t){var n=arguments;if(t==null||!En.call(t,"css"))return je.createElement.apply(void 0,n);var s=n.length,o=new Array(s);o[0]=Mu,o[1]=ku(e,t);for(var i=2;i<s;i++)o[i]=n[i];return je.createElement.apply(null,o)};(function(r){var e;e||(e=r.JSX||(r.JSX={}))})(us||(us={}));function te(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return ti(e)}const T={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)"}};te`
56
+ background: ${T.colors.background.card};
57
+ border-radius: ${T.borderRadius.card};
58
+ box-shadow: ${T.shadows.card};
59
+ font-family: ${T.typography.fontFamily};
60
+ font-size: ${T.typography.fontSizeBase};
66
61
  overflow: hidden;
67
62
 
68
63
  &[data-theme="dark"] {
69
64
  background: #1a1a1a;
70
65
  color: #ffffff;
71
66
  }
72
- `;ae`
67
+ `;te`
73
68
  display: flex;
74
69
  align-items: center;
75
70
  justify-content: center;
76
- padding: ${N.spacing.sm} ${N.spacing.md};
71
+ padding: ${T.spacing.sm} ${T.spacing.md};
77
72
  font-weight: 600;
78
73
  text-transform: uppercase;
79
74
  letter-spacing: 0.5px;
80
- `,ae`
81
- font-size: ${N.typography.fontSizeSmall};
82
- padding: 8px ${N.spacing.sm};
83
- `,ae`
84
- font-size: ${N.typography.fontSizeBase};
85
- padding: ${N.spacing.sm} ${N.spacing.md};
86
- `,ae`
87
- font-size: ${N.typography.fontSizeLarge};
88
- padding: ${N.spacing.md} ${N.spacing.lg};
89
- `,ae`
90
- border-bottom: 1px solid ${N.colors.border.default};
91
- `,ae`
92
- border-right: 1px solid ${N.colors.border.default};
75
+ `,te`
76
+ font-size: ${T.typography.fontSizeSmall};
77
+ padding: 8px ${T.spacing.sm};
78
+ `,te`
79
+ font-size: ${T.typography.fontSizeBase};
80
+ padding: ${T.spacing.sm} ${T.spacing.md};
81
+ `,te`
82
+ font-size: ${T.typography.fontSizeLarge};
83
+ padding: ${T.spacing.md} ${T.spacing.lg};
84
+ `,te`
85
+ border-bottom: 1px solid ${T.colors.border.default};
86
+ `,te`
87
+ border-right: 1px solid ${T.colors.border.default};
93
88
  writing-mode: vertical-rl;
94
89
  text-orientation: mixed;
95
- `,ae`
96
- background: ${N.colors.scene.question};
97
- color: ${N.colors.text.light};
98
- `,ae`
99
- background: ${N.colors.scene.solve};
100
- color: ${N.colors.text.light};
101
- `,ae`
102
- background: ${N.colors.scene.review};
103
- color: ${N.colors.text.light};
104
- `;ae`
105
- padding: ${N.spacing.lg};
90
+ `,te`
91
+ background: ${T.colors.scene.question};
92
+ color: ${T.colors.text.light};
93
+ `,te`
94
+ background: ${T.colors.scene.solve};
95
+ color: ${T.colors.text.light};
96
+ `,te`
97
+ background: ${T.colors.scene.review};
98
+ color: ${T.colors.text.light};
99
+ `;te`
100
+ padding: ${T.spacing.lg};
106
101
  line-height: 1.6;
107
102
 
108
103
  .content-block {
109
- margin-bottom: ${N.spacing.sm};
104
+ margin-bottom: ${T.spacing.sm};
110
105
 
111
106
  &:last-child {
112
107
  margin-bottom: 0;
@@ -122,53 +117,53 @@ ${new Error().stack?.split(`
122
117
  .image {
123
118
  max-width: 100%;
124
119
  height: auto;
125
- border-radius: ${N.borderRadius.input};
120
+ border-radius: ${T.borderRadius.input};
126
121
  }
127
- `;ae`
128
- padding: ${N.spacing.lg};
129
- border-top: 1px solid ${N.colors.border.default};
130
- `,ae`
122
+ `;te`
123
+ padding: ${T.spacing.lg};
124
+ border-top: 1px solid ${T.colors.border.default};
125
+ `,te`
131
126
  width: 100%;
132
- padding: ${N.spacing.sm} ${N.spacing.md};
133
- border: 1px solid ${N.colors.border.default};
134
- border-radius: ${N.borderRadius.input};
135
- font-size: ${N.typography.fontSizeBase};
127
+ padding: ${T.spacing.sm} ${T.spacing.md};
128
+ border: 1px solid ${T.colors.border.default};
129
+ border-radius: ${T.borderRadius.input};
130
+ font-size: ${T.typography.fontSizeBase};
136
131
 
137
132
  &:focus {
138
133
  outline: none;
139
- border-color: ${N.colors.scene.question};
134
+ border-color: ${T.colors.scene.question};
140
135
  }
141
- `,ae`
136
+ `,te`
142
137
  display: grid;
143
- gap: ${N.spacing.sm};
144
- `,ae`
145
- padding: ${N.spacing.sm} ${N.spacing.md};
146
- border: 1px solid ${N.colors.border.default};
147
- border-radius: ${N.borderRadius.input};
138
+ gap: ${T.spacing.sm};
139
+ `,te`
140
+ padding: ${T.spacing.sm} ${T.spacing.md};
141
+ border: 1px solid ${T.colors.border.default};
142
+ border-radius: ${T.borderRadius.input};
148
143
  cursor: pointer;
149
144
  transition: all 0.2s ease;
150
145
 
151
146
  &:hover {
152
- border-color: ${N.colors.scene.question};
147
+ border-color: ${T.colors.scene.question};
153
148
  }
154
149
 
155
150
  &[data-selected="true"] {
156
- background: ${N.colors.scene.question};
157
- color: ${N.colors.text.light};
158
- border-color: ${N.colors.scene.question};
151
+ background: ${T.colors.scene.question};
152
+ color: ${T.colors.text.light};
153
+ border-color: ${T.colors.scene.question};
159
154
  }
160
- `;ae`
161
- padding: ${N.spacing.lg};
162
- border-radius: ${N.borderRadius.card};
163
- margin: ${N.spacing.md} 0;
164
- `,ae`
165
- background: ${N.colors.background.feedbackCorrect};
155
+ `;te`
156
+ padding: ${T.spacing.lg};
157
+ border-radius: ${T.borderRadius.card};
158
+ margin: ${T.spacing.md} 0;
159
+ `,te`
160
+ background: ${T.colors.background.feedbackCorrect};
166
161
  border: 1px solid #22c55e;
167
- `,ae`
168
- background: ${N.colors.background.feedbackIncorrect};
162
+ `,te`
163
+ background: ${T.colors.background.feedbackIncorrect};
169
164
  border: 1px solid #ef4444;
170
- `;ae`
171
- padding: ${N.spacing.lg};
165
+ `;te`
166
+ padding: ${T.spacing.lg};
172
167
 
173
168
  .skeleton-line {
174
169
  height: 16px;
@@ -176,7 +171,7 @@ ${new Error().stack?.split(`
176
171
  background-size: 200% 100%;
177
172
  animation: loading 1.5s infinite;
178
173
  border-radius: 4px;
179
- margin-bottom: ${N.spacing.sm};
174
+ margin-bottom: ${T.spacing.sm};
180
175
 
181
176
  &:last-child {
182
177
  margin-bottom: 0;
@@ -187,17 +182,17 @@ ${new Error().stack?.split(`
187
182
  0% { background-position: 200% 0; }
188
183
  100% { background-position: -200% 0; }
189
184
  }
190
- `,ae`
185
+ `,te`
191
186
  display: flex;
192
187
  justify-content: center;
193
188
  align-items: center;
194
- padding: ${N.spacing.xl};
189
+ padding: ${T.spacing.xl};
195
190
 
196
191
  .spinner {
197
192
  width: 40px;
198
193
  height: 40px;
199
194
  border: 4px solid #f0f0f0;
200
- border-top: 4px solid ${N.colors.scene.question};
195
+ border-top: 4px solid ${T.colors.scene.question};
201
196
  border-radius: 50%;
202
197
  animation: spin 1s linear infinite;
203
198
  }
@@ -206,55 +201,55 @@ ${new Error().stack?.split(`
206
201
  0% { transform: rotate(0deg); }
207
202
  100% { transform: rotate(360deg); }
208
203
  }
209
- `;ae`
210
- padding: ${N.spacing.xl};
204
+ `;te`
205
+ padding: ${T.spacing.xl};
211
206
  text-align: center;
212
207
  color: #ef4444;
213
208
 
214
209
  .error-message {
215
- margin-bottom: ${N.spacing.md};
216
- font-size: ${N.typography.fontSizeLarge};
210
+ margin-bottom: ${T.spacing.md};
211
+ font-size: ${T.typography.fontSizeLarge};
217
212
  }
218
213
 
219
214
  .retry-button {
220
- padding: ${N.spacing.sm} ${N.spacing.md};
215
+ padding: ${T.spacing.sm} ${T.spacing.md};
221
216
  background: #ef4444;
222
217
  color: white;
223
218
  border: none;
224
- border-radius: ${N.borderRadius.button};
219
+ border-radius: ${T.borderRadius.button};
225
220
  cursor: pointer;
226
- font-size: ${N.typography.fontSizeBase};
221
+ font-size: ${T.typography.fontSizeBase};
227
222
 
228
223
  &:hover {
229
224
  background: #dc2626;
230
225
  }
231
226
  }
232
- `;ae`
227
+ `;te`
233
228
  height: 1px;
234
- background: ${N.colors.border.default};
235
- margin: ${N.spacing.md} 0;
229
+ background: ${T.colors.border.default};
230
+ margin: ${T.spacing.md} 0;
236
231
 
237
232
  &[data-size="small"] {
238
- margin: ${N.spacing.sm} 0;
233
+ margin: ${T.spacing.sm} 0;
239
234
  }
240
235
 
241
236
  &[data-size="large"] {
242
- margin: ${N.spacing.lg} 0;
237
+ margin: ${T.spacing.lg} 0;
243
238
  }
244
- `,ae`
239
+ `,te`
245
240
  width: 1px;
246
- background: ${N.colors.border.default};
247
- margin: 0 ${N.spacing.md};
241
+ background: ${T.colors.border.default};
242
+ margin: 0 ${T.spacing.md};
248
243
 
249
244
  &[data-size="small"] {
250
- margin: 0 ${N.spacing.sm};
245
+ margin: 0 ${T.spacing.sm};
251
246
  }
252
247
 
253
248
  &[data-size="large"] {
254
- margin: 0 ${N.spacing.lg};
249
+ margin: 0 ${T.spacing.lg};
255
250
  }
256
- `;const Vu="/api/v1/content",Wu="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",qu=10,Je="question",ce=Ut.create()(wi.devtools((r,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(t,n)=>{r({loading:!0,sessionId:t});try{const{gradeLevel:o,unitId:s,lessonId:i,count:a=qu}=n,d=`${Vu}/grades/${o}/units/${s}/lessons/${i}/sessions/${t}/questions`,l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wu}`},body:JSON.stringify({count:a})});if(!l.ok)throw new Error(`Failed to load questions: ${l.status} ${l.statusText}`);const u=(await l.json()).questions||[],y={};u.forEach(m=>{m.geometryShapes&&Array.isArray(m.geometryShapes)&&(y[m.problemId]=m.geometryShapes)}),r({problems:u,totalProblems:u.length,currentProblemIndex:0,currentScene:Je,geometryShapes:y,loading:!1,error:null,startTime:Date.now()})}catch(o){const s=o instanceof Error?o.message:"Unknown error occurred";throw r({error:s,loading:!1}),o}},goToNextProblem:()=>{const{currentProblemIndex:t,problems:n,currentScene:o}=e();if(o!==Je){console.warn("Cannot navigate during review/solve scene");return}t<n.length-1?r({currentProblemIndex:t+1,currentScene:Je}):r({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:t,currentScene:n}=e();n===Je&&t>0&&r({currentProblemIndex:t-1,currentScene:Je})},goToProblem:t=>{const{problems:n,currentScene:o}=e();o===Je&&(t<0||t>=n.length||r({currentProblemIndex:t,currentScene:Je}))},switchScene:t=>{r({currentScene:t})},submitAnswer:async(t,n)=>{const{problems:o,currentProblemIndex:s}=e(),i=o[s];r({loading:!0});try{const a=i?.answer.correctAnswer||[],d=n.length>0&&n[0]===a[0],l={userAnswer:n,isCorrect:d,feedback:d?"🎉 Great job! Your answer is correct!":"❌ Sorry, that's not correct."};r(c=>({userAnswers:{...c.userAnswers,[t]:n},submissionResults:{...c.submissionResults,[t]:l},loading:!1,currentScene:d?"review":"solve"}))}catch(a){r({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(t,n)=>{r(o=>({userAnswers:{...o.userAnswers,[t]:n}}))},updateShape:(t,n,o)=>{r(s=>{const a=(s.geometryShapes[t]||[]).map(d=>d.id===n&&d.type==="point"?{...d,position:o}:d);return{geometryShapes:{...s.geometryShapes,[t]:a}}})},selectShape:(t,n)=>{r({selectedShapeId:n})},setGeometryMode:(t,n)=>{r({geometryMode:n})},startTimer:()=>{r({startTime:Date.now()})},stopTimer:()=>{const{startTime:t}=e();if(t){const n=Math.floor((Date.now()-t)/1e3);r(o=>({timeSpent:o.timeSpent+n,startTime:null}))}},reset:()=>{r({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:Je,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:t,currentProblemIndex:n}=e();return t[n]||null},getProgress:()=>{const{currentProblemIndex:t,totalProblems:n}=e();return{current:t+1,total:n,percentage:n>0?(t+1)/n*100:0}},getSessionResults:()=>{const{sessionId:t,problems:n,submissionResults:o,timeSpent:s}=e(),i=n.map(d=>({problemId:d.problemId,userAnswer:o[d.problemId]?.userAnswer||[],isCorrect:o[d.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(d=>d.isCorrect).length;return{sessionId:t||"",totalProblems:n.length,correctAnswers:a,accuracy:n.length>0?a/n.length:0,timeSpent:s,averageTime:n.length>0?s/n.length:0,answers:i}}}),{name:"MathSessionStore"})),ci=(r,e,t,n,o,s,i)=>{const a=b.useMemo(()=>t==="question",[t]),d=b.useMemo(()=>r<e.length-1,[r,e.length]),l=b.useMemo(()=>r>0,[r]),c=b.useMemo(()=>!n||!o?!1:n.problemType?.includes("geometry")||s&&s[o]&&s[o].length>0?!0:i?.enableMathGraph!==void 0?i.enableMathGraph:!1,[n,o,s,i?.enableMathGraph]);return{canNavigate:a,canGoNext:d,canGoPrevious:l,shouldRenderMathGraph:c}},di=(r,e,t,n,o)=>{const s=ce(c=>c.selectShape),i=ce(c=>c.setGeometryMode),a=b.useMemo(()=>!e||!n?[]:n[e]||[],[n,e]);b.useEffect(()=>{if(!e||!t)return;let c="view";switch(r){case"question":c="edit";break;case"solve":case"review":c="view";break;default:c="view"}o!==c&&i(e,c)},[r,e,o,i,t]);const d=b.useCallback(c=>{e&&ce.setState(u=>({geometryShapes:{...u.geometryShapes,[e]:c}}))},[e]),l=b.useCallback(c=>{if(e){const u=c.length>0?c[0]:null;s(e,u)}},[e,s]);return{currentGeometryShapes:a,geometryMode:o,handleShapeChange:d,handleSelectionChange:l}},fi=(r,e,t)=>{const n=ce(m=>m.updateUserAnswer),o=ce(m=>m.submitAnswer),s=ce(m=>m.goToNextProblem),i=ce(m=>m.goToPreviousProblem),a=ce(m=>m.goToProblem),d=b.useCallback(m=>{r&&n(r,m)},[r,n]),l=b.useCallback(()=>{r&&t[r]&&o(r,t[r])},[r,t,o]),c=b.useCallback(m=>{s(),m?.(r,e+1)},[s,r,e]),u=b.useCallback(m=>{i(),m?.(r,e-1)},[i,r,e]),y=b.useCallback((m,h)=>{a(m-1),h?.(r,m-1)},[a,r]);return{handleAnswerChange:d,handleSubmit:l,handleNext:c,handlePrevious:u,handlePagination:y}},ui=({config:r={},onSessionComplete:e,onSessionExit:t,onProblemChange:n,className:o="",style:s})=>{const i=ce(M=>M.problems),a=ce(M=>M.currentProblemIndex),d=ce(M=>M.currentScene),l=ce(M=>M.loading),c=ce(M=>M.error),u=ce(M=>M.sessionComplete),y=ce(M=>M.submissionResults),m=ce(M=>M.userAnswers),h=ce(M=>M.geometryShapes),g=ce(M=>M.geometryMode),p=ce(M=>M.getSessionResults),x=b.useMemo(()=>i[a]??null,[i,a]),C=b.useMemo(()=>x?.problemId??"",[x]),{canNavigate:S,canGoNext:E,canGoPrevious:_,shouldRenderMathGraph:j}=ci(a,i,d,x,C,h,r),{currentGeometryShapes:w,handleShapeChange:P,handleSelectionChange:$}=di(d,C,j,h,g),{handleAnswerChange:O,handleSubmit:Y,handleNext:q,handlePrevious:I,handlePagination:G}=fi(C,a,m);b.useEffect(()=>{if(u&&typeof p=="function"){const M=p();e?.(M)}},[u,p,e]);const H=M=>typeof M=="string"?M:M instanceof Error?M.message:String(M);return l&&i.length===0?f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),f.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):c&&c!==null?f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:f.jsxs("div",{className:"text-center text-red-600",children:[f.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),f.jsx("p",{children:H(c)})]})}):x?f.jsxs("div",{className:`flex flex-col max-w-4xl mx-auto p-6 ${o}`,style:s,"data-testid":"math-session-container",role:"region","aria-label":"数学练习会话",children:[f.jsx("div",{className:"mb-6",children:f.jsx(ke.Pagination,{total:i.length,page:a+1,onChange:M=>G(M,n),isDisabled:!S,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),f.jsx(Ke,{problemData:x,scene:d,submissionResult:y[C],loading:l,error:c?H(c):void 0,value:m[C],onAnswerChange:O,onSubmit:Y,onNext:()=>q(n),config:{theme:r.theme??"light",submitButtonText:"提交答案",nextButtonText:d==="solve"?"Got it!":"下一题",showHints:r.enableHints}}),j&&f.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:f.jsx(Tr,{shapes:w,mode:g,onShapeChange:P,onSelectionChange:$,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),r.showProgress&&f.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[f.jsx("button",{onClick:()=>I(n),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:"上一题"}),f.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),f.jsx("button",{onClick:()=>q(n),disabled:!E||!S,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:"下一题"})]}),t&&f.jsx("div",{className:"mt-4 flex justify-center",children:f.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:f.jsx("p",{className:"text-gray-600",children:"No problems available"})})},Yu=({sessionId:r,gradeId:e,unitId:t,lessonId:n,userId:o,config:s={},className:i="",onSessionComplete:a,onSessionExit:d})=>{const[l,c]=b.useState({loading:!1,error:null,initialized:!1}),[u,y]=b.useState(0),[m,h]=b.useState(""),g=b.useRef(null),p=b.useRef(null),x=b.useRef(null),C=ce(P=>P.loadQuestions),S=ce(P=>P.reset);b.useEffect(()=>{const P=async()=>{try{c($=>({...$,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:r,gradeId:e,unitId:t,lessonId:n,userId:o}),await C(r,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:t,lessonId:n,count:s.questionCount||10}),c($=>({...$,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch($){const O=$ instanceof Error?$.message:"Failed to initialize session";c(Y=>({...Y,loading:!1,error:O,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",$)}};r&&e&&t&&n&&!l.initialized&&P()},[r,e,t,n,C,s.questionCount,l.initialized,u]),b.useEffect(()=>{l.loading&&!l.initialized?h("正在加载数学练习内容,请稍候..."):l.error?h(`加载失败:${l.error},请点击重试按钮重新加载`):l.initialized&&h("数学练习内容已加载完成,可以开始练习")},[l.loading,l.error,l.initialized]),b.useEffect(()=>{l.initialized&&g.current&&g.current.focus()},[l.initialized]),b.useEffect(()=>{l.error&&x.current&&x.current.focus()},[l.error]),b.useEffect(()=>{l.loading&&p.current&&p.current.focus()},[l.loading]),b.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),S()},[S]);const E=b.useCallback(P=>{console.log("🎉 MathSessionPage: 会话完成",P),a?.(P)},[a]),_=b.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),d?.()},[d]),j=b.useCallback((P,$)=>{console.log(`📝 MathSessionPage: 切换到题目 ${$+1}`,P)},[]),w=b.useCallback(P=>{P.key==="Escape"&&(P.preventDefault(),_()),P.key==="Enter"&&l.error&&P.target===x.current&&(P.preventDefault(),c({loading:!1,error:null,initialized:!1}),y($=>$+1))},[_,l.error]);return l.loading&&!l.initialized?f.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:w,tabIndex:-1,ref:p,children:[f.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:m}),f.jsx("div",{className:"page-loading-container",children:f.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[f.jsx("div",{className:"spinner","aria-hidden":"true"}),f.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):l.error?f.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:w,tabIndex:-1,ref:x,children:[f.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:m}),f.jsxs("div",{className:"error-container",children:[f.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),f.jsx("h3",{className:"error-title",children:"加载失败"}),f.jsx("p",{className:"error-message",children:l.error}),f.jsx("button",{onClick:()=>{c({loading:!1,error:null,initialized:!1}),y(P=>P+1)},className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):f.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:w,children:[f.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:m}),s.layout?.showHeader&&f.jsx("header",{className:"page-header",role:"banner",children:f.jsxs("div",{className:"header-content",children:[f.jsx("h1",{className:"page-title",children:"数学练习"}),f.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[f.jsxs("span",{className:"session-id",children:["会话: ",r]}),f.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),f.jsx("main",{className:"page-main",ref:g,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:f.jsx(ui,{config:{showProgress:s.showProgress??!0,enableHints:s.enableHints??!1,autoAdvance:s.autoAdvance??!1,theme:s.theme??"light"},onSessionComplete:E,onSessionExit:_,onProblemChange:j})}),s.layout?.showFooter&&f.jsx("footer",{className:"page-footer",role:"contentinfo",children:f.jsx("div",{className:"footer-content",children:f.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},Hu=b.memo(Yu),Ku=({problemData:r,userAnswer:e,onNextQuestion:t})=>f.jsxs("div",{children:[f.jsxs("div",{className:"decimal-error-banner",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),f.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",f.jsx("strong",{children:r.answer.value})]})]}),f.jsx("button",{onClick:t,className:"decimal-understand-button",children:"明白了"})]}),f.jsxs("div",{className:"decimal-content-area",children:[f.jsx(Rn,{problemData:r,userAnswer:e}),f.jsx(Sn,{problemData:r})]}),f.jsx("div",{className:"decimal-bottom-area",children:f.jsx("button",{onClick:t,className:"decimal-bottom-button",children:"明白了"})})]}),Xu="rectangle-area-003",Ju="矩形面积计算问题",Zu=5,Qu="几何与测量",em="计算矩形的面积,理解面积公式 A = l × w 的应用",tm={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},rm=[{type:"text",content:"What is the area of this rectangle?"}],nm={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"}}]}},om=[{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}}}],sm={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},im={type:"card",padding:"20px"},am={id:Xu,title:Ju,grade:Zu,unit:Qu,description:em,basicInfo:tm,content:rm,scenes:nm,explanation:om,answer:sm,layout:im},lm=({className:r=""})=>{const e=gn(),t=pn(),n=yn(),{updateUserAnswer:o,submitAnswer:s,nextQuestion:i}=bn(),a=l=>{if(!l)return l;const c=JSON.parse(JSON.stringify(l));return c.lesson||(c.lesson="面积计算"),c.skill||(c.skill="面积公式应用"),c.objective||(c.objective="掌握面积计算方法"),(!c.knowledgePoints||!Array.isArray(c.knowledgePoints))&&(c.knowledgePoints=["面积公式","几何变换"]),c.difficulty||(c.difficulty=2),c.metadata||(c.metadata={topic:"几何",skill:"面积计算",tags:["面积","公式"]}),["question","solve","review","remember"].forEach(y=>{if(c.scenes?.[y]){const m=c.scenes[y];!m.items&&m.content&&(m.items=m.content),Array.isArray(m.items)||(m.items=[])}}),c},d=b.useMemo(()=>a(am),[]);return f.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${r}`,children:[f.jsxs("header",{className:"mb-8",children:[f.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[d.grade,"年级 - ",d.unit]})]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&f.jsx(St,{problemData:d,userAnswer:t,showAnswerForm:n,onAnswerSubmit:s,onAnswerChange:o}),e==="explanation"&&f.jsx(Kt,{problemData:d,userAnswer:t,onNextQuestion:i}),e==="success"&&f.jsx(Ct,{problemData:d,onNextQuestion:i})]})]})},Tt=Ut.create(r=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{r({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{r({userAnswer:e,validationError:null})},submitAnswer:e=>{const t=Tt.getState();if(!t.problemData){r({validationError:"问题数据未加载,请刷新页面重试"});return}const n=t.problemData.answer.value.toString(),o=e.trim(),s=n.trim();let i=!1;(o===s||o===".12"&&s==="0.12"||o==="0,12"&&s==="0.12")&&(i=!0),r({userAnswer:e,isCorrect:i,showAnswerForm:!1,validationError:null,currentScene:i?"success":"explanation"})},nextQuestion:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),mi=()=>Tt(r=>r.currentScene),hi=()=>Tt(r=>r.userAnswer),gi=()=>Tt(r=>r.showAnswerForm),cm=()=>Tt(r=>r.validationError),pi=()=>Tt(on.useShallow(r=>({updateUserAnswer:r.updateUserAnswer,submitAnswer:r.submitAnswer,nextQuestion:r.nextQuestion,resetSession:r.resetSession,setProblemData:r.setProblemData}))),dm={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?
251
+ `;const Iu="/api/v1/content",Fu="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",Pu=10,He="question",ne=Ft.create()(pi.devtools((r,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(t,n)=>{r({loading:!0,sessionId:t});try{const{gradeLevel:s,unitId:o,lessonId:i,count:a=Pu}=n,c=`${Iu}/grades/${s}/units/${o}/lessons/${i}/sessions/${t}/questions`,l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Fu}`},body:JSON.stringify({count:a})});if(!l.ok)throw new Error(`Failed to load questions: ${l.status} ${l.statusText}`);const u=(await l.json()).questions||[],y={};u.forEach(m=>{m.geometryShapes&&Array.isArray(m.geometryShapes)&&(y[m.problemId]=m.geometryShapes)}),r({problems:u,totalProblems:u.length,currentProblemIndex:0,currentScene:He,geometryShapes:y,loading:!1,error:null,startTime:Date.now()})}catch(s){const o=s instanceof Error?s.message:"Unknown error occurred";throw r({error:o,loading:!1}),s}},goToNextProblem:()=>{const{currentProblemIndex:t,problems:n,currentScene:s}=e();if(s!==He){console.warn("Cannot navigate during review/solve scene");return}t<n.length-1?r({currentProblemIndex:t+1,currentScene:He}):r({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:t,currentScene:n}=e();n===He&&t>0&&r({currentProblemIndex:t-1,currentScene:He})},goToProblem:t=>{const{problems:n,currentScene:s}=e();s===He&&(t<0||t>=n.length||r({currentProblemIndex:t,currentScene:He}))},switchScene:t=>{r({currentScene:t})},submitAnswer:async(t,n)=>{const{problems:s,currentProblemIndex:o}=e(),i=s[o];r({loading:!0});try{const a=i?.answer.correctAnswer||[],c=n.length>0&&n[0]===a[0],l={userAnswer:n,isCorrect:c,feedback:c?"🎉 Great job! Your answer is correct!":"❌ Sorry, that's not correct."};r(d=>({userAnswers:{...d.userAnswers,[t]:n},submissionResults:{...d.submissionResults,[t]:l},loading:!1,currentScene:c?"review":"solve"}))}catch(a){r({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(t,n)=>{r(s=>({userAnswers:{...s.userAnswers,[t]:n}}))},updateShape:(t,n,s)=>{r(o=>{const a=(o.geometryShapes[t]||[]).map(c=>c.id===n&&c.type==="point"?{...c,position:s}:c);return{geometryShapes:{...o.geometryShapes,[t]:a}}})},selectShape:(t,n)=>{r({selectedShapeId:n})},setGeometryMode:(t,n)=>{r({geometryMode:n})},startTimer:()=>{r({startTime:Date.now()})},stopTimer:()=>{const{startTime:t}=e();if(t){const n=Math.floor((Date.now()-t)/1e3);r(s=>({timeSpent:s.timeSpent+n,startTime:null}))}},reset:()=>{r({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:He,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:t,currentProblemIndex:n}=e();return t[n]||null},getProgress:()=>{const{currentProblemIndex:t,totalProblems:n}=e();return{current:t+1,total:n,percentage:n>0?(t+1)/n*100:0}},getSessionResults:()=>{const{sessionId:t,problems:n,submissionResults:s,timeSpent:o}=e(),i=n.map(c=>({problemId:c.problemId,userAnswer:s[c.problemId]?.userAnswer||[],isCorrect:s[c.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(c=>c.isCorrect).length;return{sessionId:t||"",totalProblems:n.length,correctAnswers:a,accuracy:n.length>0?a/n.length:0,timeSpent:o,averageTime:n.length>0?o/n.length:0,answers:i}}}),{name:"MathSessionStore"})),ni=(r,e,t,n,s,o,i)=>{const a=b.useMemo(()=>t==="question",[t]),c=b.useMemo(()=>r<e.length-1,[r,e.length]),l=b.useMemo(()=>r>0,[r]),d=b.useMemo(()=>!n||!s?!1:n.problemType?.includes("geometry")||o&&o[s]&&o[s].length>0?!0:i?.enableMathGraph!==void 0?i.enableMathGraph:!1,[n,s,o,i?.enableMathGraph]);return{canNavigate:a,canGoNext:c,canGoPrevious:l,shouldRenderMathGraph:d}},si=(r,e,t,n,s)=>{const o=ne(d=>d.selectShape),i=ne(d=>d.setGeometryMode),a=b.useMemo(()=>!e||!n?[]:n[e]||[],[n,e]);b.useEffect(()=>{if(!e||!t)return;let d="view";switch(r){case"question":d="edit";break;case"solve":case"review":d="view";break;default:d="view"}s!==d&&i(e,d)},[r,e,s,i,t]);const c=b.useCallback(d=>{e&&ne.setState(u=>({geometryShapes:{...u.geometryShapes,[e]:d}}))},[e]),l=b.useCallback(d=>{if(e){const u=d.length>0?d[0]:null;o(e,u)}},[e,o]);return{currentGeometryShapes:a,geometryMode:s,handleShapeChange:c,handleSelectionChange:l}},oi=(r,e,t)=>{const n=ne(m=>m.updateUserAnswer),s=ne(m=>m.submitAnswer),o=ne(m=>m.goToNextProblem),i=ne(m=>m.goToPreviousProblem),a=ne(m=>m.goToProblem),c=b.useCallback(m=>{r&&n(r,m)},[r,n]),l=b.useCallback(()=>{r&&t[r]&&s(r,t[r])},[r,t,s]),d=b.useCallback(m=>{o(),m?.(r,e+1)},[o,r,e]),u=b.useCallback(m=>{i(),m?.(r,e-1)},[i,r,e]),y=b.useCallback((m,h)=>{a(m-1),h?.(r,m-1)},[a,r]);return{handleAnswerChange:c,handleSubmit:l,handleNext:d,handlePrevious:u,handlePagination:y}},ii=({config:r={},onSessionComplete:e,onSessionExit:t,onProblemChange:n,className:s="",style:o})=>{const i=ne(j=>j.problems),a=ne(j=>j.currentProblemIndex),c=ne(j=>j.currentScene),l=ne(j=>j.loading),d=ne(j=>j.error),u=ne(j=>j.sessionComplete),y=ne(j=>j.submissionResults),m=ne(j=>j.userAnswers),h=ne(j=>j.geometryShapes),g=ne(j=>j.geometryMode),p=ne(j=>j.getSessionResults),x=b.useMemo(()=>i[a]??null,[i,a]),S=b.useMemo(()=>x?.problemId??"",[x]),{canNavigate:R,canGoNext:C,canGoPrevious:_,shouldRenderMathGraph:O}=ni(a,i,c,x,S,h,r),{currentGeometryShapes:w,handleShapeChange:F,handleSelectionChange:$}=si(c,S,O,h,g),{handleAnswerChange:k,handleSubmit:B,handleNext:W,handlePrevious:M,handlePagination:L}=oi(S,a,m);b.useEffect(()=>{if(u&&typeof p=="function"){const j=p();e?.(j)}},[u,p,e]);const J=j=>typeof j=="string"?j:j instanceof Error?j.message:String(j);return l&&i.length===0?f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),f.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):d&&d!==null?f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:f.jsxs("div",{className:"text-center text-red-600",children:[f.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),f.jsx("p",{children:J(d)})]})}):x?f.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:[f.jsx("div",{className:"mb-6",children:f.jsx(Ne.Pagination,{total:i.length,page:a+1,onChange:j=>L(j,n),isDisabled:!R,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),f.jsx(Ve,{problemData:x,scene:c,submissionResult:y[S],loading:l,error:d?J(d):void 0,value:m[S],onAnswerChange:k,onSubmit:B,onNext:()=>W(n),config:{theme:r.theme??"light",submitButtonText:"提交答案",nextButtonText:c==="solve"?"Got it!":"下一题",showHints:r.enableHints}}),O&&f.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:f.jsx(Ar,{shapes:w,mode:g,onShapeChange:F,onSelectionChange:$,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),r.showProgress&&f.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[f.jsx("button",{onClick:()=>M(n),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:"上一题"}),f.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),f.jsx("button",{onClick:()=>W(n),disabled:!C||!R,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:"下一题"})]}),t&&f.jsx("div",{className:"mt-4 flex justify-center",children:f.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):f.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:f.jsx("p",{className:"text-gray-600",children:"No problems available"})})},Du=({sessionId:r,gradeId:e,unitId:t,lessonId:n,userId:s,config:o={},className:i="",onSessionComplete:a,onSessionExit:c})=>{const[l,d]=b.useState({loading:!1,error:null,initialized:!1}),[u,y]=b.useState(0),[m,h]=b.useState(""),g=b.useRef(null),p=b.useRef(null),x=b.useRef(null),S=ne(F=>F.loadQuestions),R=ne(F=>F.reset);b.useEffect(()=>{const F=async()=>{try{d($=>({...$,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:r,gradeId:e,unitId:t,lessonId:n,userId:s}),await S(r,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:t,lessonId:n,count:o.questionCount||10}),d($=>({...$,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch($){const k=$ instanceof Error?$.message:"Failed to initialize session";d(B=>({...B,loading:!1,error:k,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",$)}};r&&e&&t&&n&&!l.initialized&&F()},[r,e,t,n,S,o.questionCount,l.initialized,u]),b.useEffect(()=>{l.loading&&!l.initialized?h("正在加载数学练习内容,请稍候..."):l.error?h(`加载失败:${l.error},请点击重试按钮重新加载`):l.initialized&&h("数学练习内容已加载完成,可以开始练习")},[l.loading,l.error,l.initialized]),b.useEffect(()=>{l.initialized&&g.current&&g.current.focus()},[l.initialized]),b.useEffect(()=>{l.error&&x.current&&x.current.focus()},[l.error]),b.useEffect(()=>{l.loading&&p.current&&p.current.focus()},[l.loading]),b.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),R()},[R]);const C=b.useCallback(F=>{console.log("🎉 MathSessionPage: 会话完成",F),a?.(F)},[a]),_=b.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),c?.()},[c]),O=b.useCallback((F,$)=>{console.log(`📝 MathSessionPage: 切换到题目 ${$+1}`,F)},[]),w=b.useCallback(F=>{F.key==="Escape"&&(F.preventDefault(),_()),F.key==="Enter"&&l.error&&F.target===x.current&&(F.preventDefault(),d({loading:!1,error:null,initialized:!1}),y($=>$+1))},[_,l.error]);return l.loading&&!l.initialized?f.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:w,tabIndex:-1,ref:p,children:[f.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:m}),f.jsx("div",{className:"page-loading-container",children:f.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[f.jsx("div",{className:"spinner","aria-hidden":"true"}),f.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):l.error?f.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:w,tabIndex:-1,ref:x,children:[f.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:m}),f.jsxs("div",{className:"error-container",children:[f.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),f.jsx("h3",{className:"error-title",children:"加载失败"}),f.jsx("p",{className:"error-message",children:l.error}),f.jsx("button",{onClick:()=>{d({loading:!1,error:null,initialized:!1}),y(F=>F+1)},className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):f.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:w,children:[f.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:m}),o.layout?.showHeader&&f.jsx("header",{className:"page-header",role:"banner",children:f.jsxs("div",{className:"header-content",children:[f.jsx("h1",{className:"page-title",children:"数学练习"}),f.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[f.jsxs("span",{className:"session-id",children:["会话: ",r]}),f.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),f.jsx("main",{className:"page-main",ref:g,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:f.jsx(ii,{config:{showProgress:o.showProgress??!0,enableHints:o.enableHints??!1,autoAdvance:o.autoAdvance??!1,theme:o.theme??"light"},onSessionComplete:C,onSessionExit:_,onProblemChange:O})}),o.layout?.showFooter&&f.jsx("footer",{className:"page-footer",role:"contentinfo",children:f.jsx("div",{className:"footer-content",children:f.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},Lu=b.memo(Du),Uu=({problemData:r,userAnswer:e,onNextQuestion:t})=>f.jsxs("div",{children:[f.jsxs("div",{className:"decimal-error-banner",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),f.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",f.jsx("strong",{children:r.answer.value})]})]}),f.jsx("button",{onClick:t,className:"decimal-understand-button",children:"明白了"})]}),f.jsxs("div",{className:"decimal-content-area",children:[f.jsx(vn,{problemData:r,userAnswer:e}),f.jsx(_n,{problemData:r})]}),f.jsx("div",{className:"decimal-bottom-area",children:f.jsx("button",{onClick:t,className:"decimal-bottom-button",children:"明白了"})})]}),Gu="rectangle-area-003",zu="矩形面积计算问题",Bu=5,Vu="几何与测量",qu="计算矩形的面积,理解面积公式 A = l × w 的应用",Wu={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},Hu=[{type:"text",content:"What is the area of this rectangle?"}],Yu={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"}}]}},Ku=[{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}}}],Xu={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},Ju={type:"card",padding:"20px"},Zu={id:Gu,title:zu,grade:Bu,unit:Vu,description:qu,basicInfo:Wu,content:Hu,scenes:Yu,explanation:Ku,answer:Xu,layout:Ju},Qu=({className:r=""})=>{const e=fn(),t=un(),n=mn(),{updateUserAnswer:s,submitAnswer:o,nextQuestion:i}=hn(),a=l=>{if(!l)return l;const d=JSON.parse(JSON.stringify(l));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(y=>{if(d.scenes?.[y]){const m=d.scenes[y];!m.items&&m.content&&(m.items=m.content),Array.isArray(m.items)||(m.items=[])}}),d},c=b.useMemo(()=>a(Zu),[]);return f.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${r}`,children:[f.jsxs("header",{className:"mb-8",children:[f.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[c.grade,"年级 - ",c.unit]})]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&f.jsx(wt,{problemData:c,userAnswer:t,showAnswerForm:n,onAnswerSubmit:o,onAnswerChange:s}),e==="explanation"&&f.jsx(qt,{problemData:c,userAnswer:t,onNextQuestion:i}),e==="success"&&f.jsx(At,{problemData:c,onNextQuestion:i})]})]})},St=Ft.create(r=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{r({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{r({userAnswer:e,validationError:null})},submitAnswer:e=>{const t=St.getState();if(!t.problemData){r({validationError:"问题数据未加载,请刷新页面重试"});return}const n=t.problemData.answer.value.toString(),s=e.trim(),o=n.trim();let i=!1;(s===o||s===".12"&&o==="0.12"||s==="0,12"&&o==="0.12")&&(i=!0),r({userAnswer:e,isCorrect:i,showAnswerForm:!1,validationError:null,currentScene:i?"success":"explanation"})},nextQuestion:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),ai=()=>St(r=>r.currentScene),li=()=>St(r=>r.userAnswer),ci=()=>St(r=>r.showAnswerForm),em=()=>St(r=>r.validationError),di=()=>St(en.useShallow(r=>({updateUserAnswer:r.updateUserAnswer,submitAnswer:r.submitAnswer,nextQuestion:r.nextQuestion,resetSession:r.resetSession,setProblemData:r.setProblemData}))),tm={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?
257
252
  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?
258
- 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。"}},fm=({className:r="",problemData:e})=>{const t=mi(),n=hi(),o=gi(),s=cm(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:d,setProblemData:l}=pi(),c=b.useMemo(()=>e||dm,[e]);return b.useEffect(()=>{l(c)},[c,l]),f.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${r}`,children:[f.jsxs("header",{className:"mb-8",children:[f.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[c.grade,"年级 - ",c.unit]}),f.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(St,{problemData:c,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),t==="explanation"&&f.jsx(Ku,{problemData:c,userAnswer:n,onNextQuestion:d}),t==="success"&&f.jsx(Ct,{problemData:c,onNextQuestion:d})]}),f.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[t==="question"&&"请识别百格图代表的小数",t==="explanation"&&"查看详细解释",t==="success"&&"恭喜!答案正确"]})]})},Ie=(r,e,t)=>({x:r.x+(e.x-r.x)*t,y:r.y+(e.y-r.y)*t}),um=()=>{const r={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},t={x:.9,y:.75,name:"C"},n={...Ie(r,e,1/3),name:"D"},o={...Ie(r,t,1/3),name:"E"},s={...Ie(r,e,2/3),name:"M"},i={...Ie(r,t,2/3),name:"N"},a={...Ie(e,t,1/3),name:"P"},d={...Ie(e,t,2/3),name:"Q"},l={...Ie(n,o,1/3),name:"U"},c={...Ie(n,o,2/3),name:"S"},u={...Ie(s,i,1/3),name:"K"},y={...Ie(s,i,2/3),name:"L"};return{A:r,B:e,C:t,D:n,E:o,M:s,N:i,P:a,Q:d,U:l,S:c,K:u,L:y}},mm=(r,e,t)=>{const n={};for(const[o,s]of Object.entries(r))n[o]={...s,x:s.x*e,y:s.y*t};return n},hm=(r,e)=>{const[t,n,o]=e,{x:s,y:i}=r,a=(n.y-o.y)*(t.x-o.x)+(o.x-n.x)*(t.y-o.y);if(Math.abs(a)<1e-4)return!1;const d=((n.y-o.y)*(s-o.x)+(o.x-n.x)*(i-o.y))/a,l=((o.y-t.y)*(s-o.x)+(t.x-o.x)*(i-o.y))/a,c=1-d-l;return d>=-.001&&l>=-.001&&c>=-.001},gm=(r,e)=>{if(!r||!e||r.length!==3||e.length!==3)return!1;const t=r.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return t.every((o,s)=>o===n[s])},pm=(r,e)=>{if(!r||!e||r.length!==e.length)return!1;const t=r.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return t.join("")===n.join("")},ym=()=>[{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"}],bm=()=>[{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"}],xm={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},yi=(r=Yt.id)=>{const e=de.units.map((o,s)=>{const i=Math.min(100,Math.max(0,s*15+Math.random()*20)),a=Math.floor(o.lessons.length*i/100),d=o.lessons.map((l,c)=>{const u=Math.min(100,Math.max(0,i-c*10+Math.random()*30));return{lessonId:l.id,status:u>=100?"completed":u>0?"in-progress":"not-started",progressPercentage:Math.round(u),lastAccessed:u>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:u>0?Math.floor(Math.random()*120+10):void 0,score:u>=100?Math.floor(Math.random()*21+80):void 0,attempts:u>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:o.id,userId:r,totalLessons:o.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:d}}),t=e.reduce((o,s)=>o+s.progressPercentage,0)/e.length,n=e.filter(o=>o.status==="completed").length;return{courseId:de.id,userId:r,totalUnits:e.length,completedUnits:n,progressPercentage:Math.round(t),status:t>=100?"completed":t>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},bi=yi(),On=(r,e)=>r===Yt.id&&e===de.id?bi:null,xi=(r,e,t)=>{const n=On(r,e);return n&&n.units.find(o=>o.unitId===t)||null},vm=(r,e,t,n)=>{const o=xi(r,e,t);return o&&o.lessons.find(s=>s.lessonId===n)||null},_m=(r,e,t,n,o)=>(console.log("Updating lesson progress:",{userId:r,courseId:e,unitId:t,lessonId:n,progress:o}),!0),jn=(r,e)=>{const t=On(r,e);if(!t)return null;const n=de.units.map((o,s)=>{const i=t.units.find(a=>a.unitId===o.id);return{unitId:o.id,title:o.title,description:o.description,moduleCategory:o.moduleCategory,estimatedDuration:o.estimatedDuration,totalLessons:o.lessons.length,completedLessons:i?.completedLessons||0,progressPercentage:i?.progressPercentage||0,status:i?.status||"not-started",lastAccessed:i?.lastAccessed,isActive:s===0,route:`/math/grade-${de.level}/unit/${o.id}`}});return{userId:r,courseId:de.id,courseTitle:de.title,courseLevel:de.level,totalUnits:n.length,completedUnits:n.filter(o=>o.status==="completed").length,overallProgress:t.progressPercentage,status:t.status,lastAccessed:t.lastAccessed,units:n}},wm=(r,e,t)=>{const n=jn(r,e);return n&&n.units.find(o=>o.unitId===t)||null},Am=(r,e,t,n)=>(console.log("Updating unit active status:",{userId:r,courseId:e,unitId:t,isActive:n}),!0),Rm=jn(Yt.id,de.id),Sm={userId:Yt.id,courseId:de.id,courseTitle:de.title,courseLevel:de.level,totalUnits:de.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:"📊"}]},Cm=({className:r="",problemData:e,children:t})=>{const n=xn(),o=vn(),s=_n(),i=wn(),{updateUserAnswer:a,submitAnswer:d,nextQuestion:l,setProblemData:c}=An();b.useEffect(()=>{e&&c(e)},[e,c]);const y=(()=>{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 f.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[f.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[f.jsxs("div",{children:[f.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${y.titleColor}`,children:e?.title||"数学问题练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),f.jsx("div",{className:"mt-4 md:mt-0",children:f.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:y.label})})]}),e?.description&&f.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),f.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden",children:e?f.jsxs(f.Fragment,{children:[n==="question"&&f.jsx(St,{problemData:e,userAnswer:o,showAnswerForm:s,onAnswerSubmit:d,onAnswerChange:a,validationError:i}),n==="explanation"&&f.jsx(Kt,{problemData:e,userAnswer:o,onNextQuestion:l}),n==="success"&&f.jsx(Ct,{problemData:e,onNextQuestion:l})]}):f.jsxs("div",{className:"p-8 text-center",children:[f.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),f.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),f.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),f.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:f.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[f.jsx("div",{className:"mb-4 md:mb-0",children:f.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),f.jsx("div",{children:f.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),t&&f.jsx("div",{className:"w-full max-w-4xl mt-8",children:t})]})},Em=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
259
- 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AbilityAssessmentDashboard=ic;exports.AbilityProgressBar=ps;exports.AreaGeometrySessionPage=Cm;exports.Button=xt;exports.ContentAccordion=wo;exports.DEFAULT_IXL_CONFIG=Xl;exports.DecimalNumberRecognitionSessionPage=fm;exports.EquationRender=qt;exports.ExplanationScene=Kt;exports.GEOMETRY_CONFIG=xm;exports.GeometryProblemAdapterV4=nd;exports.GeometryTransform=Xo;exports.GradeNavigation=Ql;exports.GradeUnitBrowserPage=_c;exports.GradeUnitBrowserProvider=_s;exports.GraphContainer=ds;exports.HundredChart=ns;exports.IXLStyleCard=wt;exports.IXL_COLORS=Jl;exports.IXL_LABELS=Zl;exports.InputValidator=Zr;exports.MOCK_USER_COURSE_PROGRESS=bi;exports.MOCK_USER_GRADE_UNITS_NAV=Rm;exports.MOCK_USER_GRADE_UNITS_PROGRESS=Sm;exports.MathCard=Em;exports.MathCardV2=Re;exports.MathGraph=Tr;exports.MathPracticeSessionPage=lm;exports.MathSessionContainer=ui;exports.MathSessionPage=Hu;exports.MathWizHeader=Yo;exports.OutputValidator=Qr;exports.ParallelogramAreaCalculationSessionPage=If;exports.PersonalizedAdvicePanel=ys;exports.QuestionScene=St;exports.RadarChart=gs;exports.RecommendationCard=bs;exports.RememberModule=As;exports.ReviewModule=Rn;exports.SCHEMA_VERSION=Ls;exports.Sidebar=Ao;exports.SolveModule=Sn;exports.Submenu=sn;exports.SuccessScene=Ct;exports.TriangleAreaCalculationSessionPage=Ff;exports.UserProfile=qo;exports.VERSION=od;exports.ValidationManager=ft;exports.adaptGeometryData=Cn;exports.adaptGeometryDataAsync=Cn;exports.adaptGeometryDataSync=ut;exports.adaptGeometryDataV4=ut;exports.benchmarkAdapter=rd;exports.calculateBoundingBox=mn;exports.calculateDragRange=ts;exports.calculateFilledCells=Qo;exports.calculateGamePoints=um;exports.calculateValueFromDrag=rs;exports.categoryIcons=Ft;exports.checkCompatibility=sd;exports.comparePointArrays=pm;exports.courseData=de;exports.createAsyncAdapter=Ds;exports.createGeometryDataAdapter=Ds;exports.createSyncAdapter=Ps;exports.exploreItems=fc;exports.formatPercentage=Pl;exports.generateCellData=es;exports.generateMockUserCourseProgress=yi;exports.getBasicGemDefinitions=bm;exports.getBasicLineDefinitions=ym;exports.getUnitNavItem=wm;exports.getUserCourseProgress=On;exports.getUserGradeUnitsNav=jn;exports.getUserLessonProgress=vm;exports.getUserUnitProgress=xi;exports.isGeometryProblem=id;exports.isPointInTriangle=hm;exports.isV4Format=Us;exports.loadGeometryProblemData=Fs;exports.loadGeometryProblemDataAsync=Fs;exports.loadGeometryProblemDataSync=Is;exports.loadGeometryProblemDataV4=Is;exports.pointOnLine=Ie;exports.statusColors=lc;exports.statusMapping=ac;exports.toPixelCoordinates=mm;exports.trianglesMatch=gm;exports.updateUnitActiveStatus=Am;exports.updateUserLessonProgress=_m;exports.useAnswerCorrectness=Rc;exports.useAnswerFormVisibility=yn;exports.useCurrentScene=gn;exports.useDataAdapter=os;exports.useDecimalAnswerFormVisibility=gi;exports.useDecimalCurrentScene=mi;exports.useDecimalSessionActions=pi;exports.useDecimalUserAnswer=hi;exports.useGeometryManagement=di;exports.useGradeUnitBrowser=vs;exports.useHundredChartDrag=Zo;exports.useHundredChartStore=un;exports.useHundredChartValue=Jo;exports.useIXLStyle=ms;exports.useMathPracticeSessionStore=et;exports.useProblemData=Sc;exports.useResponsive=hs;exports.useSessionActions=bn;exports.useSessionCalculations=ci;exports.useSessionEventHandlers=fi;exports.useSessionStore=ce;exports.useUserAnswer=pn;exports.useValidationError=ws;exports.userData=uc;exports.validateGeometryData=td;exports.validateValue=dr;
253
+ 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。"}},rm=({className:r="",problemData:e})=>{const t=ai(),n=li(),s=ci(),o=em(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=di(),d=b.useMemo(()=>e||tm,[e]);return b.useEffect(()=>{l(d)},[d,l]),f.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${r}`,children:[f.jsxs("header",{className:"mb-8",children:[f.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[d.grade,"年级 - ",d.unit]}),f.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),f.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[t==="question"&&f.jsx(wt,{problemData:d,userAnswer:n,showAnswerForm:s,onAnswerSubmit:a,onAnswerChange:i,validationError:o}),t==="explanation"&&f.jsx(Uu,{problemData:d,userAnswer:n,onNextQuestion:c}),t==="success"&&f.jsx(At,{problemData:d,onNextQuestion:c})]}),f.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[t==="question"&&"请识别百格图代表的小数",t==="explanation"&&"查看详细解释",t==="success"&&"恭喜!答案正确"]})]})},Oe=(r,e,t)=>({x:r.x+(e.x-r.x)*t,y:r.y+(e.y-r.y)*t}),nm=()=>{const r={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},t={x:.9,y:.75,name:"C"},n={...Oe(r,e,1/3),name:"D"},s={...Oe(r,t,1/3),name:"E"},o={...Oe(r,e,2/3),name:"M"},i={...Oe(r,t,2/3),name:"N"},a={...Oe(e,t,1/3),name:"P"},c={...Oe(e,t,2/3),name:"Q"},l={...Oe(n,s,1/3),name:"U"},d={...Oe(n,s,2/3),name:"S"},u={...Oe(o,i,1/3),name:"K"},y={...Oe(o,i,2/3),name:"L"};return{A:r,B:e,C:t,D:n,E:s,M:o,N:i,P:a,Q:c,U:l,S:d,K:u,L:y}},sm=(r,e,t)=>{const n={};for(const[s,o]of Object.entries(r))n[s]={...o,x:o.x*e,y:o.y*t};return n},om=(r,e)=>{const[t,n,s]=e,{x:o,y:i}=r,a=(n.y-s.y)*(t.x-s.x)+(s.x-n.x)*(t.y-s.y);if(Math.abs(a)<1e-4)return!1;const c=((n.y-s.y)*(o-s.x)+(s.x-n.x)*(i-s.y))/a,l=((s.y-t.y)*(o-s.x)+(t.x-s.x)*(i-s.y))/a,d=1-c-l;return c>=-.001&&l>=-.001&&d>=-.001},im=(r,e)=>{if(!r||!e||r.length!==3||e.length!==3)return!1;const t=r.map(s=>s.name).sort(),n=e.map(s=>s.name).sort();return t.every((s,o)=>s===n[o])},am=(r,e)=>{if(!r||!e||r.length!==e.length)return!1;const t=r.map(s=>s.name).sort(),n=e.map(s=>s.name).sort();return t.join("")===n.join("")},lm=()=>[{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"}],cm=()=>[{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"}],dm={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},fi=(r=Bt.id)=>{const e=se.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),c=s.lessons.map((l,d)=>{const u=Math.min(100,Math.max(0,i-d*10+Math.random()*30));return{lessonId:l.id,status:u>=100?"completed":u>0?"in-progress":"not-started",progressPercentage:Math.round(u),lastAccessed:u>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:u>0?Math.floor(Math.random()*120+10):void 0,score:u>=100?Math.floor(Math.random()*21+80):void 0,attempts:u>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:s.id,userId:r,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:c}}),t=e.reduce((s,o)=>s+o.progressPercentage,0)/e.length,n=e.filter(s=>s.status==="completed").length;return{courseId:se.id,userId:r,totalUnits:e.length,completedUnits:n,progressPercentage:Math.round(t),status:t>=100?"completed":t>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},ui=fi(),Tn=(r,e)=>r===Bt.id&&e===se.id?ui:null,mi=(r,e,t)=>{const n=Tn(r,e);return n&&n.units.find(s=>s.unitId===t)||null},fm=(r,e,t,n)=>{const s=mi(r,e,t);return s&&s.lessons.find(o=>o.lessonId===n)||null},um=(r,e,t,n,s)=>(console.log("Updating lesson progress:",{userId:r,courseId:e,unitId:t,lessonId:n,progress:s}),!0),Nn=(r,e)=>{const t=Tn(r,e);if(!t)return null;const n=se.units.map((s,o)=>{const i=t.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-${se.level}/unit/${s.id}`}});return{userId:r,courseId:se.id,courseTitle:se.title,courseLevel:se.level,totalUnits:n.length,completedUnits:n.filter(s=>s.status==="completed").length,overallProgress:t.progressPercentage,status:t.status,lastAccessed:t.lastAccessed,units:n}},mm=(r,e,t)=>{const n=Nn(r,e);return n&&n.units.find(s=>s.unitId===t)||null},hm=(r,e,t,n)=>(console.log("Updating unit active status:",{userId:r,courseId:e,unitId:t,isActive:n}),!0),gm=Nn(Bt.id,se.id),pm={userId:Bt.id,courseId:se.id,courseTitle:se.title,courseLevel:se.level,totalUnits:se.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:"📊"}]},ym=({className:r="",problemData:e,children:t})=>{const n=gn(),s=pn(),o=yn(),i=bn(),{updateUserAnswer:a,submitAnswer:c,nextQuestion:l,setProblemData:d}=xn();b.useEffect(()=>{e&&d(e)},[e,d]);const y=(()=>{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 f.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[f.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[f.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[f.jsxs("div",{children:[f.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${y.titleColor}`,children:e?.title||"数学问题练习"}),f.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),f.jsx("div",{className:"mt-4 md:mt-0",children:f.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:y.label})})]}),e?.description&&f.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),f.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden",children:e?f.jsxs(f.Fragment,{children:[n==="question"&&f.jsx(wt,{problemData:e,userAnswer:s,showAnswerForm:o,onAnswerSubmit:c,onAnswerChange:a,validationError:i}),n==="explanation"&&f.jsx(qt,{problemData:e,userAnswer:s,onNextQuestion:l}),n==="success"&&f.jsx(At,{problemData:e,onNextQuestion:l})]}):f.jsxs("div",{className:"p-8 text-center",children:[f.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),f.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),f.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),f.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:f.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[f.jsx("div",{className:"mb-4 md:mb-0",children:f.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),f.jsx("div",{children:f.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),t&&f.jsx("div",{className:"w-full max-w-4xl mt-8",children:t})]})},bm=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
254
+ 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AbilityAssessmentDashboard=Jl;exports.AbilityProgressBar=co;exports.AreaGeometrySessionPage=ym;exports.Button=pt;exports.ContentAccordion=gs;exports.DEFAULT_IXL_CONFIG=Gl;exports.DecimalNumberRecognitionSessionPage=rm;exports.EquationRender=zt;exports.ExplanationScene=qt;exports.GEOMETRY_CONFIG=dm;exports.GeometryProblemAdapterV4=Yc;exports.GeometryTransform=Bs;exports.GradeNavigation=Vl;exports.GradeUnitBrowserPage=uc;exports.GradeUnitBrowserProvider=go;exports.GraphContainer=no;exports.HundredChart=Xs;exports.IXLStyleCard=xt;exports.IXL_COLORS=zl;exports.IXL_LABELS=Bl;exports.InputValidator=Yr;exports.MOCK_USER_COURSE_PROGRESS=ui;exports.MOCK_USER_GRADE_UNITS_NAV=gm;exports.MOCK_USER_GRADE_UNITS_PROGRESS=pm;exports.MathCard=bm;exports.MathCardV2=_e;exports.MathGraph=Ar;exports.MathPracticeSessionPage=Qu;exports.MathSessionContainer=ii;exports.MathSessionPage=Lu;exports.MathWizHeader=Us;exports.OutputValidator=Kr;exports.ParallelogramAreaCalculationSessionPage=Cf;exports.PersonalizedAdvicePanel=fo;exports.QuestionScene=wt;exports.RadarChart=lo;exports.RecommendationCard=uo;exports.RememberModule=yo;exports.ReviewModule=vn;exports.SCHEMA_VERSION=jo;exports.Sidebar=ps;exports.SolveModule=_n;exports.Submenu=tn;exports.SuccessScene=At;exports.TriangleAreaCalculationSessionPage=Ef;exports.UserProfile=Ls;exports.VERSION=Kc;exports.ValidationManager=lt;exports.adaptGeometryData=wn;exports.adaptGeometryDataAsync=wn;exports.adaptGeometryDataSync=ct;exports.adaptGeometryDataV4=ct;exports.benchmarkAdapter=Hc;exports.calculateBoundingBox=cn;exports.calculateDragRange=Ys;exports.calculateFilledCells=Ws;exports.calculateGamePoints=nm;exports.calculateValueFromDrag=Ks;exports.categoryIcons=Ot;exports.checkCompatibility=Xc;exports.comparePointArrays=am;exports.courseData=se;exports.createAsyncAdapter=Oo;exports.createGeometryDataAdapter=Oo;exports.createSyncAdapter=ko;exports.exploreItems=rc;exports.formatPercentage=Tl;exports.generateCellData=Hs;exports.generateMockUserCourseProgress=fi;exports.getBasicGemDefinitions=cm;exports.getBasicLineDefinitions=lm;exports.getUnitNavItem=mm;exports.getUserCourseProgress=Tn;exports.getUserGradeUnitsNav=Nn;exports.getUserLessonProgress=fm;exports.getUserUnitProgress=mi;exports.isGeometryProblem=Jc;exports.isPointInTriangle=om;exports.isV4Format=Mo;exports.loadGeometryProblemData=$o;exports.loadGeometryProblemDataAsync=$o;exports.loadGeometryProblemDataSync=No;exports.loadGeometryProblemDataV4=No;exports.pointOnLine=Oe;exports.statusColors=Ql;exports.statusMapping=Zl;exports.toPixelCoordinates=sm;exports.trianglesMatch=im;exports.updateUnitActiveStatus=hm;exports.updateUserLessonProgress=um;exports.useAnswerCorrectness=gc;exports.useAnswerFormVisibility=mn;exports.useCurrentScene=fn;exports.useDataAdapter=Js;exports.useDecimalAnswerFormVisibility=ci;exports.useDecimalCurrentScene=ai;exports.useDecimalSessionActions=di;exports.useDecimalUserAnswer=li;exports.useGeometryManagement=si;exports.useGradeUnitBrowser=ho;exports.useHundredChartDrag=qs;exports.useHundredChartStore=ln;exports.useHundredChartValue=Vs;exports.useIXLStyle=io;exports.useMathPracticeSessionStore=Xe;exports.useProblemData=pc;exports.useResponsive=ao;exports.useSessionActions=hn;exports.useSessionCalculations=ni;exports.useSessionEventHandlers=oi;exports.useSessionStore=ne;exports.useUserAnswer=un;exports.useValidationError=po;exports.userData=nc;exports.validateGeometryData=Wc;exports.validateValue=or;
260
255
  //# sourceMappingURL=index.cjs.map