@mathwiz/ui-components 0.1.30 → 0.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/components/AICopilot/AICopilot.css +237 -0
  2. package/dist/components/AICopilot/AICopilot.d.ts +10 -0
  3. package/dist/components/AICopilot/AICopilot.d.ts.map +1 -0
  4. package/dist/components/AICopilot/components/ChatContainer.d.ts +9 -0
  5. package/dist/components/AICopilot/components/ChatContainer.d.ts.map +1 -0
  6. package/dist/components/AICopilot/components/ChatInput.d.ts +9 -0
  7. package/dist/components/AICopilot/components/ChatInput.d.ts.map +1 -0
  8. package/dist/components/AICopilot/components/ChatMessage.d.ts +9 -0
  9. package/dist/components/AICopilot/components/ChatMessage.d.ts.map +1 -0
  10. package/dist/components/AICopilot/components/CollapsibleContextBar.d.ts +9 -0
  11. package/dist/components/AICopilot/components/CollapsibleContextBar.d.ts.map +1 -0
  12. package/dist/components/AICopilot/components/QuickActions.d.ts +9 -0
  13. package/dist/components/AICopilot/components/QuickActions.d.ts.map +1 -0
  14. package/dist/components/AICopilot/components/StreamMessage.d.ts +9 -0
  15. package/dist/components/AICopilot/components/StreamMessage.d.ts.map +1 -0
  16. package/dist/components/AICopilot/index.d.ts +12 -0
  17. package/dist/components/AICopilot/index.d.ts.map +1 -0
  18. package/dist/components/AICopilot/store.d.ts +30 -0
  19. package/dist/components/AICopilot/store.d.ts.map +1 -0
  20. package/dist/components/AICopilot/types.d.ts +219 -0
  21. package/dist/components/AICopilot/types.d.ts.map +1 -0
  22. package/dist/components/MathCardV2/MathCardV2.types.d.ts +20 -1
  23. package/dist/components/MathCardV2/MathCardV2.types.d.ts.map +1 -1
  24. package/dist/components/MathCardV2/components/content/MathContainerContent.d.ts +16 -0
  25. package/dist/components/MathCardV2/components/content/MathContainerContent.d.ts.map +1 -0
  26. package/dist/components/MathCardV2/components/renderers/ContentRenderer.d.ts.map +1 -1
  27. package/dist/components/MathCardV2/hooks/useDataAdapter.d.ts.map +1 -1
  28. package/dist/components/MathCardV2/hooks/useMeetingProblemAdapter.d.ts.map +1 -1
  29. package/dist/components/MathCell/MathCell.d.ts +35 -0
  30. package/dist/components/MathCell/MathCell.d.ts.map +1 -0
  31. package/dist/components/MathCell/MathCell.styles.d.ts +149 -0
  32. package/dist/components/MathCell/MathCell.styles.d.ts.map +1 -0
  33. package/dist/components/MathCell/MathCell.types.d.ts +76 -0
  34. package/dist/components/MathCell/MathCell.types.d.ts.map +1 -0
  35. package/dist/components/MathCell/index.d.ts +11 -0
  36. package/dist/components/MathCell/index.d.ts.map +1 -0
  37. package/dist/components/MathContainer/FactorTable/FactorTable.d.ts +17 -0
  38. package/dist/components/MathContainer/FactorTable/FactorTable.d.ts.map +1 -0
  39. package/dist/components/MathContainer/FactorTable/FactorTable.types.d.ts +55 -0
  40. package/dist/components/MathContainer/FactorTable/FactorTable.types.d.ts.map +1 -0
  41. package/dist/components/MathContainer/FactorTable/FactorTableView.d.ts +28 -0
  42. package/dist/components/MathContainer/FactorTable/FactorTableView.d.ts.map +1 -0
  43. package/dist/components/MathContainer/FactorTable/index.d.ts +7 -0
  44. package/dist/components/MathContainer/FactorTable/index.d.ts.map +1 -0
  45. package/dist/components/MathContainer/LongDivision/LongDivision.d.ts +12 -0
  46. package/dist/components/MathContainer/LongDivision/LongDivision.d.ts.map +1 -0
  47. package/dist/components/MathContainer/LongDivision/LongDivision.layout.d.ts +81 -0
  48. package/dist/components/MathContainer/LongDivision/LongDivision.layout.d.ts.map +1 -0
  49. package/dist/components/MathContainer/LongDivision/LongDivision.types.d.ts +37 -0
  50. package/dist/components/MathContainer/LongDivision/LongDivision.types.d.ts.map +1 -0
  51. package/dist/components/MathContainer/LongDivision/LongDivisionView.d.ts +37 -0
  52. package/dist/components/MathContainer/LongDivision/LongDivisionView.d.ts.map +1 -0
  53. package/dist/components/MathContainer/LongDivision/index.d.ts +7 -0
  54. package/dist/components/MathContainer/LongDivision/index.d.ts.map +1 -0
  55. package/dist/components/MathContainer/MathContainer.types.d.ts +151 -0
  56. package/dist/components/MathContainer/MathContainer.types.d.ts.map +1 -0
  57. package/dist/components/MathContainer/ShortDivision/ShortDivision.d.ts +15 -0
  58. package/dist/components/MathContainer/ShortDivision/ShortDivision.d.ts.map +1 -0
  59. package/dist/components/MathContainer/ShortDivision/ShortDivision.types.d.ts +67 -0
  60. package/dist/components/MathContainer/ShortDivision/ShortDivision.types.d.ts.map +1 -0
  61. package/dist/components/MathContainer/ShortDivision/ShortDivisionView.d.ts +16 -0
  62. package/dist/components/MathContainer/ShortDivision/ShortDivisionView.d.ts.map +1 -0
  63. package/dist/components/MathContainer/ShortDivision/index.d.ts +8 -0
  64. package/dist/components/MathContainer/ShortDivision/index.d.ts.map +1 -0
  65. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplication.d.ts +16 -0
  66. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplication.d.ts.map +1 -0
  67. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplication.types.d.ts +42 -0
  68. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplication.types.d.ts.map +1 -0
  69. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplicationView.d.ts +22 -0
  70. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplicationView.d.ts.map +1 -0
  71. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplicationView.utils.d.ts +19 -0
  72. package/dist/components/MathContainer/VerticalMultiplication/VerticalMultiplicationView.utils.d.ts.map +1 -0
  73. package/dist/components/MathContainer/VerticalMultiplication/index.d.ts +9 -0
  74. package/dist/components/MathContainer/VerticalMultiplication/index.d.ts.map +1 -0
  75. package/dist/components/MathContainer/hooks/index.d.ts +15 -0
  76. package/dist/components/MathContainer/hooks/index.d.ts.map +1 -0
  77. package/dist/components/MathContainer/hooks/useFactorTable.d.ts +39 -0
  78. package/dist/components/MathContainer/hooks/useFactorTable.d.ts.map +1 -0
  79. package/dist/components/MathContainer/hooks/useLongDivision.d.ts +51 -0
  80. package/dist/components/MathContainer/hooks/useLongDivision.d.ts.map +1 -0
  81. package/dist/components/MathContainer/hooks/useLongDivision.utils.d.ts +15 -0
  82. package/dist/components/MathContainer/hooks/useLongDivision.utils.d.ts.map +1 -0
  83. package/dist/components/MathContainer/hooks/useShortDivision.d.ts +41 -0
  84. package/dist/components/MathContainer/hooks/useShortDivision.d.ts.map +1 -0
  85. package/dist/components/MathContainer/hooks/useVerticalMultiplication.d.ts +28 -0
  86. package/dist/components/MathContainer/hooks/useVerticalMultiplication.d.ts.map +1 -0
  87. package/dist/components/MathContainer/hooks/useVerticalMultiplication.utils.d.ts +30 -0
  88. package/dist/components/MathContainer/hooks/useVerticalMultiplication.utils.d.ts.map +1 -0
  89. package/dist/components/MathContainer/index.d.ts +17 -0
  90. package/dist/components/MathContainer/index.d.ts.map +1 -0
  91. package/dist/components/dashboard/atoms/Badge/Badge.d.ts +32 -0
  92. package/dist/components/dashboard/atoms/Badge/Badge.d.ts.map +1 -0
  93. package/dist/components/dashboard/atoms/Badge/index.d.ts +4 -0
  94. package/dist/components/dashboard/atoms/Badge/index.d.ts.map +1 -0
  95. package/dist/index.cjs +129 -101
  96. package/dist/index.cjs.map +1 -1
  97. package/dist/index.d.ts +9 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.mjs +6214 -4315
  100. package/dist/index.mjs.map +1 -1
  101. package/dist/mathwiz-ui.css +1 -1
  102. package/dist/style.css +1 -1
  103. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,22 +1,50 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),x=require("react"),il=require("@heroui/progress"),bn=require("@heroui/card"),Ln=require("lucide-react"),Ue=require("@heroui/react"),al=require("katex"),Ms=require("jsxgraph"),gr=require("zustand"),Os=require("zustand/shallow"),lo=require("zustand/react/shallow"),ll=require("zustand/middleware");function cl(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ve=cl(x),ut=({progress:t,variant:e="solid",size:r="md",radius:n="md",children:o,className:s="",loading:i,intent:a,useNewClassName:c=!1,...l})=>{const g=t!==void 0?(h=>{const y=c?"mathwiz-btn--":"button--";return h===0?`${y}primary`:h===100?`${y}success`:`${y}secondary`})(t):c?"mathwiz-btn--primary":"button--primary",p=c?"mathwiz-btn":"button",f=c?"mathwiz-btn--":"button--",m=[p,`${f}${r}`,`${f}${e}`,`${f}radius-${n}`,g,i&&`${f}loading`,a&&c?`mathwiz-btn--${a}`:null,s].filter(Boolean).join(" ");return u.jsx("button",{type:"button",className:m,"data-progress":t,disabled:i||l.disabled,...l,children:i?"加载中...":o})},Uo=t=>t===0?"开始学习":t===100?"复习":"继续学习",dl=t=>{if(t.length===0)return 0;const e=t.reduce((r,n)=>r+n.progress,0);return Math.round(e/t.length)},ul=({knowledgeItem:t,onLearnAction:e})=>{const r=()=>{e(t)};return console.log("KnowledgeCard render:",{progress:t.progress,text:Uo(t.progress)}),u.jsxs(bn.Card,{className:"content-accordion__knowledge-card",children:[u.jsxs(bn.CardBody,{children:[u.jsx("h3",{className:"content-accordion__knowledge-title",children:t.title}),u.jsx("p",{className:"content-accordion__knowledge-description",children:t.description})]}),u.jsxs(bn.CardFooter,{className:"content-accordion__knowledge-actions",children:[u.jsxs("div",{className:"content-accordion__progress-container",children:[u.jsx(il.Progress,{value:t.progress,size:"sm",color:"primary","aria-label":`${t.title} 进度`,className:"content-accordion__progress-bar"}),u.jsxs("span",{className:"content-accordion__progress-text",children:[t.progress,"%"]})]}),u.jsx(ut,{size:"sm",radius:"md",onClick:r,progress:t.progress,variant:t.progress===100?"light":t.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:Uo(t.progress)})]})]})},fl=({lesson:t,isExpanded:e,onToggle:r,onLearnAction:n})=>{const o=()=>{r(t.id)},s=dl(t.knowledgeItems);return u.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header",onClick:o,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${t.title},点击${e?"收起":"展开"}`,children:[u.jsxs("div",{className:"content-accordion__lesson-header-content",children:[u.jsx("h2",{className:"content-accordion__lesson-title",children:t.title}),u.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",t.duration," 分钟"]})]}),u.jsxs("div",{className:"content-accordion__lesson-actions",children:[u.jsxs("span",{className:"content-accordion__lesson-progress",children:[s,"%"]}),e?u.jsx(Ln.ChevronDown,{className:"content-accordion__lesson-icon"}):u.jsx(Ln.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&u.jsx("div",{className:"content-accordion__knowledge-list",children:t.knowledgeItems.map(i=>u.jsx(ul,{knowledgeItem:i,onLearnAction:n},i.id))})]})},Is=({unit:t,activeLessonIds:e,onToggleLesson:r,onLearnAction:n,loading:o=!1,className:s="",emptyState:i})=>o?u.jsx("div",{className:"content-accordion content-accordion--loading",children:u.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):t?u.jsxs("div",{className:`content-accordion ${s}`,children:[u.jsxs("header",{className:"content-accordion__header",children:[u.jsx("h1",{className:"content-accordion__unit-title",children:t.title}),u.jsx("p",{className:"content-accordion__unit-description",children:t.description}),u.jsxs("div",{className:"content-accordion__unit-meta",children:[u.jsxs("span",{children:["总共 ",t.totalLessons," 节课"]}),u.jsx("span",{children:"•"}),u.jsxs("span",{children:["预计学习 ",t.estimatedDuration]})]})]}),u.jsx("div",{className:"content-accordion__lessons",children:t.lessons.map(a=>u.jsx(fl,{lesson:a,isExpanded:e.includes(a.id),onToggle:r,onLearnAction:n},a.id))})]}):u.jsx("div",{className:"content-accordion content-accordion--empty",children:i||u.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),gl=t=>{switch(t){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},Fs=({data:t,loading:e=!1,error:r=null,collapsed:n=!1,onToggleCollapse:o,activeUnitId:s=null,onUnitSelect:i,renderUnitItem:a,className:c="",unitItemClassName:l="",style:d={},unitItemStyle:g={}})=>{const p=(y,b)=>{b.preventDefault(),i?.(y)},f=()=>{o?.()},m=y=>u.jsxs("div",{className:`sidebar__unit-item ${l} ${s===y.unitId?"sidebar__unit-item--active":""} ${y.status?`sidebar__unit-item--${y.status}`:""}`,style:g,onClick:b=>p(y.unitId,b),role:"button",tabIndex:0,"aria-label":`${y.title},进度 ${y.progressPercentage}%`,children:[u.jsxs("div",{className:"sidebar__unit-item__content",children:[y.icon&&u.jsx("span",{className:"sidebar__unit-item__icon",children:y.icon}),!n&&u.jsx("span",{className:"sidebar__unit-item__title",children:y.title})]}),!n&&y.progressPercentage!==void 0&&u.jsxs("div",{className:"sidebar__unit-item__progress",children:[u.jsx(Ue.Progress,{value:y.progressPercentage,size:"sm",color:gl(y.status),"aria-label":`${y.title} 进度`}),u.jsxs("span",{className:"progress-percentage",children:[y.progressPercentage,"%"]})]})]},y.unitId),h=()=>e?u.jsx("div",{className:"sidebar__loading",children:"加载中..."}):r?u.jsxs("div",{className:"sidebar__error",children:["加载失败: ",r.message]}):t?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar__header",children:[u.jsx("button",{className:"sidebar__toggle-btn",onClick:f,"aria-label":"切换侧边栏折叠状态",children:n?"→":"←"}),!n&&u.jsxs("div",{className:"sidebar__course-info",children:[u.jsx("h3",{className:"sidebar__course-title",children:t.courseTitle}),u.jsxs("span",{className:"sidebar__course-level",children:[t.courseLevel,"年级"]})]})]}),u.jsx("nav",{className:"sidebar__content",children:u.jsx("ul",{className:"sidebar__unit-list",children:t.units&&t.units.length>0?t.units.map(y=>u.jsx("li",{children:a?a(y,y):m(y)},y.unitId)):u.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):u.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return u.jsx("aside",{className:`sidebar ${c} ${n?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${r?"sidebar--error":""}`,style:d,"aria-label":"课程导航侧边栏",role:"complementary",children:h()})},co=({trigger:t,items:e,position:r="bottom",alignment:n="start",openDelay:o=300,closeDelay:s=100,onOpen:i,onClose:a,renderItem:c,itemConfig:l={},className:d,menuClassName:g,itemClassName:p})=>{const[f,m]=x.useState(!1),h=x.useRef(null),y=x.useRef(null),b=()=>{h.current&&clearTimeout(h.current),y.current&&clearTimeout(y.current)},_=()=>{b(),h.current=setTimeout(()=>{m(!0),i?.()},o)},w=()=>{b(),y.current=setTimeout(()=>{m(!1),a?.()},s)},C=S=>{!S.disabled&&S.onClick&&S.onClick(S)};x.useEffect(()=>()=>b(),[]);const v=S=>u.jsxs("div",{className:`submenu-item ${S.disabled?"is-disabled":""} ${p||""}`,onClick:()=>C(S),children:[S.icon&&u.jsx("span",{className:"submenu-item-icon",children:S.icon}),u.jsx("span",{children:S.label})]},S.id),k=()=>{const S=["submenu-panel"];return g&&S.push(g),S.push(`position-${r}`),n!=="start"&&S.push(`alignment-${n}`),f&&S.push("is-open"),S.join(" ")};return u.jsxs("div",{className:`submenu-container ${d||""}`,onMouseEnter:_,onMouseLeave:w,children:[u.jsx("div",{className:"submenu-trigger",children:t}),u.jsx("div",{className:k(),children:e.map(S=>c?c(S,l):v(S))})]})};function js(t,e){return function(){return t.apply(e,arguments)}}const{toString:ml}=Object.prototype,{getPrototypeOf:uo}=Object,{iterator:tn,toStringTag:Ps}=Symbol,rn=(t=>e=>{const r=ml.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ke=t=>(t=t.toLowerCase(),e=>rn(e)===t),nn=t=>e=>typeof e===t,{isArray:qt}=Array,Vt=nn("undefined");function mr(t){return t!==null&&!Vt(t)&&t.constructor!==null&&!Vt(t.constructor)&&je(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Ds=Ke("ArrayBuffer");function pl(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Ds(t.buffer),e}const hl=nn("string"),je=nn("function"),Ls=nn("number"),pr=t=>t!==null&&typeof t=="object",yl=t=>t===!0||t===!1,Lr=t=>{if(rn(t)!=="object")return!1;const e=uo(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Ps in t)&&!(tn in t)},bl=t=>{if(!pr(t)||mr(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},xl=Ke("Date"),wl=Ke("File"),vl=Ke("Blob"),_l=Ke("FileList"),Sl=t=>pr(t)&&je(t.pipe),Rl=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||je(t.append)&&((e=rn(t))==="formdata"||e==="object"&&je(t.toString)&&t.toString()==="[object FormData]"))},Cl=Ke("URLSearchParams"),[Al,El,Tl,$l]=["ReadableStream","Request","Response","Headers"].map(Ke),Nl=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function hr(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,o;if(typeof t!="object"&&(t=[t]),qt(t))for(n=0,o=t.length;n<o;n++)e.call(null,t[n],n,t);else{if(mr(t))return;const s=r?Object.getOwnPropertyNames(t):Object.keys(t),i=s.length;let a;for(n=0;n<i;n++)a=s[n],e.call(null,t[a],a,t)}}function Gs(t,e){if(mr(t))return null;e=e.toLowerCase();const r=Object.keys(t);let n=r.length,o;for(;n-- >0;)if(o=r[n],e===o.toLowerCase())return o;return null}const Tt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Us=t=>!Vt(t)&&t!==Tt;function Gn(){const{caseless:t,skipUndefined:e}=Us(this)&&this||{},r={},n=(o,s)=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;const i=t&&Gs(r,s)||s;Lr(r[i])&&Lr(o)?r[i]=Gn(r[i],o):Lr(o)?r[i]=Gn({},o):qt(o)?r[i]=o.slice():(!e||!Vt(o))&&(r[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&hr(arguments[o],n);return r}const kl=(t,e,r,{allOwnKeys:n}={})=>(hr(e,(o,s)=>{r&&je(o)?Object.defineProperty(t,s,{value:js(o,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),t),Ml=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ol=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Il=(t,e,r,n)=>{let o,s,i;const a={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)i=o[s],(!n||n(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=r!==!1&&uo(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Fl=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return n!==-1&&n===r},jl=t=>{if(!t)return null;if(qt(t))return t;let e=t.length;if(!Ls(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Pl=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&uo(Uint8Array)),Dl=(t,e)=>{const n=(t&&t[tn]).call(t);let o;for(;(o=n.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},Ll=(t,e)=>{let r;const n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Gl=Ke("HTMLFormElement"),Ul=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,o){return n.toUpperCase()+o}),Vo=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Vl=Ke("RegExp"),Vs=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};hr(r,(o,s)=>{let i;(i=e(o,s,t))!==!1&&(n[s]=i||o)}),Object.defineProperties(t,n)},zl=t=>{Vs(t,(e,r)=>{if(je(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const n=t[r];if(je(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Bl=(t,e)=>{const r={},n=o=>{o.forEach(s=>{r[s]=!0})};return qt(t)?n(t):n(String(t).split(e)),r},Hl=()=>{},ql=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Wl(t){return!!(t&&je(t.append)&&t[Ps]==="FormData"&&t[tn])}const Yl=t=>{const e=new Array(10),r=(n,o)=>{if(pr(n)){if(e.indexOf(n)>=0)return;if(mr(n))return n;if(!("toJSON"in n)){e[o]=n;const s=qt(n)?[]:{};return hr(n,(i,a)=>{const c=r(i,o+1);!Vt(c)&&(s[a]=c)}),e[o]=void 0,s}}return n};return r(t,0)},Kl=Ke("AsyncFunction"),Xl=t=>t&&(pr(t)||je(t))&&je(t.then)&&je(t.catch),zs=((t,e)=>t?setImmediate:e?((r,n)=>(Tt.addEventListener("message",({source:o,data:s})=>{o===Tt&&s===r&&n.length&&n.shift()()},!1),o=>{n.push(o),Tt.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",je(Tt.postMessage)),Jl=typeof queueMicrotask<"u"?queueMicrotask.bind(Tt):typeof process<"u"&&process.nextTick||zs,Zl=t=>t!=null&&je(t[tn]),R={isArray:qt,isArrayBuffer:Ds,isBuffer:mr,isFormData:Rl,isArrayBufferView:pl,isString:hl,isNumber:Ls,isBoolean:yl,isObject:pr,isPlainObject:Lr,isEmptyObject:bl,isReadableStream:Al,isRequest:El,isResponse:Tl,isHeaders:$l,isUndefined:Vt,isDate:xl,isFile:wl,isBlob:vl,isRegExp:Vl,isFunction:je,isStream:Sl,isURLSearchParams:Cl,isTypedArray:Pl,isFileList:_l,forEach:hr,merge:Gn,extend:kl,trim:Nl,stripBOM:Ml,inherits:Ol,toFlatObject:Il,kindOf:rn,kindOfTest:Ke,endsWith:Fl,toArray:jl,forEachEntry:Dl,matchAll:Ll,isHTMLForm:Gl,hasOwnProperty:Vo,hasOwnProp:Vo,reduceDescriptors:Vs,freezeMethods:zl,toObjectSet:Bl,toCamelCase:Ul,noop:Hl,toFiniteNumber:ql,findKey:Gs,global:Tt,isContextDefined:Us,isSpecCompliantForm:Wl,toJSONObject:Yl,isAsyncFn:Kl,isThenable:Xl,setImmediate:zs,asap:Jl,isIterable:Zl};let H=class Bs extends Error{static from(e,r,n,o,s,i){const a=new Bs(e.message,r||e.code,n,o,s);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,r,n,o,s){super(e),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),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:R.toJSONObject(this.config),code:this.code,status:this.status}}};H.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";H.ERR_BAD_OPTION="ERR_BAD_OPTION";H.ECONNABORTED="ECONNABORTED";H.ETIMEDOUT="ETIMEDOUT";H.ERR_NETWORK="ERR_NETWORK";H.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";H.ERR_DEPRECATED="ERR_DEPRECATED";H.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";H.ERR_BAD_REQUEST="ERR_BAD_REQUEST";H.ERR_CANCELED="ERR_CANCELED";H.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";H.ERR_INVALID_URL="ERR_INVALID_URL";const Ql=null;function Un(t){return R.isPlainObject(t)||R.isArray(t)}function Hs(t){return R.endsWith(t,"[]")?t.slice(0,-2):t}function zo(t,e,r){return t?t.concat(e).map(function(o,s){return o=Hs(o),!r&&s?"["+o+"]":o}).join(r?".":""):e}function ec(t){return R.isArray(t)&&!t.some(Un)}const tc=R.toFlatObject(R,{},null,function(e){return/^is[A-Z]/.test(e)});function on(t,e,r){if(!R.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=R.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,y){return!R.isUndefined(y[h])});const n=r.metaTokens,o=r.visitor||d,s=r.dots,i=r.indexes,c=(r.Blob||typeof Blob<"u"&&Blob)&&R.isSpecCompliantForm(e);if(!R.isFunction(o))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(R.isDate(m))return m.toISOString();if(R.isBoolean(m))return m.toString();if(!c&&R.isBlob(m))throw new H("Blob is not supported. Use a Buffer instead.");return R.isArrayBuffer(m)||R.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function d(m,h,y){let b=m;if(m&&!y&&typeof m=="object"){if(R.endsWith(h,"{}"))h=n?h:h.slice(0,-2),m=JSON.stringify(m);else if(R.isArray(m)&&ec(m)||(R.isFileList(m)||R.endsWith(h,"[]"))&&(b=R.toArray(m)))return h=Hs(h),b.forEach(function(w,C){!(R.isUndefined(w)||w===null)&&e.append(i===!0?zo([h],C,s):i===null?h:h+"[]",l(w))}),!1}return Un(m)?!0:(e.append(zo(y,h,s),l(m)),!1)}const g=[],p=Object.assign(tc,{defaultVisitor:d,convertValue:l,isVisitable:Un});function f(m,h){if(!R.isUndefined(m)){if(g.indexOf(m)!==-1)throw Error("Circular reference detected in "+h.join("."));g.push(m),R.forEach(m,function(b,_){(!(R.isUndefined(b)||b===null)&&o.call(e,b,R.isString(_)?_.trim():_,h,p))===!0&&f(b,h?h.concat(_):[_])}),g.pop()}}if(!R.isObject(t))throw new TypeError("data must be an object");return f(t),e}function Bo(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function fo(t,e){this._pairs=[],t&&on(t,this,e)}const qs=fo.prototype;qs.append=function(e,r){this._pairs.push([e,r])};qs.toString=function(e){const r=e?function(n){return e.call(this,n,Bo)}:Bo;return this._pairs.map(function(o){return r(o[0])+"="+r(o[1])},"").join("&")};function rc(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ws(t,e,r){if(!e)return t;const n=r&&r.encode||rc,o=R.isFunction(r)?{serialize:r}:r,s=o&&o.serialize;let i;if(s?i=s(e,o):i=R.isURLSearchParams(e)?e.toString():new fo(e,o).toString(n),i){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+i}return t}class Ho{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,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){R.forEach(this.handlers,function(n){n!==null&&e(n)})}}const go={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},nc=typeof URLSearchParams<"u"?URLSearchParams:fo,oc=typeof FormData<"u"?FormData:null,sc=typeof Blob<"u"?Blob:null,ic={isBrowser:!0,classes:{URLSearchParams:nc,FormData:oc,Blob:sc},protocols:["http","https","file","blob","url","data"]},mo=typeof window<"u"&&typeof document<"u",Vn=typeof navigator=="object"&&navigator||void 0,ac=mo&&(!Vn||["ReactNative","NativeScript","NS"].indexOf(Vn.product)<0),lc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cc=mo&&window.location.href||"http://localhost",dc=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:mo,hasStandardBrowserEnv:ac,hasStandardBrowserWebWorkerEnv:lc,navigator:Vn,origin:cc},Symbol.toStringTag,{value:"Module"})),Me={...dc,...ic};function uc(t,e){return on(t,new Me.classes.URLSearchParams,{visitor:function(r,n,o,s){return Me.isNode&&R.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function fc(t){return R.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function gc(t){const e={},r=Object.keys(t);let n;const o=r.length;let s;for(n=0;n<o;n++)s=r[n],e[s]=t[s];return e}function Ys(t){function e(r,n,o,s){let i=r[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),c=s>=r.length;return i=!i&&R.isArray(o)?o.length:i,c?(R.hasOwnProp(o,i)?o[i]=[o[i],n]:o[i]=n,!a):((!o[i]||!R.isObject(o[i]))&&(o[i]=[]),e(r,n,o[i],s)&&R.isArray(o[i])&&(o[i]=gc(o[i])),!a)}if(R.isFormData(t)&&R.isFunction(t.entries)){const r={};return R.forEachEntry(t,(n,o)=>{e(fc(n),o,r,0)}),r}return null}function mc(t,e,r){if(R.isString(t))try{return(e||JSON.parse)(t),R.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}const yr={transitional:go,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){const n=r.getContentType()||"",o=n.indexOf("application/json")>-1,s=R.isObject(e);if(s&&R.isHTMLForm(e)&&(e=new FormData(e)),R.isFormData(e))return o?JSON.stringify(Ys(e)):e;if(R.isArrayBuffer(e)||R.isBuffer(e)||R.isStream(e)||R.isFile(e)||R.isBlob(e)||R.isReadableStream(e))return e;if(R.isArrayBufferView(e))return e.buffer;if(R.isURLSearchParams(e))return r.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 uc(e,this.formSerializer).toString();if((a=R.isFileList(e))||n.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return on(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return s||o?(r.setContentType("application/json",!1),mc(e)):e}],transformResponse:[function(e){const r=this.transitional||yr.transitional,n=r&&r.forcedJSONParsing,o=this.responseType==="json";if(R.isResponse(e)||R.isReadableStream(e))return e;if(e&&R.isString(e)&&(n&&!this.responseType||o)){const i=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?H.from(a,H.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:Me.classes.FormData,Blob:Me.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};R.forEach(["delete","get","head","post","put","patch"],t=>{yr.headers[t]={}});const pc=R.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"]),hc=t=>{const e={};let r,n,o;return t&&t.split(`
2
- `).forEach(function(i){o=i.indexOf(":"),r=i.substring(0,o).trim().toLowerCase(),n=i.substring(o+1).trim(),!(!r||e[r]&&pc[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},qo=Symbol("internals");function er(t){return t&&String(t).trim().toLowerCase()}function Gr(t){return t===!1||t==null?t:R.isArray(t)?t.map(Gr):String(t)}function yc(t){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}const bc=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function xn(t,e,r,n,o){if(R.isFunction(n))return n.call(this,e,r);if(o&&(e=r),!!R.isString(e)){if(R.isString(n))return e.indexOf(n)!==-1;if(R.isRegExp(n))return n.test(e)}}function xc(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function wc(t,e){const r=R.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(o,s,i){return this[n].call(this,e,o,s,i)},configurable:!0})})}let Pe=class{constructor(e){e&&this.set(e)}set(e,r,n){const o=this;function s(a,c,l){const d=er(c);if(!d)throw new Error("header name must be a non-empty string");const g=R.findKey(o,d);(!g||o[g]===void 0||l===!0||l===void 0&&o[g]!==!1)&&(o[g||c]=Gr(a))}const i=(a,c)=>R.forEach(a,(l,d)=>s(l,d,c));if(R.isPlainObject(e)||e instanceof this.constructor)i(e,r);else if(R.isString(e)&&(e=e.trim())&&!bc(e))i(hc(e),r);else if(R.isObject(e)&&R.isIterable(e)){let a={},c,l;for(const d of e){if(!R.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[l=d[0]]=(c=a[l])?R.isArray(c)?[...c,d[1]]:[c,d[1]]:d[1]}i(a,r)}else e!=null&&s(r,e,n);return this}get(e,r){if(e=er(e),e){const n=R.findKey(this,e);if(n){const o=this[n];if(!r)return o;if(r===!0)return yc(o);if(R.isFunction(r))return r.call(this,o,n);if(R.isRegExp(r))return r.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=er(e),e){const n=R.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||xn(this,this[n],n,r)))}return!1}delete(e,r){const n=this;let o=!1;function s(i){if(i=er(i),i){const a=R.findKey(n,i);a&&(!r||xn(n,n[a],a,r))&&(delete n[a],o=!0)}}return R.isArray(e)?e.forEach(s):s(e),o}clear(e){const r=Object.keys(this);let n=r.length,o=!1;for(;n--;){const s=r[n];(!e||xn(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const r=this,n={};return R.forEach(this,(o,s)=>{const i=R.findKey(n,s);if(i){r[i]=Gr(o),delete r[s];return}const a=e?xc(s):String(s).trim();a!==s&&delete r[s],r[a]=Gr(o),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const r=Object.create(null);return R.forEach(this,(n,o)=>{n!=null&&n!==!1&&(r[o]=e&&R.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).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,...r){const n=new this(e);return r.forEach(o=>n.set(o)),n}static accessor(e){const n=(this[qo]=this[qo]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=er(i);n[a]||(wc(o,i),n[a]=!0)}return R.isArray(e)?e.forEach(s):s(e),this}};Pe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);R.reduceDescriptors(Pe.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});R.freezeMethods(Pe);function wn(t,e){const r=this||yr,n=e||r,o=Pe.from(n.headers);let s=n.data;return R.forEach(t,function(a){s=a.call(r,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function Ks(t){return!!(t&&t.__CANCEL__)}let br=class extends H{constructor(e,r,n){super(e??"canceled",H.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function Xs(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new H("Request failed with status code "+r.status,[H.ERR_BAD_REQUEST,H.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function vc(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function _c(t,e){t=t||10;const r=new Array(t),n=new Array(t);let o=0,s=0,i;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),d=n[s];i||(i=l),r[o]=c,n[o]=l;let g=s,p=0;for(;g!==o;)p+=r[g++],g=g%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),l-i<e)return;const f=d&&l-d;return f?Math.round(p*1e3/f):void 0}}function Sc(t,e){let r=0,n=1e3/e,o,s;const i=(l,d=Date.now())=>{r=d,o=null,s&&(clearTimeout(s),s=null),t(...l)};return[(...l)=>{const d=Date.now(),g=d-r;g>=n?i(l,d):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},n-g)))},()=>o&&i(o)]}const Kr=(t,e,r=3)=>{let n=0;const o=_c(50,250);return Sc(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-n,l=o(c),d=i<=a;n=i;const g={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:s,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(g)},r)},Wo=(t,e)=>{const r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},Yo=t=>(...e)=>R.asap(()=>t(...e)),Rc=Me.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,Me.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(Me.origin),Me.navigator&&/(msie|trident)/i.test(Me.navigator.userAgent)):()=>!0,Cc=Me.hasStandardBrowserEnv?{write(t,e,r,n,o,s,i){if(typeof document>"u")return;const a=[`${t}=${encodeURIComponent(e)}`];R.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),R.isString(n)&&a.push(`path=${n}`),R.isString(o)&&a.push(`domain=${o}`),s===!0&&a.push("secure"),R.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Ac(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Ec(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Js(t,e,r){let n=!Ac(e);return t&&(n||r==!1)?Ec(t,e):e}const Ko=t=>t instanceof Pe?{...t}:t;function Nt(t,e){e=e||{};const r={};function n(l,d,g,p){return R.isPlainObject(l)&&R.isPlainObject(d)?R.merge.call({caseless:p},l,d):R.isPlainObject(d)?R.merge({},d):R.isArray(d)?d.slice():d}function o(l,d,g,p){if(R.isUndefined(d)){if(!R.isUndefined(l))return n(void 0,l,g,p)}else return n(l,d,g,p)}function s(l,d){if(!R.isUndefined(d))return n(void 0,d)}function i(l,d){if(R.isUndefined(d)){if(!R.isUndefined(l))return n(void 0,l)}else return n(void 0,d)}function a(l,d,g){if(g in e)return n(l,d);if(g in t)return n(void 0,l)}const c={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,d,g)=>o(Ko(l),Ko(d),g,!0)};return R.forEach(Object.keys({...t,...e}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const g=R.hasOwnProp(c,d)?c[d]:o,p=g(t[d],e[d],d);R.isUndefined(p)&&g!==a||(r[d]=p)}),r}const Zs=t=>{const e=Nt({},t);let{data:r,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=e;if(e.headers=i=Pe.from(i),e.url=Ws(Js(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),R.isFormData(r)){if(Me.hasStandardBrowserEnv||Me.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(R.isFunction(r.getHeaders)){const c=r.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([d,g])=>{l.includes(d.toLowerCase())&&i.set(d,g)})}}if(Me.hasStandardBrowserEnv&&(n&&R.isFunction(n)&&(n=n(e)),n||n!==!1&&Rc(e.url))){const c=o&&s&&Cc.read(s);c&&i.set(o,c)}return e},Tc=typeof XMLHttpRequest<"u",$c=Tc&&function(t){return new Promise(function(r,n){const o=Zs(t);let s=o.data;const i=Pe.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=o,d,g,p,f,m;function h(){f&&f(),m&&m(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function b(){if(!y)return;const w=Pe.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),v={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:w,config:t,request:y};Xs(function(S){r(S),h()},function(S){n(S),h()},v),y=null}"onloadend"in y?y.onloadend=b:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(b)},y.onabort=function(){y&&(n(new H("Request aborted",H.ECONNABORTED,t,y)),y=null)},y.onerror=function(C){const v=C&&C.message?C.message:"Network Error",k=new H(v,H.ERR_NETWORK,t,y);k.event=C||null,n(k),y=null},y.ontimeout=function(){let C=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const v=o.transitional||go;o.timeoutErrorMessage&&(C=o.timeoutErrorMessage),n(new H(C,v.clarifyTimeoutError?H.ETIMEDOUT:H.ECONNABORTED,t,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&R.forEach(i.toJSON(),function(C,v){y.setRequestHeader(v,C)}),R.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),l&&([p,m]=Kr(l,!0),y.addEventListener("progress",p)),c&&y.upload&&([g,f]=Kr(c),y.upload.addEventListener("progress",g),y.upload.addEventListener("loadend",f)),(o.cancelToken||o.signal)&&(d=w=>{y&&(n(!w||w.type?new br(null,t,y):w),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const _=vc(o.url);if(_&&Me.protocols.indexOf(_)===-1){n(new H("Unsupported protocol "+_+":",H.ERR_BAD_REQUEST,t));return}y.send(s||null)})},Nc=(t,e)=>{const{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,o;const s=function(l){if(!o){o=!0,a();const d=l instanceof Error?l:this.reason;n.abort(d instanceof H?d:new br(d instanceof Error?d.message:d))}};let i=e&&setTimeout(()=>{i=null,s(new H(`timeout of ${e}ms exceeded`,H.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),t=null)};t.forEach(l=>l.addEventListener("abort",s));const{signal:c}=n;return c.unsubscribe=()=>R.asap(a),c}},kc=function*(t,e){let r=t.byteLength;if(r<e){yield t;return}let n=0,o;for(;n<r;)o=n+e,yield t.slice(n,o),n=o},Mc=async function*(t,e){for await(const r of Oc(t))yield*kc(r,e)},Oc=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},Xo=(t,e,r,n)=>{const o=Mc(t,e);let s=0,i,a=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{const{done:l,value:d}=await o.next();if(l){a(),c.close();return}let g=d.byteLength;if(r){let p=s+=g;r(p)}c.enqueue(new Uint8Array(d))}catch(l){throw a(l),l}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},Jo=64*1024,{isFunction:Rr}=R,Ic=(({Request:t,Response:e})=>({Request:t,Response:e}))(R.global),{ReadableStream:Zo,TextEncoder:Qo}=R.global,es=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Fc=t=>{t=R.merge.call({skipUndefined:!0},Ic,t);const{fetch:e,Request:r,Response:n}=t,o=e?Rr(e):typeof fetch=="function",s=Rr(r),i=Rr(n);if(!o)return!1;const a=o&&Rr(Zo),c=o&&(typeof Qo=="function"?(m=>h=>m.encode(h))(new Qo):async m=>new Uint8Array(await new r(m).arrayBuffer())),l=s&&a&&es(()=>{let m=!1;const h=new r(Me.origin,{body:new Zo,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!h}),d=i&&a&&es(()=>R.isReadableStream(new n("").body)),g={stream:d&&(m=>m.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!g[m]&&(g[m]=(h,y)=>{let b=h&&h[m];if(b)return b.call(h);throw new H(`Response type '${m}' is not supported`,H.ERR_NOT_SUPPORT,y)})});const p=async m=>{if(m==null)return 0;if(R.isBlob(m))return m.size;if(R.isSpecCompliantForm(m))return(await new r(Me.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(R.isArrayBufferView(m)||R.isArrayBuffer(m))return m.byteLength;if(R.isURLSearchParams(m)&&(m=m+""),R.isString(m))return(await c(m)).byteLength},f=async(m,h)=>{const y=R.toFiniteNumber(m.getContentLength());return y??p(h)};return async m=>{let{url:h,method:y,data:b,signal:_,cancelToken:w,timeout:C,onDownloadProgress:v,onUploadProgress:k,responseType:S,headers:E,withCredentials:N="same-origin",fetchOptions:I}=Zs(m),Y=e||fetch;S=S?(S+"").toLowerCase():"text";let K=Nc([_,w&&w.toAbortSignal()],C),L=null;const O=K&&K.unsubscribe&&(()=>{K.unsubscribe()});let U;try{if(k&&l&&y!=="get"&&y!=="head"&&(U=await f(E,b))!==0){let re=new r(h,{method:"POST",body:b,duplex:"half"}),te;if(R.isFormData(b)&&(te=re.headers.get("content-type"))&&E.setContentType(te),re.body){const[G,Z]=Wo(U,Kr(Yo(k)));b=Xo(re.body,Jo,G,Z)}}R.isString(N)||(N=N?"include":"omit");const T=s&&"credentials"in r.prototype,q={...I,signal:K,method:y.toUpperCase(),headers:E.normalize().toJSON(),body:b,duplex:"half",credentials:T?N:void 0};L=s&&new r(h,q);let $=await(s?Y(L,I):Y(h,q));const ee=d&&(S==="stream"||S==="response");if(d&&(v||ee&&O)){const re={};["status","statusText","headers"].forEach(ge=>{re[ge]=$[ge]});const te=R.toFiniteNumber($.headers.get("content-length")),[G,Z]=v&&Wo(te,Kr(Yo(v),!0))||[];$=new n(Xo($.body,Jo,G,()=>{Z&&Z(),O&&O()}),re)}S=S||"text";let de=await g[R.findKey(g,S)||"text"]($,m);return!ee&&O&&O(),await new Promise((re,te)=>{Xs(re,te,{data:de,headers:Pe.from($.headers),status:$.status,statusText:$.statusText,config:m,request:L})})}catch(T){throw O&&O(),T&&T.name==="TypeError"&&/Load failed|fetch/i.test(T.message)?Object.assign(new H("Network Error",H.ERR_NETWORK,m,L,T&&T.response),{cause:T.cause||T}):H.from(T,T&&T.code,m,L,T&&T.response)}}},jc=new Map,Qs=t=>{let e=t&&t.env||{};const{fetch:r,Request:n,Response:o}=e,s=[n,o,r];let i=s.length,a=i,c,l,d=jc;for(;a--;)c=s[a],l=d.get(c),l===void 0&&d.set(c,l=a?new Map:Fc(e)),d=l;return l};Qs();const po={http:Ql,xhr:$c,fetch:{get:Qs}};R.forEach(po,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const ts=t=>`- ${t}`,Pc=t=>R.isFunction(t)||t===null||t===!1;function Dc(t,e){t=R.isArray(t)?t:[t];const{length:r}=t;let n,o;const s={};for(let i=0;i<r;i++){n=t[i];let a;if(o=n,!Pc(n)&&(o=po[(a=String(n)).toLowerCase()],o===void 0))throw new H(`Unknown adapter '${a}'`);if(o&&(R.isFunction(o)||(o=o.get(e))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=r?i.length>1?`since :
4
- `+i.map(ts).join(`
5
- `):" "+ts(i[0]):"as no adapter specified";throw new H("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o}const ei={getAdapter:Dc,adapters:po};function vn(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new br(null,t)}function rs(t){return vn(t),t.headers=Pe.from(t.headers),t.data=wn.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ei.getAdapter(t.adapter||yr.adapter,t)(t).then(function(n){return vn(t),n.data=wn.call(t,t.transformResponse,n),n.headers=Pe.from(n.headers),n},function(n){return Ks(n)||(vn(t),n&&n.response&&(n.response.data=wn.call(t,t.transformResponse,n.response),n.response.headers=Pe.from(n.response.headers))),Promise.reject(n)})}const ti="1.13.5",sn={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{sn[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const ns={};sn.transitional=function(e,r,n){function o(s,i){return"[Axios v"+ti+"] Transitional option '"+s+"'"+i+(n?". "+n:"")}return(s,i,a)=>{if(e===!1)throw new H(o(i," has been removed"+(r?" in "+r:"")),H.ERR_DEPRECATED);return r&&!ns[i]&&(ns[i]=!0,console.warn(o(i," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,i,a):!0}};sn.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Lc(t,e,r){if(typeof t!="object")throw new H("options must be an object",H.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let o=n.length;for(;o-- >0;){const s=n[o],i=e[s];if(i){const a=t[s],c=a===void 0||i(a,s,t);if(c!==!0)throw new H("option "+s+" must be "+c,H.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new H("Unknown option "+s,H.ERR_BAD_OPTION)}}const Ur={assertOptions:Lc,validators:sn},qe=Ur.validators;let $t=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ho,response:new Ho}}async request(e,r){try{return await this._request(e,r)}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+=`
6
- `+s):n.stack=s}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Nt(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&Ur.assertOptions(n,{silentJSONParsing:qe.transitional(qe.boolean),forcedJSONParsing:qe.transitional(qe.boolean),clarifyTimeoutError:qe.transitional(qe.boolean),legacyInterceptorReqResOrdering:qe.transitional(qe.boolean)},!1),o!=null&&(R.isFunction(o)?r.paramsSerializer={serialize:o}:Ur.assertOptions(o,{encode:qe.function,serialize:qe.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Ur.assertOptions(r,{baseUrl:qe.spelling("baseURL"),withXsrfToken:qe.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[r.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),r.headers=Pe.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;c=c&&h.synchronous;const y=r.transitional||go;y&&y.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});const l=[];this.interceptors.response.forEach(function(h){l.push(h.fulfilled,h.rejected)});let d,g=0,p;if(!c){const m=[rs.bind(this),void 0];for(m.unshift(...a),m.push(...l),p=m.length,d=Promise.resolve(r);g<p;)d=d.then(m[g++],m[g++]);return d}p=a.length;let f=r;for(;g<p;){const m=a[g++],h=a[g++];try{f=m(f)}catch(y){h.call(this,y);break}}try{d=rs.call(this,f)}catch(m){return Promise.reject(m)}for(g=0,p=l.length;g<p;)d=d.then(l[g++],l[g++]);return d}getUri(e){e=Nt(this.defaults,e);const r=Js(e.baseURL,e.url,e.allowAbsoluteUrls);return Ws(r,e.params,e.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(e){$t.prototype[e]=function(r,n){return this.request(Nt(n||{},{method:e,url:r,data:(n||{}).data}))}});R.forEach(["post","put","patch"],function(e){function r(n){return function(s,i,a){return this.request(Nt(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}$t.prototype[e]=r(),$t.prototype[e+"Form"]=r(!0)});let Gc=class ri{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=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 br(s,i,a),r(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 r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new ri(function(o){e=o}),cancel:e}}};function Uc(t){return function(r){return t.apply(null,r)}}function Vc(t){return R.isObject(t)&&t.isAxiosError===!0}const zn={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(zn).forEach(([t,e])=>{zn[e]=t});function ni(t){const e=new $t(t),r=js($t.prototype.request,e);return R.extend(r,$t.prototype,e,{allOwnKeys:!0}),R.extend(r,e,null,{allOwnKeys:!0}),r.create=function(o){return ni(Nt(t,o))},r}const he=ni(yr);he.Axios=$t;he.CanceledError=br;he.CancelToken=Gc;he.isCancel=Ks;he.VERSION=ti;he.toFormData=on;he.AxiosError=H;he.Cancel=he.CanceledError;he.all=function(e){return Promise.all(e)};he.spread=Uc;he.isAxiosError=Vc;he.mergeConfig=Nt;he.AxiosHeaders=Pe;he.formToJSON=t=>Ys(R.isHTMLForm(t)?new FormData(t):t);he.getAdapter=ei.getAdapter;he.HttpStatusCode=zn;he.default=he;const{Axios:vy,AxiosError:_y,CanceledError:Sy,isCancel:Ry,CancelToken:Cy,VERSION:Ay,all:Ey,Cancel:Ty,isAxiosError:$y,spread:Ny,toFormData:ky,AxiosHeaders:My,HttpStatusCode:Oy,formToJSON:Iy,getAdapter:Fy,mergeConfig:jy}=he,zc=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),Bc=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),Hc=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),qc=()=>u.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),Wc=[{id:"profile",label:"个人主页",icon:u.jsx(zc,{})},{id:"settings",label:"设置",icon:u.jsx(Bc,{})},{id:"help",label:"帮助",icon:u.jsx(Hc,{})},{id:"logout",label:"退出",icon:u.jsx(qc,{})}],oi=({userId:t,userName:e,userAvatar:r,apiConfig:n,menuItems:o=Wc,avatarSize:s="md",isLoading:i=!1,error:a=null,avatarClassName:c,userNameClassName:l,containerClassName:d,onMenuOpen:g,onMenuClose:p,onMenuItemClick:f,onLogout:m,renderMenuItem:h,renderUserInfo:y})=>{const[b,_]=x.useState({id:t||"",name:e||"",avatar:r||"",level:0,badges:[]}),[w,C]=x.useState(i),[v,k]=x.useState(a);x.useEffect(()=>{t&&n&&!e&&!r&&S()},[t,n,e,r]);const S=async()=>{C(!0),k(null);try{const L=n.endpoints.userProfile.replace(":userId",t),O=await he.get(`${n.baseURL}${L}`,{headers:n.headers});_(O.data)}catch(L){k(L)}finally{C(!1)}},E=L=>{f?.(L.id),L.id==="logout"&&m?.()},N=()=>{g?.()},I=()=>{p?.()},Y=()=>u.jsxs("div",{className:"user-profile-trigger",children:[u.jsx(Ue.Avatar,{src:b.avatar,size:s,className:c,alt:"用户头像"}),u.jsx("span",{className:`user-name ${l||""}`,children:b.name})]}),K=L=>u.jsxs("div",{className:"submenu-item",onClick:()=>E(L),children:[L.icon&&u.jsx("span",{className:"submenu-item-icon",children:L.icon}),u.jsx("span",{children:L.label})]},L.id);return w?u.jsx("div",{className:`user-profile-container ${d||""} is-loading`,children:u.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):v?u.jsx("div",{className:`user-profile-container ${d||""} has-error`,children:u.jsxs("div",{className:"user-profile-error",children:["错误: ",v.message]})}):b.name?u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx(co,{trigger:y?y(b):Y(),items:o.map(L=>({...L,onClick:()=>E(L)})),position:"bottom",alignment:"end",onOpen:N,onClose:I,renderItem:h?L=>h(L,b):K})}):u.jsx("div",{className:`user-profile-container ${d||""}`,children:u.jsx("div",{className:"user-profile-loading",children:"未登录"})})},Yc=t=>u.jsxs("div",{className:"explore-menu-item",onClick:()=>t.onClick?.(t),children:[u.jsx("span",{className:"explore-item-label",children:t.label}),t.status&&u.jsx("span",{className:`explore-item-status status-${t.status.toLowerCase().replace("%","").replace(" ","-")}`,children:t.status})]},t.id),Kc=({className:t})=>u.jsxs("button",{className:t,"aria-label":"探索数学课程",children:[u.jsx("span",{className:"explore-icon",children:"🌍"}),u.jsx("span",{className:"explore-text",children:"探索"})]}),Xc=({className:t="",style:e,logoHref:r="/",logoText:n="MathWiz",onLogoClick:o,exploreItems:s=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:c,renderExploreItem:l=Yc,userData:d,userMenuItems:g,onUserMenuItemClick:p,onLogout:f,isLoading:m=!1,error:h=null,headerClassName:y="",logoClassName:b="",exploreClassName:_="",userProfileClassName:w="",variant:C="gradient",color:v,background:k,height:S,gradientFrom:E,gradientTo:N,gradientVia:I,logoColor:Y,logoSize:K="md",exploreButtonVariant:L="flat",exploreButtonColor:O="primary","aria-label":U,"aria-labelledby":T,...q})=>{const $=s.map(G=>({id:G.id,label:l(G),onClick:()=>c?.(G)})),ee=["mathwiz-header",`mathwiz-header--${C}`,v&&`mathwiz-header--color-${v}`,y,t].filter(Boolean).join(" "),de=["logo",`logo--${K}`,b].filter(Boolean).join(" "),re=["explore-button",`explore-button--${L}`,`explore-button--color-${O}`,_].filter(Boolean).join(" "),te={...e,...S&&{height:typeof S=="number"?`${S}px`:S},...k&&{"--custom-bg":k},...Y&&{"--logo-color":Y},...E&&N&&{"--header-bg":I?`linear-gradient(to right, ${E}, ${I}, ${N})`:`linear-gradient(to right, ${E}, ${N})`}};return u.jsx("header",{className:ee,style:te,"aria-label":U,"aria-labelledby":T,role:"banner",...q,children:u.jsxs("div",{className:"header-content",children:[u.jsx("div",{className:"header-section left",children:u.jsx(co,{trigger:u.jsx(Kc,{className:re}),items:$,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),u.jsx("div",{className:"header-section center",children:u.jsx("a",{href:r,className:de,onClick:o,"aria-label":"MathWiz 首页",children:n})}),u.jsx("div",{className:"header-section right",children:u.jsx(oi,{userName:d?.name,userAvatar:d?.avatar,menuItems:g,onMenuItemClick:p,onLogout:f,containerClassName:w,isLoading:m,error:h})})]})})},si=x.memo(Xc,(t,e)=>t.logoText===e.logoText&&t.logoHref===e.logoHref&&t.className===e.className&&t.headerClassName===e.headerClassName&&t.logoClassName===e.logoClassName&&t.exploreClassName===e.exploreClassName&&t.userProfileClassName===e.userProfileClassName&&t["aria-label"]===e["aria-label"]&&t["aria-labelledby"]===e["aria-labelledby"]&&t.isLoading===e.isLoading&&t.error===e.error&&t.variant===e.variant&&t.color===e.color&&t.background===e.background&&t.height===e.height&&t.gradientFrom===e.gradientFrom&&t.gradientTo===e.gradientTo&&t.gradientVia===e.gradientVia&&t.logoColor===e.logoColor&&t.logoSize===e.logoSize&&t.exploreButtonVariant===e.exploreButtonVariant&&t.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(t.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(t.userData)===JSON.stringify(e.userData)&&JSON.stringify(t.userMenuItems)===JSON.stringify(e.userMenuItems)),or={LEFT:"left",RIGHT:"right",TOP:"top",BOTTOM:"bottom"},_n={NUMBER:"number",TIME:"time",CUSTOM:"custom"},os={iconPosition:or.LEFT,interactive:!1},ii=t=>{const{label:e,value:r,unit:n,color:o,icon:s,iconPosition:i=os.iconPosition,render:a,onClick:c,className:l="",style:d,interactive:g=os.interactive,"aria-label":p,"aria-role":f,"data-testid":m,subtitle:h,showHelpIcon:y,helpIconTitle:b="What is this?",contentType:_=_n.NUMBER,timeValue:w,themeColorVar:C}=t,v=x.useMemo(()=>f||(c?"button":"group"),[f,c]),k=x.useMemo(()=>{const N=["mathwiz-statblock"];return l&&N.push(l),g&&N.push("mathwiz-statblock-interactive"),o&&!o.startsWith("#")&&N.push(`mathwiz-statblock-color-${o}`),N.join(" ")},[l,g,o]),S=x.useMemo(()=>{const N={...d};return o&&o.startsWith("#")&&(N.backgroundColor=o),C&&(N["--statblock-current-theme-color"]=`var(${C})`),N},[d,o,C]),E={label:e,value:r,unit:n,icon:s,iconPosition:i,color:o,interactive:g,className:k,style:S,subtitle:h,showHelpIcon:y,contentType:_,timeValue:w};return a?a(E):u.jsxs("div",{className:k,style:S,onClick:c,role:v,"aria-label":p,"data-testid":m,tabIndex:g?0:void 0,children:[u.jsxs("div",{className:"mathwiz-statblock-header",children:[u.jsx("div",{className:"mathwiz-statblock-title",children:e}),(h||y)&&u.jsxs("div",{className:"mathwiz-statblock-subtitle",children:[h,y&&u.jsx("span",{className:"mathwiz-statblock-help-icon",title:b,children:"?"})]})]}),u.jsx("div",{className:"mathwiz-statblock-body",children:_===_n.TIME&&w?u.jsxs("div",{className:"mathwiz-statblock-time-display",children:[u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.hours).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"HR"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.minutes).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"MIN"})]}),u.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[u.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.seconds).padStart(2,"0")}),u.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"SEC"})]})]}):_===_n.CUSTOM?u.jsxs(u.Fragment,{children:[i===or.TOP&&s&&u.jsx("div",{className:"mathwiz-statblock-icon-top",children:s}),u.jsxs("div",{className:"mathwiz-statblock-content",children:[i===or.LEFT&&s&&u.jsx("div",{className:"mathwiz-statblock-icon-left",children:s}),u.jsxs("div",{className:"mathwiz-statblock-text",children:[u.jsx("div",{className:"mathwiz-statblock-label",children:e}),u.jsxs("div",{className:"mathwiz-statblock-value-container",children:[u.jsx("span",{className:"mathwiz-statblock-value",children:r}),n&&u.jsx("span",{className:"mathwiz-statblock-unit",children:n})]})]}),i===or.RIGHT&&s&&u.jsx("div",{className:"mathwiz-statblock-icon-right",children:s})]}),i===or.BOTTOM&&s&&u.jsx("div",{className:"mathwiz-statblock-icon-bottom",children:s})]}):u.jsx("div",{className:"mathwiz-statblock-value-large",children:r})})]})};x.memo(ii);var Jc=/\s+/g,Zc=t=>typeof t!="string"||!t?t:t.replace(Jc," ").trim(),Xr=(...t)=>{const e=[],r=n=>{if(!n&&n!==0&&n!==0n)return;if(Array.isArray(n)){for(let s=0,i=n.length;s<i;s++)r(n[s]);return}const o=typeof n;if(o==="string"||o==="number"||o==="bigint"){if(o==="number"&&n!==n)return;e.push(String(n))}else if(o==="object"){const s=Object.keys(n);for(let i=0,a=s.length;i<a;i++){const c=s[i];n[c]&&e.push(c)}}};for(let n=0,o=t.length;n<o;n++){const s=t[n];s!=null&&r(s)}return e.length>0?Zc(e.join(" ")):void 0},ss=t=>t===!1?"false":t===!0?"true":t===0?"0":t,Ie=t=>{if(!t||typeof t!="object")return!0;for(const e in t)return!1;return!0},Qc=(t,e)=>{if(t===e)return!0;if(!t||!e)return!1;const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o=0;o<r.length;o++){const s=r[o];if(!n.includes(s)||t[s]!==e[s])return!1}return!0},ed=(t,e)=>{for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const n=e[r];r in t?t[r]=Xr(t[r],n):t[r]=n}return t},ai=(t,e)=>{for(let r=0;r<t.length;r++){const n=t[r];Array.isArray(n)?ai(n,e):n&&e.push(n)}},li=(...t)=>{const e=[];ai(t,e);const r=[];for(let n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},Bn=(t,e)=>{const r={};for(const n in t){const o=t[n];if(n in e){const s=e[n];Array.isArray(o)||Array.isArray(s)?r[n]=li(s,o):typeof o=="object"&&typeof s=="object"&&o&&s?r[n]=Bn(o,s):r[n]=s+" "+o}else r[n]=o}for(const n in e)n in t||(r[n]=e[n]);return r},td={twMerge:!0,twMergeConfig:{}};function rd(){let t=null,e={},r=!1;return{get cachedTwMerge(){return t},set cachedTwMerge(n){t=n},get cachedTwMergeConfig(){return e},set cachedTwMergeConfig(n){e=n},get didTwMergeConfigChange(){return r},set didTwMergeConfigChange(n){r=n},reset(){t=null,e={},r=!1}}}var lt=rd(),nd=t=>{const e=(n,o)=>{const{extend:s=null,slots:i={},variants:a={},compoundVariants:c=[],compoundSlots:l=[],defaultVariants:d={}}=n,g={...td,...o},p=s?.base?Xr(s.base,n?.base):n?.base,f=s?.variants&&!Ie(s.variants)?Bn(a,s.variants):a,m=s?.defaultVariants&&!Ie(s.defaultVariants)?{...s.defaultVariants,...d}:d;!Ie(g.twMergeConfig)&&!Qc(g.twMergeConfig,lt.cachedTwMergeConfig)&&(lt.didTwMergeConfigChange=!0,lt.cachedTwMergeConfig=g.twMergeConfig);const h=Ie(s?.slots),y=Ie(i)?{}:{base:Xr(n?.base,h&&s?.base),...i},b=h?y:ed({...s?.slots},Ie(y)?{base:n?.base}:y),_=Ie(s?.compoundVariants)?c:li(s?.compoundVariants,c),w=v=>{if(Ie(f)&&Ie(i)&&h)return t(p,v?.class,v?.className)(g);if(_&&!Array.isArray(_))throw new TypeError(`The "compoundVariants" prop must be an array. Received: ${typeof _}`);if(l&&!Array.isArray(l))throw new TypeError(`The "compoundSlots" prop must be an array. Received: ${typeof l}`);const k=(O,U=f,T=null,q=null)=>{const $=U[O];if(!$||Ie($))return null;const ee=q?.[O]??v?.[O];if(ee===null)return null;const de=ss(ee);if(typeof de=="object")return null;const re=m?.[O],te=de??ss(re);return $[te||"false"]},S=()=>{if(!f)return null;const O=Object.keys(f),U=[];for(let T=0;T<O.length;T++){const q=k(O[T],f);q&&U.push(q)}return U},E=(O,U)=>{if(!f||typeof f!="object")return null;const T=[];for(const q in f){const $=k(q,f,O,U),ee=O==="base"&&typeof $=="string"?$:$&&$[O];ee&&T.push(ee)}return T},N={};for(const O in v){const U=v[O];U!==void 0&&(N[O]=U)}const I=(O,U)=>{const T=typeof v?.[O]=="object"?{[O]:v[O]?.initial}:{};return{...m,...N,...T,...U}},Y=(O=[],U)=>{const T=[],q=O.length;for(let $=0;$<q;$++){const{class:ee,className:de,...re}=O[$];let te=!0;const G=I(null,U);for(const Z in re){const ge=re[Z],Ce=G[Z];if(Array.isArray(ge)){if(!ge.includes(Ce)){te=!1;break}}else{if((ge==null||ge===!1)&&(Ce==null||Ce===!1))continue;if(Ce!==ge){te=!1;break}}}te&&(ee&&T.push(ee),de&&T.push(de))}return T},K=O=>{const U=Y(_,O);if(!Array.isArray(U))return U;const T={},q=t;for(let $=0;$<U.length;$++){const ee=U[$];if(typeof ee=="string")T.base=q(T.base,ee)(g);else if(typeof ee=="object")for(const de in ee)T[de]=q(T[de],ee[de])(g)}return T},L=O=>{if(l.length<1)return null;const U={},T=I(null,O);for(let q=0;q<l.length;q++){const{slots:$=[],class:ee,className:de,...re}=l[q];if(!Ie(re)){let te=!0;for(const G in re){const Z=T[G],ge=re[G];if(Z===void 0||(Array.isArray(ge)?!ge.includes(Z):ge!==Z)){te=!1;break}}if(!te)continue}for(let te=0;te<$.length;te++){const G=$[te];U[G]||(U[G]=[]),U[G].push([ee,de])}}return U};if(!Ie(i)||!h){const O={};if(typeof b=="object"&&!Ie(b)){const U=t;for(const T in b)O[T]=q=>{const $=K(q),ee=L(q);return U(b[T],E(T,q),$?$[T]:void 0,ee?ee[T]:void 0,q?.class,q?.className)(g)}}return O}return t(p,S(),Y(_),v?.class,v?.className)(g)},C=()=>{if(!(!f||typeof f!="object"))return Object.keys(f)};return w.variantKeys=C(),w.extend=s,w.base=p,w.slots=b,w.variants=f,w.defaultVariants=m,w.compoundSlots=l,w.compoundVariants=_,w};return{tv:e,createTV:n=>(o,s)=>e(o,s?Bn(n,s):n)}};const od=(t,e)=>{const r=new Array(t.length+e.length);for(let n=0;n<t.length;n++)r[n]=t[n];for(let n=0;n<e.length;n++)r[t.length+n]=e[n];return r},sd=(t,e)=>({classGroupId:t,validator:e}),ci=(t=new Map,e=null,r)=>({nextPart:t,validators:e,classGroupId:r}),Jr="-",is=[],id="arbitrary..",ad=t=>{const e=cd(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return ld(i);const a=i.split(Jr),c=a[0]===""&&a.length>1?1:0;return di(a,c,e)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=n[i],l=r[i];return c?l?od(l,c):c:l||is}return r[i]||is}}},di=(t,e,r)=>{if(t.length-e===0)return r.classGroupId;const o=t[e],s=r.nextPart.get(o);if(s){const l=di(t,e+1,s);if(l)return l}const i=r.validators;if(i===null)return;const a=e===0?t.join(Jr):t.slice(e).join(Jr),c=i.length;for(let l=0;l<c;l++){const d=i[l];if(d.validator(a))return d.classGroupId}},ld=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),r=e.indexOf(":"),n=e.slice(0,r);return n?id+n:void 0})(),cd=t=>{const{theme:e,classGroups:r}=t;return dd(r,e)},dd=(t,e)=>{const r=ci();for(const n in t){const o=t[n];ho(o,r,n,e)}return r},ho=(t,e,r,n)=>{const o=t.length;for(let s=0;s<o;s++){const i=t[s];ud(i,e,r,n)}},ud=(t,e,r,n)=>{if(typeof t=="string"){fd(t,e,r);return}if(typeof t=="function"){gd(t,e,r,n);return}md(t,e,r,n)},fd=(t,e,r)=>{const n=t===""?e:ui(e,t);n.classGroupId=r},gd=(t,e,r,n)=>{if(pd(t)){ho(t(n),e,r,n);return}e.validators===null&&(e.validators=[]),e.validators.push(sd(r,t))},md=(t,e,r,n)=>{const o=Object.entries(t),s=o.length;for(let i=0;i<s;i++){const[a,c]=o[i];ho(c,ui(e,a),r,n)}},ui=(t,e)=>{let r=t;const n=e.split(Jr),o=n.length;for(let s=0;s<o;s++){const i=n[s];let a=r.nextPart.get(i);a||(a=ci(),r.nextPart.set(i,a)),r=a}return r},pd=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,hd=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=Object.create(null),n=Object.create(null);const o=(s,i)=>{r[s]=i,e++,e>t&&(e=0,n=r,r=Object.create(null))};return{get(s){let i=r[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set(s,i){s in r?r[s]=i:o(s,i)}}},Hn="!",as=":",yd=[],ls=(t,e,r,n,o)=>({modifiers:t,hasImportantModifier:e,baseClassName:r,maybePostfixModifierPosition:n,isExternal:o}),bd=t=>{const{prefix:e,experimentalParseClassName:r}=t;let n=o=>{const s=[];let i=0,a=0,c=0,l;const d=o.length;for(let h=0;h<d;h++){const y=o[h];if(i===0&&a===0){if(y===as){s.push(o.slice(c,h)),c=h+1;continue}if(y==="/"){l=h;continue}}y==="["?i++:y==="]"?i--:y==="("?a++:y===")"&&a--}const g=s.length===0?o:o.slice(c);let p=g,f=!1;g.endsWith(Hn)?(p=g.slice(0,-1),f=!0):g.startsWith(Hn)&&(p=g.slice(1),f=!0);const m=l&&l>c?l-c:void 0;return ls(s,f,p,m)};if(e){const o=e+as,s=n;n=i=>i.startsWith(o)?s(i.slice(o.length)):ls(yd,!1,i,void 0,!0)}if(r){const o=n;n=s=>r({className:s,parseClassName:o})}return n},xd=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((r,n)=>{e.set(r,1e6+n)}),r=>{const n=[];let o=[];for(let s=0;s<r.length;s++){const i=r[s],a=i[0]==="[",c=e.has(i);a||c?(o.length>0&&(o.sort(),n.push(...o),o=[]),n.push(i)):o.push(i)}return o.length>0&&(o.sort(),n.push(...o)),n}},wd=t=>({cache:hd(t.cacheSize),parseClassName:bd(t),sortModifiers:xd(t),...ad(t)}),vd=/\s+/,_d=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:o,sortModifiers:s}=e,i=[],a=t.trim().split(vd);let c="";for(let l=a.length-1;l>=0;l-=1){const d=a[l],{isExternal:g,modifiers:p,hasImportantModifier:f,baseClassName:m,maybePostfixModifierPosition:h}=r(d);if(g){c=d+(c.length>0?" "+c:c);continue}let y=!!h,b=n(y?m.substring(0,h):m);if(!b){if(!y){c=d+(c.length>0?" "+c:c);continue}if(b=n(m),!b){c=d+(c.length>0?" "+c:c);continue}y=!1}const _=p.length===0?"":p.length===1?p[0]:s(p).join(":"),w=f?_+Hn:_,C=w+b;if(i.indexOf(C)>-1)continue;i.push(C);const v=o(b,y);for(let k=0;k<v.length;++k){const S=v[k];i.push(w+S)}c=d+(c.length>0?" "+c:c)}return c},Sd=(...t)=>{let e=0,r,n,o="";for(;e<t.length;)(r=t[e++])&&(n=fi(r))&&(o&&(o+=" "),o+=n);return o},fi=t=>{if(typeof t=="string")return t;let e,r="";for(let n=0;n<t.length;n++)t[n]&&(e=fi(t[n]))&&(r&&(r+=" "),r+=e);return r},qn=(t,...e)=>{let r,n,o,s;const i=c=>{const l=e.reduce((d,g)=>g(d),t());return r=wd(l),n=r.cache.get,o=r.cache.set,s=a,a(c)},a=c=>{const l=n(c);if(l)return l;const d=_d(c,r);return o(c,d),d};return s=i,(...c)=>s(Sd(...c))},Rd=[],_e=t=>{const e=r=>r[t]||Rd;return e.isThemeGetter=!0,e},gi=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,mi=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Cd=/^\d+\/\d+$/,Ad=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ed=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Td=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$d=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Nd=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ft=t=>Cd.test(t),J=t=>!!t&&!Number.isNaN(Number(t)),gt=t=>!!t&&Number.isInteger(Number(t)),Sn=t=>t.endsWith("%")&&J(t.slice(0,-1)),it=t=>Ad.test(t),kd=()=>!0,Md=t=>Ed.test(t)&&!Td.test(t),pi=()=>!1,Od=t=>$d.test(t),Id=t=>Nd.test(t),Fd=t=>!P(t)&&!D(t),jd=t=>Wt(t,bi,pi),P=t=>gi.test(t),_t=t=>Wt(t,xi,Md),Rn=t=>Wt(t,Ud,J),cs=t=>Wt(t,hi,pi),Pd=t=>Wt(t,yi,Id),Cr=t=>Wt(t,wi,Od),D=t=>mi.test(t),tr=t=>Yt(t,xi),Dd=t=>Yt(t,Vd),ds=t=>Yt(t,hi),Ld=t=>Yt(t,bi),Gd=t=>Yt(t,yi),Ar=t=>Yt(t,wi,!0),Wt=(t,e,r)=>{const n=gi.exec(t);return n?n[1]?e(n[1]):r(n[2]):!1},Yt=(t,e,r=!1)=>{const n=mi.exec(t);return n?n[1]?e(n[1]):r:!1},hi=t=>t==="position"||t==="percentage",yi=t=>t==="image"||t==="url",bi=t=>t==="length"||t==="size"||t==="bg-size",xi=t=>t==="length",Ud=t=>t==="number",Vd=t=>t==="family-name",wi=t=>t==="shadow",Wn=()=>{const t=_e("color"),e=_e("font"),r=_e("text"),n=_e("font-weight"),o=_e("tracking"),s=_e("leading"),i=_e("breakpoint"),a=_e("container"),c=_e("spacing"),l=_e("radius"),d=_e("shadow"),g=_e("inset-shadow"),p=_e("text-shadow"),f=_e("drop-shadow"),m=_e("blur"),h=_e("perspective"),y=_e("aspect"),b=_e("ease"),_=_e("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...C(),D,P],k=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],E=()=>[D,P,c],N=()=>[Ft,"full","auto",...E()],I=()=>[gt,"none","subgrid",D,P],Y=()=>["auto",{span:["full",gt,D,P]},gt,D,P],K=()=>[gt,"auto",D,P],L=()=>["auto","min","max","fr",D,P],O=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...E()],q=()=>[Ft,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...E()],$=()=>[t,D,P],ee=()=>[...C(),ds,cs,{position:[D,P]}],de=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",Ld,jd,{size:[D,P]}],te=()=>[Sn,tr,_t],G=()=>["","none","full",l,D,P],Z=()=>["",J,tr,_t],ge=()=>["solid","dashed","dotted","double"],Ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ce=()=>[J,Sn,ds,cs],ft=()=>["","none",m,D,P],st=()=>["none",J,D,P],F=()=>["none",J,D,P],M=()=>[J,D,P],A=()=>[Ft,"full",...E()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[it],breakpoint:[it],color:[kd],container:[it],"drop-shadow":[it],ease:["in","out","in-out"],font:[Fd],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[it],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[it],shadow:[it],spacing:["px",J],text:[it],"text-shadow":[it],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ft,P,D,y]}],container:["container"],columns:[{columns:[J,P,D,a]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:k()}],"overflow-x":[{"overflow-x":k()}],"overflow-y":[{"overflow-y":k()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{start:N()}],end:[{end:N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[gt,"auto",D,P]}],basis:[{basis:[Ft,"full","auto",a,...E()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[J,Ft,"auto","initial","none",P]}],grow:[{grow:["",J,D,P]}],shrink:[{shrink:["",J,D,P]}],order:[{order:[gt,"first","last","none",D,P]}],"grid-cols":[{"grid-cols":I()}],"col-start-end":[{col:Y()}],"col-start":[{"col-start":K()}],"col-end":[{"col-end":K()}],"grid-rows":[{"grid-rows":I()}],"row-start-end":[{row:Y()}],"row-start":[{"row-start":K()}],"row-end":[{"row-end":K()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":L()}],"auto-rows":[{"auto-rows":L()}],gap:[{gap:E()}],"gap-x":[{"gap-x":E()}],"gap-y":[{"gap-y":E()}],"justify-content":[{justify:[...O(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...O()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":O()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:E()}],px:[{px:E()}],py:[{py:E()}],ps:[{ps:E()}],pe:[{pe:E()}],pt:[{pt:E()}],pr:[{pr:E()}],pb:[{pb:E()}],pl:[{pl:E()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":E()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":E()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],w:[{w:[a,"screen",...q()]}],"min-w":[{"min-w":[a,"screen","none",...q()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",r,tr,_t]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,D,Rn]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Sn,P]}],"font-family":[{font:[Dd,P,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,D,P]}],"line-clamp":[{"line-clamp":[J,"none",D,Rn]}],leading:[{leading:[s,...E()]}],"list-image":[{"list-image":["none",D,P]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",D,P]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ge(),"wavy"]}],"text-decoration-thickness":[{decoration:[J,"from-font","auto",D,_t]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[J,"auto",D,P]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:E()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",D,P]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",D,P]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ee()}],"bg-repeat":[{bg:de()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},gt,D,P],radial:["",D,P],conic:[gt,D,P]},Gd,Pd]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:te()}],"gradient-via-pos":[{via:te()}],"gradient-to-pos":[{to:te()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:G()}],"rounded-s":[{"rounded-s":G()}],"rounded-e":[{"rounded-e":G()}],"rounded-t":[{"rounded-t":G()}],"rounded-r":[{"rounded-r":G()}],"rounded-b":[{"rounded-b":G()}],"rounded-l":[{"rounded-l":G()}],"rounded-ss":[{"rounded-ss":G()}],"rounded-se":[{"rounded-se":G()}],"rounded-ee":[{"rounded-ee":G()}],"rounded-es":[{"rounded-es":G()}],"rounded-tl":[{"rounded-tl":G()}],"rounded-tr":[{"rounded-tr":G()}],"rounded-br":[{"rounded-br":G()}],"rounded-bl":[{"rounded-bl":G()}],"border-w":[{border:Z()}],"border-w-x":[{"border-x":Z()}],"border-w-y":[{"border-y":Z()}],"border-w-s":[{"border-s":Z()}],"border-w-e":[{"border-e":Z()}],"border-w-t":[{"border-t":Z()}],"border-w-r":[{"border-r":Z()}],"border-w-b":[{"border-b":Z()}],"border-w-l":[{"border-l":Z()}],"divide-x":[{"divide-x":Z()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Z()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ge(),"hidden","none"]}],"divide-style":[{divide:[...ge(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...ge(),"none","hidden"]}],"outline-offset":[{"outline-offset":[J,D,P]}],"outline-w":[{outline:["",J,tr,_t]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","none",d,Ar,Cr]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",g,Ar,Cr]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[J,_t]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":Z()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",p,Ar,Cr]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[J,D,P]}],"mix-blend":[{"mix-blend":[...Ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[J]}],"mask-image-linear-from-pos":[{"mask-linear-from":ce()}],"mask-image-linear-to-pos":[{"mask-linear-to":ce()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":ce()}],"mask-image-t-to-pos":[{"mask-t-to":ce()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":ce()}],"mask-image-r-to-pos":[{"mask-r-to":ce()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":ce()}],"mask-image-b-to-pos":[{"mask-b-to":ce()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":ce()}],"mask-image-l-to-pos":[{"mask-l-to":ce()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":ce()}],"mask-image-x-to-pos":[{"mask-x-to":ce()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":ce()}],"mask-image-y-to-pos":[{"mask-y-to":ce()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[D,P]}],"mask-image-radial-from-pos":[{"mask-radial-from":ce()}],"mask-image-radial-to-pos":[{"mask-radial-to":ce()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[J]}],"mask-image-conic-from-pos":[{"mask-conic-from":ce()}],"mask-image-conic-to-pos":[{"mask-conic-to":ce()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ee()}],"mask-repeat":[{mask:de()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",D,P]}],filter:[{filter:["","none",D,P]}],blur:[{blur:ft()}],brightness:[{brightness:[J,D,P]}],contrast:[{contrast:[J,D,P]}],"drop-shadow":[{"drop-shadow":["","none",f,Ar,Cr]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",J,D,P]}],"hue-rotate":[{"hue-rotate":[J,D,P]}],invert:[{invert:["",J,D,P]}],saturate:[{saturate:[J,D,P]}],sepia:[{sepia:["",J,D,P]}],"backdrop-filter":[{"backdrop-filter":["","none",D,P]}],"backdrop-blur":[{"backdrop-blur":ft()}],"backdrop-brightness":[{"backdrop-brightness":[J,D,P]}],"backdrop-contrast":[{"backdrop-contrast":[J,D,P]}],"backdrop-grayscale":[{"backdrop-grayscale":["",J,D,P]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[J,D,P]}],"backdrop-invert":[{"backdrop-invert":["",J,D,P]}],"backdrop-opacity":[{"backdrop-opacity":[J,D,P]}],"backdrop-saturate":[{"backdrop-saturate":[J,D,P]}],"backdrop-sepia":[{"backdrop-sepia":["",J,D,P]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":E()}],"border-spacing-x":[{"border-spacing-x":E()}],"border-spacing-y":[{"border-spacing-y":E()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",D,P]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[J,"initial",D,P]}],ease:[{ease:["linear","initial",b,D,P]}],delay:[{delay:[J,D,P]}],animate:[{animate:["none",_,D,P]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[h,D,P]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:st()}],"rotate-x":[{"rotate-x":st()}],"rotate-y":[{"rotate-y":st()}],"rotate-z":[{"rotate-z":st()}],scale:[{scale:F()}],"scale-x":[{"scale-x":F()}],"scale-y":[{"scale-y":F()}],"scale-z":[{"scale-z":F()}],"scale-3d":["scale-3d"],skew:[{skew:M()}],"skew-x":[{"skew-x":M()}],"skew-y":[{"skew-y":M()}],transform:[{transform:[D,P,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:A()}],"translate-x":[{"translate-x":A()}],"translate-y":[{"translate-y":A()}],"translate-z":[{"translate-z":A()}],"translate-none":["translate-none"],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",D,P]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":E()}],"scroll-mx":[{"scroll-mx":E()}],"scroll-my":[{"scroll-my":E()}],"scroll-ms":[{"scroll-ms":E()}],"scroll-me":[{"scroll-me":E()}],"scroll-mt":[{"scroll-mt":E()}],"scroll-mr":[{"scroll-mr":E()}],"scroll-mb":[{"scroll-mb":E()}],"scroll-ml":[{"scroll-ml":E()}],"scroll-p":[{"scroll-p":E()}],"scroll-px":[{"scroll-px":E()}],"scroll-py":[{"scroll-py":E()}],"scroll-ps":[{"scroll-ps":E()}],"scroll-pe":[{"scroll-pe":E()}],"scroll-pt":[{"scroll-pt":E()}],"scroll-pr":[{"scroll-pr":E()}],"scroll-pb":[{"scroll-pb":E()}],"scroll-pl":[{"scroll-pl":E()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",D,P]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[J,tr,_t,Rn]}],stroke:[{stroke:["none",...$()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},zd=(t,{cacheSize:e,prefix:r,experimentalParseClassName:n,extend:o={},override:s={}})=>(sr(t,"cacheSize",e),sr(t,"prefix",r),sr(t,"experimentalParseClassName",n),Er(t.theme,s.theme),Er(t.classGroups,s.classGroups),Er(t.conflictingClassGroups,s.conflictingClassGroups),Er(t.conflictingClassGroupModifiers,s.conflictingClassGroupModifiers),sr(t,"orderSensitiveModifiers",s.orderSensitiveModifiers),Tr(t.theme,o.theme),Tr(t.classGroups,o.classGroups),Tr(t.conflictingClassGroups,o.conflictingClassGroups),Tr(t.conflictingClassGroupModifiers,o.conflictingClassGroupModifiers),vi(t,o,"orderSensitiveModifiers"),t),sr=(t,e,r)=>{r!==void 0&&(t[e]=r)},Er=(t,e)=>{if(e)for(const r in e)sr(t,r,e[r])},Tr=(t,e)=>{if(e)for(const r in e)vi(t,e,r)},vi=(t,e,r)=>{const n=e[r];n!==void 0&&(t[r]=t[r]?t[r].concat(n):n)},Bd=(t,...e)=>typeof t=="function"?qn(Wn,t,...e):qn(()=>zd(Wn(),t),...e),Hd=qn(Wn);var qd=t=>Ie(t)?Hd:Bd({...t,extend:{theme:t.theme,classGroups:t.classGroups,conflictingClassGroupModifiers:t.conflictingClassGroupModifiers,conflictingClassGroups:t.conflictingClassGroups,...t.extend}}),Wd=(t,e)=>{const r=Xr(t);return!r||!(e?.twMerge??!0)?r:((!lt.cachedTwMerge||lt.didTwMergeConfigChange)&&(lt.didTwMergeConfigChange=!1,lt.cachedTwMerge=qd(lt.cachedTwMergeConfig)),lt.cachedTwMerge(r)||void 0)},Yd=(...t)=>e=>Wd(t,e),{tv:_i}=nd(Yd);const Kd=_i({base:["rounded-lg border p-4 transition-all duration-200","flex items-center justify-between gap-4","cursor-pointer select-none","focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2","w-full max-w-md"],variants:{selected:{true:"!bg-blue-100 !border-blue-500 shadow-sm",false:""},disabled:{true:"opacity-50 cursor-not-allowed",false:""},correct:{true:"!border-green-500 !bg-green-50",false:""},wrong:{true:"!border-red-500 !bg-red-50",false:""},variant:{default:"border-gray-200 bg-white hover:bg-blue-50 hover:border-blue-300",ixl:"border-transparent bg-transparent hover:bg-gray-50"}},compoundVariants:[{selected:!0,disabled:!0,class:"opacity-70"},{selected:!0,variant:"ixl",class:"bg-blue-50 border-l-4 border-l-blue-500 border-t-transparent border-r-transparent border-b-transparent"},{correct:!0,variant:"ixl",class:"!border-l-4 !border-l-green-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-green-50/50"},{wrong:!0,variant:"ixl",class:"!border-l-4 !border-l-red-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-red-50/50"}],defaultVariants:{selected:!1,disabled:!1,correct:!1,wrong:!1,variant:"default"}}),Xd=_i({base:"flex gap-3",variants:{layout:{vertical:"flex-col",horizontal:"flex-row flex-wrap"}},defaultVariants:{layout:"vertical"}}),yo=x.memo(({id:t,children:e,selected:r,disabled:n=!1,correct:o=!1,wrong:s=!1,variant:i="default",onClick:a,className:c,style:l})=>{const d=x.useCallback(f=>{n||(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),a())},[n,a]),g=x.useCallback(()=>{n||a()},[n,a]),p=Kd({selected:r,disabled:n,correct:o,wrong:s,variant:i,className:c});return u.jsx("div",{id:t,role:"radio","aria-checked":r,"aria-disabled":n,tabIndex:n?-1:0,className:p,style:l,onClick:g,onKeyDown:d,children:e})});yo.displayName="OptionCard";const bo=x.memo(({type:t,options:e,value:r,onChange:n,disabled:o=!1,showResult:s=!1,correctAnswers:i=[],layout:a="vertical",variant:c="default",className:l,style:d})=>{const g=x.useMemo(()=>new Set(r.map(h=>h.id)),[r]),p=x.useMemo(()=>new Set(i),[i]),f=x.useCallback((h,y,b)=>{if(!o)if(t==="single")n([{id:h,content:y,contentType:b}]);else{const _=g.has(h);let w;_?w=r.filter(C=>C.id!==h):w=[...r,{id:h,content:y,contentType:b}],n(w)}},[t,o,g,r,n]),m=Xd({layout:a,className:l});return u.jsx("div",{role:"radiogroup",className:m,style:d,children:e.map(h=>{const y=g.has(h.id),b=s&&p.has(h.id),_=s&&y&&!p.has(h.id);return u.jsx(yo,{id:h.id,selected:y,disabled:o,correct:b,wrong:_,variant:c,onClick:()=>f(h.id,h.rawContent,h.contentType),children:h.label},h.id)})})});bo.displayName="OptionGroup";function Si(t){const[e,r]=x.useState(()=>new Set(t.map(h=>h.id))),[n,o]=x.useState(()=>{const h=new Set;return t.forEach(y=>{y.categories.forEach(b=>h.add(b.id))}),h}),s=x.useCallback(h=>{r(y=>{const b=new Set(y);return b.has(h)?b.delete(h):b.add(h),b})},[]),i=x.useCallback(h=>{o(y=>{const b=new Set(y);return b.has(h)?b.delete(h):b.add(h),b})},[]),a=x.useCallback(h=>{r(y=>new Set([...y,h]))},[]),c=x.useCallback(h=>{r(y=>{const b=new Set(y);return b.delete(h),b})},[]),l=x.useCallback(h=>{o(y=>new Set([...y,h]))},[]),d=x.useCallback(h=>{o(y=>{const b=new Set(y);return b.delete(h),b})},[]),g=x.useCallback(()=>{const h=new Set(t.map(b=>b.id)),y=new Set;t.forEach(b=>{b.categories.forEach(_=>y.add(_.id))}),r(h),o(y)},[t]),p=x.useCallback(()=>{r(new Set),o(new Set)},[]),f=x.useMemo(()=>({expandedGroups:e,expandedCategories:n}),[e,n]),m=x.useMemo(()=>({toggleGroup:s,toggleCategory:i,expandGroup:a,collapseGroup:c,expandCategory:l,collapseCategory:d,expandAll:g,collapseAll:p}),[s,i,a,c,l,d,g,p]);return{state:f,actions:m}}function Ri({data:t,renderGroupHeader:e,renderCategoryHeader:r,renderRow:n,renderCell:o,onCellClick:s,onRowClick:i,columns:a,enableTanStack:c=!1,className:l,getRowKey:d,"aria-label":g,"aria-labelledby":p}){const{state:f,actions:m}=Si(t),h=x.useCallback(w=>t.find(C=>C.categories.some(v=>v.id===w)),[t]),y=x.useCallback((w,C,v)=>{const k=h(v.id);if(!k)return null;const S={index:C,category:v,group:k,isFirst:C===0,isLast:C===v.items.length-1},E=d?d(w,C):`row-${v.id}-${C}`,N=()=>{i?.(w)},I=()=>a&&a.length>0?a.map((Y,K)=>{const L=Y.accessorKey,O=L?w[L]:null;return u.jsx("td",{onClick:()=>s?.(w,String(L)),children:o?o(O,w,Y):String(O??"")},K)}):u.jsx("td",{});return u.jsx("tr",{onClick:N,role:"row",className:i?"cursor-pointer":void 0,children:n?n(w,S):I()},E)},[n,o,i,s,a,d,h]),b=x.useCallback(w=>{const C=f.expandedCategories.has(w.id),v=()=>u.jsxs("div",{className:"table-category-header",onClick:()=>m.toggleCategory(w.id),role:"button","aria-expanded":C,children:[u.jsx("span",{children:C?"▼":"▶"}),u.jsx("span",{children:w.title})]});return u.jsxs("div",{className:"table-category","data-category-id":w.id,children:[r?r(w,{isExpanded:C,onToggle:()=>m.toggleCategory(w.id)}):v(),C&&u.jsx("table",{className:"w-full border-collapse",role:"table",children:u.jsx("tbody",{children:w.items.map((k,S)=>y(k,S,w))})})]},w.id)},[f.expandedCategories,m.toggleCategory,r,y]),_=x.useCallback(w=>{const C=f.expandedGroups.has(w.id),v=()=>u.jsxs("div",{className:"table-group-header",onClick:()=>m.toggleGroup(w.id),role:"button","aria-expanded":C,children:[u.jsx("span",{children:C?"▼":"▶"}),u.jsx("span",{children:w.title})]});return u.jsxs("div",{className:"table-group","data-group-id":w.id,children:[e?e(w,{isExpanded:C,onToggle:()=>m.toggleGroup(w.id)}):v(),C&&w.categories.map(b)]},w.id)},[f.expandedGroups,m.toggleGroup,e,b]);return u.jsx("div",{className:l,role:"region","aria-label":g,"aria-labelledby":p,children:t.map(_)})}x.memo(Ri);function ht(t,e){return typeof t=="function"?t(e):t}function He(t,e){return r=>{e.setState(n=>({...n,[t]:ht(r,n[t])}))}}function an(t){return t instanceof Function}function Jd(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Zd(t,e){const r=[],n=o=>{o.forEach(s=>{r.push(s);const i=e(s);i!=null&&i.length&&n(i)})};return n(t),r}function z(t,e,r){let n=[],o;return s=>{let i;r.key&&r.debug&&(i=Date.now());const a=t(s);if(!(a.length!==n.length||a.some((d,g)=>n[g]!==d)))return o;n=a;let l;if(r.key&&r.debug&&(l=Date.now()),o=e(...a),r==null||r.onChange==null||r.onChange(o),r.key&&r.debug&&r!=null&&r.debug()){const d=Math.round((Date.now()-i)*100)/100,g=Math.round((Date.now()-l)*100)/100,p=g/16,f=(m,h)=>{for(m=String(m);m.length<h;)m=" "+m;return m};console.info(`%c⏱ ${f(g,5)} /${f(d,5)} ms`,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),b=require("react"),zl=require("@heroui/progress"),Cn=require("@heroui/card"),xe=require("lucide-react"),X=require("@heroui/react"),Ul=require("katex"),Us=require("jsxgraph"),Yt=require("zustand"),Bs=require("zustand/shallow"),It=require("zustand/react/shallow"),Bl=require("zustand/middleware");function Hl(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ue=Hl(b),ft=({progress:t,variant:e="solid",size:r="md",radius:n="md",children:o,className:s="",loading:i,intent:a,useNewClassName:c=!1,...l})=>{const g=t!==void 0?(h=>{const y=c?"mathwiz-btn--":"button--";return h===0?`${y}primary`:h===100?`${y}success`:`${y}secondary`})(t):c?"mathwiz-btn--primary":"button--primary",m=c?"mathwiz-btn":"button",f=c?"mathwiz-btn--":"button--",p=[m,`${f}${r}`,`${f}${e}`,`${f}radius-${n}`,g,i&&`${f}loading`,a&&c?`mathwiz-btn--${a}`:null,s].filter(Boolean).join(" ");return d.jsx("button",{type:"button",className:p,"data-progress":t,disabled:i||l.disabled,...l,children:i?"加载中...":o})},Xo=t=>t===0?"开始学习":t===100?"复习":"继续学习",ql=t=>{if(t.length===0)return 0;const e=t.reduce((r,n)=>r+n.progress,0);return Math.round(e/t.length)},Wl=({knowledgeItem:t,onLearnAction:e})=>{const r=()=>{e(t)};return console.log("KnowledgeCard render:",{progress:t.progress,text:Xo(t.progress)}),d.jsxs(Cn.Card,{className:"content-accordion__knowledge-card",children:[d.jsxs(Cn.CardBody,{children:[d.jsx("h3",{className:"content-accordion__knowledge-title",children:t.title}),d.jsx("p",{className:"content-accordion__knowledge-description",children:t.description})]}),d.jsxs(Cn.CardFooter,{className:"content-accordion__knowledge-actions",children:[d.jsxs("div",{className:"content-accordion__progress-container",children:[d.jsx(zl.Progress,{value:t.progress,size:"sm",color:"primary","aria-label":`${t.title} 进度`,className:"content-accordion__progress-bar"}),d.jsxs("span",{className:"content-accordion__progress-text",children:[t.progress,"%"]})]}),d.jsx(ft,{size:"sm",radius:"md",onClick:r,progress:t.progress,variant:t.progress===100?"light":t.progress===0?"solid":"bordered",className:"content-accordion__learn-button",children:Xo(t.progress)})]})]})},Yl=({lesson:t,isExpanded:e,onToggle:r,onLearnAction:n})=>{const o=()=>{r(t.id)},s=ql(t.knowledgeItems);return d.jsxs("div",{className:`content-accordion__lesson-item ${e?"content-accordion__lesson-item--expanded":""}`,children:[d.jsxs("div",{className:"content-accordion__lesson-header",onClick:o,role:"button",tabIndex:0,"aria-expanded":e,"aria-label":`${t.title},点击${e?"收起":"展开"}`,children:[d.jsxs("div",{className:"content-accordion__lesson-header-content",children:[d.jsx("h2",{className:"content-accordion__lesson-title",children:t.title}),d.jsxs("span",{className:"content-accordion__lesson-duration",children:["约 ",t.duration," 分钟"]})]}),d.jsxs("div",{className:"content-accordion__lesson-actions",children:[d.jsxs("span",{className:"content-accordion__lesson-progress",children:[s,"%"]}),e?d.jsx(xe.ChevronDown,{className:"content-accordion__lesson-icon"}):d.jsx(xe.ChevronRight,{className:"content-accordion__lesson-icon"})]})]}),e&&d.jsx("div",{className:"content-accordion__knowledge-list",children:t.knowledgeItems.map(i=>d.jsx(Wl,{knowledgeItem:i,onLearnAction:n},i.id))})]})},Hs=({unit:t,activeLessonIds:e,onToggleLesson:r,onLearnAction:n,loading:o=!1,className:s="",emptyState:i})=>o?d.jsx("div",{className:"content-accordion content-accordion--loading",children:d.jsx("div",{className:"content-accordion__loading",children:"加载中..."})}):t?d.jsxs("div",{className:`content-accordion ${s}`,children:[d.jsxs("header",{className:"content-accordion__header",children:[d.jsx("h1",{className:"content-accordion__unit-title",children:t.title}),d.jsx("p",{className:"content-accordion__unit-description",children:t.description}),d.jsxs("div",{className:"content-accordion__unit-meta",children:[d.jsxs("span",{children:["总共 ",t.totalLessons," 节课"]}),d.jsx("span",{children:"•"}),d.jsxs("span",{children:["预计学习 ",t.estimatedDuration]})]})]}),d.jsx("div",{className:"content-accordion__lessons",children:t.lessons.map(a=>d.jsx(Yl,{lesson:a,isExpanded:e.includes(a.id),onToggle:r,onLearnAction:n},a.id))})]}):d.jsx("div",{className:"content-accordion content-accordion--empty",children:i||d.jsx("div",{className:"content-accordion__empty",children:"暂无学习内容"})}),Kl=t=>{switch(t){case"completed":return"success";case"in-progress":return"primary";default:return"default"}},qs=({data:t,loading:e=!1,error:r=null,collapsed:n=!1,onToggleCollapse:o,activeUnitId:s=null,onUnitSelect:i,renderUnitItem:a,className:c="",unitItemClassName:l="",style:u={},unitItemStyle:g={}})=>{const m=(y,x)=>{x.preventDefault(),i?.(y)},f=()=>{o?.()},p=y=>d.jsxs("div",{className:`sidebar__unit-item ${l} ${s===y.unitId?"sidebar__unit-item--active":""} ${y.status?`sidebar__unit-item--${y.status}`:""}`,style:g,onClick:x=>m(y.unitId,x),role:"button",tabIndex:0,"aria-label":`${y.title},进度 ${y.progressPercentage}%`,children:[d.jsxs("div",{className:"sidebar__unit-item__content",children:[y.icon&&d.jsx("span",{className:"sidebar__unit-item__icon",children:y.icon}),!n&&d.jsx("span",{className:"sidebar__unit-item__title",children:y.title})]}),!n&&y.progressPercentage!==void 0&&d.jsxs("div",{className:"sidebar__unit-item__progress",children:[d.jsx(X.Progress,{value:y.progressPercentage,size:"sm",color:Kl(y.status),"aria-label":`${y.title} 进度`}),d.jsxs("span",{className:"progress-percentage",children:[y.progressPercentage,"%"]})]})]},y.unitId),h=()=>e?d.jsx("div",{className:"sidebar__loading",children:"加载中..."}):r?d.jsxs("div",{className:"sidebar__error",children:["加载失败: ",r.message]}):t?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"sidebar__header",children:[d.jsx("button",{className:"sidebar__toggle-btn",onClick:f,"aria-label":"切换侧边栏折叠状态",children:n?"→":"←"}),!n&&d.jsxs("div",{className:"sidebar__course-info",children:[d.jsx("h3",{className:"sidebar__course-title",children:t.courseTitle}),d.jsxs("span",{className:"sidebar__course-level",children:[t.courseLevel,"年级"]})]})]}),d.jsx("nav",{className:"sidebar__content",children:d.jsx("ul",{className:"sidebar__unit-list",children:t.units&&t.units.length>0?t.units.map(y=>d.jsx("li",{children:a?a(y,y):p(y)},y.unitId)):d.jsx("div",{className:"sidebar__empty",children:"暂无单元数据"})})})]}):d.jsx("div",{className:"sidebar__empty",children:"暂无课程数据"});return d.jsx("aside",{className:`sidebar ${c} ${n?"sidebar--collapsed":""} ${e?"sidebar--loading":""} ${r?"sidebar--error":""}`,style:u,"aria-label":"课程导航侧边栏",role:"complementary",children:h()})},go=({trigger:t,items:e,position:r="bottom",alignment:n="start",openDelay:o=300,closeDelay:s=100,onOpen:i,onClose:a,renderItem:c,itemConfig:l={},className:u,menuClassName:g,itemClassName:m})=>{const[f,p]=b.useState(!1),h=b.useRef(null),y=b.useRef(null),x=()=>{h.current&&clearTimeout(h.current),y.current&&clearTimeout(y.current)},v=()=>{x(),h.current=setTimeout(()=>{p(!0),i?.()},o)},w=()=>{x(),y.current=setTimeout(()=>{p(!1),a?.()},s)},S=_=>{!_.disabled&&_.onClick&&_.onClick(_)};b.useEffect(()=>()=>x(),[]);const C=_=>d.jsxs("div",{className:`submenu-item ${_.disabled?"is-disabled":""} ${m||""}`,onClick:()=>S(_),children:[_.icon&&d.jsx("span",{className:"submenu-item-icon",children:_.icon}),d.jsx("span",{children:_.label})]},_.id),E=()=>{const _=["submenu-panel"];return g&&_.push(g),_.push(`position-${r}`),n!=="start"&&_.push(`alignment-${n}`),f&&_.push("is-open"),_.join(" ")};return d.jsxs("div",{className:`submenu-container ${u||""}`,onMouseEnter:v,onMouseLeave:w,children:[d.jsx("div",{className:"submenu-trigger",children:t}),d.jsx("div",{className:E(),children:e.map(_=>c?c(_,l):C(_))})]})};function Ws(t,e){return function(){return t.apply(e,arguments)}}const{toString:Xl}=Object.prototype,{getPrototypeOf:mo}=Object,{iterator:on,toStringTag:Ys}=Symbol,sn=(t=>e=>{const r=Xl.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Xe=t=>(t=t.toLowerCase(),e=>sn(e)===t),an=t=>e=>typeof e===t,{isArray:Kt}=Array,Bt=an("undefined");function hr(t){return t!==null&&!Bt(t)&&t.constructor!==null&&!Bt(t.constructor)&&De(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Ks=Xe("ArrayBuffer");function Jl(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Ks(t.buffer),e}const Zl=an("string"),De=an("function"),Xs=an("number"),yr=t=>t!==null&&typeof t=="object",Ql=t=>t===!0||t===!1,zr=t=>{if(sn(t)!=="object")return!1;const e=mo(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Ys in t)&&!(on in t)},ec=t=>{if(!yr(t)||hr(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},tc=Xe("Date"),rc=Xe("File"),nc=Xe("Blob"),oc=Xe("FileList"),sc=t=>yr(t)&&De(t.pipe),ic=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||De(t.append)&&((e=sn(t))==="formdata"||e==="object"&&De(t.toString)&&t.toString()==="[object FormData]"))},ac=Xe("URLSearchParams"),[lc,cc,dc,uc]=["ReadableStream","Request","Response","Headers"].map(Xe),fc=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function br(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,o;if(typeof t!="object"&&(t=[t]),Kt(t))for(n=0,o=t.length;n<o;n++)e.call(null,t[n],n,t);else{if(hr(t))return;const s=r?Object.getOwnPropertyNames(t):Object.keys(t),i=s.length;let a;for(n=0;n<i;n++)a=s[n],e.call(null,t[a],a,t)}}function Js(t,e){if(hr(t))return null;e=e.toLowerCase();const r=Object.keys(t);let n=r.length,o;for(;n-- >0;)if(o=r[n],e===o.toLowerCase())return o;return null}const Tt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Zs=t=>!Bt(t)&&t!==Tt;function Un(){const{caseless:t,skipUndefined:e}=Zs(this)&&this||{},r={},n=(o,s)=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;const i=t&&Js(r,s)||s;zr(r[i])&&zr(o)?r[i]=Un(r[i],o):zr(o)?r[i]=Un({},o):Kt(o)?r[i]=o.slice():(!e||!Bt(o))&&(r[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&br(arguments[o],n);return r}const gc=(t,e,r,{allOwnKeys:n}={})=>(br(e,(o,s)=>{r&&De(o)?Object.defineProperty(t,s,{value:Ws(o,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),t),mc=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),pc=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},hc=(t,e,r,n)=>{let o,s,i;const a={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),s=o.length;s-- >0;)i=o[s],(!n||n(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=r!==!1&&mo(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},yc=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return n!==-1&&n===r},bc=t=>{if(!t)return null;if(Kt(t))return t;let e=t.length;if(!Xs(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},xc=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&mo(Uint8Array)),wc=(t,e)=>{const n=(t&&t[on]).call(t);let o;for(;(o=n.next())&&!o.done;){const s=o.value;e.call(t,s[0],s[1])}},vc=(t,e)=>{let r;const n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Cc=Xe("HTMLFormElement"),Sc=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,o){return n.toUpperCase()+o}),Jo=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),_c=Xe("RegExp"),Qs=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};br(r,(o,s)=>{let i;(i=e(o,s,t))!==!1&&(n[s]=i||o)}),Object.defineProperties(t,n)},Rc=t=>{Qs(t,(e,r)=>{if(De(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const n=t[r];if(De(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Ac=(t,e)=>{const r={},n=o=>{o.forEach(s=>{r[s]=!0})};return Kt(t)?n(t):n(String(t).split(e)),r},Ec=()=>{},Nc=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Tc(t){return!!(t&&De(t.append)&&t[Ys]==="FormData"&&t[on])}const $c=t=>{const e=new Array(10),r=(n,o)=>{if(yr(n)){if(e.indexOf(n)>=0)return;if(hr(n))return n;if(!("toJSON"in n)){e[o]=n;const s=Kt(n)?[]:{};return br(n,(i,a)=>{const c=r(i,o+1);!Bt(c)&&(s[a]=c)}),e[o]=void 0,s}}return n};return r(t,0)},kc=Xe("AsyncFunction"),jc=t=>t&&(yr(t)||De(t))&&De(t.then)&&De(t.catch),ei=((t,e)=>t?setImmediate:e?((r,n)=>(Tt.addEventListener("message",({source:o,data:s})=>{o===Tt&&s===r&&n.length&&n.shift()()},!1),o=>{n.push(o),Tt.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",De(Tt.postMessage)),Ic=typeof queueMicrotask<"u"?queueMicrotask.bind(Tt):typeof process<"u"&&process.nextTick||ei,Mc=t=>t!=null&&De(t[on]),R={isArray:Kt,isArrayBuffer:Ks,isBuffer:hr,isFormData:ic,isArrayBufferView:Jl,isString:Zl,isNumber:Xs,isBoolean:Ql,isObject:yr,isPlainObject:zr,isEmptyObject:ec,isReadableStream:lc,isRequest:cc,isResponse:dc,isHeaders:uc,isUndefined:Bt,isDate:tc,isFile:rc,isBlob:nc,isRegExp:_c,isFunction:De,isStream:sc,isURLSearchParams:ac,isTypedArray:xc,isFileList:oc,forEach:br,merge:Un,extend:gc,trim:fc,stripBOM:mc,inherits:pc,toFlatObject:hc,kindOf:sn,kindOfTest:Xe,endsWith:yc,toArray:bc,forEachEntry:wc,matchAll:vc,isHTMLForm:Cc,hasOwnProperty:Jo,hasOwnProp:Jo,reduceDescriptors:Qs,freezeMethods:Rc,toObjectSet:Ac,toCamelCase:Sc,noop:Ec,toFiniteNumber:Nc,findKey:Js,global:Tt,isContextDefined:Zs,isSpecCompliantForm:Tc,toJSONObject:$c,isAsyncFn:kc,isThenable:jc,setImmediate:ei,asap:Ic,isIterable:Mc};let Y=class ti extends Error{static from(e,r,n,o,s,i){const a=new ti(e.message,r||e.code,n,o,s);return a.cause=e,a.name=e.name,i&&Object.assign(a,i),a}constructor(e,r,n,o,s){super(e),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),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:R.toJSONObject(this.config),code:this.code,status:this.status}}};Y.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Y.ERR_BAD_OPTION="ERR_BAD_OPTION";Y.ECONNABORTED="ECONNABORTED";Y.ETIMEDOUT="ETIMEDOUT";Y.ERR_NETWORK="ERR_NETWORK";Y.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Y.ERR_DEPRECATED="ERR_DEPRECATED";Y.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Y.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Y.ERR_CANCELED="ERR_CANCELED";Y.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Y.ERR_INVALID_URL="ERR_INVALID_URL";const Oc=null;function Bn(t){return R.isPlainObject(t)||R.isArray(t)}function ri(t){return R.endsWith(t,"[]")?t.slice(0,-2):t}function Zo(t,e,r){return t?t.concat(e).map(function(o,s){return o=ri(o),!r&&s?"["+o+"]":o}).join(r?".":""):e}function Fc(t){return R.isArray(t)&&!t.some(Bn)}const Pc=R.toFlatObject(R,{},null,function(e){return/^is[A-Z]/.test(e)});function ln(t,e,r){if(!R.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=R.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,y){return!R.isUndefined(y[h])});const n=r.metaTokens,o=r.visitor||u,s=r.dots,i=r.indexes,c=(r.Blob||typeof Blob<"u"&&Blob)&&R.isSpecCompliantForm(e);if(!R.isFunction(o))throw new TypeError("visitor must be a function");function l(p){if(p===null)return"";if(R.isDate(p))return p.toISOString();if(R.isBoolean(p))return p.toString();if(!c&&R.isBlob(p))throw new Y("Blob is not supported. Use a Buffer instead.");return R.isArrayBuffer(p)||R.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,h,y){let x=p;if(p&&!y&&typeof p=="object"){if(R.endsWith(h,"{}"))h=n?h:h.slice(0,-2),p=JSON.stringify(p);else if(R.isArray(p)&&Fc(p)||(R.isFileList(p)||R.endsWith(h,"[]"))&&(x=R.toArray(p)))return h=ri(h),x.forEach(function(w,S){!(R.isUndefined(w)||w===null)&&e.append(i===!0?Zo([h],S,s):i===null?h:h+"[]",l(w))}),!1}return Bn(p)?!0:(e.append(Zo(y,h,s),l(p)),!1)}const g=[],m=Object.assign(Pc,{defaultVisitor:u,convertValue:l,isVisitable:Bn});function f(p,h){if(!R.isUndefined(p)){if(g.indexOf(p)!==-1)throw Error("Circular reference detected in "+h.join("."));g.push(p),R.forEach(p,function(x,v){(!(R.isUndefined(x)||x===null)&&o.call(e,x,R.isString(v)?v.trim():v,h,m))===!0&&f(x,h?h.concat(v):[v])}),g.pop()}}if(!R.isObject(t))throw new TypeError("data must be an object");return f(t),e}function Qo(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function po(t,e){this._pairs=[],t&&ln(t,this,e)}const ni=po.prototype;ni.append=function(e,r){this._pairs.push([e,r])};ni.toString=function(e){const r=e?function(n){return e.call(this,n,Qo)}:Qo;return this._pairs.map(function(o){return r(o[0])+"="+r(o[1])},"").join("&")};function Dc(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function oi(t,e,r){if(!e)return t;const n=r&&r.encode||Dc,o=R.isFunction(r)?{serialize:r}:r,s=o&&o.serialize;let i;if(s?i=s(e,o):i=R.isURLSearchParams(e)?e.toString():new po(e,o).toString(n),i){const a=t.indexOf("#");a!==-1&&(t=t.slice(0,a)),t+=(t.indexOf("?")===-1?"?":"&")+i}return t}class es{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,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){R.forEach(this.handlers,function(n){n!==null&&e(n)})}}const ho={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},Lc=typeof URLSearchParams<"u"?URLSearchParams:po,Gc=typeof FormData<"u"?FormData:null,Vc=typeof Blob<"u"?Blob:null,zc={isBrowser:!0,classes:{URLSearchParams:Lc,FormData:Gc,Blob:Vc},protocols:["http","https","file","blob","url","data"]},yo=typeof window<"u"&&typeof document<"u",Hn=typeof navigator=="object"&&navigator||void 0,Uc=yo&&(!Hn||["ReactNative","NativeScript","NS"].indexOf(Hn.product)<0),Bc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Hc=yo&&window.location.href||"http://localhost",qc=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:yo,hasStandardBrowserEnv:Uc,hasStandardBrowserWebWorkerEnv:Bc,navigator:Hn,origin:Hc},Symbol.toStringTag,{value:"Module"})),Me={...qc,...zc};function Wc(t,e){return ln(t,new Me.classes.URLSearchParams,{visitor:function(r,n,o,s){return Me.isNode&&R.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...e})}function Yc(t){return R.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Kc(t){const e={},r=Object.keys(t);let n;const o=r.length;let s;for(n=0;n<o;n++)s=r[n],e[s]=t[s];return e}function si(t){function e(r,n,o,s){let i=r[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),c=s>=r.length;return i=!i&&R.isArray(o)?o.length:i,c?(R.hasOwnProp(o,i)?o[i]=[o[i],n]:o[i]=n,!a):((!o[i]||!R.isObject(o[i]))&&(o[i]=[]),e(r,n,o[i],s)&&R.isArray(o[i])&&(o[i]=Kc(o[i])),!a)}if(R.isFormData(t)&&R.isFunction(t.entries)){const r={};return R.forEachEntry(t,(n,o)=>{e(Yc(n),o,r,0)}),r}return null}function Xc(t,e,r){if(R.isString(t))try{return(e||JSON.parse)(t),R.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}const xr={transitional:ho,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){const n=r.getContentType()||"",o=n.indexOf("application/json")>-1,s=R.isObject(e);if(s&&R.isHTMLForm(e)&&(e=new FormData(e)),R.isFormData(e))return o?JSON.stringify(si(e)):e;if(R.isArrayBuffer(e)||R.isBuffer(e)||R.isStream(e)||R.isFile(e)||R.isBlob(e)||R.isReadableStream(e))return e;if(R.isArrayBufferView(e))return e.buffer;if(R.isURLSearchParams(e))return r.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 Wc(e,this.formSerializer).toString();if((a=R.isFileList(e))||n.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return ln(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return s||o?(r.setContentType("application/json",!1),Xc(e)):e}],transformResponse:[function(e){const r=this.transitional||xr.transitional,n=r&&r.forcedJSONParsing,o=this.responseType==="json";if(R.isResponse(e)||R.isReadableStream(e))return e;if(e&&R.isString(e)&&(n&&!this.responseType||o)){const i=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?Y.from(a,Y.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:Me.classes.FormData,Blob:Me.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};R.forEach(["delete","get","head","post","put","patch"],t=>{xr.headers[t]={}});const Jc=R.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"]),Zc=t=>{const e={};let r,n,o;return t&&t.split(`
2
+ `).forEach(function(i){o=i.indexOf(":"),r=i.substring(0,o).trim().toLowerCase(),n=i.substring(o+1).trim(),!(!r||e[r]&&Jc[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},ts=Symbol("internals");function nr(t){return t&&String(t).trim().toLowerCase()}function Ur(t){return t===!1||t==null?t:R.isArray(t)?t.map(Ur):String(t)}function Qc(t){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}const ed=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Sn(t,e,r,n,o){if(R.isFunction(n))return n.call(this,e,r);if(o&&(e=r),!!R.isString(e)){if(R.isString(n))return e.indexOf(n)!==-1;if(R.isRegExp(n))return n.test(e)}}function td(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function rd(t,e){const r=R.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(o,s,i){return this[n].call(this,e,o,s,i)},configurable:!0})})}let Le=class{constructor(e){e&&this.set(e)}set(e,r,n){const o=this;function s(a,c,l){const u=nr(c);if(!u)throw new Error("header name must be a non-empty string");const g=R.findKey(o,u);(!g||o[g]===void 0||l===!0||l===void 0&&o[g]!==!1)&&(o[g||c]=Ur(a))}const i=(a,c)=>R.forEach(a,(l,u)=>s(l,u,c));if(R.isPlainObject(e)||e instanceof this.constructor)i(e,r);else if(R.isString(e)&&(e=e.trim())&&!ed(e))i(Zc(e),r);else if(R.isObject(e)&&R.isIterable(e)){let a={},c,l;for(const u of e){if(!R.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[l=u[0]]=(c=a[l])?R.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}i(a,r)}else e!=null&&s(r,e,n);return this}get(e,r){if(e=nr(e),e){const n=R.findKey(this,e);if(n){const o=this[n];if(!r)return o;if(r===!0)return Qc(o);if(R.isFunction(r))return r.call(this,o,n);if(R.isRegExp(r))return r.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=nr(e),e){const n=R.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||Sn(this,this[n],n,r)))}return!1}delete(e,r){const n=this;let o=!1;function s(i){if(i=nr(i),i){const a=R.findKey(n,i);a&&(!r||Sn(n,n[a],a,r))&&(delete n[a],o=!0)}}return R.isArray(e)?e.forEach(s):s(e),o}clear(e){const r=Object.keys(this);let n=r.length,o=!1;for(;n--;){const s=r[n];(!e||Sn(this,this[s],s,e,!0))&&(delete this[s],o=!0)}return o}normalize(e){const r=this,n={};return R.forEach(this,(o,s)=>{const i=R.findKey(n,s);if(i){r[i]=Ur(o),delete r[s];return}const a=e?td(s):String(s).trim();a!==s&&delete r[s],r[a]=Ur(o),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const r=Object.create(null);return R.forEach(this,(n,o)=>{n!=null&&n!==!1&&(r[o]=e&&R.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).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,...r){const n=new this(e);return r.forEach(o=>n.set(o)),n}static accessor(e){const n=(this[ts]=this[ts]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=nr(i);n[a]||(rd(o,i),n[a]=!0)}return R.isArray(e)?e.forEach(s):s(e),this}};Le.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);R.reduceDescriptors(Le.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});R.freezeMethods(Le);function _n(t,e){const r=this||xr,n=e||r,o=Le.from(n.headers);let s=n.data;return R.forEach(t,function(a){s=a.call(r,s,o.normalize(),e?e.status:void 0)}),o.normalize(),s}function ii(t){return!!(t&&t.__CANCEL__)}let wr=class extends Y{constructor(e,r,n){super(e??"canceled",Y.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function ai(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Y("Request failed with status code "+r.status,[Y.ERR_BAD_REQUEST,Y.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function nd(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function od(t,e){t=t||10;const r=new Array(t),n=new Array(t);let o=0,s=0,i;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),u=n[s];i||(i=l),r[o]=c,n[o]=l;let g=s,m=0;for(;g!==o;)m+=r[g++],g=g%t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),l-i<e)return;const f=u&&l-u;return f?Math.round(m*1e3/f):void 0}}function sd(t,e){let r=0,n=1e3/e,o,s;const i=(l,u=Date.now())=>{r=u,o=null,s&&(clearTimeout(s),s=null),t(...l)};return[(...l)=>{const u=Date.now(),g=u-r;g>=n?i(l,u):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},n-g)))},()=>o&&i(o)]}const Zr=(t,e,r=3)=>{let n=0;const o=od(50,250);return sd(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-n,l=o(c),u=i<=a;n=i;const g={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&u?(a-i)/l:void 0,event:s,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(g)},r)},rs=(t,e)=>{const r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},ns=t=>(...e)=>R.asap(()=>t(...e)),id=Me.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,Me.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(Me.origin),Me.navigator&&/(msie|trident)/i.test(Me.navigator.userAgent)):()=>!0,ad=Me.hasStandardBrowserEnv?{write(t,e,r,n,o,s,i){if(typeof document>"u")return;const a=[`${t}=${encodeURIComponent(e)}`];R.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),R.isString(n)&&a.push(`path=${n}`),R.isString(o)&&a.push(`domain=${o}`),s===!0&&a.push("secure"),R.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function ld(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function cd(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function li(t,e,r){let n=!ld(e);return t&&(n||r==!1)?cd(t,e):e}const os=t=>t instanceof Le?{...t}:t;function kt(t,e){e=e||{};const r={};function n(l,u,g,m){return R.isPlainObject(l)&&R.isPlainObject(u)?R.merge.call({caseless:m},l,u):R.isPlainObject(u)?R.merge({},u):R.isArray(u)?u.slice():u}function o(l,u,g,m){if(R.isUndefined(u)){if(!R.isUndefined(l))return n(void 0,l,g,m)}else return n(l,u,g,m)}function s(l,u){if(!R.isUndefined(u))return n(void 0,u)}function i(l,u){if(R.isUndefined(u)){if(!R.isUndefined(l))return n(void 0,l)}else return n(void 0,u)}function a(l,u,g){if(g in e)return n(l,u);if(g in t)return n(void 0,l)}const c={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,u,g)=>o(os(l),os(u),g,!0)};return R.forEach(Object.keys({...t,...e}),function(u){if(u==="__proto__"||u==="constructor"||u==="prototype")return;const g=R.hasOwnProp(c,u)?c[u]:o,m=g(t[u],e[u],u);R.isUndefined(m)&&g!==a||(r[u]=m)}),r}const ci=t=>{const e=kt({},t);let{data:r,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=e;if(e.headers=i=Le.from(i),e.url=oi(li(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),R.isFormData(r)){if(Me.hasStandardBrowserEnv||Me.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(R.isFunction(r.getHeaders)){const c=r.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([u,g])=>{l.includes(u.toLowerCase())&&i.set(u,g)})}}if(Me.hasStandardBrowserEnv&&(n&&R.isFunction(n)&&(n=n(e)),n||n!==!1&&id(e.url))){const c=o&&s&&ad.read(s);c&&i.set(o,c)}return e},dd=typeof XMLHttpRequest<"u",ud=dd&&function(t){return new Promise(function(r,n){const o=ci(t);let s=o.data;const i=Le.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=o,u,g,m,f,p;function h(){f&&f(),p&&p(),o.cancelToken&&o.cancelToken.unsubscribe(u),o.signal&&o.signal.removeEventListener("abort",u)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const w=Le.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:w,config:t,request:y};ai(function(_){r(_),h()},function(_){n(_),h()},C),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(n(new Y("Request aborted",Y.ECONNABORTED,t,y)),y=null)},y.onerror=function(S){const C=S&&S.message?S.message:"Network Error",E=new Y(C,Y.ERR_NETWORK,t,y);E.event=S||null,n(E),y=null},y.ontimeout=function(){let S=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||ho;o.timeoutErrorMessage&&(S=o.timeoutErrorMessage),n(new Y(S,C.clarifyTimeoutError?Y.ETIMEDOUT:Y.ECONNABORTED,t,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&R.forEach(i.toJSON(),function(S,C){y.setRequestHeader(C,S)}),R.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),l&&([m,p]=Zr(l,!0),y.addEventListener("progress",m)),c&&y.upload&&([g,f]=Zr(c),y.upload.addEventListener("progress",g),y.upload.addEventListener("loadend",f)),(o.cancelToken||o.signal)&&(u=w=>{y&&(n(!w||w.type?new wr(null,t,y):w),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(u),o.signal&&(o.signal.aborted?u():o.signal.addEventListener("abort",u)));const v=nd(o.url);if(v&&Me.protocols.indexOf(v)===-1){n(new Y("Unsupported protocol "+v+":",Y.ERR_BAD_REQUEST,t));return}y.send(s||null)})},fd=(t,e)=>{const{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,o;const s=function(l){if(!o){o=!0,a();const u=l instanceof Error?l:this.reason;n.abort(u instanceof Y?u:new wr(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,s(new Y(`timeout of ${e}ms exceeded`,Y.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),t=null)};t.forEach(l=>l.addEventListener("abort",s));const{signal:c}=n;return c.unsubscribe=()=>R.asap(a),c}},gd=function*(t,e){let r=t.byteLength;if(r<e){yield t;return}let n=0,o;for(;n<r;)o=n+e,yield t.slice(n,o),n=o},md=async function*(t,e){for await(const r of pd(t))yield*gd(r,e)},pd=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},ss=(t,e,r,n)=>{const o=md(t,e);let s=0,i,a=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{const{done:l,value:u}=await o.next();if(l){a(),c.close();return}let g=u.byteLength;if(r){let m=s+=g;r(m)}c.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},is=64*1024,{isFunction:Er}=R,hd=(({Request:t,Response:e})=>({Request:t,Response:e}))(R.global),{ReadableStream:as,TextEncoder:ls}=R.global,cs=(t,...e)=>{try{return!!t(...e)}catch{return!1}},yd=t=>{t=R.merge.call({skipUndefined:!0},hd,t);const{fetch:e,Request:r,Response:n}=t,o=e?Er(e):typeof fetch=="function",s=Er(r),i=Er(n);if(!o)return!1;const a=o&&Er(as),c=o&&(typeof ls=="function"?(p=>h=>p.encode(h))(new ls):async p=>new Uint8Array(await new r(p).arrayBuffer())),l=s&&a&&cs(()=>{let p=!1;const h=new r(Me.origin,{body:new as,method:"POST",get duplex(){return p=!0,"half"}}).headers.has("Content-Type");return p&&!h}),u=i&&a&&cs(()=>R.isReadableStream(new n("").body)),g={stream:u&&(p=>p.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(p=>{!g[p]&&(g[p]=(h,y)=>{let x=h&&h[p];if(x)return x.call(h);throw new Y(`Response type '${p}' is not supported`,Y.ERR_NOT_SUPPORT,y)})});const m=async p=>{if(p==null)return 0;if(R.isBlob(p))return p.size;if(R.isSpecCompliantForm(p))return(await new r(Me.origin,{method:"POST",body:p}).arrayBuffer()).byteLength;if(R.isArrayBufferView(p)||R.isArrayBuffer(p))return p.byteLength;if(R.isURLSearchParams(p)&&(p=p+""),R.isString(p))return(await c(p)).byteLength},f=async(p,h)=>{const y=R.toFiniteNumber(p.getContentLength());return y??m(h)};return async p=>{let{url:h,method:y,data:x,signal:v,cancelToken:w,timeout:S,onDownloadProgress:C,onUploadProgress:E,responseType:_,headers:A,withCredentials:T="same-origin",fetchOptions:j}=ci(p),U=e||fetch;_=_?(_+"").toLowerCase():"text";let z=fd([v,w&&w.toAbortSignal()],S),O=null;const M=z&&z.unsubscribe&&(()=>{z.unsubscribe()});let F;try{if(E&&l&&y!=="get"&&y!=="head"&&(F=await f(A,x))!==0){let ne=new r(h,{method:"POST",body:x,duplex:"half"}),re;if(R.isFormData(x)&&(re=ne.headers.get("content-type"))&&A.setContentType(re),ne.body){const[V,Q]=rs(F,Zr(ns(E)));x=ss(ne.body,is,V,Q)}}R.isString(T)||(T=T?"include":"omit");const $=s&&"credentials"in r.prototype,B={...j,signal:z,method:y.toUpperCase(),headers:A.normalize().toJSON(),body:x,duplex:"half",credentials:$?T:void 0};O=s&&new r(h,B);let k=await(s?U(O,j):U(h,B));const te=u&&(_==="stream"||_==="response");if(u&&(C||te&&M)){const ne={};["status","statusText","headers"].forEach(me=>{ne[me]=k[me]});const re=R.toFiniteNumber(k.headers.get("content-length")),[V,Q]=C&&rs(re,Zr(ns(C),!0))||[];k=new n(ss(k.body,is,V,()=>{Q&&Q(),M&&M()}),ne)}_=_||"text";let ue=await g[R.findKey(g,_)||"text"](k,p);return!te&&M&&M(),await new Promise((ne,re)=>{ai(ne,re,{data:ue,headers:Le.from(k.headers),status:k.status,statusText:k.statusText,config:p,request:O})})}catch($){throw M&&M(),$&&$.name==="TypeError"&&/Load failed|fetch/i.test($.message)?Object.assign(new Y("Network Error",Y.ERR_NETWORK,p,O,$&&$.response),{cause:$.cause||$}):Y.from($,$&&$.code,p,O,$&&$.response)}}},bd=new Map,di=t=>{let e=t&&t.env||{};const{fetch:r,Request:n,Response:o}=e,s=[n,o,r];let i=s.length,a=i,c,l,u=bd;for(;a--;)c=s[a],l=u.get(c),l===void 0&&u.set(c,l=a?new Map:yd(e)),u=l;return l};di();const bo={http:Oc,xhr:ud,fetch:{get:di}};R.forEach(bo,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const ds=t=>`- ${t}`,xd=t=>R.isFunction(t)||t===null||t===!1;function wd(t,e){t=R.isArray(t)?t:[t];const{length:r}=t;let n,o;const s={};for(let i=0;i<r;i++){n=t[i];let a;if(o=n,!xd(n)&&(o=bo[(a=String(n)).toLowerCase()],o===void 0))throw new Y(`Unknown adapter '${a}'`);if(o&&(R.isFunction(o)||(o=o.get(e))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=r?i.length>1?`since :
4
+ `+i.map(ds).join(`
5
+ `):" "+ds(i[0]):"as no adapter specified";throw new Y("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o}const ui={getAdapter:wd,adapters:bo};function Rn(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new wr(null,t)}function us(t){return Rn(t),t.headers=Le.from(t.headers),t.data=_n.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ui.getAdapter(t.adapter||xr.adapter,t)(t).then(function(n){return Rn(t),n.data=_n.call(t,t.transformResponse,n),n.headers=Le.from(n.headers),n},function(n){return ii(n)||(Rn(t),n&&n.response&&(n.response.data=_n.call(t,t.transformResponse,n.response),n.response.headers=Le.from(n.response.headers))),Promise.reject(n)})}const fi="1.13.5",cn={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{cn[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const fs={};cn.transitional=function(e,r,n){function o(s,i){return"[Axios v"+fi+"] Transitional option '"+s+"'"+i+(n?". "+n:"")}return(s,i,a)=>{if(e===!1)throw new Y(o(i," has been removed"+(r?" in "+r:"")),Y.ERR_DEPRECATED);return r&&!fs[i]&&(fs[i]=!0,console.warn(o(i," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,i,a):!0}};cn.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function vd(t,e,r){if(typeof t!="object")throw new Y("options must be an object",Y.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let o=n.length;for(;o-- >0;){const s=n[o],i=e[s];if(i){const a=t[s],c=a===void 0||i(a,s,t);if(c!==!0)throw new Y("option "+s+" must be "+c,Y.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Y("Unknown option "+s,Y.ERR_BAD_OPTION)}}const Br={assertOptions:vd,validators:cn},We=Br.validators;let $t=class{constructor(e){this.defaults=e||{},this.interceptors={request:new es,response:new es}}async request(e,r){try{return await this._request(e,r)}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+=`
6
+ `+s):n.stack=s}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=kt(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&Br.assertOptions(n,{silentJSONParsing:We.transitional(We.boolean),forcedJSONParsing:We.transitional(We.boolean),clarifyTimeoutError:We.transitional(We.boolean),legacyInterceptorReqResOrdering:We.transitional(We.boolean)},!1),o!=null&&(R.isFunction(o)?r.paramsSerializer={serialize:o}:Br.assertOptions(o,{encode:We.function,serialize:We.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Br.assertOptions(r,{baseUrl:We.spelling("baseURL"),withXsrfToken:We.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[r.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],p=>{delete s[p]}),r.headers=Le.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;c=c&&h.synchronous;const y=r.transitional||ho;y&&y.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});const l=[];this.interceptors.response.forEach(function(h){l.push(h.fulfilled,h.rejected)});let u,g=0,m;if(!c){const p=[us.bind(this),void 0];for(p.unshift(...a),p.push(...l),m=p.length,u=Promise.resolve(r);g<m;)u=u.then(p[g++],p[g++]);return u}m=a.length;let f=r;for(;g<m;){const p=a[g++],h=a[g++];try{f=p(f)}catch(y){h.call(this,y);break}}try{u=us.call(this,f)}catch(p){return Promise.reject(p)}for(g=0,m=l.length;g<m;)u=u.then(l[g++],l[g++]);return u}getUri(e){e=kt(this.defaults,e);const r=li(e.baseURL,e.url,e.allowAbsoluteUrls);return oi(r,e.params,e.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(e){$t.prototype[e]=function(r,n){return this.request(kt(n||{},{method:e,url:r,data:(n||{}).data}))}});R.forEach(["post","put","patch"],function(e){function r(n){return function(s,i,a){return this.request(kt(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}$t.prototype[e]=r(),$t.prototype[e+"Form"]=r(!0)});let Cd=class gi{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=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 wr(s,i,a),r(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 r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new gi(function(o){e=o}),cancel:e}}};function Sd(t){return function(r){return t.apply(null,r)}}function _d(t){return R.isObject(t)&&t.isAxiosError===!0}const qn={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(qn).forEach(([t,e])=>{qn[e]=t});function mi(t){const e=new $t(t),r=Ws($t.prototype.request,e);return R.extend(r,$t.prototype,e,{allOwnKeys:!0}),R.extend(r,e,null,{allOwnKeys:!0}),r.create=function(o){return mi(kt(t,o))},r}const ye=mi(xr);ye.Axios=$t;ye.CanceledError=wr;ye.CancelToken=Cd;ye.isCancel=ii;ye.VERSION=fi;ye.toFormData=ln;ye.AxiosError=Y;ye.Cancel=ye.CanceledError;ye.all=function(e){return Promise.all(e)};ye.spread=Sd;ye.isAxiosError=_d;ye.mergeConfig=kt;ye.AxiosHeaders=Le;ye.formToJSON=t=>si(R.isHTMLForm(t)?new FormData(t):t);ye.getAdapter=ui.getAdapter;ye.HttpStatusCode=qn;ye.default=ye;const{Axios:Tb,AxiosError:$b,CanceledError:kb,isCancel:jb,CancelToken:Ib,VERSION:Mb,all:Ob,Cancel:Fb,isAxiosError:Pb,spread:Db,toFormData:Lb,AxiosHeaders:Gb,HttpStatusCode:Vb,formToJSON:zb,getAdapter:Ub,mergeConfig:Bb}=ye,Rd=()=>d.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"👤"}),Ad=()=>d.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"⚙️"}),Ed=()=>d.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"❓"}),Nd=()=>d.jsx("span",{style:{marginRight:8,fontSize:"1.2em"},children:"🚪"}),Td=[{id:"profile",label:"个人主页",icon:d.jsx(Rd,{})},{id:"settings",label:"设置",icon:d.jsx(Ad,{})},{id:"help",label:"帮助",icon:d.jsx(Ed,{})},{id:"logout",label:"退出",icon:d.jsx(Nd,{})}],pi=({userId:t,userName:e,userAvatar:r,apiConfig:n,menuItems:o=Td,avatarSize:s="md",isLoading:i=!1,error:a=null,avatarClassName:c,userNameClassName:l,containerClassName:u,onMenuOpen:g,onMenuClose:m,onMenuItemClick:f,onLogout:p,renderMenuItem:h,renderUserInfo:y})=>{const[x,v]=b.useState({id:t||"",name:e||"",avatar:r||"",level:0,badges:[]}),[w,S]=b.useState(i),[C,E]=b.useState(a);b.useEffect(()=>{t&&n&&!e&&!r&&_()},[t,n,e,r]);const _=async()=>{S(!0),E(null);try{const O=n.endpoints.userProfile.replace(":userId",t),M=await ye.get(`${n.baseURL}${O}`,{headers:n.headers});v(M.data)}catch(O){E(O)}finally{S(!1)}},A=O=>{f?.(O.id),O.id==="logout"&&p?.()},T=()=>{g?.()},j=()=>{m?.()},U=()=>d.jsxs("div",{className:"user-profile-trigger",children:[d.jsx(X.Avatar,{src:x.avatar,size:s,className:c,alt:"用户头像"}),d.jsx("span",{className:`user-name ${l||""}`,children:x.name})]}),z=O=>d.jsxs("div",{className:"submenu-item",onClick:()=>A(O),children:[O.icon&&d.jsx("span",{className:"submenu-item-icon",children:O.icon}),d.jsx("span",{children:O.label})]},O.id);return w?d.jsx("div",{className:`user-profile-container ${u||""} is-loading`,children:d.jsx("div",{className:"user-profile-loading",children:"加载中..."})}):C?d.jsx("div",{className:`user-profile-container ${u||""} has-error`,children:d.jsxs("div",{className:"user-profile-error",children:["错误: ",C.message]})}):x.name?d.jsx("div",{className:`user-profile-container ${u||""}`,children:d.jsx(go,{trigger:y?y(x):U(),items:o.map(O=>({...O,onClick:()=>A(O)})),position:"bottom",alignment:"end",onOpen:T,onClose:j,renderItem:h?O=>h(O,x):z})}):d.jsx("div",{className:`user-profile-container ${u||""}`,children:d.jsx("div",{className:"user-profile-loading",children:"未登录"})})},$d=t=>d.jsxs("div",{className:"explore-menu-item",onClick:()=>t.onClick?.(t),children:[d.jsx("span",{className:"explore-item-label",children:t.label}),t.status&&d.jsx("span",{className:`explore-item-status status-${t.status.toLowerCase().replace("%","").replace(" ","-")}`,children:t.status})]},t.id),kd=({className:t})=>d.jsxs("button",{className:t,"aria-label":"探索数学课程",children:[d.jsx("span",{className:"explore-icon",children:"🌍"}),d.jsx("span",{className:"explore-text",children:"探索"})]}),jd=({className:t="",style:e,logoHref:r="/",logoText:n="MathWiz",onLogoClick:o,exploreItems:s=[],exploreMenuOpen:i=!1,onExploreMenuToggle:a,onExploreItemClick:c,renderExploreItem:l=$d,userData:u,userMenuItems:g,onUserMenuItemClick:m,onLogout:f,isLoading:p=!1,error:h=null,headerClassName:y="",logoClassName:x="",exploreClassName:v="",userProfileClassName:w="",variant:S="gradient",color:C,background:E,height:_,gradientFrom:A,gradientTo:T,gradientVia:j,logoColor:U,logoSize:z="md",exploreButtonVariant:O="flat",exploreButtonColor:M="primary","aria-label":F,"aria-labelledby":$,...B})=>{const k=s.map(V=>({id:V.id,label:l(V),onClick:()=>c?.(V)})),te=["mathwiz-header",`mathwiz-header--${S}`,C&&`mathwiz-header--color-${C}`,y,t].filter(Boolean).join(" "),ue=["logo",`logo--${z}`,x].filter(Boolean).join(" "),ne=["explore-button",`explore-button--${O}`,`explore-button--color-${M}`,v].filter(Boolean).join(" "),re={...e,..._&&{height:typeof _=="number"?`${_}px`:_},...E&&{"--custom-bg":E},...U&&{"--logo-color":U},...A&&T&&{"--header-bg":j?`linear-gradient(to right, ${A}, ${j}, ${T})`:`linear-gradient(to right, ${A}, ${T})`}};return d.jsx("header",{className:te,style:re,"aria-label":F,"aria-labelledby":$,role:"banner",...B,children:d.jsxs("div",{className:"header-content",children:[d.jsx("div",{className:"header-section left",children:d.jsx(go,{trigger:d.jsx(kd,{className:ne}),items:k,position:"bottom",alignment:"start",openDelay:300,closeDelay:100,onOpen:()=>a?.(!0),onClose:()=>a?.(!1),className:"explore-submenu",menuClassName:"explore-panel"})}),d.jsx("div",{className:"header-section center",children:d.jsx("a",{href:r,className:ue,onClick:o,"aria-label":"MathWiz 首页",children:n})}),d.jsx("div",{className:"header-section right",children:d.jsx(pi,{userName:u?.name,userAvatar:u?.avatar,menuItems:g,onMenuItemClick:m,onLogout:f,containerClassName:w,isLoading:p,error:h})})]})})},hi=b.memo(jd,(t,e)=>t.logoText===e.logoText&&t.logoHref===e.logoHref&&t.className===e.className&&t.headerClassName===e.headerClassName&&t.logoClassName===e.logoClassName&&t.exploreClassName===e.exploreClassName&&t.userProfileClassName===e.userProfileClassName&&t["aria-label"]===e["aria-label"]&&t["aria-labelledby"]===e["aria-labelledby"]&&t.isLoading===e.isLoading&&t.error===e.error&&t.variant===e.variant&&t.color===e.color&&t.background===e.background&&t.height===e.height&&t.gradientFrom===e.gradientFrom&&t.gradientTo===e.gradientTo&&t.gradientVia===e.gradientVia&&t.logoColor===e.logoColor&&t.logoSize===e.logoSize&&t.exploreButtonVariant===e.exploreButtonVariant&&t.exploreButtonColor===e.exploreButtonColor&&JSON.stringify(t.exploreItems)===JSON.stringify(e.exploreItems)&&JSON.stringify(t.userData)===JSON.stringify(e.userData)&&JSON.stringify(t.userMenuItems)===JSON.stringify(e.userMenuItems)),ar={LEFT:"left",RIGHT:"right",TOP:"top",BOTTOM:"bottom"},An={NUMBER:"number",TIME:"time",CUSTOM:"custom"},gs={iconPosition:ar.LEFT,interactive:!1},yi=t=>{const{label:e,value:r,unit:n,color:o,icon:s,iconPosition:i=gs.iconPosition,render:a,onClick:c,className:l="",style:u,interactive:g=gs.interactive,"aria-label":m,"aria-role":f,"data-testid":p,subtitle:h,showHelpIcon:y,helpIconTitle:x="What is this?",contentType:v=An.NUMBER,timeValue:w,themeColorVar:S}=t,C=b.useMemo(()=>f||(c?"button":"group"),[f,c]),E=b.useMemo(()=>{const T=["mathwiz-statblock"];return l&&T.push(l),g&&T.push("mathwiz-statblock-interactive"),o&&!o.startsWith("#")&&T.push(`mathwiz-statblock-color-${o}`),T.join(" ")},[l,g,o]),_=b.useMemo(()=>{const T={...u};return o&&o.startsWith("#")&&(T.backgroundColor=o),S&&(T["--statblock-current-theme-color"]=`var(${S})`),T},[u,o,S]),A={label:e,value:r,unit:n,icon:s,iconPosition:i,color:o,interactive:g,className:E,style:_,subtitle:h,showHelpIcon:y,contentType:v,timeValue:w};return a?a(A):d.jsxs("div",{className:E,style:_,onClick:c,role:C,"aria-label":m,"data-testid":p,tabIndex:g?0:void 0,children:[d.jsxs("div",{className:"mathwiz-statblock-header",children:[d.jsx("div",{className:"mathwiz-statblock-title",children:e}),(h||y)&&d.jsxs("div",{className:"mathwiz-statblock-subtitle",children:[h,y&&d.jsx("span",{className:"mathwiz-statblock-help-icon",title:x,children:"?"})]})]}),d.jsx("div",{className:"mathwiz-statblock-body",children:v===An.TIME&&w?d.jsxs("div",{className:"mathwiz-statblock-time-display",children:[d.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[d.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.hours).padStart(2,"0")}),d.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"HR"})]}),d.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[d.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.minutes).padStart(2,"0")}),d.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"MIN"})]}),d.jsxs("div",{className:"mathwiz-statblock-time-unit",children:[d.jsx("div",{className:"mathwiz-statblock-time-unit-box",children:String(w.seconds).padStart(2,"0")}),d.jsx("div",{className:"mathwiz-statblock-time-unit-label",children:"SEC"})]})]}):v===An.CUSTOM?d.jsxs(d.Fragment,{children:[i===ar.TOP&&s&&d.jsx("div",{className:"mathwiz-statblock-icon-top",children:s}),d.jsxs("div",{className:"mathwiz-statblock-content",children:[i===ar.LEFT&&s&&d.jsx("div",{className:"mathwiz-statblock-icon-left",children:s}),d.jsxs("div",{className:"mathwiz-statblock-text",children:[d.jsx("div",{className:"mathwiz-statblock-label",children:e}),d.jsxs("div",{className:"mathwiz-statblock-value-container",children:[d.jsx("span",{className:"mathwiz-statblock-value",children:r}),n&&d.jsx("span",{className:"mathwiz-statblock-unit",children:n})]})]}),i===ar.RIGHT&&s&&d.jsx("div",{className:"mathwiz-statblock-icon-right",children:s})]}),i===ar.BOTTOM&&s&&d.jsx("div",{className:"mathwiz-statblock-icon-bottom",children:s})]}):d.jsx("div",{className:"mathwiz-statblock-value-large",children:r})})]})};b.memo(yi);var Id=/\s+/g,Md=t=>typeof t!="string"||!t?t:t.replace(Id," ").trim(),Qr=(...t)=>{const e=[],r=n=>{if(!n&&n!==0&&n!==0n)return;if(Array.isArray(n)){for(let s=0,i=n.length;s<i;s++)r(n[s]);return}const o=typeof n;if(o==="string"||o==="number"||o==="bigint"){if(o==="number"&&n!==n)return;e.push(String(n))}else if(o==="object"){const s=Object.keys(n);for(let i=0,a=s.length;i<a;i++){const c=s[i];n[c]&&e.push(c)}}};for(let n=0,o=t.length;n<o;n++){const s=t[n];s!=null&&r(s)}return e.length>0?Md(e.join(" ")):void 0},ms=t=>t===!1?"false":t===!0?"true":t===0?"0":t,Fe=t=>{if(!t||typeof t!="object")return!0;for(const e in t)return!1;return!0},Od=(t,e)=>{if(t===e)return!0;if(!t||!e)return!1;const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o=0;o<r.length;o++){const s=r[o];if(!n.includes(s)||t[s]!==e[s])return!1}return!0},Fd=(t,e)=>{for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const n=e[r];r in t?t[r]=Qr(t[r],n):t[r]=n}return t},bi=(t,e)=>{for(let r=0;r<t.length;r++){const n=t[r];Array.isArray(n)?bi(n,e):n&&e.push(n)}},xi=(...t)=>{const e=[];bi(t,e);const r=[];for(let n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},Wn=(t,e)=>{const r={};for(const n in t){const o=t[n];if(n in e){const s=e[n];Array.isArray(o)||Array.isArray(s)?r[n]=xi(s,o):typeof o=="object"&&typeof s=="object"&&o&&s?r[n]=Wn(o,s):r[n]=s+" "+o}else r[n]=o}for(const n in e)n in t||(r[n]=e[n]);return r},Pd={twMerge:!0,twMergeConfig:{}};function Dd(){let t=null,e={},r=!1;return{get cachedTwMerge(){return t},set cachedTwMerge(n){t=n},get cachedTwMergeConfig(){return e},set cachedTwMergeConfig(n){e=n},get didTwMergeConfigChange(){return r},set didTwMergeConfigChange(n){r=n},reset(){t=null,e={},r=!1}}}var ct=Dd(),Ld=t=>{const e=(n,o)=>{const{extend:s=null,slots:i={},variants:a={},compoundVariants:c=[],compoundSlots:l=[],defaultVariants:u={}}=n,g={...Pd,...o},m=s?.base?Qr(s.base,n?.base):n?.base,f=s?.variants&&!Fe(s.variants)?Wn(a,s.variants):a,p=s?.defaultVariants&&!Fe(s.defaultVariants)?{...s.defaultVariants,...u}:u;!Fe(g.twMergeConfig)&&!Od(g.twMergeConfig,ct.cachedTwMergeConfig)&&(ct.didTwMergeConfigChange=!0,ct.cachedTwMergeConfig=g.twMergeConfig);const h=Fe(s?.slots),y=Fe(i)?{}:{base:Qr(n?.base,h&&s?.base),...i},x=h?y:Fd({...s?.slots},Fe(y)?{base:n?.base}:y),v=Fe(s?.compoundVariants)?c:xi(s?.compoundVariants,c),w=C=>{if(Fe(f)&&Fe(i)&&h)return t(m,C?.class,C?.className)(g);if(v&&!Array.isArray(v))throw new TypeError(`The "compoundVariants" prop must be an array. Received: ${typeof v}`);if(l&&!Array.isArray(l))throw new TypeError(`The "compoundSlots" prop must be an array. Received: ${typeof l}`);const E=(M,F=f,$=null,B=null)=>{const k=F[M];if(!k||Fe(k))return null;const te=B?.[M]??C?.[M];if(te===null)return null;const ue=ms(te);if(typeof ue=="object")return null;const ne=p?.[M],re=ue??ms(ne);return k[re||"false"]},_=()=>{if(!f)return null;const M=Object.keys(f),F=[];for(let $=0;$<M.length;$++){const B=E(M[$],f);B&&F.push(B)}return F},A=(M,F)=>{if(!f||typeof f!="object")return null;const $=[];for(const B in f){const k=E(B,f,M,F),te=M==="base"&&typeof k=="string"?k:k&&k[M];te&&$.push(te)}return $},T={};for(const M in C){const F=C[M];F!==void 0&&(T[M]=F)}const j=(M,F)=>{const $=typeof C?.[M]=="object"?{[M]:C[M]?.initial}:{};return{...p,...T,...$,...F}},U=(M=[],F)=>{const $=[],B=M.length;for(let k=0;k<B;k++){const{class:te,className:ue,...ne}=M[k];let re=!0;const V=j(null,F);for(const Q in ne){const me=ne[Q],Ee=V[Q];if(Array.isArray(me)){if(!me.includes(Ee)){re=!1;break}}else{if((me==null||me===!1)&&(Ee==null||Ee===!1))continue;if(Ee!==me){re=!1;break}}}re&&(te&&$.push(te),ue&&$.push(ue))}return $},z=M=>{const F=U(v,M);if(!Array.isArray(F))return F;const $={},B=t;for(let k=0;k<F.length;k++){const te=F[k];if(typeof te=="string")$.base=B($.base,te)(g);else if(typeof te=="object")for(const ue in te)$[ue]=B($[ue],te[ue])(g)}return $},O=M=>{if(l.length<1)return null;const F={},$=j(null,M);for(let B=0;B<l.length;B++){const{slots:k=[],class:te,className:ue,...ne}=l[B];if(!Fe(ne)){let re=!0;for(const V in ne){const Q=$[V],me=ne[V];if(Q===void 0||(Array.isArray(me)?!me.includes(Q):me!==Q)){re=!1;break}}if(!re)continue}for(let re=0;re<k.length;re++){const V=k[re];F[V]||(F[V]=[]),F[V].push([te,ue])}}return F};if(!Fe(i)||!h){const M={};if(typeof x=="object"&&!Fe(x)){const F=t;for(const $ in x)M[$]=B=>{const k=z(B),te=O(B);return F(x[$],A($,B),k?k[$]:void 0,te?te[$]:void 0,B?.class,B?.className)(g)}}return M}return t(m,_(),U(v),C?.class,C?.className)(g)},S=()=>{if(!(!f||typeof f!="object"))return Object.keys(f)};return w.variantKeys=S(),w.extend=s,w.base=m,w.slots=x,w.variants=f,w.defaultVariants=p,w.compoundSlots=l,w.compoundVariants=v,w};return{tv:e,createTV:n=>(o,s)=>e(o,s?Wn(n,s):n)}};const Gd=(t,e)=>{const r=new Array(t.length+e.length);for(let n=0;n<t.length;n++)r[n]=t[n];for(let n=0;n<e.length;n++)r[t.length+n]=e[n];return r},Vd=(t,e)=>({classGroupId:t,validator:e}),wi=(t=new Map,e=null,r)=>({nextPart:t,validators:e,classGroupId:r}),en="-",ps=[],zd="arbitrary..",Ud=t=>{const e=Hd(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return Bd(i);const a=i.split(en),c=a[0]===""&&a.length>1?1:0;return vi(a,c,e)},getConflictingClassGroupIds:(i,a)=>{if(a){const c=n[i],l=r[i];return c?l?Gd(l,c):c:l||ps}return r[i]||ps}}},vi=(t,e,r)=>{if(t.length-e===0)return r.classGroupId;const o=t[e],s=r.nextPart.get(o);if(s){const l=vi(t,e+1,s);if(l)return l}const i=r.validators;if(i===null)return;const a=e===0?t.join(en):t.slice(e).join(en),c=i.length;for(let l=0;l<c;l++){const u=i[l];if(u.validator(a))return u.classGroupId}},Bd=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),r=e.indexOf(":"),n=e.slice(0,r);return n?zd+n:void 0})(),Hd=t=>{const{theme:e,classGroups:r}=t;return qd(r,e)},qd=(t,e)=>{const r=wi();for(const n in t){const o=t[n];xo(o,r,n,e)}return r},xo=(t,e,r,n)=>{const o=t.length;for(let s=0;s<o;s++){const i=t[s];Wd(i,e,r,n)}},Wd=(t,e,r,n)=>{if(typeof t=="string"){Yd(t,e,r);return}if(typeof t=="function"){Kd(t,e,r,n);return}Xd(t,e,r,n)},Yd=(t,e,r)=>{const n=t===""?e:Ci(e,t);n.classGroupId=r},Kd=(t,e,r,n)=>{if(Jd(t)){xo(t(n),e,r,n);return}e.validators===null&&(e.validators=[]),e.validators.push(Vd(r,t))},Xd=(t,e,r,n)=>{const o=Object.entries(t),s=o.length;for(let i=0;i<s;i++){const[a,c]=o[i];xo(c,Ci(e,a),r,n)}},Ci=(t,e)=>{let r=t;const n=e.split(en),o=n.length;for(let s=0;s<o;s++){const i=n[s];let a=r.nextPart.get(i);a||(a=wi(),r.nextPart.set(i,a)),r=a}return r},Jd=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,Zd=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=Object.create(null),n=Object.create(null);const o=(s,i)=>{r[s]=i,e++,e>t&&(e=0,n=r,r=Object.create(null))};return{get(s){let i=r[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set(s,i){s in r?r[s]=i:o(s,i)}}},Yn="!",hs=":",Qd=[],ys=(t,e,r,n,o)=>({modifiers:t,hasImportantModifier:e,baseClassName:r,maybePostfixModifierPosition:n,isExternal:o}),eu=t=>{const{prefix:e,experimentalParseClassName:r}=t;let n=o=>{const s=[];let i=0,a=0,c=0,l;const u=o.length;for(let h=0;h<u;h++){const y=o[h];if(i===0&&a===0){if(y===hs){s.push(o.slice(c,h)),c=h+1;continue}if(y==="/"){l=h;continue}}y==="["?i++:y==="]"?i--:y==="("?a++:y===")"&&a--}const g=s.length===0?o:o.slice(c);let m=g,f=!1;g.endsWith(Yn)?(m=g.slice(0,-1),f=!0):g.startsWith(Yn)&&(m=g.slice(1),f=!0);const p=l&&l>c?l-c:void 0;return ys(s,f,m,p)};if(e){const o=e+hs,s=n;n=i=>i.startsWith(o)?s(i.slice(o.length)):ys(Qd,!1,i,void 0,!0)}if(r){const o=n;n=s=>r({className:s,parseClassName:o})}return n},tu=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((r,n)=>{e.set(r,1e6+n)}),r=>{const n=[];let o=[];for(let s=0;s<r.length;s++){const i=r[s],a=i[0]==="[",c=e.has(i);a||c?(o.length>0&&(o.sort(),n.push(...o),o=[]),n.push(i)):o.push(i)}return o.length>0&&(o.sort(),n.push(...o)),n}},ru=t=>({cache:Zd(t.cacheSize),parseClassName:eu(t),sortModifiers:tu(t),...Ud(t)}),nu=/\s+/,ou=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:o,sortModifiers:s}=e,i=[],a=t.trim().split(nu);let c="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{isExternal:g,modifiers:m,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:h}=r(u);if(g){c=u+(c.length>0?" "+c:c);continue}let y=!!h,x=n(y?p.substring(0,h):p);if(!x){if(!y){c=u+(c.length>0?" "+c:c);continue}if(x=n(p),!x){c=u+(c.length>0?" "+c:c);continue}y=!1}const v=m.length===0?"":m.length===1?m[0]:s(m).join(":"),w=f?v+Yn:v,S=w+x;if(i.indexOf(S)>-1)continue;i.push(S);const C=o(x,y);for(let E=0;E<C.length;++E){const _=C[E];i.push(w+_)}c=u+(c.length>0?" "+c:c)}return c},su=(...t)=>{let e=0,r,n,o="";for(;e<t.length;)(r=t[e++])&&(n=Si(r))&&(o&&(o+=" "),o+=n);return o},Si=t=>{if(typeof t=="string")return t;let e,r="";for(let n=0;n<t.length;n++)t[n]&&(e=Si(t[n]))&&(r&&(r+=" "),r+=e);return r},Kn=(t,...e)=>{let r,n,o,s;const i=c=>{const l=e.reduce((u,g)=>g(u),t());return r=ru(l),n=r.cache.get,o=r.cache.set,s=a,a(c)},a=c=>{const l=n(c);if(l)return l;const u=ou(c,r);return o(c,u),u};return s=i,(...c)=>s(su(...c))},iu=[],_e=t=>{const e=r=>r[t]||iu;return e.isThemeGetter=!0,e},_i=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ri=/^\((?:(\w[\w-]*):)?(.+)\)$/i,au=/^\d+\/\d+$/,lu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,cu=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,du=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,uu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,fu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Pt=t=>au.test(t),Z=t=>!!t&&!Number.isNaN(Number(t)),mt=t=>!!t&&Number.isInteger(Number(t)),En=t=>t.endsWith("%")&&Z(t.slice(0,-1)),at=t=>lu.test(t),gu=()=>!0,mu=t=>cu.test(t)&&!du.test(t),Ai=()=>!1,pu=t=>uu.test(t),hu=t=>fu.test(t),yu=t=>!L(t)&&!G(t),bu=t=>Xt(t,Ti,Ai),L=t=>_i.test(t),St=t=>Xt(t,$i,mu),Nn=t=>Xt(t,Su,Z),bs=t=>Xt(t,Ei,Ai),xu=t=>Xt(t,Ni,hu),Nr=t=>Xt(t,ki,pu),G=t=>Ri.test(t),or=t=>Jt(t,$i),wu=t=>Jt(t,_u),xs=t=>Jt(t,Ei),vu=t=>Jt(t,Ti),Cu=t=>Jt(t,Ni),Tr=t=>Jt(t,ki,!0),Xt=(t,e,r)=>{const n=_i.exec(t);return n?n[1]?e(n[1]):r(n[2]):!1},Jt=(t,e,r=!1)=>{const n=Ri.exec(t);return n?n[1]?e(n[1]):r:!1},Ei=t=>t==="position"||t==="percentage",Ni=t=>t==="image"||t==="url",Ti=t=>t==="length"||t==="size"||t==="bg-size",$i=t=>t==="length",Su=t=>t==="number",_u=t=>t==="family-name",ki=t=>t==="shadow",Xn=()=>{const t=_e("color"),e=_e("font"),r=_e("text"),n=_e("font-weight"),o=_e("tracking"),s=_e("leading"),i=_e("breakpoint"),a=_e("container"),c=_e("spacing"),l=_e("radius"),u=_e("shadow"),g=_e("inset-shadow"),m=_e("text-shadow"),f=_e("drop-shadow"),p=_e("blur"),h=_e("perspective"),y=_e("aspect"),x=_e("ease"),v=_e("animate"),w=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],C=()=>[...S(),G,L],E=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto","contain","none"],A=()=>[G,L,c],T=()=>[Pt,"full","auto",...A()],j=()=>[mt,"none","subgrid",G,L],U=()=>["auto",{span:["full",mt,G,L]},mt,G,L],z=()=>[mt,"auto",G,L],O=()=>["auto","min","max","fr",G,L],M=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],F=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...A()],B=()=>[Pt,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],k=()=>[t,G,L],te=()=>[...S(),xs,bs,{position:[G,L]}],ue=()=>["no-repeat",{repeat:["","x","y","space","round"]}],ne=()=>["auto","cover","contain",vu,bu,{size:[G,L]}],re=()=>[En,or,St],V=()=>["","none","full",l,G,L],Q=()=>["",Z,or,St],me=()=>["solid","dashed","dotted","double"],Ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],de=()=>[Z,En,xs,bs],gt=()=>["","none",p,G,L],it=()=>["none",Z,G,L],P=()=>["none",Z,G,L],I=()=>[Z,G,L],N=()=>[Pt,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[at],breakpoint:[at],color:[gu],container:[at],"drop-shadow":[at],ease:["in","out","in-out"],font:[yu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[at],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[at],shadow:[at],spacing:["px",Z],text:[at],"text-shadow":[at],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Pt,L,G,y]}],container:["container"],columns:[{columns:[Z,L,G,a]}],"break-after":[{"break-after":w()}],"break-before":[{"break-before":w()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:C()}],overflow:[{overflow:E()}],"overflow-x":[{"overflow-x":E()}],"overflow-y":[{"overflow-y":E()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[mt,"auto",G,L]}],basis:[{basis:[Pt,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Z,Pt,"auto","initial","none",L]}],grow:[{grow:["",Z,G,L]}],shrink:[{shrink:["",Z,G,L]}],order:[{order:[mt,"first","last","none",G,L]}],"grid-cols":[{"grid-cols":j()}],"col-start-end":[{col:U()}],"col-start":[{"col-start":z()}],"col-end":[{"col-end":z()}],"grid-rows":[{"grid-rows":j()}],"row-start-end":[{row:U()}],"row-start":[{"row-start":z()}],"row-end":[{"row-end":z()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":O()}],"auto-rows":[{"auto-rows":O()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...M(),"normal"]}],"justify-items":[{"justify-items":[...F(),"normal"]}],"justify-self":[{"justify-self":["auto",...F()]}],"align-content":[{content:["normal",...M()]}],"align-items":[{items:[...F(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...F(),{baseline:["","last"]}]}],"place-content":[{"place-content":M()}],"place-items":[{"place-items":[...F(),"baseline"]}],"place-self":[{"place-self":["auto",...F()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:B()}],w:[{w:[a,"screen",...B()]}],"min-w":[{"min-w":[a,"screen","none",...B()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[i]},...B()]}],h:[{h:["screen","lh",...B()]}],"min-h":[{"min-h":["screen","lh","none",...B()]}],"max-h":[{"max-h":["screen","lh",...B()]}],"font-size":[{text:["base",r,or,St]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,G,Nn]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",En,L]}],"font-family":[{font:[wu,L,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,G,L]}],"line-clamp":[{"line-clamp":[Z,"none",G,Nn]}],leading:[{leading:[s,...A()]}],"list-image":[{"list-image":["none",G,L]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",G,L]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:k()}],"text-color":[{text:k()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...me(),"wavy"]}],"text-decoration-thickness":[{decoration:[Z,"from-font","auto",G,St]}],"text-decoration-color":[{decoration:k()}],"underline-offset":[{"underline-offset":[Z,"auto",G,L]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",G,L]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",G,L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:ue()}],"bg-size":[{bg:ne()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},mt,G,L],radial:["",G,L],conic:[mt,G,L]},Cu,xu]}],"bg-color":[{bg:k()}],"gradient-from-pos":[{from:re()}],"gradient-via-pos":[{via:re()}],"gradient-to-pos":[{to:re()}],"gradient-from":[{from:k()}],"gradient-via":[{via:k()}],"gradient-to":[{to:k()}],rounded:[{rounded:V()}],"rounded-s":[{"rounded-s":V()}],"rounded-e":[{"rounded-e":V()}],"rounded-t":[{"rounded-t":V()}],"rounded-r":[{"rounded-r":V()}],"rounded-b":[{"rounded-b":V()}],"rounded-l":[{"rounded-l":V()}],"rounded-ss":[{"rounded-ss":V()}],"rounded-se":[{"rounded-se":V()}],"rounded-ee":[{"rounded-ee":V()}],"rounded-es":[{"rounded-es":V()}],"rounded-tl":[{"rounded-tl":V()}],"rounded-tr":[{"rounded-tr":V()}],"rounded-br":[{"rounded-br":V()}],"rounded-bl":[{"rounded-bl":V()}],"border-w":[{border:Q()}],"border-w-x":[{"border-x":Q()}],"border-w-y":[{"border-y":Q()}],"border-w-s":[{"border-s":Q()}],"border-w-e":[{"border-e":Q()}],"border-w-t":[{"border-t":Q()}],"border-w-r":[{"border-r":Q()}],"border-w-b":[{"border-b":Q()}],"border-w-l":[{"border-l":Q()}],"divide-x":[{"divide-x":Q()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Q()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...me(),"hidden","none"]}],"divide-style":[{divide:[...me(),"hidden","none"]}],"border-color":[{border:k()}],"border-color-x":[{"border-x":k()}],"border-color-y":[{"border-y":k()}],"border-color-s":[{"border-s":k()}],"border-color-e":[{"border-e":k()}],"border-color-t":[{"border-t":k()}],"border-color-r":[{"border-r":k()}],"border-color-b":[{"border-b":k()}],"border-color-l":[{"border-l":k()}],"divide-color":[{divide:k()}],"outline-style":[{outline:[...me(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Z,G,L]}],"outline-w":[{outline:["",Z,or,St]}],"outline-color":[{outline:k()}],shadow:[{shadow:["","none",u,Tr,Nr]}],"shadow-color":[{shadow:k()}],"inset-shadow":[{"inset-shadow":["none",g,Tr,Nr]}],"inset-shadow-color":[{"inset-shadow":k()}],"ring-w":[{ring:Q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:k()}],"ring-offset-w":[{"ring-offset":[Z,St]}],"ring-offset-color":[{"ring-offset":k()}],"inset-ring-w":[{"inset-ring":Q()}],"inset-ring-color":[{"inset-ring":k()}],"text-shadow":[{"text-shadow":["none",m,Tr,Nr]}],"text-shadow-color":[{"text-shadow":k()}],opacity:[{opacity:[Z,G,L]}],"mix-blend":[{"mix-blend":[...Ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ee()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Z]}],"mask-image-linear-from-pos":[{"mask-linear-from":de()}],"mask-image-linear-to-pos":[{"mask-linear-to":de()}],"mask-image-linear-from-color":[{"mask-linear-from":k()}],"mask-image-linear-to-color":[{"mask-linear-to":k()}],"mask-image-t-from-pos":[{"mask-t-from":de()}],"mask-image-t-to-pos":[{"mask-t-to":de()}],"mask-image-t-from-color":[{"mask-t-from":k()}],"mask-image-t-to-color":[{"mask-t-to":k()}],"mask-image-r-from-pos":[{"mask-r-from":de()}],"mask-image-r-to-pos":[{"mask-r-to":de()}],"mask-image-r-from-color":[{"mask-r-from":k()}],"mask-image-r-to-color":[{"mask-r-to":k()}],"mask-image-b-from-pos":[{"mask-b-from":de()}],"mask-image-b-to-pos":[{"mask-b-to":de()}],"mask-image-b-from-color":[{"mask-b-from":k()}],"mask-image-b-to-color":[{"mask-b-to":k()}],"mask-image-l-from-pos":[{"mask-l-from":de()}],"mask-image-l-to-pos":[{"mask-l-to":de()}],"mask-image-l-from-color":[{"mask-l-from":k()}],"mask-image-l-to-color":[{"mask-l-to":k()}],"mask-image-x-from-pos":[{"mask-x-from":de()}],"mask-image-x-to-pos":[{"mask-x-to":de()}],"mask-image-x-from-color":[{"mask-x-from":k()}],"mask-image-x-to-color":[{"mask-x-to":k()}],"mask-image-y-from-pos":[{"mask-y-from":de()}],"mask-image-y-to-pos":[{"mask-y-to":de()}],"mask-image-y-from-color":[{"mask-y-from":k()}],"mask-image-y-to-color":[{"mask-y-to":k()}],"mask-image-radial":[{"mask-radial":[G,L]}],"mask-image-radial-from-pos":[{"mask-radial-from":de()}],"mask-image-radial-to-pos":[{"mask-radial-to":de()}],"mask-image-radial-from-color":[{"mask-radial-from":k()}],"mask-image-radial-to-color":[{"mask-radial-to":k()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[Z]}],"mask-image-conic-from-pos":[{"mask-conic-from":de()}],"mask-image-conic-to-pos":[{"mask-conic-to":de()}],"mask-image-conic-from-color":[{"mask-conic-from":k()}],"mask-image-conic-to-color":[{"mask-conic-to":k()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:ue()}],"mask-size":[{mask:ne()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",G,L]}],filter:[{filter:["","none",G,L]}],blur:[{blur:gt()}],brightness:[{brightness:[Z,G,L]}],contrast:[{contrast:[Z,G,L]}],"drop-shadow":[{"drop-shadow":["","none",f,Tr,Nr]}],"drop-shadow-color":[{"drop-shadow":k()}],grayscale:[{grayscale:["",Z,G,L]}],"hue-rotate":[{"hue-rotate":[Z,G,L]}],invert:[{invert:["",Z,G,L]}],saturate:[{saturate:[Z,G,L]}],sepia:[{sepia:["",Z,G,L]}],"backdrop-filter":[{"backdrop-filter":["","none",G,L]}],"backdrop-blur":[{"backdrop-blur":gt()}],"backdrop-brightness":[{"backdrop-brightness":[Z,G,L]}],"backdrop-contrast":[{"backdrop-contrast":[Z,G,L]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Z,G,L]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Z,G,L]}],"backdrop-invert":[{"backdrop-invert":["",Z,G,L]}],"backdrop-opacity":[{"backdrop-opacity":[Z,G,L]}],"backdrop-saturate":[{"backdrop-saturate":[Z,G,L]}],"backdrop-sepia":[{"backdrop-sepia":["",Z,G,L]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",G,L]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Z,"initial",G,L]}],ease:[{ease:["linear","initial",x,G,L]}],delay:[{delay:[Z,G,L]}],animate:[{animate:["none",v,G,L]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[h,G,L]}],"perspective-origin":[{"perspective-origin":C()}],rotate:[{rotate:it()}],"rotate-x":[{"rotate-x":it()}],"rotate-y":[{"rotate-y":it()}],"rotate-z":[{"rotate-z":it()}],scale:[{scale:P()}],"scale-x":[{"scale-x":P()}],"scale-y":[{"scale-y":P()}],"scale-z":[{"scale-z":P()}],"scale-3d":["scale-3d"],skew:[{skew:I()}],"skew-x":[{"skew-x":I()}],"skew-y":[{"skew-y":I()}],transform:[{transform:[G,L,"","none","gpu","cpu"]}],"transform-origin":[{origin:C()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:N()}],"translate-x":[{"translate-x":N()}],"translate-y":[{"translate-y":N()}],"translate-z":[{"translate-z":N()}],"translate-none":["translate-none"],accent:[{accent:k()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:k()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",G,L]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",G,L]}],fill:[{fill:["none",...k()]}],"stroke-w":[{stroke:[Z,or,St,Nn]}],stroke:[{stroke:["none",...k()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Ru=(t,{cacheSize:e,prefix:r,experimentalParseClassName:n,extend:o={},override:s={}})=>(lr(t,"cacheSize",e),lr(t,"prefix",r),lr(t,"experimentalParseClassName",n),$r(t.theme,s.theme),$r(t.classGroups,s.classGroups),$r(t.conflictingClassGroups,s.conflictingClassGroups),$r(t.conflictingClassGroupModifiers,s.conflictingClassGroupModifiers),lr(t,"orderSensitiveModifiers",s.orderSensitiveModifiers),kr(t.theme,o.theme),kr(t.classGroups,o.classGroups),kr(t.conflictingClassGroups,o.conflictingClassGroups),kr(t.conflictingClassGroupModifiers,o.conflictingClassGroupModifiers),ji(t,o,"orderSensitiveModifiers"),t),lr=(t,e,r)=>{r!==void 0&&(t[e]=r)},$r=(t,e)=>{if(e)for(const r in e)lr(t,r,e[r])},kr=(t,e)=>{if(e)for(const r in e)ji(t,e,r)},ji=(t,e,r)=>{const n=e[r];n!==void 0&&(t[r]=t[r]?t[r].concat(n):n)},Au=(t,...e)=>typeof t=="function"?Kn(Xn,t,...e):Kn(()=>Ru(Xn(),t),...e),Eu=Kn(Xn);var Nu=t=>Fe(t)?Eu:Au({...t,extend:{theme:t.theme,classGroups:t.classGroups,conflictingClassGroupModifiers:t.conflictingClassGroupModifiers,conflictingClassGroups:t.conflictingClassGroups,...t.extend}}),Tu=(t,e)=>{const r=Qr(t);return!r||!(e?.twMerge??!0)?r:((!ct.cachedTwMerge||ct.didTwMergeConfigChange)&&(ct.didTwMergeConfigChange=!1,ct.cachedTwMerge=Nu(ct.cachedTwMergeConfig)),ct.cachedTwMerge(r)||void 0)},$u=(...t)=>e=>Tu(t,e),{tv:dn}=Ld($u);const ku=dn({base:["rounded-lg border p-4 transition-all duration-200","flex items-center justify-between gap-4","cursor-pointer select-none","focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2","w-full max-w-md"],variants:{selected:{true:"!bg-blue-100 !border-blue-500 shadow-sm",false:""},disabled:{true:"opacity-50 cursor-not-allowed",false:""},correct:{true:"!border-green-500 !bg-green-50",false:""},wrong:{true:"!border-red-500 !bg-red-50",false:""},variant:{default:"border-gray-200 bg-white hover:bg-blue-50 hover:border-blue-300",ixl:"border-transparent bg-transparent hover:bg-gray-50"}},compoundVariants:[{selected:!0,disabled:!0,class:"opacity-70"},{selected:!0,variant:"ixl",class:"bg-blue-50 border-l-4 border-l-blue-500 border-t-transparent border-r-transparent border-b-transparent"},{correct:!0,variant:"ixl",class:"!border-l-4 !border-l-green-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-green-50/50"},{wrong:!0,variant:"ixl",class:"!border-l-4 !border-l-red-500 !border-t-transparent !border-r-transparent !border-b-transparent !bg-red-50/50"}],defaultVariants:{selected:!1,disabled:!1,correct:!1,wrong:!1,variant:"default"}}),ju=dn({base:"flex gap-3",variants:{layout:{vertical:"flex-col",horizontal:"flex-row flex-wrap"}},defaultVariants:{layout:"vertical"}}),wo=b.memo(({id:t,children:e,selected:r,disabled:n=!1,correct:o=!1,wrong:s=!1,variant:i="default",onClick:a,className:c,style:l})=>{const u=b.useCallback(f=>{n||(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),a())},[n,a]),g=b.useCallback(()=>{n||a()},[n,a]),m=ku({selected:r,disabled:n,correct:o,wrong:s,variant:i,className:c});return d.jsx("div",{id:t,role:"radio","aria-checked":r,"aria-disabled":n,tabIndex:n?-1:0,className:m,style:l,onClick:g,onKeyDown:u,children:e})});wo.displayName="OptionCard";const vo=b.memo(({type:t,options:e,value:r,onChange:n,disabled:o=!1,showResult:s=!1,correctAnswers:i=[],layout:a="vertical",variant:c="default",className:l,style:u})=>{const g=b.useMemo(()=>new Set(r.map(h=>h.id)),[r]),m=b.useMemo(()=>new Set(i),[i]),f=b.useCallback((h,y,x)=>{if(!o)if(t==="single")n([{id:h,content:y,contentType:x}]);else{const v=g.has(h);let w;v?w=r.filter(S=>S.id!==h):w=[...r,{id:h,content:y,contentType:x}],n(w)}},[t,o,g,r,n]),p=ju({layout:a,className:l});return d.jsx("div",{role:"radiogroup",className:p,style:u,children:e.map(h=>{const y=g.has(h.id),x=s&&m.has(h.id),v=s&&y&&!m.has(h.id);return d.jsx(wo,{id:h.id,selected:y,disabled:o,correct:x,wrong:v,variant:c,onClick:()=>f(h.id,h.rawContent,h.contentType),children:h.label},h.id)})})});vo.displayName="OptionGroup";function Ii(t){const[e,r]=b.useState(()=>new Set(t.map(h=>h.id))),[n,o]=b.useState(()=>{const h=new Set;return t.forEach(y=>{y.categories.forEach(x=>h.add(x.id))}),h}),s=b.useCallback(h=>{r(y=>{const x=new Set(y);return x.has(h)?x.delete(h):x.add(h),x})},[]),i=b.useCallback(h=>{o(y=>{const x=new Set(y);return x.has(h)?x.delete(h):x.add(h),x})},[]),a=b.useCallback(h=>{r(y=>new Set([...y,h]))},[]),c=b.useCallback(h=>{r(y=>{const x=new Set(y);return x.delete(h),x})},[]),l=b.useCallback(h=>{o(y=>new Set([...y,h]))},[]),u=b.useCallback(h=>{o(y=>{const x=new Set(y);return x.delete(h),x})},[]),g=b.useCallback(()=>{const h=new Set(t.map(x=>x.id)),y=new Set;t.forEach(x=>{x.categories.forEach(v=>y.add(v.id))}),r(h),o(y)},[t]),m=b.useCallback(()=>{r(new Set),o(new Set)},[]),f=b.useMemo(()=>({expandedGroups:e,expandedCategories:n}),[e,n]),p=b.useMemo(()=>({toggleGroup:s,toggleCategory:i,expandGroup:a,collapseGroup:c,expandCategory:l,collapseCategory:u,expandAll:g,collapseAll:m}),[s,i,a,c,l,u,g,m]);return{state:f,actions:p}}function Mi({data:t,renderGroupHeader:e,renderCategoryHeader:r,renderRow:n,renderCell:o,onCellClick:s,onRowClick:i,columns:a,enableTanStack:c=!1,className:l,getRowKey:u,"aria-label":g,"aria-labelledby":m}){const{state:f,actions:p}=Ii(t),h=b.useCallback(w=>t.find(S=>S.categories.some(C=>C.id===w)),[t]),y=b.useCallback((w,S,C)=>{const E=h(C.id);if(!E)return null;const _={index:S,category:C,group:E,isFirst:S===0,isLast:S===C.items.length-1},A=u?u(w,S):`row-${C.id}-${S}`,T=()=>{i?.(w)},j=()=>a&&a.length>0?a.map((U,z)=>{const O=U.accessorKey,M=O?w[O]:null;return d.jsx("td",{onClick:()=>s?.(w,String(O)),children:o?o(M,w,U):String(M??"")},z)}):d.jsx("td",{});return d.jsx("tr",{onClick:T,role:"row",className:i?"cursor-pointer":void 0,children:n?n(w,_):j()},A)},[n,o,i,s,a,u,h]),x=b.useCallback(w=>{const S=f.expandedCategories.has(w.id),C=()=>d.jsxs("div",{className:"table-category-header",onClick:()=>p.toggleCategory(w.id),role:"button","aria-expanded":S,children:[d.jsx("span",{children:S?"▼":"▶"}),d.jsx("span",{children:w.title})]});return d.jsxs("div",{className:"table-category","data-category-id":w.id,children:[r?r(w,{isExpanded:S,onToggle:()=>p.toggleCategory(w.id)}):C(),S&&d.jsx("table",{className:"w-full border-collapse",role:"table",children:d.jsx("tbody",{children:w.items.map((E,_)=>y(E,_,w))})})]},w.id)},[f.expandedCategories,p.toggleCategory,r,y]),v=b.useCallback(w=>{const S=f.expandedGroups.has(w.id),C=()=>d.jsxs("div",{className:"table-group-header",onClick:()=>p.toggleGroup(w.id),role:"button","aria-expanded":S,children:[d.jsx("span",{children:S?"▼":"▶"}),d.jsx("span",{children:w.title})]});return d.jsxs("div",{className:"table-group","data-group-id":w.id,children:[e?e(w,{isExpanded:S,onToggle:()=>p.toggleGroup(w.id)}):C(),S&&w.categories.map(x)]},w.id)},[f.expandedGroups,p.toggleGroup,e,x]);return d.jsx("div",{className:l,role:"region","aria-label":g,"aria-labelledby":m,children:t.map(v)})}b.memo(Mi);function yt(t,e){return typeof t=="function"?t(e):t}function qe(t,e){return r=>{e.setState(n=>({...n,[t]:yt(r,n[t])}))}}function un(t){return t instanceof Function}function Iu(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Mu(t,e){const r=[],n=o=>{o.forEach(s=>{r.push(s);const i=e(s);i!=null&&i.length&&n(i)})};return n(t),r}function q(t,e,r){let n=[],o;return s=>{let i;r.key&&r.debug&&(i=Date.now());const a=t(s);if(!(a.length!==n.length||a.some((u,g)=>n[g]!==u)))return o;n=a;let l;if(r.key&&r.debug&&(l=Date.now()),o=e(...a),r==null||r.onChange==null||r.onChange(o),r.key&&r.debug&&r!=null&&r.debug()){const u=Math.round((Date.now()-i)*100)/100,g=Math.round((Date.now()-l)*100)/100,m=g/16,f=(p,h)=>{for(p=String(p);p.length<h;)p=" "+p;return p};console.info(`%c⏱ ${f(g,5)} /${f(u,5)} ms`,`
7
7
  font-size: .6rem;
8
8
  font-weight: bold;
9
- color: hsl(${Math.max(0,Math.min(120-120*p,120))}deg 100% 31%);`,r?.key)}return o}}function B(t,e,r,n){return{debug:()=>{var o;return(o=t?.debugAll)!=null?o:t[e]},key:process.env.NODE_ENV==="development"&&r,onChange:n}}function Qd(t,e,r,n){const o=()=>{var i;return(i=s.getValue())!=null?i:t.options.renderFallbackValue},s={id:`${e.id}_${r.id}`,row:e,column:r,getValue:()=>e.getValue(n),renderValue:o,getContext:z(()=>[t,r,e,s],(i,a,c,l)=>({table:i,column:a,row:c,cell:l,getValue:l.getValue,renderValue:l.renderValue}),B(t.options,"debugCells","cell.getContext"))};return t._features.forEach(i=>{i.createCell==null||i.createCell(s,r,e,t)},{}),s}function eu(t,e,r,n){var o,s;const a={...t._getDefaultColumnDef(),...e},c=a.accessorKey;let l=(o=(s=a.id)!=null?s:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?o:typeof a.header=="string"?a.header:void 0,d;if(a.accessorFn?d=a.accessorFn:c&&(c.includes(".")?d=p=>{let f=p;for(const h of c.split(".")){var m;f=(m=f)==null?void 0:m[h],process.env.NODE_ENV!=="production"&&f===void 0&&console.warn(`"${h}" in deeply nested key "${c}" returned undefined.`)}return f}:d=p=>p[a.accessorKey]),!l)throw process.env.NODE_ENV!=="production"?new Error(a.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let g={id:`${String(l)}`,accessorFn:d,parent:n,depth:r,columnDef:a,columns:[],getFlatColumns:z(()=>[!0],()=>{var p;return[g,...(p=g.columns)==null?void 0:p.flatMap(f=>f.getFlatColumns())]},B(t.options,"debugColumns","column.getFlatColumns")),getLeafColumns:z(()=>[t._getOrderColumnsFn()],p=>{var f;if((f=g.columns)!=null&&f.length){let m=g.columns.flatMap(h=>h.getLeafColumns());return p(m)}return[g]},B(t.options,"debugColumns","column.getLeafColumns"))};for(const p of t._features)p.createColumn==null||p.createColumn(g,t);return g}const Te="debugHeaders";function us(t,e,r){var n;let s={id:(n=r.id)!=null?n:e.id,column:e,index:r.index,isPlaceholder:!!r.isPlaceholder,placeholderId:r.placeholderId,depth:r.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],a=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(a),i.push(c)};return a(s),i},getContext:()=>({table:t,header:s,column:e})};return t._features.forEach(i=>{i.createHeader==null||i.createHeader(s,t)}),s}const tu={createTable:t=>{t.getHeaderGroups=z(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n,o)=>{var s,i;const a=(s=n?.map(g=>r.find(p=>p.id===g)).filter(Boolean))!=null?s:[],c=(i=o?.map(g=>r.find(p=>p.id===g)).filter(Boolean))!=null?i:[],l=r.filter(g=>!(n!=null&&n.includes(g.id))&&!(o!=null&&o.includes(g.id)));return $r(e,[...a,...l,...c],t)},B(t.options,Te,"getHeaderGroups")),t.getCenterHeaderGroups=z(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n,o)=>(r=r.filter(s=>!(n!=null&&n.includes(s.id))&&!(o!=null&&o.includes(s.id))),$r(e,r,t,"center")),B(t.options,Te,"getCenterHeaderGroups")),t.getLeftHeaderGroups=z(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left],(e,r,n)=>{var o;const s=(o=n?.map(i=>r.find(a=>a.id===i)).filter(Boolean))!=null?o:[];return $r(e,s,t,"left")},B(t.options,Te,"getLeftHeaderGroups")),t.getRightHeaderGroups=z(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.right],(e,r,n)=>{var o;const s=(o=n?.map(i=>r.find(a=>a.id===i)).filter(Boolean))!=null?o:[];return $r(e,s,t,"right")},B(t.options,Te,"getRightHeaderGroups")),t.getFooterGroups=z(()=>[t.getHeaderGroups()],e=>[...e].reverse(),B(t.options,Te,"getFooterGroups")),t.getLeftFooterGroups=z(()=>[t.getLeftHeaderGroups()],e=>[...e].reverse(),B(t.options,Te,"getLeftFooterGroups")),t.getCenterFooterGroups=z(()=>[t.getCenterHeaderGroups()],e=>[...e].reverse(),B(t.options,Te,"getCenterFooterGroups")),t.getRightFooterGroups=z(()=>[t.getRightHeaderGroups()],e=>[...e].reverse(),B(t.options,Te,"getRightFooterGroups")),t.getFlatHeaders=z(()=>[t.getHeaderGroups()],e=>e.map(r=>r.headers).flat(),B(t.options,Te,"getFlatHeaders")),t.getLeftFlatHeaders=z(()=>[t.getLeftHeaderGroups()],e=>e.map(r=>r.headers).flat(),B(t.options,Te,"getLeftFlatHeaders")),t.getCenterFlatHeaders=z(()=>[t.getCenterHeaderGroups()],e=>e.map(r=>r.headers).flat(),B(t.options,Te,"getCenterFlatHeaders")),t.getRightFlatHeaders=z(()=>[t.getRightHeaderGroups()],e=>e.map(r=>r.headers).flat(),B(t.options,Te,"getRightFlatHeaders")),t.getCenterLeafHeaders=z(()=>[t.getCenterFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),B(t.options,Te,"getCenterLeafHeaders")),t.getLeftLeafHeaders=z(()=>[t.getLeftFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),B(t.options,Te,"getLeftLeafHeaders")),t.getRightLeafHeaders=z(()=>[t.getRightFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),B(t.options,Te,"getRightLeafHeaders")),t.getLeafHeaders=z(()=>[t.getLeftHeaderGroups(),t.getCenterHeaderGroups(),t.getRightHeaderGroups()],(e,r,n)=>{var o,s,i,a,c,l;return[...(o=(s=e[0])==null?void 0:s.headers)!=null?o:[],...(i=(a=r[0])==null?void 0:a.headers)!=null?i:[],...(c=(l=n[0])==null?void 0:l.headers)!=null?c:[]].map(d=>d.getLeafHeaders()).flat()},B(t.options,Te,"getLeafHeaders"))}};function $r(t,e,r,n){var o,s;let i=0;const a=function(p,f){f===void 0&&(f=1),i=Math.max(i,f),p.filter(m=>m.getIsVisible()).forEach(m=>{var h;(h=m.columns)!=null&&h.length&&a(m.columns,f+1)},0)};a(t);let c=[];const l=(p,f)=>{const m={depth:f,id:[n,`${f}`].filter(Boolean).join("_"),headers:[]},h=[];p.forEach(y=>{const b=[...h].reverse()[0],_=y.column.depth===m.depth;let w,C=!1;if(_&&y.column.parent?w=y.column.parent:(w=y.column,C=!0),b&&b?.column===w)b.subHeaders.push(y);else{const v=us(r,w,{id:[n,f,w.id,y?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${h.filter(k=>k.column===w).length}`:void 0,depth:f,index:h.length});v.subHeaders.push(y),h.push(v)}m.headers.push(y),y.headerGroup=m}),c.push(m),f>0&&l(h,f-1)},d=e.map((p,f)=>us(r,p,{depth:i,index:f}));l(d,i-1),c.reverse();const g=p=>p.filter(m=>m.column.getIsVisible()).map(m=>{let h=0,y=0,b=[0];m.subHeaders&&m.subHeaders.length?(b=[],g(m.subHeaders).forEach(w=>{let{colSpan:C,rowSpan:v}=w;h+=C,b.push(v)})):h=1;const _=Math.min(...b);return y=y+_,m.colSpan=h,m.rowSpan=y,{colSpan:h,rowSpan:y}});return g((o=(s=c[0])==null?void 0:s.headers)!=null?o:[]),c}const xo=(t,e,r,n,o,s,i)=>{let a={id:e,index:n,original:r,depth:o,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(a._valuesCache.hasOwnProperty(c))return a._valuesCache[c];const l=t.getColumn(c);if(l!=null&&l.accessorFn)return a._valuesCache[c]=l.accessorFn(a.original,n),a._valuesCache[c]},getUniqueValues:c=>{if(a._uniqueValuesCache.hasOwnProperty(c))return a._uniqueValuesCache[c];const l=t.getColumn(c);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(a._uniqueValuesCache[c]=l.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[c]):(a._uniqueValuesCache[c]=[a.getValue(c)],a._uniqueValuesCache[c])},renderValue:c=>{var l;return(l=a.getValue(c))!=null?l:t.options.renderFallbackValue},subRows:[],getLeafRows:()=>Zd(a.subRows,c=>c.subRows),getParentRow:()=>a.parentId?t.getRow(a.parentId,!0):void 0,getParentRows:()=>{let c=[],l=a;for(;;){const d=l.getParentRow();if(!d)break;c.push(d),l=d}return c.reverse()},getAllCells:z(()=>[t.getAllLeafColumns()],c=>c.map(l=>Qd(t,a,l,l.id)),B(t.options,"debugRows","getAllCells")),_getAllCellsByColumnId:z(()=>[a.getAllCells()],c=>c.reduce((l,d)=>(l[d.column.id]=d,l),{}),B(t.options,"debugRows","getAllCellsByColumnId"))};for(let c=0;c<t._features.length;c++){const l=t._features[c];l==null||l.createRow==null||l.createRow(a,t)}return a},ru={createColumn:(t,e)=>{t._getFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,t.id),t.getFacetedRowModel=()=>t._getFacetedRowModel?t._getFacetedRowModel():e.getPreFilteredRowModel(),t._getFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,t.id),t.getFacetedUniqueValues=()=>t._getFacetedUniqueValues?t._getFacetedUniqueValues():new Map,t._getFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,t.id),t.getFacetedMinMaxValues=()=>{if(t._getFacetedMinMaxValues)return t._getFacetedMinMaxValues()}}},Ci=(t,e,r)=>{var n,o;const s=r==null||(n=r.toString())==null?void 0:n.toLowerCase();return!!(!((o=t.getValue(e))==null||(o=o.toString())==null||(o=o.toLowerCase())==null)&&o.includes(s))};Ci.autoRemove=t=>Ye(t);const Ai=(t,e,r)=>{var n;return!!(!((n=t.getValue(e))==null||(n=n.toString())==null)&&n.includes(r))};Ai.autoRemove=t=>Ye(t);const Ei=(t,e,r)=>{var n;return((n=t.getValue(e))==null||(n=n.toString())==null?void 0:n.toLowerCase())===r?.toLowerCase()};Ei.autoRemove=t=>Ye(t);const Ti=(t,e,r)=>{var n;return(n=t.getValue(e))==null?void 0:n.includes(r)};Ti.autoRemove=t=>Ye(t);const $i=(t,e,r)=>!r.some(n=>{var o;return!((o=t.getValue(e))!=null&&o.includes(n))});$i.autoRemove=t=>Ye(t)||!(t!=null&&t.length);const Ni=(t,e,r)=>r.some(n=>{var o;return(o=t.getValue(e))==null?void 0:o.includes(n)});Ni.autoRemove=t=>Ye(t)||!(t!=null&&t.length);const ki=(t,e,r)=>t.getValue(e)===r;ki.autoRemove=t=>Ye(t);const Mi=(t,e,r)=>t.getValue(e)==r;Mi.autoRemove=t=>Ye(t);const wo=(t,e,r)=>{let[n,o]=r;const s=t.getValue(e);return s>=n&&s<=o};wo.resolveFilterValue=t=>{let[e,r]=t,n=typeof e!="number"?parseFloat(e):e,o=typeof r!="number"?parseFloat(r):r,s=e===null||Number.isNaN(n)?-1/0:n,i=r===null||Number.isNaN(o)?1/0:o;if(s>i){const a=s;s=i,i=a}return[s,i]};wo.autoRemove=t=>Ye(t)||Ye(t[0])&&Ye(t[1]);const at={includesString:Ci,includesStringSensitive:Ai,equalsString:Ei,arrIncludes:Ti,arrIncludesAll:$i,arrIncludesSome:Ni,equals:ki,weakEquals:Mi,inNumberRange:wo};function Ye(t){return t==null||t===""}const nu={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:t=>({columnFilters:[],...t}),getDefaultOptions:t=>({onColumnFiltersChange:He("columnFilters",t),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(t,e)=>{t.getAutoFilterFn=()=>{const r=e.getCoreRowModel().flatRows[0],n=r?.getValue(t.id);return typeof n=="string"?at.includesString:typeof n=="number"?at.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?at.equals:Array.isArray(n)?at.arrIncludes:at.weakEquals},t.getFilterFn=()=>{var r,n;return an(t.columnDef.filterFn)?t.columnDef.filterFn:t.columnDef.filterFn==="auto"?t.getAutoFilterFn():(r=(n=e.options.filterFns)==null?void 0:n[t.columnDef.filterFn])!=null?r:at[t.columnDef.filterFn]},t.getCanFilter=()=>{var r,n,o;return((r=t.columnDef.enableColumnFilter)!=null?r:!0)&&((n=e.options.enableColumnFilters)!=null?n:!0)&&((o=e.options.enableFilters)!=null?o:!0)&&!!t.accessorFn},t.getIsFiltered=()=>t.getFilterIndex()>-1,t.getFilterValue=()=>{var r;return(r=e.getState().columnFilters)==null||(r=r.find(n=>n.id===t.id))==null?void 0:r.value},t.getFilterIndex=()=>{var r,n;return(r=(n=e.getState().columnFilters)==null?void 0:n.findIndex(o=>o.id===t.id))!=null?r:-1},t.setFilterValue=r=>{e.setColumnFilters(n=>{const o=t.getFilterFn(),s=n?.find(d=>d.id===t.id),i=ht(r,s?s.value:void 0);if(fs(o,i,t)){var a;return(a=n?.filter(d=>d.id!==t.id))!=null?a:[]}const c={id:t.id,value:i};if(s){var l;return(l=n?.map(d=>d.id===t.id?c:d))!=null?l:[]}return n!=null&&n.length?[...n,c]:[c]})}},createRow:(t,e)=>{t.columnFilters={},t.columnFiltersMeta={}},createTable:t=>{t.setColumnFilters=e=>{const r=t.getAllLeafColumns(),n=o=>{var s;return(s=ht(e,o))==null?void 0:s.filter(i=>{const a=r.find(c=>c.id===i.id);if(a){const c=a.getFilterFn();if(fs(c,i.value,a))return!1}return!0})};t.options.onColumnFiltersChange==null||t.options.onColumnFiltersChange(n)},t.resetColumnFilters=e=>{var r,n;t.setColumnFilters(e?[]:(r=(n=t.initialState)==null?void 0:n.columnFilters)!=null?r:[])},t.getPreFilteredRowModel=()=>t.getCoreRowModel(),t.getFilteredRowModel=()=>(!t._getFilteredRowModel&&t.options.getFilteredRowModel&&(t._getFilteredRowModel=t.options.getFilteredRowModel(t)),t.options.manualFiltering||!t._getFilteredRowModel?t.getPreFilteredRowModel():t._getFilteredRowModel())}};function fs(t,e,r){return(t&&t.autoRemove?t.autoRemove(e,r):!1)||typeof e>"u"||typeof e=="string"&&!e}const ou=(t,e,r)=>r.reduce((n,o)=>{const s=o.getValue(t);return n+(typeof s=="number"?s:0)},0),su=(t,e,r)=>{let n;return r.forEach(o=>{const s=o.getValue(t);s!=null&&(n>s||n===void 0&&s>=s)&&(n=s)}),n},iu=(t,e,r)=>{let n;return r.forEach(o=>{const s=o.getValue(t);s!=null&&(n<s||n===void 0&&s>=s)&&(n=s)}),n},au=(t,e,r)=>{let n,o;return r.forEach(s=>{const i=s.getValue(t);i!=null&&(n===void 0?i>=i&&(n=o=i):(n>i&&(n=i),o<i&&(o=i)))}),[n,o]},lu=(t,e)=>{let r=0,n=0;if(e.forEach(o=>{let s=o.getValue(t);s!=null&&(s=+s)>=s&&(++r,n+=s)}),r)return n/r},cu=(t,e)=>{if(!e.length)return;const r=e.map(s=>s.getValue(t));if(!Jd(r))return;if(r.length===1)return r[0];const n=Math.floor(r.length/2),o=r.sort((s,i)=>s-i);return r.length%2!==0?o[n]:(o[n-1]+o[n])/2},du=(t,e)=>Array.from(new Set(e.map(r=>r.getValue(t))).values()),uu=(t,e)=>new Set(e.map(r=>r.getValue(t))).size,fu=(t,e)=>e.length,Cn={sum:ou,min:su,max:iu,extent:au,mean:lu,median:cu,unique:du,uniqueCount:uu,count:fu},gu={getDefaultColumnDef:()=>({aggregatedCell:t=>{var e,r;return(e=(r=t.getValue())==null||r.toString==null?void 0:r.toString())!=null?e:null},aggregationFn:"auto"}),getInitialState:t=>({grouping:[],...t}),getDefaultOptions:t=>({onGroupingChange:He("grouping",t),groupedColumnMode:"reorder"}),createColumn:(t,e)=>{t.toggleGrouping=()=>{e.setGrouping(r=>r!=null&&r.includes(t.id)?r.filter(n=>n!==t.id):[...r??[],t.id])},t.getCanGroup=()=>{var r,n;return((r=t.columnDef.enableGrouping)!=null?r:!0)&&((n=e.options.enableGrouping)!=null?n:!0)&&(!!t.accessorFn||!!t.columnDef.getGroupingValue)},t.getIsGrouped=()=>{var r;return(r=e.getState().grouping)==null?void 0:r.includes(t.id)},t.getGroupedIndex=()=>{var r;return(r=e.getState().grouping)==null?void 0:r.indexOf(t.id)},t.getToggleGroupingHandler=()=>{const r=t.getCanGroup();return()=>{r&&t.toggleGrouping()}},t.getAutoAggregationFn=()=>{const r=e.getCoreRowModel().flatRows[0],n=r?.getValue(t.id);if(typeof n=="number")return Cn.sum;if(Object.prototype.toString.call(n)==="[object Date]")return Cn.extent},t.getAggregationFn=()=>{var r,n;if(!t)throw new Error;return an(t.columnDef.aggregationFn)?t.columnDef.aggregationFn:t.columnDef.aggregationFn==="auto"?t.getAutoAggregationFn():(r=(n=e.options.aggregationFns)==null?void 0:n[t.columnDef.aggregationFn])!=null?r:Cn[t.columnDef.aggregationFn]}},createTable:t=>{t.setGrouping=e=>t.options.onGroupingChange==null?void 0:t.options.onGroupingChange(e),t.resetGrouping=e=>{var r,n;t.setGrouping(e?[]:(r=(n=t.initialState)==null?void 0:n.grouping)!=null?r:[])},t.getPreGroupedRowModel=()=>t.getFilteredRowModel(),t.getGroupedRowModel=()=>(!t._getGroupedRowModel&&t.options.getGroupedRowModel&&(t._getGroupedRowModel=t.options.getGroupedRowModel(t)),t.options.manualGrouping||!t._getGroupedRowModel?t.getPreGroupedRowModel():t._getGroupedRowModel())},createRow:(t,e)=>{t.getIsGrouped=()=>!!t.groupingColumnId,t.getGroupingValue=r=>{if(t._groupingValuesCache.hasOwnProperty(r))return t._groupingValuesCache[r];const n=e.getColumn(r);return n!=null&&n.columnDef.getGroupingValue?(t._groupingValuesCache[r]=n.columnDef.getGroupingValue(t.original),t._groupingValuesCache[r]):t.getValue(r)},t._groupingValuesCache={}},createCell:(t,e,r,n)=>{t.getIsGrouped=()=>e.getIsGrouped()&&e.id===r.groupingColumnId,t.getIsPlaceholder=()=>!t.getIsGrouped()&&e.getIsGrouped(),t.getIsAggregated=()=>{var o;return!t.getIsGrouped()&&!t.getIsPlaceholder()&&!!((o=r.subRows)!=null&&o.length)}}};function mu(t,e,r){if(!(e!=null&&e.length)||!r)return t;const n=t.filter(s=>!e.includes(s.id));return r==="remove"?n:[...e.map(s=>t.find(i=>i.id===s)).filter(Boolean),...n]}const pu={getInitialState:t=>({columnOrder:[],...t}),getDefaultOptions:t=>({onColumnOrderChange:He("columnOrder",t)}),createColumn:(t,e)=>{t.getIndex=z(r=>[lr(e,r)],r=>r.findIndex(n=>n.id===t.id),B(e.options,"debugColumns","getIndex")),t.getIsFirstColumn=r=>{var n;return((n=lr(e,r)[0])==null?void 0:n.id)===t.id},t.getIsLastColumn=r=>{var n;const o=lr(e,r);return((n=o[o.length-1])==null?void 0:n.id)===t.id}},createTable:t=>{t.setColumnOrder=e=>t.options.onColumnOrderChange==null?void 0:t.options.onColumnOrderChange(e),t.resetColumnOrder=e=>{var r;t.setColumnOrder(e?[]:(r=t.initialState.columnOrder)!=null?r:[])},t._getOrderColumnsFn=z(()=>[t.getState().columnOrder,t.getState().grouping,t.options.groupedColumnMode],(e,r,n)=>o=>{let s=[];if(!(e!=null&&e.length))s=o;else{const i=[...e],a=[...o];for(;a.length&&i.length;){const c=i.shift(),l=a.findIndex(d=>d.id===c);l>-1&&s.push(a.splice(l,1)[0])}s=[...s,...a]}return mu(s,r,n)},B(t.options,"debugTable","_getOrderColumnsFn"))}},An=()=>({left:[],right:[]}),hu={getInitialState:t=>({columnPinning:An(),...t}),getDefaultOptions:t=>({onColumnPinningChange:He("columnPinning",t)}),createColumn:(t,e)=>{t.pin=r=>{const n=t.getLeafColumns().map(o=>o.id).filter(Boolean);e.setColumnPinning(o=>{var s,i;if(r==="right"){var a,c;return{left:((a=o?.left)!=null?a:[]).filter(g=>!(n!=null&&n.includes(g))),right:[...((c=o?.right)!=null?c:[]).filter(g=>!(n!=null&&n.includes(g))),...n]}}if(r==="left"){var l,d;return{left:[...((l=o?.left)!=null?l:[]).filter(g=>!(n!=null&&n.includes(g))),...n],right:((d=o?.right)!=null?d:[]).filter(g=>!(n!=null&&n.includes(g)))}}return{left:((s=o?.left)!=null?s:[]).filter(g=>!(n!=null&&n.includes(g))),right:((i=o?.right)!=null?i:[]).filter(g=>!(n!=null&&n.includes(g)))}})},t.getCanPin=()=>t.getLeafColumns().some(n=>{var o,s,i;return((o=n.columnDef.enablePinning)!=null?o:!0)&&((s=(i=e.options.enableColumnPinning)!=null?i:e.options.enablePinning)!=null?s:!0)}),t.getIsPinned=()=>{const r=t.getLeafColumns().map(a=>a.id),{left:n,right:o}=e.getState().columnPinning,s=r.some(a=>n?.includes(a)),i=r.some(a=>o?.includes(a));return s?"left":i?"right":!1},t.getPinnedIndex=()=>{var r,n;const o=t.getIsPinned();return o?(r=(n=e.getState().columnPinning)==null||(n=n[o])==null?void 0:n.indexOf(t.id))!=null?r:-1:0}},createRow:(t,e)=>{t.getCenterVisibleCells=z(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left,e.getState().columnPinning.right],(r,n,o)=>{const s=[...n??[],...o??[]];return r.filter(i=>!s.includes(i.column.id))},B(e.options,"debugRows","getCenterVisibleCells")),t.getLeftVisibleCells=z(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left],(r,n)=>(n??[]).map(s=>r.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"left"})),B(e.options,"debugRows","getLeftVisibleCells")),t.getRightVisibleCells=z(()=>[t._getAllVisibleCells(),e.getState().columnPinning.right],(r,n)=>(n??[]).map(s=>r.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"right"})),B(e.options,"debugRows","getRightVisibleCells"))},createTable:t=>{t.setColumnPinning=e=>t.options.onColumnPinningChange==null?void 0:t.options.onColumnPinningChange(e),t.resetColumnPinning=e=>{var r,n;return t.setColumnPinning(e?An():(r=(n=t.initialState)==null?void 0:n.columnPinning)!=null?r:An())},t.getIsSomeColumnsPinned=e=>{var r;const n=t.getState().columnPinning;if(!e){var o,s;return!!((o=n.left)!=null&&o.length||(s=n.right)!=null&&s.length)}return!!((r=n[e])!=null&&r.length)},t.getLeftLeafColumns=z(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left],(e,r)=>(r??[]).map(n=>e.find(o=>o.id===n)).filter(Boolean),B(t.options,"debugColumns","getLeftLeafColumns")),t.getRightLeafColumns=z(()=>[t.getAllLeafColumns(),t.getState().columnPinning.right],(e,r)=>(r??[]).map(n=>e.find(o=>o.id===n)).filter(Boolean),B(t.options,"debugColumns","getRightLeafColumns")),t.getCenterLeafColumns=z(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n)=>{const o=[...r??[],...n??[]];return e.filter(s=>!o.includes(s.id))},B(t.options,"debugColumns","getCenterLeafColumns"))}};function yu(t){return t||(typeof document<"u"?document:null)}const Nr={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},En=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),bu={getDefaultColumnDef:()=>Nr,getInitialState:t=>({columnSizing:{},columnSizingInfo:En(),...t}),getDefaultOptions:t=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:He("columnSizing",t),onColumnSizingInfoChange:He("columnSizingInfo",t)}),createColumn:(t,e)=>{t.getSize=()=>{var r,n,o;const s=e.getState().columnSizing[t.id];return Math.min(Math.max((r=t.columnDef.minSize)!=null?r:Nr.minSize,(n=s??t.columnDef.size)!=null?n:Nr.size),(o=t.columnDef.maxSize)!=null?o:Nr.maxSize)},t.getStart=z(r=>[r,lr(e,r),e.getState().columnSizing],(r,n)=>n.slice(0,t.getIndex(r)).reduce((o,s)=>o+s.getSize(),0),B(e.options,"debugColumns","getStart")),t.getAfter=z(r=>[r,lr(e,r),e.getState().columnSizing],(r,n)=>n.slice(t.getIndex(r)+1).reduce((o,s)=>o+s.getSize(),0),B(e.options,"debugColumns","getAfter")),t.resetSize=()=>{e.setColumnSizing(r=>{let{[t.id]:n,...o}=r;return o})},t.getCanResize=()=>{var r,n;return((r=t.columnDef.enableResizing)!=null?r:!0)&&((n=e.options.enableColumnResizing)!=null?n:!0)},t.getIsResizing=()=>e.getState().columnSizingInfo.isResizingColumn===t.id},createHeader:(t,e)=>{t.getSize=()=>{let r=0;const n=o=>{if(o.subHeaders.length)o.subHeaders.forEach(n);else{var s;r+=(s=o.column.getSize())!=null?s:0}};return n(t),r},t.getStart=()=>{if(t.index>0){const r=t.headerGroup.headers[t.index-1];return r.getStart()+r.getSize()}return 0},t.getResizeHandler=r=>{const n=e.getColumn(t.column.id),o=n?.getCanResize();return s=>{if(!n||!o||(s.persist==null||s.persist(),Tn(s)&&s.touches&&s.touches.length>1))return;const i=t.getSize(),a=t?t.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[n.id,n.getSize()]],c=Tn(s)?Math.round(s.touches[0].clientX):s.clientX,l={},d=(b,_)=>{typeof _=="number"&&(e.setColumnSizingInfo(w=>{var C,v;const k=e.options.columnResizeDirection==="rtl"?-1:1,S=(_-((C=w?.startOffset)!=null?C:0))*k,E=Math.max(S/((v=w?.startSize)!=null?v:0),-.999999);return w.columnSizingStart.forEach(N=>{let[I,Y]=N;l[I]=Math.round(Math.max(Y+Y*E,0)*100)/100}),{...w,deltaOffset:S,deltaPercentage:E}}),(e.options.columnResizeMode==="onChange"||b==="end")&&e.setColumnSizing(w=>({...w,...l})))},g=b=>d("move",b),p=b=>{d("end",b),e.setColumnSizingInfo(_=>({..._,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=yu(r),m={moveHandler:b=>g(b.clientX),upHandler:b=>{f?.removeEventListener("mousemove",m.moveHandler),f?.removeEventListener("mouseup",m.upHandler),p(b.clientX)}},h={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),g(b.touches[0].clientX),!1),upHandler:b=>{var _;f?.removeEventListener("touchmove",h.moveHandler),f?.removeEventListener("touchend",h.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),p((_=b.touches[0])==null?void 0:_.clientX)}},y=xu()?{passive:!1}:!1;Tn(s)?(f?.addEventListener("touchmove",h.moveHandler,y),f?.addEventListener("touchend",h.upHandler,y)):(f?.addEventListener("mousemove",m.moveHandler,y),f?.addEventListener("mouseup",m.upHandler,y)),e.setColumnSizingInfo(b=>({...b,startOffset:c,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:n.id}))}}},createTable:t=>{t.setColumnSizing=e=>t.options.onColumnSizingChange==null?void 0:t.options.onColumnSizingChange(e),t.setColumnSizingInfo=e=>t.options.onColumnSizingInfoChange==null?void 0:t.options.onColumnSizingInfoChange(e),t.resetColumnSizing=e=>{var r;t.setColumnSizing(e?{}:(r=t.initialState.columnSizing)!=null?r:{})},t.resetHeaderSizeInfo=e=>{var r;t.setColumnSizingInfo(e?En():(r=t.initialState.columnSizingInfo)!=null?r:En())},t.getTotalSize=()=>{var e,r;return(e=(r=t.getHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getLeftTotalSize=()=>{var e,r;return(e=(r=t.getLeftHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getCenterTotalSize=()=>{var e,r;return(e=(r=t.getCenterHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getRightTotalSize=()=>{var e,r;return(e=(r=t.getRightHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0}}};let kr=null;function xu(){if(typeof kr=="boolean")return kr;let t=!1;try{const e={get passive(){return t=!0,!1}},r=()=>{};window.addEventListener("test",r,e),window.removeEventListener("test",r)}catch{t=!1}return kr=t,kr}function Tn(t){return t.type==="touchstart"}const wu={getInitialState:t=>({columnVisibility:{},...t}),getDefaultOptions:t=>({onColumnVisibilityChange:He("columnVisibility",t)}),createColumn:(t,e)=>{t.toggleVisibility=r=>{t.getCanHide()&&e.setColumnVisibility(n=>({...n,[t.id]:r??!t.getIsVisible()}))},t.getIsVisible=()=>{var r,n;const o=t.columns;return(r=o.length?o.some(s=>s.getIsVisible()):(n=e.getState().columnVisibility)==null?void 0:n[t.id])!=null?r:!0},t.getCanHide=()=>{var r,n;return((r=t.columnDef.enableHiding)!=null?r:!0)&&((n=e.options.enableHiding)!=null?n:!0)},t.getToggleVisibilityHandler=()=>r=>{t.toggleVisibility==null||t.toggleVisibility(r.target.checked)}},createRow:(t,e)=>{t._getAllVisibleCells=z(()=>[t.getAllCells(),e.getState().columnVisibility],r=>r.filter(n=>n.column.getIsVisible()),B(e.options,"debugRows","_getAllVisibleCells")),t.getVisibleCells=z(()=>[t.getLeftVisibleCells(),t.getCenterVisibleCells(),t.getRightVisibleCells()],(r,n,o)=>[...r,...n,...o],B(e.options,"debugRows","getVisibleCells"))},createTable:t=>{const e=(r,n)=>z(()=>[n(),n().filter(o=>o.getIsVisible()).map(o=>o.id).join("_")],o=>o.filter(s=>s.getIsVisible==null?void 0:s.getIsVisible()),B(t.options,"debugColumns",r));t.getVisibleFlatColumns=e("getVisibleFlatColumns",()=>t.getAllFlatColumns()),t.getVisibleLeafColumns=e("getVisibleLeafColumns",()=>t.getAllLeafColumns()),t.getLeftVisibleLeafColumns=e("getLeftVisibleLeafColumns",()=>t.getLeftLeafColumns()),t.getRightVisibleLeafColumns=e("getRightVisibleLeafColumns",()=>t.getRightLeafColumns()),t.getCenterVisibleLeafColumns=e("getCenterVisibleLeafColumns",()=>t.getCenterLeafColumns()),t.setColumnVisibility=r=>t.options.onColumnVisibilityChange==null?void 0:t.options.onColumnVisibilityChange(r),t.resetColumnVisibility=r=>{var n;t.setColumnVisibility(r?{}:(n=t.initialState.columnVisibility)!=null?n:{})},t.toggleAllColumnsVisible=r=>{var n;r=(n=r)!=null?n:!t.getIsAllColumnsVisible(),t.setColumnVisibility(t.getAllLeafColumns().reduce((o,s)=>({...o,[s.id]:r||!(s.getCanHide!=null&&s.getCanHide())}),{}))},t.getIsAllColumnsVisible=()=>!t.getAllLeafColumns().some(r=>!(r.getIsVisible!=null&&r.getIsVisible())),t.getIsSomeColumnsVisible=()=>t.getAllLeafColumns().some(r=>r.getIsVisible==null?void 0:r.getIsVisible()),t.getToggleAllColumnsVisibilityHandler=()=>r=>{var n;t.toggleAllColumnsVisible((n=r.target)==null?void 0:n.checked)}}};function lr(t,e){return e?e==="center"?t.getCenterVisibleLeafColumns():e==="left"?t.getLeftVisibleLeafColumns():t.getRightVisibleLeafColumns():t.getVisibleLeafColumns()}const vu={createTable:t=>{t._getGlobalFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,"__global__"),t.getGlobalFacetedRowModel=()=>t.options.manualFiltering||!t._getGlobalFacetedRowModel?t.getPreFilteredRowModel():t._getGlobalFacetedRowModel(),t._getGlobalFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,"__global__"),t.getGlobalFacetedUniqueValues=()=>t._getGlobalFacetedUniqueValues?t._getGlobalFacetedUniqueValues():new Map,t._getGlobalFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,"__global__"),t.getGlobalFacetedMinMaxValues=()=>{if(t._getGlobalFacetedMinMaxValues)return t._getGlobalFacetedMinMaxValues()}}},_u={getInitialState:t=>({globalFilter:void 0,...t}),getDefaultOptions:t=>({onGlobalFilterChange:He("globalFilter",t),globalFilterFn:"auto",getColumnCanGlobalFilter:e=>{var r;const n=(r=t.getCoreRowModel().flatRows[0])==null||(r=r._getAllCellsByColumnId()[e.id])==null?void 0:r.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(t,e)=>{t.getCanGlobalFilter=()=>{var r,n,o,s;return((r=t.columnDef.enableGlobalFilter)!=null?r:!0)&&((n=e.options.enableGlobalFilter)!=null?n:!0)&&((o=e.options.enableFilters)!=null?o:!0)&&((s=e.options.getColumnCanGlobalFilter==null?void 0:e.options.getColumnCanGlobalFilter(t))!=null?s:!0)&&!!t.accessorFn}},createTable:t=>{t.getGlobalAutoFilterFn=()=>at.includesString,t.getGlobalFilterFn=()=>{var e,r;const{globalFilterFn:n}=t.options;return an(n)?n:n==="auto"?t.getGlobalAutoFilterFn():(e=(r=t.options.filterFns)==null?void 0:r[n])!=null?e:at[n]},t.setGlobalFilter=e=>{t.options.onGlobalFilterChange==null||t.options.onGlobalFilterChange(e)},t.resetGlobalFilter=e=>{t.setGlobalFilter(e?void 0:t.initialState.globalFilter)}}},Su={getInitialState:t=>({expanded:{},...t}),getDefaultOptions:t=>({onExpandedChange:He("expanded",t),paginateExpandedRows:!0}),createTable:t=>{let e=!1,r=!1;t._autoResetExpanded=()=>{var n,o;if(!e){t._queue(()=>{e=!0});return}if((n=(o=t.options.autoResetAll)!=null?o:t.options.autoResetExpanded)!=null?n:!t.options.manualExpanding){if(r)return;r=!0,t._queue(()=>{t.resetExpanded(),r=!1})}},t.setExpanded=n=>t.options.onExpandedChange==null?void 0:t.options.onExpandedChange(n),t.toggleAllRowsExpanded=n=>{n??!t.getIsAllRowsExpanded()?t.setExpanded(!0):t.setExpanded({})},t.resetExpanded=n=>{var o,s;t.setExpanded(n?{}:(o=(s=t.initialState)==null?void 0:s.expanded)!=null?o:{})},t.getCanSomeRowsExpand=()=>t.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),t.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),t.toggleAllRowsExpanded()},t.getIsSomeRowsExpanded=()=>{const n=t.getState().expanded;return n===!0||Object.values(n).some(Boolean)},t.getIsAllRowsExpanded=()=>{const n=t.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||t.getRowModel().flatRows.some(o=>!o.getIsExpanded()))},t.getExpandedDepth=()=>{let n=0;return(t.getState().expanded===!0?Object.keys(t.getRowModel().rowsById):Object.keys(t.getState().expanded)).forEach(s=>{const i=s.split(".");n=Math.max(n,i.length)}),n},t.getPreExpandedRowModel=()=>t.getSortedRowModel(),t.getExpandedRowModel=()=>(!t._getExpandedRowModel&&t.options.getExpandedRowModel&&(t._getExpandedRowModel=t.options.getExpandedRowModel(t)),t.options.manualExpanding||!t._getExpandedRowModel?t.getPreExpandedRowModel():t._getExpandedRowModel())},createRow:(t,e)=>{t.toggleExpanded=r=>{e.setExpanded(n=>{var o;const s=n===!0?!0:!!(n!=null&&n[t.id]);let i={};if(n===!0?Object.keys(e.getRowModel().rowsById).forEach(a=>{i[a]=!0}):i=n,r=(o=r)!=null?o:!s,!s&&r)return{...i,[t.id]:!0};if(s&&!r){const{[t.id]:a,...c}=i;return c}return n})},t.getIsExpanded=()=>{var r;const n=e.getState().expanded;return!!((r=e.options.getIsRowExpanded==null?void 0:e.options.getIsRowExpanded(t))!=null?r:n===!0||n?.[t.id])},t.getCanExpand=()=>{var r,n,o;return(r=e.options.getRowCanExpand==null?void 0:e.options.getRowCanExpand(t))!=null?r:((n=e.options.enableExpanding)!=null?n:!0)&&!!((o=t.subRows)!=null&&o.length)},t.getIsAllParentsExpanded=()=>{let r=!0,n=t;for(;r&&n.parentId;)n=e.getRow(n.parentId,!0),r=n.getIsExpanded();return r},t.getToggleExpandedHandler=()=>{const r=t.getCanExpand();return()=>{r&&t.toggleExpanded()}}}},Yn=0,Kn=10,$n=()=>({pageIndex:Yn,pageSize:Kn}),Ru={getInitialState:t=>({...t,pagination:{...$n(),...t?.pagination}}),getDefaultOptions:t=>({onPaginationChange:He("pagination",t)}),createTable:t=>{let e=!1,r=!1;t._autoResetPageIndex=()=>{var n,o;if(!e){t._queue(()=>{e=!0});return}if((n=(o=t.options.autoResetAll)!=null?o:t.options.autoResetPageIndex)!=null?n:!t.options.manualPagination){if(r)return;r=!0,t._queue(()=>{t.resetPageIndex(),r=!1})}},t.setPagination=n=>{const o=s=>ht(n,s);return t.options.onPaginationChange==null?void 0:t.options.onPaginationChange(o)},t.resetPagination=n=>{var o;t.setPagination(n?$n():(o=t.initialState.pagination)!=null?o:$n())},t.setPageIndex=n=>{t.setPagination(o=>{let s=ht(n,o.pageIndex);const i=typeof t.options.pageCount>"u"||t.options.pageCount===-1?Number.MAX_SAFE_INTEGER:t.options.pageCount-1;return s=Math.max(0,Math.min(s,i)),{...o,pageIndex:s}})},t.resetPageIndex=n=>{var o,s;t.setPageIndex(n?Yn:(o=(s=t.initialState)==null||(s=s.pagination)==null?void 0:s.pageIndex)!=null?o:Yn)},t.resetPageSize=n=>{var o,s;t.setPageSize(n?Kn:(o=(s=t.initialState)==null||(s=s.pagination)==null?void 0:s.pageSize)!=null?o:Kn)},t.setPageSize=n=>{t.setPagination(o=>{const s=Math.max(1,ht(n,o.pageSize)),i=o.pageSize*o.pageIndex,a=Math.floor(i/s);return{...o,pageIndex:a,pageSize:s}})},t.setPageCount=n=>t.setPagination(o=>{var s;let i=ht(n,(s=t.options.pageCount)!=null?s:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...o,pageCount:i}}),t.getPageOptions=z(()=>[t.getPageCount()],n=>{let o=[];return n&&n>0&&(o=[...new Array(n)].fill(null).map((s,i)=>i)),o},B(t.options,"debugTable","getPageOptions")),t.getCanPreviousPage=()=>t.getState().pagination.pageIndex>0,t.getCanNextPage=()=>{const{pageIndex:n}=t.getState().pagination,o=t.getPageCount();return o===-1?!0:o===0?!1:n<o-1},t.previousPage=()=>t.setPageIndex(n=>n-1),t.nextPage=()=>t.setPageIndex(n=>n+1),t.firstPage=()=>t.setPageIndex(0),t.lastPage=()=>t.setPageIndex(t.getPageCount()-1),t.getPrePaginationRowModel=()=>t.getExpandedRowModel(),t.getPaginationRowModel=()=>(!t._getPaginationRowModel&&t.options.getPaginationRowModel&&(t._getPaginationRowModel=t.options.getPaginationRowModel(t)),t.options.manualPagination||!t._getPaginationRowModel?t.getPrePaginationRowModel():t._getPaginationRowModel()),t.getPageCount=()=>{var n;return(n=t.options.pageCount)!=null?n:Math.ceil(t.getRowCount()/t.getState().pagination.pageSize)},t.getRowCount=()=>{var n;return(n=t.options.rowCount)!=null?n:t.getPrePaginationRowModel().rows.length}}},Nn=()=>({top:[],bottom:[]}),Cu={getInitialState:t=>({rowPinning:Nn(),...t}),getDefaultOptions:t=>({onRowPinningChange:He("rowPinning",t)}),createRow:(t,e)=>{t.pin=(r,n,o)=>{const s=n?t.getLeafRows().map(c=>{let{id:l}=c;return l}):[],i=o?t.getParentRows().map(c=>{let{id:l}=c;return l}):[],a=new Set([...i,t.id,...s]);e.setRowPinning(c=>{var l,d;if(r==="bottom"){var g,p;return{top:((g=c?.top)!=null?g:[]).filter(h=>!(a!=null&&a.has(h))),bottom:[...((p=c?.bottom)!=null?p:[]).filter(h=>!(a!=null&&a.has(h))),...Array.from(a)]}}if(r==="top"){var f,m;return{top:[...((f=c?.top)!=null?f:[]).filter(h=>!(a!=null&&a.has(h))),...Array.from(a)],bottom:((m=c?.bottom)!=null?m:[]).filter(h=>!(a!=null&&a.has(h)))}}return{top:((l=c?.top)!=null?l:[]).filter(h=>!(a!=null&&a.has(h))),bottom:((d=c?.bottom)!=null?d:[]).filter(h=>!(a!=null&&a.has(h)))}})},t.getCanPin=()=>{var r;const{enableRowPinning:n,enablePinning:o}=e.options;return typeof n=="function"?n(t):(r=n??o)!=null?r:!0},t.getIsPinned=()=>{const r=[t.id],{top:n,bottom:o}=e.getState().rowPinning,s=r.some(a=>n?.includes(a)),i=r.some(a=>o?.includes(a));return s?"top":i?"bottom":!1},t.getPinnedIndex=()=>{var r,n;const o=t.getIsPinned();if(!o)return-1;const s=(r=o==="top"?e.getTopRows():e.getBottomRows())==null?void 0:r.map(i=>{let{id:a}=i;return a});return(n=s?.indexOf(t.id))!=null?n:-1}},createTable:t=>{t.setRowPinning=e=>t.options.onRowPinningChange==null?void 0:t.options.onRowPinningChange(e),t.resetRowPinning=e=>{var r,n;return t.setRowPinning(e?Nn():(r=(n=t.initialState)==null?void 0:n.rowPinning)!=null?r:Nn())},t.getIsSomeRowsPinned=e=>{var r;const n=t.getState().rowPinning;if(!e){var o,s;return!!((o=n.top)!=null&&o.length||(s=n.bottom)!=null&&s.length)}return!!((r=n[e])!=null&&r.length)},t._getPinnedRows=(e,r,n)=>{var o;return((o=t.options.keepPinnedRows)==null||o?(r??[]).map(i=>{const a=t.getRow(i,!0);return a.getIsAllParentsExpanded()?a:null}):(r??[]).map(i=>e.find(a=>a.id===i))).filter(Boolean).map(i=>({...i,position:n}))},t.getTopRows=z(()=>[t.getRowModel().rows,t.getState().rowPinning.top],(e,r)=>t._getPinnedRows(e,r,"top"),B(t.options,"debugRows","getTopRows")),t.getBottomRows=z(()=>[t.getRowModel().rows,t.getState().rowPinning.bottom],(e,r)=>t._getPinnedRows(e,r,"bottom"),B(t.options,"debugRows","getBottomRows")),t.getCenterRows=z(()=>[t.getRowModel().rows,t.getState().rowPinning.top,t.getState().rowPinning.bottom],(e,r,n)=>{const o=new Set([...r??[],...n??[]]);return e.filter(s=>!o.has(s.id))},B(t.options,"debugRows","getCenterRows"))}},Au={getInitialState:t=>({rowSelection:{},...t}),getDefaultOptions:t=>({onRowSelectionChange:He("rowSelection",t),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:t=>{t.setRowSelection=e=>t.options.onRowSelectionChange==null?void 0:t.options.onRowSelectionChange(e),t.resetRowSelection=e=>{var r;return t.setRowSelection(e?{}:(r=t.initialState.rowSelection)!=null?r:{})},t.toggleAllRowsSelected=e=>{t.setRowSelection(r=>{e=typeof e<"u"?e:!t.getIsAllRowsSelected();const n={...r},o=t.getPreGroupedRowModel().flatRows;return e?o.forEach(s=>{s.getCanSelect()&&(n[s.id]=!0)}):o.forEach(s=>{delete n[s.id]}),n})},t.toggleAllPageRowsSelected=e=>t.setRowSelection(r=>{const n=typeof e<"u"?e:!t.getIsAllPageRowsSelected(),o={...r};return t.getRowModel().rows.forEach(s=>{Xn(o,s.id,n,!0,t)}),o}),t.getPreSelectedRowModel=()=>t.getCoreRowModel(),t.getSelectedRowModel=z(()=>[t.getState().rowSelection,t.getCoreRowModel()],(e,r)=>Object.keys(e).length?kn(t,r):{rows:[],flatRows:[],rowsById:{}},B(t.options,"debugTable","getSelectedRowModel")),t.getFilteredSelectedRowModel=z(()=>[t.getState().rowSelection,t.getFilteredRowModel()],(e,r)=>Object.keys(e).length?kn(t,r):{rows:[],flatRows:[],rowsById:{}},B(t.options,"debugTable","getFilteredSelectedRowModel")),t.getGroupedSelectedRowModel=z(()=>[t.getState().rowSelection,t.getSortedRowModel()],(e,r)=>Object.keys(e).length?kn(t,r):{rows:[],flatRows:[],rowsById:{}},B(t.options,"debugTable","getGroupedSelectedRowModel")),t.getIsAllRowsSelected=()=>{const e=t.getFilteredRowModel().flatRows,{rowSelection:r}=t.getState();let n=!!(e.length&&Object.keys(r).length);return n&&e.some(o=>o.getCanSelect()&&!r[o.id])&&(n=!1),n},t.getIsAllPageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows.filter(o=>o.getCanSelect()),{rowSelection:r}=t.getState();let n=!!e.length;return n&&e.some(o=>!r[o.id])&&(n=!1),n},t.getIsSomeRowsSelected=()=>{var e;const r=Object.keys((e=t.getState().rowSelection)!=null?e:{}).length;return r>0&&r<t.getFilteredRowModel().flatRows.length},t.getIsSomePageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows;return t.getIsAllPageRowsSelected()?!1:e.filter(r=>r.getCanSelect()).some(r=>r.getIsSelected()||r.getIsSomeSelected())},t.getToggleAllRowsSelectedHandler=()=>e=>{t.toggleAllRowsSelected(e.target.checked)},t.getToggleAllPageRowsSelectedHandler=()=>e=>{t.toggleAllPageRowsSelected(e.target.checked)}},createRow:(t,e)=>{t.toggleSelected=(r,n)=>{const o=t.getIsSelected();e.setRowSelection(s=>{var i;if(r=typeof r<"u"?r:!o,t.getCanSelect()&&o===r)return s;const a={...s};return Xn(a,t.id,r,(i=n?.selectChildren)!=null?i:!0,e),a})},t.getIsSelected=()=>{const{rowSelection:r}=e.getState();return vo(t,r)},t.getIsSomeSelected=()=>{const{rowSelection:r}=e.getState();return Jn(t,r)==="some"},t.getIsAllSubRowsSelected=()=>{const{rowSelection:r}=e.getState();return Jn(t,r)==="all"},t.getCanSelect=()=>{var r;return typeof e.options.enableRowSelection=="function"?e.options.enableRowSelection(t):(r=e.options.enableRowSelection)!=null?r:!0},t.getCanSelectSubRows=()=>{var r;return typeof e.options.enableSubRowSelection=="function"?e.options.enableSubRowSelection(t):(r=e.options.enableSubRowSelection)!=null?r:!0},t.getCanMultiSelect=()=>{var r;return typeof e.options.enableMultiRowSelection=="function"?e.options.enableMultiRowSelection(t):(r=e.options.enableMultiRowSelection)!=null?r:!0},t.getToggleSelectedHandler=()=>{const r=t.getCanSelect();return n=>{var o;r&&t.toggleSelected((o=n.target)==null?void 0:o.checked)}}}},Xn=(t,e,r,n,o)=>{var s;const i=o.getRow(e,!0);r?(i.getCanMultiSelect()||Object.keys(t).forEach(a=>delete t[a]),i.getCanSelect()&&(t[e]=!0)):delete t[e],n&&(s=i.subRows)!=null&&s.length&&i.getCanSelectSubRows()&&i.subRows.forEach(a=>Xn(t,a.id,r,n,o))};function kn(t,e){const r=t.getState().rowSelection,n=[],o={},s=function(i,a){return i.map(c=>{var l;const d=vo(c,r);if(d&&(n.push(c),o[c.id]=c),(l=c.subRows)!=null&&l.length&&(c={...c,subRows:s(c.subRows)}),d)return c}).filter(Boolean)};return{rows:s(e.rows),flatRows:n,rowsById:o}}function vo(t,e){var r;return(r=e[t.id])!=null?r:!1}function Jn(t,e,r){var n;if(!((n=t.subRows)!=null&&n.length))return!1;let o=!0,s=!1;return t.subRows.forEach(i=>{if(!(s&&!o)&&(i.getCanSelect()&&(vo(i,e)?s=!0:o=!1),i.subRows&&i.subRows.length)){const a=Jn(i,e);a==="all"?s=!0:(a==="some"&&(s=!0),o=!1)}}),o?"all":s?"some":!1}const Zn=/([0-9]+)/gm,Eu=(t,e,r)=>Oi(bt(t.getValue(r)).toLowerCase(),bt(e.getValue(r)).toLowerCase()),Tu=(t,e,r)=>Oi(bt(t.getValue(r)),bt(e.getValue(r))),$u=(t,e,r)=>_o(bt(t.getValue(r)).toLowerCase(),bt(e.getValue(r)).toLowerCase()),Nu=(t,e,r)=>_o(bt(t.getValue(r)),bt(e.getValue(r))),ku=(t,e,r)=>{const n=t.getValue(r),o=e.getValue(r);return n>o?1:n<o?-1:0},Mu=(t,e,r)=>_o(t.getValue(r),e.getValue(r));function _o(t,e){return t===e?0:t>e?1:-1}function bt(t){return typeof t=="number"?isNaN(t)||t===1/0||t===-1/0?"":String(t):typeof t=="string"?t:""}function Oi(t,e){const r=t.split(Zn).filter(Boolean),n=e.split(Zn).filter(Boolean);for(;r.length&&n.length;){const o=r.shift(),s=n.shift(),i=parseInt(o,10),a=parseInt(s,10),c=[i,a].sort();if(isNaN(c[0])){if(o>s)return 1;if(s>o)return-1;continue}if(isNaN(c[1]))return isNaN(i)?-1:1;if(i>a)return 1;if(a>i)return-1}return r.length-n.length}const rr={alphanumeric:Eu,alphanumericCaseSensitive:Tu,text:$u,textCaseSensitive:Nu,datetime:ku,basic:Mu},Ou={getInitialState:t=>({sorting:[],...t}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:t=>({onSortingChange:He("sorting",t),isMultiSortEvent:e=>e.shiftKey}),createColumn:(t,e)=>{t.getAutoSortingFn=()=>{const r=e.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const o of r){const s=o?.getValue(t.id);if(Object.prototype.toString.call(s)==="[object Date]")return rr.datetime;if(typeof s=="string"&&(n=!0,s.split(Zn).length>1))return rr.alphanumeric}return n?rr.text:rr.basic},t.getAutoSortDir=()=>{const r=e.getFilteredRowModel().flatRows[0];return typeof r?.getValue(t.id)=="string"?"asc":"desc"},t.getSortingFn=()=>{var r,n;if(!t)throw new Error;return an(t.columnDef.sortingFn)?t.columnDef.sortingFn:t.columnDef.sortingFn==="auto"?t.getAutoSortingFn():(r=(n=e.options.sortingFns)==null?void 0:n[t.columnDef.sortingFn])!=null?r:rr[t.columnDef.sortingFn]},t.toggleSorting=(r,n)=>{const o=t.getNextSortingOrder(),s=typeof r<"u"&&r!==null;e.setSorting(i=>{const a=i?.find(f=>f.id===t.id),c=i?.findIndex(f=>f.id===t.id);let l=[],d,g=s?r:o==="desc";if(i!=null&&i.length&&t.getCanMultiSort()&&n?a?d="toggle":d="add":i!=null&&i.length&&c!==i.length-1?d="replace":a?d="toggle":d="replace",d==="toggle"&&(s||o||(d="remove")),d==="add"){var p;l=[...i,{id:t.id,desc:g}],l.splice(0,l.length-((p=e.options.maxMultiSortColCount)!=null?p:Number.MAX_SAFE_INTEGER))}else d==="toggle"?l=i.map(f=>f.id===t.id?{...f,desc:g}:f):d==="remove"?l=i.filter(f=>f.id!==t.id):l=[{id:t.id,desc:g}];return l})},t.getFirstSortDir=()=>{var r,n;return((r=(n=t.columnDef.sortDescFirst)!=null?n:e.options.sortDescFirst)!=null?r:t.getAutoSortDir()==="desc")?"desc":"asc"},t.getNextSortingOrder=r=>{var n,o;const s=t.getFirstSortDir(),i=t.getIsSorted();return i?i!==s&&((n=e.options.enableSortingRemoval)==null||n)&&(!(r&&(o=e.options.enableMultiRemove)!=null)||o)?!1:i==="desc"?"asc":"desc":s},t.getCanSort=()=>{var r,n;return((r=t.columnDef.enableSorting)!=null?r:!0)&&((n=e.options.enableSorting)!=null?n:!0)&&!!t.accessorFn},t.getCanMultiSort=()=>{var r,n;return(r=(n=t.columnDef.enableMultiSort)!=null?n:e.options.enableMultiSort)!=null?r:!!t.accessorFn},t.getIsSorted=()=>{var r;const n=(r=e.getState().sorting)==null?void 0:r.find(o=>o.id===t.id);return n?n.desc?"desc":"asc":!1},t.getSortIndex=()=>{var r,n;return(r=(n=e.getState().sorting)==null?void 0:n.findIndex(o=>o.id===t.id))!=null?r:-1},t.clearSorting=()=>{e.setSorting(r=>r!=null&&r.length?r.filter(n=>n.id!==t.id):[])},t.getToggleSortingHandler=()=>{const r=t.getCanSort();return n=>{r&&(n.persist==null||n.persist(),t.toggleSorting==null||t.toggleSorting(void 0,t.getCanMultiSort()?e.options.isMultiSortEvent==null?void 0:e.options.isMultiSortEvent(n):!1))}}},createTable:t=>{t.setSorting=e=>t.options.onSortingChange==null?void 0:t.options.onSortingChange(e),t.resetSorting=e=>{var r,n;t.setSorting(e?[]:(r=(n=t.initialState)==null?void 0:n.sorting)!=null?r:[])},t.getPreSortedRowModel=()=>t.getGroupedRowModel(),t.getSortedRowModel=()=>(!t._getSortedRowModel&&t.options.getSortedRowModel&&(t._getSortedRowModel=t.options.getSortedRowModel(t)),t.options.manualSorting||!t._getSortedRowModel?t.getPreSortedRowModel():t._getSortedRowModel())}},Iu=[tu,wu,pu,hu,ru,nu,vu,_u,Ou,gu,Su,Ru,Cu,Au,bu];function Fu(t){var e,r;process.env.NODE_ENV!=="production"&&(t.debugAll||t.debugTable)&&console.info("Creating Table Instance...");const n=[...Iu,...(e=t._features)!=null?e:[]];let o={_features:n};const s=o._features.reduce((p,f)=>Object.assign(p,f.getDefaultOptions==null?void 0:f.getDefaultOptions(o)),{}),i=p=>o.options.mergeOptions?o.options.mergeOptions(s,p):{...s,...p};let c={...{},...(r=t.initialState)!=null?r:{}};o._features.forEach(p=>{var f;c=(f=p.getInitialState==null?void 0:p.getInitialState(c))!=null?f:c});const l=[];let d=!1;const g={_features:n,options:{...s,...t},initialState:c,_queue:p=>{l.push(p),d||(d=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();d=!1}).catch(f=>setTimeout(()=>{throw f})))},reset:()=>{o.setState(o.initialState)},setOptions:p=>{const f=ht(p,o.options);o.options=i(f)},getState:()=>o.options.state,setState:p=>{o.options.onStateChange==null||o.options.onStateChange(p)},_getRowId:(p,f,m)=>{var h;return(h=o.options.getRowId==null?void 0:o.options.getRowId(p,f,m))!=null?h:`${m?[m.id,f].join("."):f}`},getCoreRowModel:()=>(o._getCoreRowModel||(o._getCoreRowModel=o.options.getCoreRowModel(o)),o._getCoreRowModel()),getRowModel:()=>o.getPaginationRowModel(),getRow:(p,f)=>{let m=(f?o.getPrePaginationRowModel():o.getRowModel()).rowsById[p];if(!m&&(m=o.getCoreRowModel().rowsById[p],!m))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${p}`):new Error;return m},_getDefaultColumnDef:z(()=>[o.options.defaultColumn],p=>{var f;return p=(f=p)!=null?f:{},{header:m=>{const h=m.header.column.columnDef;return h.accessorKey?h.accessorKey:h.accessorFn?h.id:null},cell:m=>{var h,y;return(h=(y=m.renderValue())==null||y.toString==null?void 0:y.toString())!=null?h:null},...o._features.reduce((m,h)=>Object.assign(m,h.getDefaultColumnDef==null?void 0:h.getDefaultColumnDef()),{}),...p}},B(t,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>o.options.columns,getAllColumns:z(()=>[o._getColumnDefs()],p=>{const f=function(m,h,y){return y===void 0&&(y=0),m.map(b=>{const _=eu(o,b,y,h),w=b;return _.columns=w.columns?f(w.columns,_,y+1):[],_})};return f(p)},B(t,"debugColumns","getAllColumns")),getAllFlatColumns:z(()=>[o.getAllColumns()],p=>p.flatMap(f=>f.getFlatColumns()),B(t,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:z(()=>[o.getAllFlatColumns()],p=>p.reduce((f,m)=>(f[m.id]=m,f),{}),B(t,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:z(()=>[o.getAllColumns(),o._getOrderColumnsFn()],(p,f)=>{let m=p.flatMap(h=>h.getLeafColumns());return f(m)},B(t,"debugColumns","getAllLeafColumns")),getColumn:p=>{const f=o._getAllFlatColumnsById()[p];return process.env.NODE_ENV!=="production"&&!f&&console.error(`[Table] Column with id '${p}' does not exist.`),f}};Object.assign(o,g);for(let p=0;p<o._features.length;p++){const f=o._features[p];f==null||f.createTable==null||f.createTable(o)}return o}function ju(){return t=>z(()=>[t.options.data],e=>{const r={rows:[],flatRows:[],rowsById:{}},n=function(o,s,i){s===void 0&&(s=0);const a=[];for(let l=0;l<o.length;l++){const d=xo(t,t._getRowId(o[l],l,i),o[l],l,s,void 0,i?.id);if(r.flatRows.push(d),r.rowsById[d.id]=d,a.push(d),t.options.getSubRows){var c;d.originalSubRows=t.options.getSubRows(o[l],l),(c=d.originalSubRows)!=null&&c.length&&(d.subRows=n(d.originalSubRows,s+1,d))}}return a};return r.rows=n(e),r},B(t.options,"debugTable","getRowModel",()=>t._autoResetPageIndex()))}function Pu(t){const e=[],r=n=>{var o;e.push(n),(o=n.subRows)!=null&&o.length&&n.getIsExpanded()&&n.subRows.forEach(r)};return t.rows.forEach(r),{rows:e,flatRows:t.flatRows,rowsById:t.rowsById}}function Du(t,e,r){return r.options.filterFromLeafRows?Lu(t,e,r):Gu(t,e,r)}function Lu(t,e,r){var n;const o=[],s={},i=(n=r.options.maxLeafRowFilterDepth)!=null?n:100,a=function(c,l){l===void 0&&(l=0);const d=[];for(let p=0;p<c.length;p++){var g;let f=c[p];const m=xo(r,f.id,f.original,f.index,f.depth,void 0,f.parentId);if(m.columnFilters=f.columnFilters,(g=f.subRows)!=null&&g.length&&l<i){if(m.subRows=a(f.subRows,l+1),f=m,e(f)&&!m.subRows.length){d.push(f),s[f.id]=f,o.push(f);continue}if(e(f)||m.subRows.length){d.push(f),s[f.id]=f,o.push(f);continue}}else f=m,e(f)&&(d.push(f),s[f.id]=f,o.push(f))}return d};return{rows:a(t),flatRows:o,rowsById:s}}function Gu(t,e,r){var n;const o=[],s={},i=(n=r.options.maxLeafRowFilterDepth)!=null?n:100,a=function(c,l){l===void 0&&(l=0);const d=[];for(let p=0;p<c.length;p++){let f=c[p];if(e(f)){var g;if((g=f.subRows)!=null&&g.length&&l<i){const h=xo(r,f.id,f.original,f.index,f.depth,void 0,f.parentId);h.subRows=a(f.subRows,l+1),f=h}d.push(f),o.push(f),s[f.id]=f}}return d};return{rows:a(t),flatRows:o,rowsById:s}}function Uu(){return t=>z(()=>[t.getPreFilteredRowModel(),t.getState().columnFilters,t.getState().globalFilter],(e,r,n)=>{if(!e.rows.length||!(r!=null&&r.length)&&!n){for(let p=0;p<e.flatRows.length;p++)e.flatRows[p].columnFilters={},e.flatRows[p].columnFiltersMeta={};return e}const o=[],s=[];(r??[]).forEach(p=>{var f;const m=t.getColumn(p.id);if(!m)return;const h=m.getFilterFn();if(!h){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${m.id}.`);return}o.push({id:p.id,filterFn:h,resolvedValue:(f=h.resolveFilterValue==null?void 0:h.resolveFilterValue(p.value))!=null?f:p.value})});const i=(r??[]).map(p=>p.id),a=t.getGlobalFilterFn(),c=t.getAllLeafColumns().filter(p=>p.getCanGlobalFilter());n&&a&&c.length&&(i.push("__global__"),c.forEach(p=>{var f;s.push({id:p.id,filterFn:a,resolvedValue:(f=a.resolveFilterValue==null?void 0:a.resolveFilterValue(n))!=null?f:n})}));let l,d;for(let p=0;p<e.flatRows.length;p++){const f=e.flatRows[p];if(f.columnFilters={},o.length)for(let m=0;m<o.length;m++){l=o[m];const h=l.id;f.columnFilters[h]=l.filterFn(f,h,l.resolvedValue,y=>{f.columnFiltersMeta[h]=y})}if(s.length){for(let m=0;m<s.length;m++){d=s[m];const h=d.id;if(d.filterFn(f,h,d.resolvedValue,y=>{f.columnFiltersMeta[h]=y})){f.columnFilters.__global__=!0;break}}f.columnFilters.__global__!==!0&&(f.columnFilters.__global__=!1)}}const g=p=>{for(let f=0;f<i.length;f++)if(p.columnFilters[i[f]]===!1)return!1;return!0};return Du(e.rows,g,t)},B(t.options,"debugTable","getFilteredRowModel",()=>t._autoResetPageIndex()))}function Vu(t){return e=>z(()=>[e.getState().pagination,e.getPrePaginationRowModel(),e.options.paginateExpandedRows?void 0:e.getState().expanded],(r,n)=>{if(!n.rows.length)return n;const{pageSize:o,pageIndex:s}=r;let{rows:i,flatRows:a,rowsById:c}=n;const l=o*s,d=l+o;i=i.slice(l,d);let g;e.options.paginateExpandedRows?g={rows:i,flatRows:a,rowsById:c}:g=Pu({rows:i,flatRows:a,rowsById:c}),g.flatRows=[];const p=f=>{g.flatRows.push(f),f.subRows.length&&f.subRows.forEach(p)};return g.rows.forEach(p),g},B(e.options,"debugTable","getPaginationRowModel"))}function zu(){return t=>z(()=>[t.getState().sorting,t.getPreSortedRowModel()],(e,r)=>{if(!r.rows.length||!(e!=null&&e.length))return r;const n=t.getState().sorting,o=[],s=n.filter(c=>{var l;return(l=t.getColumn(c.id))==null?void 0:l.getCanSort()}),i={};s.forEach(c=>{const l=t.getColumn(c.id);l&&(i[c.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const a=c=>{const l=c.map(d=>({...d}));return l.sort((d,g)=>{for(let f=0;f<s.length;f+=1){var p;const m=s[f],h=i[m.id],y=h.sortUndefined,b=(p=m?.desc)!=null?p:!1;let _=0;if(y){const w=d.getValue(m.id),C=g.getValue(m.id),v=w===void 0,k=C===void 0;if(v||k){if(y==="first")return v?-1:1;if(y==="last")return v?1:-1;_=v&&k?0:v?y:-y}}if(_===0&&(_=h.sortingFn(d,g,m.id)),_!==0)return b&&(_*=-1),h.invertSorting&&(_*=-1),_}return d.index-g.index}),l.forEach(d=>{var g;o.push(d),(g=d.subRows)!=null&&g.length&&(d.subRows=a(d.subRows))}),l};return{rows:a(r.rows),flatRows:o,rowsById:r.rowsById}},B(t.options,"debugTable","getSortedRowModel",()=>t._autoResetPageIndex()))}function Bu(t){const e={state:{},onStateChange:()=>{},renderFallbackValue:null,...t},[r]=Ve.useState(()=>({current:Fu(e)})),[n,o]=Ve.useState(()=>r.current.initialState);return r.current.setOptions(s=>({...s,...t,state:{...n,...t.state},onStateChange:i=>{o(i),t.onStateChange==null||t.onStateChange(i)}})),r.current}function Hu({data:t,columns:e,enabled:r=!1}){const n=x.useMemo(()=>t,[t]),o=Bu({data:n,columns:e||[],getCoreRowModel:ju(),getSortedRowModel:zu(),getFilteredRowModel:Uu(),getPaginationRowModel:Vu(),enableSorting:r,enableFilters:r});return r?o:null}const Kt=x.memo(({parts:t=[],children:e=null,fontSize:r="1rem",color:n="#333333",displayMode:o=!1,className:s=""})=>{x.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(g=>{try{return g.href&&g.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
9
+ color: hsl(${Math.max(0,Math.min(120-120*m,120))}deg 100% 31%);`,r?.key)}return o}}function W(t,e,r,n){return{debug:()=>{var o;return(o=t?.debugAll)!=null?o:t[e]},key:process.env.NODE_ENV==="development"&&r,onChange:n}}function Ou(t,e,r,n){const o=()=>{var i;return(i=s.getValue())!=null?i:t.options.renderFallbackValue},s={id:`${e.id}_${r.id}`,row:e,column:r,getValue:()=>e.getValue(n),renderValue:o,getContext:q(()=>[t,r,e,s],(i,a,c,l)=>({table:i,column:a,row:c,cell:l,getValue:l.getValue,renderValue:l.renderValue}),W(t.options,"debugCells","cell.getContext"))};return t._features.forEach(i=>{i.createCell==null||i.createCell(s,r,e,t)},{}),s}function Fu(t,e,r,n){var o,s;const a={...t._getDefaultColumnDef(),...e},c=a.accessorKey;let l=(o=(s=a.id)!=null?s:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?o:typeof a.header=="string"?a.header:void 0,u;if(a.accessorFn?u=a.accessorFn:c&&(c.includes(".")?u=m=>{let f=m;for(const h of c.split(".")){var p;f=(p=f)==null?void 0:p[h],process.env.NODE_ENV!=="production"&&f===void 0&&console.warn(`"${h}" in deeply nested key "${c}" returned undefined.`)}return f}:u=m=>m[a.accessorKey]),!l)throw process.env.NODE_ENV!=="production"?new Error(a.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let g={id:`${String(l)}`,accessorFn:u,parent:n,depth:r,columnDef:a,columns:[],getFlatColumns:q(()=>[!0],()=>{var m;return[g,...(m=g.columns)==null?void 0:m.flatMap(f=>f.getFlatColumns())]},W(t.options,"debugColumns","column.getFlatColumns")),getLeafColumns:q(()=>[t._getOrderColumnsFn()],m=>{var f;if((f=g.columns)!=null&&f.length){let p=g.columns.flatMap(h=>h.getLeafColumns());return m(p)}return[g]},W(t.options,"debugColumns","column.getLeafColumns"))};for(const m of t._features)m.createColumn==null||m.createColumn(g,t);return g}const $e="debugHeaders";function ws(t,e,r){var n;let s={id:(n=r.id)!=null?n:e.id,column:e,index:r.index,isPlaceholder:!!r.isPlaceholder,placeholderId:r.placeholderId,depth:r.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],a=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(a),i.push(c)};return a(s),i},getContext:()=>({table:t,header:s,column:e})};return t._features.forEach(i=>{i.createHeader==null||i.createHeader(s,t)}),s}const Pu={createTable:t=>{t.getHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n,o)=>{var s,i;const a=(s=n?.map(g=>r.find(m=>m.id===g)).filter(Boolean))!=null?s:[],c=(i=o?.map(g=>r.find(m=>m.id===g)).filter(Boolean))!=null?i:[],l=r.filter(g=>!(n!=null&&n.includes(g.id))&&!(o!=null&&o.includes(g.id)));return jr(e,[...a,...l,...c],t)},W(t.options,$e,"getHeaderGroups")),t.getCenterHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n,o)=>(r=r.filter(s=>!(n!=null&&n.includes(s.id))&&!(o!=null&&o.includes(s.id))),jr(e,r,t,"center")),W(t.options,$e,"getCenterHeaderGroups")),t.getLeftHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.left],(e,r,n)=>{var o;const s=(o=n?.map(i=>r.find(a=>a.id===i)).filter(Boolean))!=null?o:[];return jr(e,s,t,"left")},W(t.options,$e,"getLeftHeaderGroups")),t.getRightHeaderGroups=q(()=>[t.getAllColumns(),t.getVisibleLeafColumns(),t.getState().columnPinning.right],(e,r,n)=>{var o;const s=(o=n?.map(i=>r.find(a=>a.id===i)).filter(Boolean))!=null?o:[];return jr(e,s,t,"right")},W(t.options,$e,"getRightHeaderGroups")),t.getFooterGroups=q(()=>[t.getHeaderGroups()],e=>[...e].reverse(),W(t.options,$e,"getFooterGroups")),t.getLeftFooterGroups=q(()=>[t.getLeftHeaderGroups()],e=>[...e].reverse(),W(t.options,$e,"getLeftFooterGroups")),t.getCenterFooterGroups=q(()=>[t.getCenterHeaderGroups()],e=>[...e].reverse(),W(t.options,$e,"getCenterFooterGroups")),t.getRightFooterGroups=q(()=>[t.getRightHeaderGroups()],e=>[...e].reverse(),W(t.options,$e,"getRightFooterGroups")),t.getFlatHeaders=q(()=>[t.getHeaderGroups()],e=>e.map(r=>r.headers).flat(),W(t.options,$e,"getFlatHeaders")),t.getLeftFlatHeaders=q(()=>[t.getLeftHeaderGroups()],e=>e.map(r=>r.headers).flat(),W(t.options,$e,"getLeftFlatHeaders")),t.getCenterFlatHeaders=q(()=>[t.getCenterHeaderGroups()],e=>e.map(r=>r.headers).flat(),W(t.options,$e,"getCenterFlatHeaders")),t.getRightFlatHeaders=q(()=>[t.getRightHeaderGroups()],e=>e.map(r=>r.headers).flat(),W(t.options,$e,"getRightFlatHeaders")),t.getCenterLeafHeaders=q(()=>[t.getCenterFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),W(t.options,$e,"getCenterLeafHeaders")),t.getLeftLeafHeaders=q(()=>[t.getLeftFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),W(t.options,$e,"getLeftLeafHeaders")),t.getRightLeafHeaders=q(()=>[t.getRightFlatHeaders()],e=>e.filter(r=>{var n;return!((n=r.subHeaders)!=null&&n.length)}),W(t.options,$e,"getRightLeafHeaders")),t.getLeafHeaders=q(()=>[t.getLeftHeaderGroups(),t.getCenterHeaderGroups(),t.getRightHeaderGroups()],(e,r,n)=>{var o,s,i,a,c,l;return[...(o=(s=e[0])==null?void 0:s.headers)!=null?o:[],...(i=(a=r[0])==null?void 0:a.headers)!=null?i:[],...(c=(l=n[0])==null?void 0:l.headers)!=null?c:[]].map(u=>u.getLeafHeaders()).flat()},W(t.options,$e,"getLeafHeaders"))}};function jr(t,e,r,n){var o,s;let i=0;const a=function(m,f){f===void 0&&(f=1),i=Math.max(i,f),m.filter(p=>p.getIsVisible()).forEach(p=>{var h;(h=p.columns)!=null&&h.length&&a(p.columns,f+1)},0)};a(t);let c=[];const l=(m,f)=>{const p={depth:f,id:[n,`${f}`].filter(Boolean).join("_"),headers:[]},h=[];m.forEach(y=>{const x=[...h].reverse()[0],v=y.column.depth===p.depth;let w,S=!1;if(v&&y.column.parent?w=y.column.parent:(w=y.column,S=!0),x&&x?.column===w)x.subHeaders.push(y);else{const C=ws(r,w,{id:[n,f,w.id,y?.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${h.filter(E=>E.column===w).length}`:void 0,depth:f,index:h.length});C.subHeaders.push(y),h.push(C)}p.headers.push(y),y.headerGroup=p}),c.push(p),f>0&&l(h,f-1)},u=e.map((m,f)=>ws(r,m,{depth:i,index:f}));l(u,i-1),c.reverse();const g=m=>m.filter(p=>p.column.getIsVisible()).map(p=>{let h=0,y=0,x=[0];p.subHeaders&&p.subHeaders.length?(x=[],g(p.subHeaders).forEach(w=>{let{colSpan:S,rowSpan:C}=w;h+=S,x.push(C)})):h=1;const v=Math.min(...x);return y=y+v,p.colSpan=h,p.rowSpan=y,{colSpan:h,rowSpan:y}});return g((o=(s=c[0])==null?void 0:s.headers)!=null?o:[]),c}const Co=(t,e,r,n,o,s,i)=>{let a={id:e,index:n,original:r,depth:o,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(a._valuesCache.hasOwnProperty(c))return a._valuesCache[c];const l=t.getColumn(c);if(l!=null&&l.accessorFn)return a._valuesCache[c]=l.accessorFn(a.original,n),a._valuesCache[c]},getUniqueValues:c=>{if(a._uniqueValuesCache.hasOwnProperty(c))return a._uniqueValuesCache[c];const l=t.getColumn(c);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(a._uniqueValuesCache[c]=l.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[c]):(a._uniqueValuesCache[c]=[a.getValue(c)],a._uniqueValuesCache[c])},renderValue:c=>{var l;return(l=a.getValue(c))!=null?l:t.options.renderFallbackValue},subRows:[],getLeafRows:()=>Mu(a.subRows,c=>c.subRows),getParentRow:()=>a.parentId?t.getRow(a.parentId,!0):void 0,getParentRows:()=>{let c=[],l=a;for(;;){const u=l.getParentRow();if(!u)break;c.push(u),l=u}return c.reverse()},getAllCells:q(()=>[t.getAllLeafColumns()],c=>c.map(l=>Ou(t,a,l,l.id)),W(t.options,"debugRows","getAllCells")),_getAllCellsByColumnId:q(()=>[a.getAllCells()],c=>c.reduce((l,u)=>(l[u.column.id]=u,l),{}),W(t.options,"debugRows","getAllCellsByColumnId"))};for(let c=0;c<t._features.length;c++){const l=t._features[c];l==null||l.createRow==null||l.createRow(a,t)}return a},Du={createColumn:(t,e)=>{t._getFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,t.id),t.getFacetedRowModel=()=>t._getFacetedRowModel?t._getFacetedRowModel():e.getPreFilteredRowModel(),t._getFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,t.id),t.getFacetedUniqueValues=()=>t._getFacetedUniqueValues?t._getFacetedUniqueValues():new Map,t._getFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,t.id),t.getFacetedMinMaxValues=()=>{if(t._getFacetedMinMaxValues)return t._getFacetedMinMaxValues()}}},Oi=(t,e,r)=>{var n,o;const s=r==null||(n=r.toString())==null?void 0:n.toLowerCase();return!!(!((o=t.getValue(e))==null||(o=o.toString())==null||(o=o.toLowerCase())==null)&&o.includes(s))};Oi.autoRemove=t=>Ke(t);const Fi=(t,e,r)=>{var n;return!!(!((n=t.getValue(e))==null||(n=n.toString())==null)&&n.includes(r))};Fi.autoRemove=t=>Ke(t);const Pi=(t,e,r)=>{var n;return((n=t.getValue(e))==null||(n=n.toString())==null?void 0:n.toLowerCase())===r?.toLowerCase()};Pi.autoRemove=t=>Ke(t);const Di=(t,e,r)=>{var n;return(n=t.getValue(e))==null?void 0:n.includes(r)};Di.autoRemove=t=>Ke(t);const Li=(t,e,r)=>!r.some(n=>{var o;return!((o=t.getValue(e))!=null&&o.includes(n))});Li.autoRemove=t=>Ke(t)||!(t!=null&&t.length);const Gi=(t,e,r)=>r.some(n=>{var o;return(o=t.getValue(e))==null?void 0:o.includes(n)});Gi.autoRemove=t=>Ke(t)||!(t!=null&&t.length);const Vi=(t,e,r)=>t.getValue(e)===r;Vi.autoRemove=t=>Ke(t);const zi=(t,e,r)=>t.getValue(e)==r;zi.autoRemove=t=>Ke(t);const So=(t,e,r)=>{let[n,o]=r;const s=t.getValue(e);return s>=n&&s<=o};So.resolveFilterValue=t=>{let[e,r]=t,n=typeof e!="number"?parseFloat(e):e,o=typeof r!="number"?parseFloat(r):r,s=e===null||Number.isNaN(n)?-1/0:n,i=r===null||Number.isNaN(o)?1/0:o;if(s>i){const a=s;s=i,i=a}return[s,i]};So.autoRemove=t=>Ke(t)||Ke(t[0])&&Ke(t[1]);const lt={includesString:Oi,includesStringSensitive:Fi,equalsString:Pi,arrIncludes:Di,arrIncludesAll:Li,arrIncludesSome:Gi,equals:Vi,weakEquals:zi,inNumberRange:So};function Ke(t){return t==null||t===""}const Lu={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:t=>({columnFilters:[],...t}),getDefaultOptions:t=>({onColumnFiltersChange:qe("columnFilters",t),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(t,e)=>{t.getAutoFilterFn=()=>{const r=e.getCoreRowModel().flatRows[0],n=r?.getValue(t.id);return typeof n=="string"?lt.includesString:typeof n=="number"?lt.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?lt.equals:Array.isArray(n)?lt.arrIncludes:lt.weakEquals},t.getFilterFn=()=>{var r,n;return un(t.columnDef.filterFn)?t.columnDef.filterFn:t.columnDef.filterFn==="auto"?t.getAutoFilterFn():(r=(n=e.options.filterFns)==null?void 0:n[t.columnDef.filterFn])!=null?r:lt[t.columnDef.filterFn]},t.getCanFilter=()=>{var r,n,o;return((r=t.columnDef.enableColumnFilter)!=null?r:!0)&&((n=e.options.enableColumnFilters)!=null?n:!0)&&((o=e.options.enableFilters)!=null?o:!0)&&!!t.accessorFn},t.getIsFiltered=()=>t.getFilterIndex()>-1,t.getFilterValue=()=>{var r;return(r=e.getState().columnFilters)==null||(r=r.find(n=>n.id===t.id))==null?void 0:r.value},t.getFilterIndex=()=>{var r,n;return(r=(n=e.getState().columnFilters)==null?void 0:n.findIndex(o=>o.id===t.id))!=null?r:-1},t.setFilterValue=r=>{e.setColumnFilters(n=>{const o=t.getFilterFn(),s=n?.find(u=>u.id===t.id),i=yt(r,s?s.value:void 0);if(vs(o,i,t)){var a;return(a=n?.filter(u=>u.id!==t.id))!=null?a:[]}const c={id:t.id,value:i};if(s){var l;return(l=n?.map(u=>u.id===t.id?c:u))!=null?l:[]}return n!=null&&n.length?[...n,c]:[c]})}},createRow:(t,e)=>{t.columnFilters={},t.columnFiltersMeta={}},createTable:t=>{t.setColumnFilters=e=>{const r=t.getAllLeafColumns(),n=o=>{var s;return(s=yt(e,o))==null?void 0:s.filter(i=>{const a=r.find(c=>c.id===i.id);if(a){const c=a.getFilterFn();if(vs(c,i.value,a))return!1}return!0})};t.options.onColumnFiltersChange==null||t.options.onColumnFiltersChange(n)},t.resetColumnFilters=e=>{var r,n;t.setColumnFilters(e?[]:(r=(n=t.initialState)==null?void 0:n.columnFilters)!=null?r:[])},t.getPreFilteredRowModel=()=>t.getCoreRowModel(),t.getFilteredRowModel=()=>(!t._getFilteredRowModel&&t.options.getFilteredRowModel&&(t._getFilteredRowModel=t.options.getFilteredRowModel(t)),t.options.manualFiltering||!t._getFilteredRowModel?t.getPreFilteredRowModel():t._getFilteredRowModel())}};function vs(t,e,r){return(t&&t.autoRemove?t.autoRemove(e,r):!1)||typeof e>"u"||typeof e=="string"&&!e}const Gu=(t,e,r)=>r.reduce((n,o)=>{const s=o.getValue(t);return n+(typeof s=="number"?s:0)},0),Vu=(t,e,r)=>{let n;return r.forEach(o=>{const s=o.getValue(t);s!=null&&(n>s||n===void 0&&s>=s)&&(n=s)}),n},zu=(t,e,r)=>{let n;return r.forEach(o=>{const s=o.getValue(t);s!=null&&(n<s||n===void 0&&s>=s)&&(n=s)}),n},Uu=(t,e,r)=>{let n,o;return r.forEach(s=>{const i=s.getValue(t);i!=null&&(n===void 0?i>=i&&(n=o=i):(n>i&&(n=i),o<i&&(o=i)))}),[n,o]},Bu=(t,e)=>{let r=0,n=0;if(e.forEach(o=>{let s=o.getValue(t);s!=null&&(s=+s)>=s&&(++r,n+=s)}),r)return n/r},Hu=(t,e)=>{if(!e.length)return;const r=e.map(s=>s.getValue(t));if(!Iu(r))return;if(r.length===1)return r[0];const n=Math.floor(r.length/2),o=r.sort((s,i)=>s-i);return r.length%2!==0?o[n]:(o[n-1]+o[n])/2},qu=(t,e)=>Array.from(new Set(e.map(r=>r.getValue(t))).values()),Wu=(t,e)=>new Set(e.map(r=>r.getValue(t))).size,Yu=(t,e)=>e.length,Tn={sum:Gu,min:Vu,max:zu,extent:Uu,mean:Bu,median:Hu,unique:qu,uniqueCount:Wu,count:Yu},Ku={getDefaultColumnDef:()=>({aggregatedCell:t=>{var e,r;return(e=(r=t.getValue())==null||r.toString==null?void 0:r.toString())!=null?e:null},aggregationFn:"auto"}),getInitialState:t=>({grouping:[],...t}),getDefaultOptions:t=>({onGroupingChange:qe("grouping",t),groupedColumnMode:"reorder"}),createColumn:(t,e)=>{t.toggleGrouping=()=>{e.setGrouping(r=>r!=null&&r.includes(t.id)?r.filter(n=>n!==t.id):[...r??[],t.id])},t.getCanGroup=()=>{var r,n;return((r=t.columnDef.enableGrouping)!=null?r:!0)&&((n=e.options.enableGrouping)!=null?n:!0)&&(!!t.accessorFn||!!t.columnDef.getGroupingValue)},t.getIsGrouped=()=>{var r;return(r=e.getState().grouping)==null?void 0:r.includes(t.id)},t.getGroupedIndex=()=>{var r;return(r=e.getState().grouping)==null?void 0:r.indexOf(t.id)},t.getToggleGroupingHandler=()=>{const r=t.getCanGroup();return()=>{r&&t.toggleGrouping()}},t.getAutoAggregationFn=()=>{const r=e.getCoreRowModel().flatRows[0],n=r?.getValue(t.id);if(typeof n=="number")return Tn.sum;if(Object.prototype.toString.call(n)==="[object Date]")return Tn.extent},t.getAggregationFn=()=>{var r,n;if(!t)throw new Error;return un(t.columnDef.aggregationFn)?t.columnDef.aggregationFn:t.columnDef.aggregationFn==="auto"?t.getAutoAggregationFn():(r=(n=e.options.aggregationFns)==null?void 0:n[t.columnDef.aggregationFn])!=null?r:Tn[t.columnDef.aggregationFn]}},createTable:t=>{t.setGrouping=e=>t.options.onGroupingChange==null?void 0:t.options.onGroupingChange(e),t.resetGrouping=e=>{var r,n;t.setGrouping(e?[]:(r=(n=t.initialState)==null?void 0:n.grouping)!=null?r:[])},t.getPreGroupedRowModel=()=>t.getFilteredRowModel(),t.getGroupedRowModel=()=>(!t._getGroupedRowModel&&t.options.getGroupedRowModel&&(t._getGroupedRowModel=t.options.getGroupedRowModel(t)),t.options.manualGrouping||!t._getGroupedRowModel?t.getPreGroupedRowModel():t._getGroupedRowModel())},createRow:(t,e)=>{t.getIsGrouped=()=>!!t.groupingColumnId,t.getGroupingValue=r=>{if(t._groupingValuesCache.hasOwnProperty(r))return t._groupingValuesCache[r];const n=e.getColumn(r);return n!=null&&n.columnDef.getGroupingValue?(t._groupingValuesCache[r]=n.columnDef.getGroupingValue(t.original),t._groupingValuesCache[r]):t.getValue(r)},t._groupingValuesCache={}},createCell:(t,e,r,n)=>{t.getIsGrouped=()=>e.getIsGrouped()&&e.id===r.groupingColumnId,t.getIsPlaceholder=()=>!t.getIsGrouped()&&e.getIsGrouped(),t.getIsAggregated=()=>{var o;return!t.getIsGrouped()&&!t.getIsPlaceholder()&&!!((o=r.subRows)!=null&&o.length)}}};function Xu(t,e,r){if(!(e!=null&&e.length)||!r)return t;const n=t.filter(s=>!e.includes(s.id));return r==="remove"?n:[...e.map(s=>t.find(i=>i.id===s)).filter(Boolean),...n]}const Ju={getInitialState:t=>({columnOrder:[],...t}),getDefaultOptions:t=>({onColumnOrderChange:qe("columnOrder",t)}),createColumn:(t,e)=>{t.getIndex=q(r=>[ur(e,r)],r=>r.findIndex(n=>n.id===t.id),W(e.options,"debugColumns","getIndex")),t.getIsFirstColumn=r=>{var n;return((n=ur(e,r)[0])==null?void 0:n.id)===t.id},t.getIsLastColumn=r=>{var n;const o=ur(e,r);return((n=o[o.length-1])==null?void 0:n.id)===t.id}},createTable:t=>{t.setColumnOrder=e=>t.options.onColumnOrderChange==null?void 0:t.options.onColumnOrderChange(e),t.resetColumnOrder=e=>{var r;t.setColumnOrder(e?[]:(r=t.initialState.columnOrder)!=null?r:[])},t._getOrderColumnsFn=q(()=>[t.getState().columnOrder,t.getState().grouping,t.options.groupedColumnMode],(e,r,n)=>o=>{let s=[];if(!(e!=null&&e.length))s=o;else{const i=[...e],a=[...o];for(;a.length&&i.length;){const c=i.shift(),l=a.findIndex(u=>u.id===c);l>-1&&s.push(a.splice(l,1)[0])}s=[...s,...a]}return Xu(s,r,n)},W(t.options,"debugTable","_getOrderColumnsFn"))}},$n=()=>({left:[],right:[]}),Zu={getInitialState:t=>({columnPinning:$n(),...t}),getDefaultOptions:t=>({onColumnPinningChange:qe("columnPinning",t)}),createColumn:(t,e)=>{t.pin=r=>{const n=t.getLeafColumns().map(o=>o.id).filter(Boolean);e.setColumnPinning(o=>{var s,i;if(r==="right"){var a,c;return{left:((a=o?.left)!=null?a:[]).filter(g=>!(n!=null&&n.includes(g))),right:[...((c=o?.right)!=null?c:[]).filter(g=>!(n!=null&&n.includes(g))),...n]}}if(r==="left"){var l,u;return{left:[...((l=o?.left)!=null?l:[]).filter(g=>!(n!=null&&n.includes(g))),...n],right:((u=o?.right)!=null?u:[]).filter(g=>!(n!=null&&n.includes(g)))}}return{left:((s=o?.left)!=null?s:[]).filter(g=>!(n!=null&&n.includes(g))),right:((i=o?.right)!=null?i:[]).filter(g=>!(n!=null&&n.includes(g)))}})},t.getCanPin=()=>t.getLeafColumns().some(n=>{var o,s,i;return((o=n.columnDef.enablePinning)!=null?o:!0)&&((s=(i=e.options.enableColumnPinning)!=null?i:e.options.enablePinning)!=null?s:!0)}),t.getIsPinned=()=>{const r=t.getLeafColumns().map(a=>a.id),{left:n,right:o}=e.getState().columnPinning,s=r.some(a=>n?.includes(a)),i=r.some(a=>o?.includes(a));return s?"left":i?"right":!1},t.getPinnedIndex=()=>{var r,n;const o=t.getIsPinned();return o?(r=(n=e.getState().columnPinning)==null||(n=n[o])==null?void 0:n.indexOf(t.id))!=null?r:-1:0}},createRow:(t,e)=>{t.getCenterVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left,e.getState().columnPinning.right],(r,n,o)=>{const s=[...n??[],...o??[]];return r.filter(i=>!s.includes(i.column.id))},W(e.options,"debugRows","getCenterVisibleCells")),t.getLeftVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.left],(r,n)=>(n??[]).map(s=>r.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"left"})),W(e.options,"debugRows","getLeftVisibleCells")),t.getRightVisibleCells=q(()=>[t._getAllVisibleCells(),e.getState().columnPinning.right],(r,n)=>(n??[]).map(s=>r.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"right"})),W(e.options,"debugRows","getRightVisibleCells"))},createTable:t=>{t.setColumnPinning=e=>t.options.onColumnPinningChange==null?void 0:t.options.onColumnPinningChange(e),t.resetColumnPinning=e=>{var r,n;return t.setColumnPinning(e?$n():(r=(n=t.initialState)==null?void 0:n.columnPinning)!=null?r:$n())},t.getIsSomeColumnsPinned=e=>{var r;const n=t.getState().columnPinning;if(!e){var o,s;return!!((o=n.left)!=null&&o.length||(s=n.right)!=null&&s.length)}return!!((r=n[e])!=null&&r.length)},t.getLeftLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left],(e,r)=>(r??[]).map(n=>e.find(o=>o.id===n)).filter(Boolean),W(t.options,"debugColumns","getLeftLeafColumns")),t.getRightLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.right],(e,r)=>(r??[]).map(n=>e.find(o=>o.id===n)).filter(Boolean),W(t.options,"debugColumns","getRightLeafColumns")),t.getCenterLeafColumns=q(()=>[t.getAllLeafColumns(),t.getState().columnPinning.left,t.getState().columnPinning.right],(e,r,n)=>{const o=[...r??[],...n??[]];return e.filter(s=>!o.includes(s.id))},W(t.options,"debugColumns","getCenterLeafColumns"))}};function Qu(t){return t||(typeof document<"u"?document:null)}const Ir={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},kn=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),ef={getDefaultColumnDef:()=>Ir,getInitialState:t=>({columnSizing:{},columnSizingInfo:kn(),...t}),getDefaultOptions:t=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:qe("columnSizing",t),onColumnSizingInfoChange:qe("columnSizingInfo",t)}),createColumn:(t,e)=>{t.getSize=()=>{var r,n,o;const s=e.getState().columnSizing[t.id];return Math.min(Math.max((r=t.columnDef.minSize)!=null?r:Ir.minSize,(n=s??t.columnDef.size)!=null?n:Ir.size),(o=t.columnDef.maxSize)!=null?o:Ir.maxSize)},t.getStart=q(r=>[r,ur(e,r),e.getState().columnSizing],(r,n)=>n.slice(0,t.getIndex(r)).reduce((o,s)=>o+s.getSize(),0),W(e.options,"debugColumns","getStart")),t.getAfter=q(r=>[r,ur(e,r),e.getState().columnSizing],(r,n)=>n.slice(t.getIndex(r)+1).reduce((o,s)=>o+s.getSize(),0),W(e.options,"debugColumns","getAfter")),t.resetSize=()=>{e.setColumnSizing(r=>{let{[t.id]:n,...o}=r;return o})},t.getCanResize=()=>{var r,n;return((r=t.columnDef.enableResizing)!=null?r:!0)&&((n=e.options.enableColumnResizing)!=null?n:!0)},t.getIsResizing=()=>e.getState().columnSizingInfo.isResizingColumn===t.id},createHeader:(t,e)=>{t.getSize=()=>{let r=0;const n=o=>{if(o.subHeaders.length)o.subHeaders.forEach(n);else{var s;r+=(s=o.column.getSize())!=null?s:0}};return n(t),r},t.getStart=()=>{if(t.index>0){const r=t.headerGroup.headers[t.index-1];return r.getStart()+r.getSize()}return 0},t.getResizeHandler=r=>{const n=e.getColumn(t.column.id),o=n?.getCanResize();return s=>{if(!n||!o||(s.persist==null||s.persist(),jn(s)&&s.touches&&s.touches.length>1))return;const i=t.getSize(),a=t?t.getLeafHeaders().map(x=>[x.column.id,x.column.getSize()]):[[n.id,n.getSize()]],c=jn(s)?Math.round(s.touches[0].clientX):s.clientX,l={},u=(x,v)=>{typeof v=="number"&&(e.setColumnSizingInfo(w=>{var S,C;const E=e.options.columnResizeDirection==="rtl"?-1:1,_=(v-((S=w?.startOffset)!=null?S:0))*E,A=Math.max(_/((C=w?.startSize)!=null?C:0),-.999999);return w.columnSizingStart.forEach(T=>{let[j,U]=T;l[j]=Math.round(Math.max(U+U*A,0)*100)/100}),{...w,deltaOffset:_,deltaPercentage:A}}),(e.options.columnResizeMode==="onChange"||x==="end")&&e.setColumnSizing(w=>({...w,...l})))},g=x=>u("move",x),m=x=>{u("end",x),e.setColumnSizingInfo(v=>({...v,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=Qu(r),p={moveHandler:x=>g(x.clientX),upHandler:x=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),m(x.clientX)}},h={moveHandler:x=>(x.cancelable&&(x.preventDefault(),x.stopPropagation()),g(x.touches[0].clientX),!1),upHandler:x=>{var v;f?.removeEventListener("touchmove",h.moveHandler),f?.removeEventListener("touchend",h.upHandler),x.cancelable&&(x.preventDefault(),x.stopPropagation()),m((v=x.touches[0])==null?void 0:v.clientX)}},y=tf()?{passive:!1}:!1;jn(s)?(f?.addEventListener("touchmove",h.moveHandler,y),f?.addEventListener("touchend",h.upHandler,y)):(f?.addEventListener("mousemove",p.moveHandler,y),f?.addEventListener("mouseup",p.upHandler,y)),e.setColumnSizingInfo(x=>({...x,startOffset:c,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:n.id}))}}},createTable:t=>{t.setColumnSizing=e=>t.options.onColumnSizingChange==null?void 0:t.options.onColumnSizingChange(e),t.setColumnSizingInfo=e=>t.options.onColumnSizingInfoChange==null?void 0:t.options.onColumnSizingInfoChange(e),t.resetColumnSizing=e=>{var r;t.setColumnSizing(e?{}:(r=t.initialState.columnSizing)!=null?r:{})},t.resetHeaderSizeInfo=e=>{var r;t.setColumnSizingInfo(e?kn():(r=t.initialState.columnSizingInfo)!=null?r:kn())},t.getTotalSize=()=>{var e,r;return(e=(r=t.getHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getLeftTotalSize=()=>{var e,r;return(e=(r=t.getLeftHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getCenterTotalSize=()=>{var e,r;return(e=(r=t.getCenterHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0},t.getRightTotalSize=()=>{var e,r;return(e=(r=t.getRightHeaderGroups()[0])==null?void 0:r.headers.reduce((n,o)=>n+o.getSize(),0))!=null?e:0}}};let Mr=null;function tf(){if(typeof Mr=="boolean")return Mr;let t=!1;try{const e={get passive(){return t=!0,!1}},r=()=>{};window.addEventListener("test",r,e),window.removeEventListener("test",r)}catch{t=!1}return Mr=t,Mr}function jn(t){return t.type==="touchstart"}const rf={getInitialState:t=>({columnVisibility:{},...t}),getDefaultOptions:t=>({onColumnVisibilityChange:qe("columnVisibility",t)}),createColumn:(t,e)=>{t.toggleVisibility=r=>{t.getCanHide()&&e.setColumnVisibility(n=>({...n,[t.id]:r??!t.getIsVisible()}))},t.getIsVisible=()=>{var r,n;const o=t.columns;return(r=o.length?o.some(s=>s.getIsVisible()):(n=e.getState().columnVisibility)==null?void 0:n[t.id])!=null?r:!0},t.getCanHide=()=>{var r,n;return((r=t.columnDef.enableHiding)!=null?r:!0)&&((n=e.options.enableHiding)!=null?n:!0)},t.getToggleVisibilityHandler=()=>r=>{t.toggleVisibility==null||t.toggleVisibility(r.target.checked)}},createRow:(t,e)=>{t._getAllVisibleCells=q(()=>[t.getAllCells(),e.getState().columnVisibility],r=>r.filter(n=>n.column.getIsVisible()),W(e.options,"debugRows","_getAllVisibleCells")),t.getVisibleCells=q(()=>[t.getLeftVisibleCells(),t.getCenterVisibleCells(),t.getRightVisibleCells()],(r,n,o)=>[...r,...n,...o],W(e.options,"debugRows","getVisibleCells"))},createTable:t=>{const e=(r,n)=>q(()=>[n(),n().filter(o=>o.getIsVisible()).map(o=>o.id).join("_")],o=>o.filter(s=>s.getIsVisible==null?void 0:s.getIsVisible()),W(t.options,"debugColumns",r));t.getVisibleFlatColumns=e("getVisibleFlatColumns",()=>t.getAllFlatColumns()),t.getVisibleLeafColumns=e("getVisibleLeafColumns",()=>t.getAllLeafColumns()),t.getLeftVisibleLeafColumns=e("getLeftVisibleLeafColumns",()=>t.getLeftLeafColumns()),t.getRightVisibleLeafColumns=e("getRightVisibleLeafColumns",()=>t.getRightLeafColumns()),t.getCenterVisibleLeafColumns=e("getCenterVisibleLeafColumns",()=>t.getCenterLeafColumns()),t.setColumnVisibility=r=>t.options.onColumnVisibilityChange==null?void 0:t.options.onColumnVisibilityChange(r),t.resetColumnVisibility=r=>{var n;t.setColumnVisibility(r?{}:(n=t.initialState.columnVisibility)!=null?n:{})},t.toggleAllColumnsVisible=r=>{var n;r=(n=r)!=null?n:!t.getIsAllColumnsVisible(),t.setColumnVisibility(t.getAllLeafColumns().reduce((o,s)=>({...o,[s.id]:r||!(s.getCanHide!=null&&s.getCanHide())}),{}))},t.getIsAllColumnsVisible=()=>!t.getAllLeafColumns().some(r=>!(r.getIsVisible!=null&&r.getIsVisible())),t.getIsSomeColumnsVisible=()=>t.getAllLeafColumns().some(r=>r.getIsVisible==null?void 0:r.getIsVisible()),t.getToggleAllColumnsVisibilityHandler=()=>r=>{var n;t.toggleAllColumnsVisible((n=r.target)==null?void 0:n.checked)}}};function ur(t,e){return e?e==="center"?t.getCenterVisibleLeafColumns():e==="left"?t.getLeftVisibleLeafColumns():t.getRightVisibleLeafColumns():t.getVisibleLeafColumns()}const nf={createTable:t=>{t._getGlobalFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,"__global__"),t.getGlobalFacetedRowModel=()=>t.options.manualFiltering||!t._getGlobalFacetedRowModel?t.getPreFilteredRowModel():t._getGlobalFacetedRowModel(),t._getGlobalFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,"__global__"),t.getGlobalFacetedUniqueValues=()=>t._getGlobalFacetedUniqueValues?t._getGlobalFacetedUniqueValues():new Map,t._getGlobalFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,"__global__"),t.getGlobalFacetedMinMaxValues=()=>{if(t._getGlobalFacetedMinMaxValues)return t._getGlobalFacetedMinMaxValues()}}},of={getInitialState:t=>({globalFilter:void 0,...t}),getDefaultOptions:t=>({onGlobalFilterChange:qe("globalFilter",t),globalFilterFn:"auto",getColumnCanGlobalFilter:e=>{var r;const n=(r=t.getCoreRowModel().flatRows[0])==null||(r=r._getAllCellsByColumnId()[e.id])==null?void 0:r.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(t,e)=>{t.getCanGlobalFilter=()=>{var r,n,o,s;return((r=t.columnDef.enableGlobalFilter)!=null?r:!0)&&((n=e.options.enableGlobalFilter)!=null?n:!0)&&((o=e.options.enableFilters)!=null?o:!0)&&((s=e.options.getColumnCanGlobalFilter==null?void 0:e.options.getColumnCanGlobalFilter(t))!=null?s:!0)&&!!t.accessorFn}},createTable:t=>{t.getGlobalAutoFilterFn=()=>lt.includesString,t.getGlobalFilterFn=()=>{var e,r;const{globalFilterFn:n}=t.options;return un(n)?n:n==="auto"?t.getGlobalAutoFilterFn():(e=(r=t.options.filterFns)==null?void 0:r[n])!=null?e:lt[n]},t.setGlobalFilter=e=>{t.options.onGlobalFilterChange==null||t.options.onGlobalFilterChange(e)},t.resetGlobalFilter=e=>{t.setGlobalFilter(e?void 0:t.initialState.globalFilter)}}},sf={getInitialState:t=>({expanded:{},...t}),getDefaultOptions:t=>({onExpandedChange:qe("expanded",t),paginateExpandedRows:!0}),createTable:t=>{let e=!1,r=!1;t._autoResetExpanded=()=>{var n,o;if(!e){t._queue(()=>{e=!0});return}if((n=(o=t.options.autoResetAll)!=null?o:t.options.autoResetExpanded)!=null?n:!t.options.manualExpanding){if(r)return;r=!0,t._queue(()=>{t.resetExpanded(),r=!1})}},t.setExpanded=n=>t.options.onExpandedChange==null?void 0:t.options.onExpandedChange(n),t.toggleAllRowsExpanded=n=>{n??!t.getIsAllRowsExpanded()?t.setExpanded(!0):t.setExpanded({})},t.resetExpanded=n=>{var o,s;t.setExpanded(n?{}:(o=(s=t.initialState)==null?void 0:s.expanded)!=null?o:{})},t.getCanSomeRowsExpand=()=>t.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),t.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),t.toggleAllRowsExpanded()},t.getIsSomeRowsExpanded=()=>{const n=t.getState().expanded;return n===!0||Object.values(n).some(Boolean)},t.getIsAllRowsExpanded=()=>{const n=t.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||t.getRowModel().flatRows.some(o=>!o.getIsExpanded()))},t.getExpandedDepth=()=>{let n=0;return(t.getState().expanded===!0?Object.keys(t.getRowModel().rowsById):Object.keys(t.getState().expanded)).forEach(s=>{const i=s.split(".");n=Math.max(n,i.length)}),n},t.getPreExpandedRowModel=()=>t.getSortedRowModel(),t.getExpandedRowModel=()=>(!t._getExpandedRowModel&&t.options.getExpandedRowModel&&(t._getExpandedRowModel=t.options.getExpandedRowModel(t)),t.options.manualExpanding||!t._getExpandedRowModel?t.getPreExpandedRowModel():t._getExpandedRowModel())},createRow:(t,e)=>{t.toggleExpanded=r=>{e.setExpanded(n=>{var o;const s=n===!0?!0:!!(n!=null&&n[t.id]);let i={};if(n===!0?Object.keys(e.getRowModel().rowsById).forEach(a=>{i[a]=!0}):i=n,r=(o=r)!=null?o:!s,!s&&r)return{...i,[t.id]:!0};if(s&&!r){const{[t.id]:a,...c}=i;return c}return n})},t.getIsExpanded=()=>{var r;const n=e.getState().expanded;return!!((r=e.options.getIsRowExpanded==null?void 0:e.options.getIsRowExpanded(t))!=null?r:n===!0||n?.[t.id])},t.getCanExpand=()=>{var r,n,o;return(r=e.options.getRowCanExpand==null?void 0:e.options.getRowCanExpand(t))!=null?r:((n=e.options.enableExpanding)!=null?n:!0)&&!!((o=t.subRows)!=null&&o.length)},t.getIsAllParentsExpanded=()=>{let r=!0,n=t;for(;r&&n.parentId;)n=e.getRow(n.parentId,!0),r=n.getIsExpanded();return r},t.getToggleExpandedHandler=()=>{const r=t.getCanExpand();return()=>{r&&t.toggleExpanded()}}}},Jn=0,Zn=10,In=()=>({pageIndex:Jn,pageSize:Zn}),af={getInitialState:t=>({...t,pagination:{...In(),...t?.pagination}}),getDefaultOptions:t=>({onPaginationChange:qe("pagination",t)}),createTable:t=>{let e=!1,r=!1;t._autoResetPageIndex=()=>{var n,o;if(!e){t._queue(()=>{e=!0});return}if((n=(o=t.options.autoResetAll)!=null?o:t.options.autoResetPageIndex)!=null?n:!t.options.manualPagination){if(r)return;r=!0,t._queue(()=>{t.resetPageIndex(),r=!1})}},t.setPagination=n=>{const o=s=>yt(n,s);return t.options.onPaginationChange==null?void 0:t.options.onPaginationChange(o)},t.resetPagination=n=>{var o;t.setPagination(n?In():(o=t.initialState.pagination)!=null?o:In())},t.setPageIndex=n=>{t.setPagination(o=>{let s=yt(n,o.pageIndex);const i=typeof t.options.pageCount>"u"||t.options.pageCount===-1?Number.MAX_SAFE_INTEGER:t.options.pageCount-1;return s=Math.max(0,Math.min(s,i)),{...o,pageIndex:s}})},t.resetPageIndex=n=>{var o,s;t.setPageIndex(n?Jn:(o=(s=t.initialState)==null||(s=s.pagination)==null?void 0:s.pageIndex)!=null?o:Jn)},t.resetPageSize=n=>{var o,s;t.setPageSize(n?Zn:(o=(s=t.initialState)==null||(s=s.pagination)==null?void 0:s.pageSize)!=null?o:Zn)},t.setPageSize=n=>{t.setPagination(o=>{const s=Math.max(1,yt(n,o.pageSize)),i=o.pageSize*o.pageIndex,a=Math.floor(i/s);return{...o,pageIndex:a,pageSize:s}})},t.setPageCount=n=>t.setPagination(o=>{var s;let i=yt(n,(s=t.options.pageCount)!=null?s:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...o,pageCount:i}}),t.getPageOptions=q(()=>[t.getPageCount()],n=>{let o=[];return n&&n>0&&(o=[...new Array(n)].fill(null).map((s,i)=>i)),o},W(t.options,"debugTable","getPageOptions")),t.getCanPreviousPage=()=>t.getState().pagination.pageIndex>0,t.getCanNextPage=()=>{const{pageIndex:n}=t.getState().pagination,o=t.getPageCount();return o===-1?!0:o===0?!1:n<o-1},t.previousPage=()=>t.setPageIndex(n=>n-1),t.nextPage=()=>t.setPageIndex(n=>n+1),t.firstPage=()=>t.setPageIndex(0),t.lastPage=()=>t.setPageIndex(t.getPageCount()-1),t.getPrePaginationRowModel=()=>t.getExpandedRowModel(),t.getPaginationRowModel=()=>(!t._getPaginationRowModel&&t.options.getPaginationRowModel&&(t._getPaginationRowModel=t.options.getPaginationRowModel(t)),t.options.manualPagination||!t._getPaginationRowModel?t.getPrePaginationRowModel():t._getPaginationRowModel()),t.getPageCount=()=>{var n;return(n=t.options.pageCount)!=null?n:Math.ceil(t.getRowCount()/t.getState().pagination.pageSize)},t.getRowCount=()=>{var n;return(n=t.options.rowCount)!=null?n:t.getPrePaginationRowModel().rows.length}}},Mn=()=>({top:[],bottom:[]}),lf={getInitialState:t=>({rowPinning:Mn(),...t}),getDefaultOptions:t=>({onRowPinningChange:qe("rowPinning",t)}),createRow:(t,e)=>{t.pin=(r,n,o)=>{const s=n?t.getLeafRows().map(c=>{let{id:l}=c;return l}):[],i=o?t.getParentRows().map(c=>{let{id:l}=c;return l}):[],a=new Set([...i,t.id,...s]);e.setRowPinning(c=>{var l,u;if(r==="bottom"){var g,m;return{top:((g=c?.top)!=null?g:[]).filter(h=>!(a!=null&&a.has(h))),bottom:[...((m=c?.bottom)!=null?m:[]).filter(h=>!(a!=null&&a.has(h))),...Array.from(a)]}}if(r==="top"){var f,p;return{top:[...((f=c?.top)!=null?f:[]).filter(h=>!(a!=null&&a.has(h))),...Array.from(a)],bottom:((p=c?.bottom)!=null?p:[]).filter(h=>!(a!=null&&a.has(h)))}}return{top:((l=c?.top)!=null?l:[]).filter(h=>!(a!=null&&a.has(h))),bottom:((u=c?.bottom)!=null?u:[]).filter(h=>!(a!=null&&a.has(h)))}})},t.getCanPin=()=>{var r;const{enableRowPinning:n,enablePinning:o}=e.options;return typeof n=="function"?n(t):(r=n??o)!=null?r:!0},t.getIsPinned=()=>{const r=[t.id],{top:n,bottom:o}=e.getState().rowPinning,s=r.some(a=>n?.includes(a)),i=r.some(a=>o?.includes(a));return s?"top":i?"bottom":!1},t.getPinnedIndex=()=>{var r,n;const o=t.getIsPinned();if(!o)return-1;const s=(r=o==="top"?e.getTopRows():e.getBottomRows())==null?void 0:r.map(i=>{let{id:a}=i;return a});return(n=s?.indexOf(t.id))!=null?n:-1}},createTable:t=>{t.setRowPinning=e=>t.options.onRowPinningChange==null?void 0:t.options.onRowPinningChange(e),t.resetRowPinning=e=>{var r,n;return t.setRowPinning(e?Mn():(r=(n=t.initialState)==null?void 0:n.rowPinning)!=null?r:Mn())},t.getIsSomeRowsPinned=e=>{var r;const n=t.getState().rowPinning;if(!e){var o,s;return!!((o=n.top)!=null&&o.length||(s=n.bottom)!=null&&s.length)}return!!((r=n[e])!=null&&r.length)},t._getPinnedRows=(e,r,n)=>{var o;return((o=t.options.keepPinnedRows)==null||o?(r??[]).map(i=>{const a=t.getRow(i,!0);return a.getIsAllParentsExpanded()?a:null}):(r??[]).map(i=>e.find(a=>a.id===i))).filter(Boolean).map(i=>({...i,position:n}))},t.getTopRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top],(e,r)=>t._getPinnedRows(e,r,"top"),W(t.options,"debugRows","getTopRows")),t.getBottomRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.bottom],(e,r)=>t._getPinnedRows(e,r,"bottom"),W(t.options,"debugRows","getBottomRows")),t.getCenterRows=q(()=>[t.getRowModel().rows,t.getState().rowPinning.top,t.getState().rowPinning.bottom],(e,r,n)=>{const o=new Set([...r??[],...n??[]]);return e.filter(s=>!o.has(s.id))},W(t.options,"debugRows","getCenterRows"))}},cf={getInitialState:t=>({rowSelection:{},...t}),getDefaultOptions:t=>({onRowSelectionChange:qe("rowSelection",t),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:t=>{t.setRowSelection=e=>t.options.onRowSelectionChange==null?void 0:t.options.onRowSelectionChange(e),t.resetRowSelection=e=>{var r;return t.setRowSelection(e?{}:(r=t.initialState.rowSelection)!=null?r:{})},t.toggleAllRowsSelected=e=>{t.setRowSelection(r=>{e=typeof e<"u"?e:!t.getIsAllRowsSelected();const n={...r},o=t.getPreGroupedRowModel().flatRows;return e?o.forEach(s=>{s.getCanSelect()&&(n[s.id]=!0)}):o.forEach(s=>{delete n[s.id]}),n})},t.toggleAllPageRowsSelected=e=>t.setRowSelection(r=>{const n=typeof e<"u"?e:!t.getIsAllPageRowsSelected(),o={...r};return t.getRowModel().rows.forEach(s=>{Qn(o,s.id,n,!0,t)}),o}),t.getPreSelectedRowModel=()=>t.getCoreRowModel(),t.getSelectedRowModel=q(()=>[t.getState().rowSelection,t.getCoreRowModel()],(e,r)=>Object.keys(e).length?On(t,r):{rows:[],flatRows:[],rowsById:{}},W(t.options,"debugTable","getSelectedRowModel")),t.getFilteredSelectedRowModel=q(()=>[t.getState().rowSelection,t.getFilteredRowModel()],(e,r)=>Object.keys(e).length?On(t,r):{rows:[],flatRows:[],rowsById:{}},W(t.options,"debugTable","getFilteredSelectedRowModel")),t.getGroupedSelectedRowModel=q(()=>[t.getState().rowSelection,t.getSortedRowModel()],(e,r)=>Object.keys(e).length?On(t,r):{rows:[],flatRows:[],rowsById:{}},W(t.options,"debugTable","getGroupedSelectedRowModel")),t.getIsAllRowsSelected=()=>{const e=t.getFilteredRowModel().flatRows,{rowSelection:r}=t.getState();let n=!!(e.length&&Object.keys(r).length);return n&&e.some(o=>o.getCanSelect()&&!r[o.id])&&(n=!1),n},t.getIsAllPageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows.filter(o=>o.getCanSelect()),{rowSelection:r}=t.getState();let n=!!e.length;return n&&e.some(o=>!r[o.id])&&(n=!1),n},t.getIsSomeRowsSelected=()=>{var e;const r=Object.keys((e=t.getState().rowSelection)!=null?e:{}).length;return r>0&&r<t.getFilteredRowModel().flatRows.length},t.getIsSomePageRowsSelected=()=>{const e=t.getPaginationRowModel().flatRows;return t.getIsAllPageRowsSelected()?!1:e.filter(r=>r.getCanSelect()).some(r=>r.getIsSelected()||r.getIsSomeSelected())},t.getToggleAllRowsSelectedHandler=()=>e=>{t.toggleAllRowsSelected(e.target.checked)},t.getToggleAllPageRowsSelectedHandler=()=>e=>{t.toggleAllPageRowsSelected(e.target.checked)}},createRow:(t,e)=>{t.toggleSelected=(r,n)=>{const o=t.getIsSelected();e.setRowSelection(s=>{var i;if(r=typeof r<"u"?r:!o,t.getCanSelect()&&o===r)return s;const a={...s};return Qn(a,t.id,r,(i=n?.selectChildren)!=null?i:!0,e),a})},t.getIsSelected=()=>{const{rowSelection:r}=e.getState();return _o(t,r)},t.getIsSomeSelected=()=>{const{rowSelection:r}=e.getState();return eo(t,r)==="some"},t.getIsAllSubRowsSelected=()=>{const{rowSelection:r}=e.getState();return eo(t,r)==="all"},t.getCanSelect=()=>{var r;return typeof e.options.enableRowSelection=="function"?e.options.enableRowSelection(t):(r=e.options.enableRowSelection)!=null?r:!0},t.getCanSelectSubRows=()=>{var r;return typeof e.options.enableSubRowSelection=="function"?e.options.enableSubRowSelection(t):(r=e.options.enableSubRowSelection)!=null?r:!0},t.getCanMultiSelect=()=>{var r;return typeof e.options.enableMultiRowSelection=="function"?e.options.enableMultiRowSelection(t):(r=e.options.enableMultiRowSelection)!=null?r:!0},t.getToggleSelectedHandler=()=>{const r=t.getCanSelect();return n=>{var o;r&&t.toggleSelected((o=n.target)==null?void 0:o.checked)}}}},Qn=(t,e,r,n,o)=>{var s;const i=o.getRow(e,!0);r?(i.getCanMultiSelect()||Object.keys(t).forEach(a=>delete t[a]),i.getCanSelect()&&(t[e]=!0)):delete t[e],n&&(s=i.subRows)!=null&&s.length&&i.getCanSelectSubRows()&&i.subRows.forEach(a=>Qn(t,a.id,r,n,o))};function On(t,e){const r=t.getState().rowSelection,n=[],o={},s=function(i,a){return i.map(c=>{var l;const u=_o(c,r);if(u&&(n.push(c),o[c.id]=c),(l=c.subRows)!=null&&l.length&&(c={...c,subRows:s(c.subRows)}),u)return c}).filter(Boolean)};return{rows:s(e.rows),flatRows:n,rowsById:o}}function _o(t,e){var r;return(r=e[t.id])!=null?r:!1}function eo(t,e,r){var n;if(!((n=t.subRows)!=null&&n.length))return!1;let o=!0,s=!1;return t.subRows.forEach(i=>{if(!(s&&!o)&&(i.getCanSelect()&&(_o(i,e)?s=!0:o=!1),i.subRows&&i.subRows.length)){const a=eo(i,e);a==="all"?s=!0:(a==="some"&&(s=!0),o=!1)}}),o?"all":s?"some":!1}const to=/([0-9]+)/gm,df=(t,e,r)=>Ui(xt(t.getValue(r)).toLowerCase(),xt(e.getValue(r)).toLowerCase()),uf=(t,e,r)=>Ui(xt(t.getValue(r)),xt(e.getValue(r))),ff=(t,e,r)=>Ro(xt(t.getValue(r)).toLowerCase(),xt(e.getValue(r)).toLowerCase()),gf=(t,e,r)=>Ro(xt(t.getValue(r)),xt(e.getValue(r))),mf=(t,e,r)=>{const n=t.getValue(r),o=e.getValue(r);return n>o?1:n<o?-1:0},pf=(t,e,r)=>Ro(t.getValue(r),e.getValue(r));function Ro(t,e){return t===e?0:t>e?1:-1}function xt(t){return typeof t=="number"?isNaN(t)||t===1/0||t===-1/0?"":String(t):typeof t=="string"?t:""}function Ui(t,e){const r=t.split(to).filter(Boolean),n=e.split(to).filter(Boolean);for(;r.length&&n.length;){const o=r.shift(),s=n.shift(),i=parseInt(o,10),a=parseInt(s,10),c=[i,a].sort();if(isNaN(c[0])){if(o>s)return 1;if(s>o)return-1;continue}if(isNaN(c[1]))return isNaN(i)?-1:1;if(i>a)return 1;if(a>i)return-1}return r.length-n.length}const sr={alphanumeric:df,alphanumericCaseSensitive:uf,text:ff,textCaseSensitive:gf,datetime:mf,basic:pf},hf={getInitialState:t=>({sorting:[],...t}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:t=>({onSortingChange:qe("sorting",t),isMultiSortEvent:e=>e.shiftKey}),createColumn:(t,e)=>{t.getAutoSortingFn=()=>{const r=e.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const o of r){const s=o?.getValue(t.id);if(Object.prototype.toString.call(s)==="[object Date]")return sr.datetime;if(typeof s=="string"&&(n=!0,s.split(to).length>1))return sr.alphanumeric}return n?sr.text:sr.basic},t.getAutoSortDir=()=>{const r=e.getFilteredRowModel().flatRows[0];return typeof r?.getValue(t.id)=="string"?"asc":"desc"},t.getSortingFn=()=>{var r,n;if(!t)throw new Error;return un(t.columnDef.sortingFn)?t.columnDef.sortingFn:t.columnDef.sortingFn==="auto"?t.getAutoSortingFn():(r=(n=e.options.sortingFns)==null?void 0:n[t.columnDef.sortingFn])!=null?r:sr[t.columnDef.sortingFn]},t.toggleSorting=(r,n)=>{const o=t.getNextSortingOrder(),s=typeof r<"u"&&r!==null;e.setSorting(i=>{const a=i?.find(f=>f.id===t.id),c=i?.findIndex(f=>f.id===t.id);let l=[],u,g=s?r:o==="desc";if(i!=null&&i.length&&t.getCanMultiSort()&&n?a?u="toggle":u="add":i!=null&&i.length&&c!==i.length-1?u="replace":a?u="toggle":u="replace",u==="toggle"&&(s||o||(u="remove")),u==="add"){var m;l=[...i,{id:t.id,desc:g}],l.splice(0,l.length-((m=e.options.maxMultiSortColCount)!=null?m:Number.MAX_SAFE_INTEGER))}else u==="toggle"?l=i.map(f=>f.id===t.id?{...f,desc:g}:f):u==="remove"?l=i.filter(f=>f.id!==t.id):l=[{id:t.id,desc:g}];return l})},t.getFirstSortDir=()=>{var r,n;return((r=(n=t.columnDef.sortDescFirst)!=null?n:e.options.sortDescFirst)!=null?r:t.getAutoSortDir()==="desc")?"desc":"asc"},t.getNextSortingOrder=r=>{var n,o;const s=t.getFirstSortDir(),i=t.getIsSorted();return i?i!==s&&((n=e.options.enableSortingRemoval)==null||n)&&(!(r&&(o=e.options.enableMultiRemove)!=null)||o)?!1:i==="desc"?"asc":"desc":s},t.getCanSort=()=>{var r,n;return((r=t.columnDef.enableSorting)!=null?r:!0)&&((n=e.options.enableSorting)!=null?n:!0)&&!!t.accessorFn},t.getCanMultiSort=()=>{var r,n;return(r=(n=t.columnDef.enableMultiSort)!=null?n:e.options.enableMultiSort)!=null?r:!!t.accessorFn},t.getIsSorted=()=>{var r;const n=(r=e.getState().sorting)==null?void 0:r.find(o=>o.id===t.id);return n?n.desc?"desc":"asc":!1},t.getSortIndex=()=>{var r,n;return(r=(n=e.getState().sorting)==null?void 0:n.findIndex(o=>o.id===t.id))!=null?r:-1},t.clearSorting=()=>{e.setSorting(r=>r!=null&&r.length?r.filter(n=>n.id!==t.id):[])},t.getToggleSortingHandler=()=>{const r=t.getCanSort();return n=>{r&&(n.persist==null||n.persist(),t.toggleSorting==null||t.toggleSorting(void 0,t.getCanMultiSort()?e.options.isMultiSortEvent==null?void 0:e.options.isMultiSortEvent(n):!1))}}},createTable:t=>{t.setSorting=e=>t.options.onSortingChange==null?void 0:t.options.onSortingChange(e),t.resetSorting=e=>{var r,n;t.setSorting(e?[]:(r=(n=t.initialState)==null?void 0:n.sorting)!=null?r:[])},t.getPreSortedRowModel=()=>t.getGroupedRowModel(),t.getSortedRowModel=()=>(!t._getSortedRowModel&&t.options.getSortedRowModel&&(t._getSortedRowModel=t.options.getSortedRowModel(t)),t.options.manualSorting||!t._getSortedRowModel?t.getPreSortedRowModel():t._getSortedRowModel())}},yf=[Pu,rf,Ju,Zu,Du,Lu,nf,of,hf,Ku,sf,af,lf,cf,ef];function bf(t){var e,r;process.env.NODE_ENV!=="production"&&(t.debugAll||t.debugTable)&&console.info("Creating Table Instance...");const n=[...yf,...(e=t._features)!=null?e:[]];let o={_features:n};const s=o._features.reduce((m,f)=>Object.assign(m,f.getDefaultOptions==null?void 0:f.getDefaultOptions(o)),{}),i=m=>o.options.mergeOptions?o.options.mergeOptions(s,m):{...s,...m};let c={...{},...(r=t.initialState)!=null?r:{}};o._features.forEach(m=>{var f;c=(f=m.getInitialState==null?void 0:m.getInitialState(c))!=null?f:c});const l=[];let u=!1;const g={_features:n,options:{...s,...t},initialState:c,_queue:m=>{l.push(m),u||(u=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();u=!1}).catch(f=>setTimeout(()=>{throw f})))},reset:()=>{o.setState(o.initialState)},setOptions:m=>{const f=yt(m,o.options);o.options=i(f)},getState:()=>o.options.state,setState:m=>{o.options.onStateChange==null||o.options.onStateChange(m)},_getRowId:(m,f,p)=>{var h;return(h=o.options.getRowId==null?void 0:o.options.getRowId(m,f,p))!=null?h:`${p?[p.id,f].join("."):f}`},getCoreRowModel:()=>(o._getCoreRowModel||(o._getCoreRowModel=o.options.getCoreRowModel(o)),o._getCoreRowModel()),getRowModel:()=>o.getPaginationRowModel(),getRow:(m,f)=>{let p=(f?o.getPrePaginationRowModel():o.getRowModel()).rowsById[m];if(!p&&(p=o.getCoreRowModel().rowsById[m],!p))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${m}`):new Error;return p},_getDefaultColumnDef:q(()=>[o.options.defaultColumn],m=>{var f;return m=(f=m)!=null?f:{},{header:p=>{const h=p.header.column.columnDef;return h.accessorKey?h.accessorKey:h.accessorFn?h.id:null},cell:p=>{var h,y;return(h=(y=p.renderValue())==null||y.toString==null?void 0:y.toString())!=null?h:null},...o._features.reduce((p,h)=>Object.assign(p,h.getDefaultColumnDef==null?void 0:h.getDefaultColumnDef()),{}),...m}},W(t,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>o.options.columns,getAllColumns:q(()=>[o._getColumnDefs()],m=>{const f=function(p,h,y){return y===void 0&&(y=0),p.map(x=>{const v=Fu(o,x,y,h),w=x;return v.columns=w.columns?f(w.columns,v,y+1):[],v})};return f(m)},W(t,"debugColumns","getAllColumns")),getAllFlatColumns:q(()=>[o.getAllColumns()],m=>m.flatMap(f=>f.getFlatColumns()),W(t,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:q(()=>[o.getAllFlatColumns()],m=>m.reduce((f,p)=>(f[p.id]=p,f),{}),W(t,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:q(()=>[o.getAllColumns(),o._getOrderColumnsFn()],(m,f)=>{let p=m.flatMap(h=>h.getLeafColumns());return f(p)},W(t,"debugColumns","getAllLeafColumns")),getColumn:m=>{const f=o._getAllFlatColumnsById()[m];return process.env.NODE_ENV!=="production"&&!f&&console.error(`[Table] Column with id '${m}' does not exist.`),f}};Object.assign(o,g);for(let m=0;m<o._features.length;m++){const f=o._features[m];f==null||f.createTable==null||f.createTable(o)}return o}function xf(){return t=>q(()=>[t.options.data],e=>{const r={rows:[],flatRows:[],rowsById:{}},n=function(o,s,i){s===void 0&&(s=0);const a=[];for(let l=0;l<o.length;l++){const u=Co(t,t._getRowId(o[l],l,i),o[l],l,s,void 0,i?.id);if(r.flatRows.push(u),r.rowsById[u.id]=u,a.push(u),t.options.getSubRows){var c;u.originalSubRows=t.options.getSubRows(o[l],l),(c=u.originalSubRows)!=null&&c.length&&(u.subRows=n(u.originalSubRows,s+1,u))}}return a};return r.rows=n(e),r},W(t.options,"debugTable","getRowModel",()=>t._autoResetPageIndex()))}function wf(t){const e=[],r=n=>{var o;e.push(n),(o=n.subRows)!=null&&o.length&&n.getIsExpanded()&&n.subRows.forEach(r)};return t.rows.forEach(r),{rows:e,flatRows:t.flatRows,rowsById:t.rowsById}}function vf(t,e,r){return r.options.filterFromLeafRows?Cf(t,e,r):Sf(t,e,r)}function Cf(t,e,r){var n;const o=[],s={},i=(n=r.options.maxLeafRowFilterDepth)!=null?n:100,a=function(c,l){l===void 0&&(l=0);const u=[];for(let m=0;m<c.length;m++){var g;let f=c[m];const p=Co(r,f.id,f.original,f.index,f.depth,void 0,f.parentId);if(p.columnFilters=f.columnFilters,(g=f.subRows)!=null&&g.length&&l<i){if(p.subRows=a(f.subRows,l+1),f=p,e(f)&&!p.subRows.length){u.push(f),s[f.id]=f,o.push(f);continue}if(e(f)||p.subRows.length){u.push(f),s[f.id]=f,o.push(f);continue}}else f=p,e(f)&&(u.push(f),s[f.id]=f,o.push(f))}return u};return{rows:a(t),flatRows:o,rowsById:s}}function Sf(t,e,r){var n;const o=[],s={},i=(n=r.options.maxLeafRowFilterDepth)!=null?n:100,a=function(c,l){l===void 0&&(l=0);const u=[];for(let m=0;m<c.length;m++){let f=c[m];if(e(f)){var g;if((g=f.subRows)!=null&&g.length&&l<i){const h=Co(r,f.id,f.original,f.index,f.depth,void 0,f.parentId);h.subRows=a(f.subRows,l+1),f=h}u.push(f),o.push(f),s[f.id]=f}}return u};return{rows:a(t),flatRows:o,rowsById:s}}function _f(){return t=>q(()=>[t.getPreFilteredRowModel(),t.getState().columnFilters,t.getState().globalFilter],(e,r,n)=>{if(!e.rows.length||!(r!=null&&r.length)&&!n){for(let m=0;m<e.flatRows.length;m++)e.flatRows[m].columnFilters={},e.flatRows[m].columnFiltersMeta={};return e}const o=[],s=[];(r??[]).forEach(m=>{var f;const p=t.getColumn(m.id);if(!p)return;const h=p.getFilterFn();if(!h){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${p.id}.`);return}o.push({id:m.id,filterFn:h,resolvedValue:(f=h.resolveFilterValue==null?void 0:h.resolveFilterValue(m.value))!=null?f:m.value})});const i=(r??[]).map(m=>m.id),a=t.getGlobalFilterFn(),c=t.getAllLeafColumns().filter(m=>m.getCanGlobalFilter());n&&a&&c.length&&(i.push("__global__"),c.forEach(m=>{var f;s.push({id:m.id,filterFn:a,resolvedValue:(f=a.resolveFilterValue==null?void 0:a.resolveFilterValue(n))!=null?f:n})}));let l,u;for(let m=0;m<e.flatRows.length;m++){const f=e.flatRows[m];if(f.columnFilters={},o.length)for(let p=0;p<o.length;p++){l=o[p];const h=l.id;f.columnFilters[h]=l.filterFn(f,h,l.resolvedValue,y=>{f.columnFiltersMeta[h]=y})}if(s.length){for(let p=0;p<s.length;p++){u=s[p];const h=u.id;if(u.filterFn(f,h,u.resolvedValue,y=>{f.columnFiltersMeta[h]=y})){f.columnFilters.__global__=!0;break}}f.columnFilters.__global__!==!0&&(f.columnFilters.__global__=!1)}}const g=m=>{for(let f=0;f<i.length;f++)if(m.columnFilters[i[f]]===!1)return!1;return!0};return vf(e.rows,g,t)},W(t.options,"debugTable","getFilteredRowModel",()=>t._autoResetPageIndex()))}function Rf(t){return e=>q(()=>[e.getState().pagination,e.getPrePaginationRowModel(),e.options.paginateExpandedRows?void 0:e.getState().expanded],(r,n)=>{if(!n.rows.length)return n;const{pageSize:o,pageIndex:s}=r;let{rows:i,flatRows:a,rowsById:c}=n;const l=o*s,u=l+o;i=i.slice(l,u);let g;e.options.paginateExpandedRows?g={rows:i,flatRows:a,rowsById:c}:g=wf({rows:i,flatRows:a,rowsById:c}),g.flatRows=[];const m=f=>{g.flatRows.push(f),f.subRows.length&&f.subRows.forEach(m)};return g.rows.forEach(m),g},W(e.options,"debugTable","getPaginationRowModel"))}function Af(){return t=>q(()=>[t.getState().sorting,t.getPreSortedRowModel()],(e,r)=>{if(!r.rows.length||!(e!=null&&e.length))return r;const n=t.getState().sorting,o=[],s=n.filter(c=>{var l;return(l=t.getColumn(c.id))==null?void 0:l.getCanSort()}),i={};s.forEach(c=>{const l=t.getColumn(c.id);l&&(i[c.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const a=c=>{const l=c.map(u=>({...u}));return l.sort((u,g)=>{for(let f=0;f<s.length;f+=1){var m;const p=s[f],h=i[p.id],y=h.sortUndefined,x=(m=p?.desc)!=null?m:!1;let v=0;if(y){const w=u.getValue(p.id),S=g.getValue(p.id),C=w===void 0,E=S===void 0;if(C||E){if(y==="first")return C?-1:1;if(y==="last")return C?1:-1;v=C&&E?0:C?y:-y}}if(v===0&&(v=h.sortingFn(u,g,p.id)),v!==0)return x&&(v*=-1),h.invertSorting&&(v*=-1),v}return u.index-g.index}),l.forEach(u=>{var g;o.push(u),(g=u.subRows)!=null&&g.length&&(u.subRows=a(u.subRows))}),l};return{rows:a(r.rows),flatRows:o,rowsById:r.rowsById}},W(t.options,"debugTable","getSortedRowModel",()=>t._autoResetPageIndex()))}function Ef(t){const e={state:{},onStateChange:()=>{},renderFallbackValue:null,...t},[r]=Ue.useState(()=>({current:bf(e)})),[n,o]=Ue.useState(()=>r.current.initialState);return r.current.setOptions(s=>({...s,...t,state:{...n,...t.state},onStateChange:i=>{o(i),t.onStateChange==null||t.onStateChange(i)}})),r.current}function Nf({data:t,columns:e,enabled:r=!1}){const n=b.useMemo(()=>t,[t]),o=Ef({data:n,columns:e||[],getCoreRowModel:xf(),getSortedRowModel:Af(),getFilteredRowModel:_f(),getPaginationRowModel:Rf(),enableSorting:r,enableFilters:r});return r?o:null}const Zt=b.memo(({parts:t=[],children:e=null,fontSize:r="1rem",color:n="#333333",displayMode:o=!1,className:s=""})=>{b.useEffect(()=>{process.env.NODE_ENV==="development"&&typeof window<"u"&&(Array.from(document.styleSheets).some(g=>{try{return g.href&&g.href.includes("katex")}catch{return!1}})||console.warn(`EquationRender: KaTeX CSS 未检测到。请确保在项目入口文件中导入 KaTeX CSS:
10
10
  import 'katex/dist/katex.min.css';
11
- 更多详情请参考组件库文档。`))},[]);const i=x.useMemo(()=>t.length===0?[]:t.map((d,g)=>{try{return al.renderToString(d,{displayMode:o,throwOnError:!1,errorColor:"#ff0000"})}catch(p){return console.error(`KaTeX rendering error in part ${g}:`,p),'<span style="color: red;">KaTeX Error</span>'}}),[t,o]);if(t.length===0)return null;const a=o?"div":"span",c=x.Children.toArray(e),l=[];return i.forEach((d,g)=>{l.push(u.jsx("span",{dangerouslySetInnerHTML:{__html:d},style:{display:"inline-block"}},`part-${g}`)),g<c.length&&g<t.length-1&&l.push(u.jsx("span",{style:{display:"inline-block"},children:c[g]},`slot-${g}`))}),u.jsx(a,{className:`equation-render ${s}`.trim(),style:{fontSize:r,color:n,display:"flex",alignItems:"center",gap:"0.3em",...o?{justifyContent:"center",margin:"1em 0"}:{}},children:l})});function ir(t){return t.type!=="composite"}function ar(t){return t.type==="composite"}function qu(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function zt(t){if(!t)return qu();if(t.type==="composite"&&Array.isArray(t.transforms))return{type:"composite",transforms:t.transforms.map(s=>zt(s)),executionMode:t.executionMode||"sequential"};if(t.type&&t.config)return t;const e=t;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((s,i)=>zt(s)),executionMode:"sequential"};let r,n="translation";return e.rotation?(n="rotation",r=e.rotation):e.translation?(n="translation",r=e.translation):e.scale?(n="scale",r=e.scale):(n="translation",r={direction:"horizontal",distance:0}),{type:n,config:r,targetGroup:e.targetGroup}}const ln=t=>{if(t.length===0)return[0,0];let e=0,r=0;for(const[n,o]of t)e+=n,r+=o;return[e/t.length,r/t.length]},Qn=t=>{if(ir(t)){const e=t;if(!e.config)return`${e.type}变换缺少配置`;switch(e.type){case"translation":if(e.config.distance<=0)return"平移距离必须大于0";break;case"rotation":if(e.config.startAngle===e.config.endAngle)return"旋转起始角度和结束角度不能相同";break;case"scale":const r=e.config;if(r.startScale<=0||r.endScale<=0)return"缩放比例必须大于0";break}return null}if(ar(t)){const e=t;if(!e.transforms)return"复合变换缺少transforms字段";for(const r of e.transforms){const n=Qn(r);if(n)return`复合变换子配置错误: ${n}`}return null}return"未知的变换配置类型"},Wu=(t,e,r,n)=>{if(t<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(r.animated.length===0)return"至少需要一个动画图形";const o=Qn(n);if(o)return`全局变换配置错误: ${o}`;for(const s of r.animated)if(s.transform){const i=zt(s.transform),a=Qn(i);if(a)return`形状"${s.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const s of[...r.static,...r.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,c]=i;if(typeof a!="number"||typeof c!="number"||!isFinite(a)||!isFinite(c))return`形状"${s.metadata?.id||"未知"}"顶点坐标无效`}}return null},Yu=t=>{const{base:e,height:r,shapes:n,transform:o}=t,s=zt(o),i=Wu(e,r,n,s);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},Ku=t=>{if(t.slider){const{slider:e}=t;if(e.length<=0)return"滑块长度必须大于0";if(e.min!==void 0&&e.max!==void 0&&e.min>=e.max)return"滑块最小值必须小于最大值";if(e.step!==void 0&&e.step<=0)return"滑块步长必须大于0"}return null},Xu=t=>{if(!t)return null;if(t.boundingBox){const[e,r,n,o]=t.boundingBox;if(e>=n||r<=o)return"画板边界框配置无效:left < right 且 top > bottom"}return t.gridSize!==void 0&&t.gridSize<=0?"网格大小必须大于0":null},Ju=t=>{const e=Yu({base:t.base,height:t.height,shapes:t.shapes,transform:t.transform});if(e)return e;const r=Ku(t.animation);if(r)return{code:"INVALID_CONFIG",message:r,timestamp:new Date().toISOString()};const n=Xu(t.boardConfig);return n?{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()}:t.autoCompleteThreshold!==void 0&&(t.autoCompleteThreshold<0||t.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class cn{validateNumber(e,r,n,o){if(typeof e!="number"||isNaN(e))return`${r}必须是有效的数字`;if(n!==void 0&&e<n)return`${r}不能小于${n}`;if(o!==void 0&&e>o)return`${r}不能大于${o}`}validateArray(e,r,n){if(!Array.isArray(e))return`${r}必须是数组`;if(n!==void 0&&e.length!==n)return`${r}必须是长度为${n}的数组`}validateString(e,r,n){if(typeof e!="string")return`${r}必须是字符串`;if(n!==void 0&&!n.includes(e))return`${r}必须是以下值之一: ${n.join(", ")}`}createValidationResult(e,r,n){return{isValid:e,errors:r?.filter(Boolean),warnings:n?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let r=0;r<e.length;r++){const n=e[r],o=this.validateArray(n,`顶点[${r}]`,2);if(o)return o;const[s,i]=n,a=this.validateNumber(s,`顶点[${r}].x`),c=this.validateNumber(i,`顶点[${r}].y`);if(a||c)return`${a||c} (顶点[${r}])`}}}const Zu=(t,e,r)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:t,progress:e,config:r,distance:r.distance,distanceType:typeof r.distance,direction:r.direction,directionType:typeof r.direction,configType:typeof r,configKeys:Object.keys(r)});let n;r.direction==="horizontal"?n=[r.distance,0]:r.direction==="vertical"?n=[0,r.distance]:n=[r.direction[0]*r.distance,r.direction[1]*r.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:t[0],firstVertexTransformed:[t[0][0]+o,t[0][1]+s]}),t.map(([i,a])=>[i+o,a+s])},Qu=(t,e,r)=>{const n=r.center==="auto"?ln(t):r.center,[o,s]=n,i=r.endAngle-r.startAngle,a=r.direction==="clockwise"?-1:1,c=r.startAngle+i*e*a;return t.map(([l,d])=>{const g=l-o,p=d-s,f=Math.cos(c),m=Math.sin(c);return[o+g*f-p*m,s+g*m+p*f]})},ef=(t,e,r)=>{const n=r.center==="centroid"?ln(t):r.center,[o,s]=n,i=r.endScale-r.startScale,a=r.startScale+i*e;return t.map(([c,l])=>{const d=c-o,g=l-s;return[o+d*a,s+g*a]})},tf=(t,e=.95)=>t>=e;class rf extends cn{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,r,n){return Zu(e,r,n)}validate(e){const r=[],n=[];if(typeof e.direction=="string"){const s=this.validateString(e.direction,"direction",["horizontal","vertical"]);s&&r.push(s)}else if(Array.isArray(e.direction)){const s=this.validateArray(e.direction,"direction",2);if(s)r.push(s);else{const[i,a]=e.direction,c=this.validateNumber(i,"direction[0]"),l=this.validateNumber(a,"direction[1]");c&&r.push(c),l&&r.push(l)}}else r.push("direction必须是字符串或数组");const o=this.validateNumber(e.distance,"distance",0);if(o&&r.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(r.length===0,r,n)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,r){const n=this.getDirectionVector(e),o=e.startOffset||0,s=Math.max(0,Math.min(1,r-o))/(1-o);return[n[0]*e.distance*s,n[1]*e.distance*s]}}class nf extends cn{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,r,n){return Qu(e,r,n)}validate(e){const r=[],n=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)r.push(a);else{const[c,l]=e.center,d=this.validateNumber(c,"center[0]"),g=this.validateNumber(l,"center[1]");d&&r.push(d),g&&r.push(g)}}else r.push('center必须是"auto"或数组[x, y]');const o=this.validateNumber(e.startAngle,"startAngle");o&&r.push(o);const s=this.validateNumber(e.endAngle,"endAngle");if(s&&r.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&&r.push(i),this.createValidationResult(r.length===0,r,n)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let r=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,c]=e[i];r=Math.min(r,a),n=Math.max(n,a),o=Math.min(o,c),s=Math.max(s,c)}return{minX:r,maxX:n,minY:o,maxY:s}}getActualCenter(e,r){return r.center==="auto"?ln(e):r.center}calculateCurrentAngle(e,r){const n=e.endAngle-e.startAngle,o=e.direction==="clockwise"?-1:1;return e.startAngle+n*r*o}}class of extends cn{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,r,n){return ef(e,r,n)}validate(e){const r=[],n=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)r.push(i);else{const[a,c]=e.center,l=this.validateNumber(a,"center[0]"),d=this.validateNumber(c,"center[1]");l&&r.push(l),d&&r.push(d)}}else r.push('center必须是"centroid"或数组[x, y]');const o=this.validateNumber(e.startScale,"startScale",.01);o&&r.push(o);const s=this.validateNumber(e.endScale,"endScale",.01);if(s&&r.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"?r.push("uniform必须是布尔值"):e.uniform||n.push("非均匀缩放可能导致图形变形"),this.createValidationResult(r.length===0,r,n)}getActualCenter(e,r){return r.center==="centroid"?ln(e):r.center}calculateCurrentScale(e,r){const n=e.endScale-e.startScale;return e.startScale+n*r}calculateSizeChange(e,r,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,c=this.calculateCurrentScale(r,n),l=(r.uniform,c),d=s*l,g=i*l,p=d*g;return{widthChange:(d-s)/s,heightChange:(g-i)/i,areaChange:(p-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let r=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,c]=e[i];r=Math.min(r,a),n=Math.max(n,a),o=Math.min(o,c),s=Math.max(s,c)}return{minX:r,maxX:n,minY:o,maxY:s}}}function gs(t){let e=t.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(`无效的十六进制颜色格式: ${t}`);const r=parseInt(e.substring(0,2),16),n=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16);if(isNaN(r)||isNaN(n)||isNaN(o))throw new Error(`无效的十六进制颜色值: ${t}`);return[r,n,o]}function sf(t,e,r){const n=a=>Math.max(0,Math.min(255,Math.round(a))),o=n(t).toString(16).padStart(2,"0"),s=n(e).toString(16).padStart(2,"0"),i=n(r).toString(16).padStart(2,"0");return`#${o}${s}${i}`.toUpperCase()}function eo(t){const e=t.trim();if(e.startsWith("#"))return gs(e);const r=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(r){const s=parseInt(r[1],10),i=parseInt(r[2],10),a=parseInt(r[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]:gs(n[o]);throw new Error(`无法解析的颜色格式: ${t}`)}function Zr(t){try{return eo(t),!0}catch{return!1}}function af(t,e,r){if(r<=0)return t;if(r>=1)return e;try{const n=eo(t),o=eo(e),s=n[0]+(o[0]-n[0])*r,i=n[1]+(o[1]-n[1])*r,a=n[2]+(o[2]-n[2])*r;return sf(s,i,a)}catch(n){return console.warn("颜色插值失败,返回起始颜色:",n),t}}function Ii(t,e,r,n="linear"){let o=r;switch(n){case"ease-in":o=r*r;break;case"ease-out":o=1-(1-r)*(1-r);break;case"ease-in-out":o=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2;break;case"step":o=r>=1?1:0;break}return af(t,e,o)}class lf extends cn{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,r,n){return e}validate(e){const r=[],n=[];if(!e.targetColor||typeof e.targetColor!="string"?r.push("targetColor 是必需的且必须是字符串"):Zr(e.targetColor)||r.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?r.push("fromColor 必须是字符串"):Zr(e.fromColor)||r.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const o=this.validateNumber(e.startAt,"startAt",0,1);o&&r.push(o)}if(e.endAt!==void 0){const o=this.validateNumber(e.endAt,"endAt",0,1);o&&r.push(o)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&r.push("startAt 必须小于 endAt"),e.easing!==void 0){const o=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);o&&r.push(o)}return e.targetColor&&e.fromColor,this.createValidationResult(r.length===0,r,n)}calculateCurrentColor(e,r,n){const o=r.fromColor||n,s=r.targetColor,i=this.calculateEffectiveProgress(e,r);return Ii(o,s,i,r.easing)}calculateEffectiveProgress(e,r){const n=r.startAt??0,o=r.endAt??1;return e<=n?0:e>=o?1:(e-n)/(o-n)}isActive(e,r){const n=r.startAt??0,o=r.endAt??1;return e>=n&&e<=o}}class cf{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[r,n]of this.executors)e[r]=n.getDisplayName();return e}validateConfig(e,r){const n=this.get(e);return n?n.validate(r):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,r,n,o){const s=this.get(e);if(!s)return console.error(`不支持变换类型: ${e}`),r;const i=s.validate(o);return i.isValid?s.execute(r,n,o):(console.error("配置验证失败:",i.errors),r)}executeTransforms(e,r,n){let o=r;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 St=null;function Fi(){return St||(St=new cf,St.register(new rf),St.register(new nf),St.register(new of),St.register(new lf)),St}class to{static matchesShape(e,r,n){if(!r)return!n||this.extractGroupId(e)===n;if("targetGroup"in r&&r.targetGroup)return this.matchesSimpleGroup(e,r.targetGroup,r.metadataField);if("pattern"in r){if(r.strategy==="any")return this.matchesWithConfig(e,r);if(r.pattern)return this.matchesWithConfig(e,r)}return!1}static matchesSimpleGroup(e,r,n){const o=this.extractGroupId(e,n);if(!o)return!1;if(r.includes("*")){const s=r.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(o)}return o===r}static matchesWithConfig(e,r){const n=this.extractGroupId(e,r.metadataField);if(!n)return!1;const o=r.pattern,s=r.strategy||"exact",i=r.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(d=>this.matchesSimpleGroup(e,d,r.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,r="rotationGroup"){if(!e)return;const n=r.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 r=[],n=[];if(!e||typeof e!="object")return r.push("配置必须是对象"),{isValid:!1,errors:r,warnings:n};switch(e.pattern||r.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&r.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&r.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&r.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:r.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&r.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&r.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&n.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:r.length===0,errors:r,warnings:n}}static convertToGroupMatchConfig(e,r){if(!e)return;const n=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:n,metadataField:r}}}function df(t,e,r){return!e&&!r?t.filter(n=>!n.targetGroup&&!n.groupMatch):t.filter(n=>{if(n.groupMatch&&r)return to.matchesShape(r,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 uf{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,r,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,r,a);case"parallel":return this.executeInParallel(e,r,a);default:return console.warn(`未知的执行模式: ${n.executionMode},使用顺序执行`),this.executeSequentially(e,r,a)}}validate(e){const r=[],n=[];if(!e||e.type!=="composite")return r.push("配置必须是复合变换类型"),this.createValidationResult(!1,r,n);if(!Array.isArray(e.transforms))return r.push("transforms必须是数组"),this.createValidationResult(!1,r,n);e.transforms.length===0&&n.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&r.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],c=this.validateSingleTransform(a,i);c&&r.push(c)}const o=e.transforms.map(i=>i.id).filter(Boolean),s=new Set(o);return o.length!==s.size&&n.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(r.length===0,r,n)}getTransformInfo(e){const r=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:r,groups:n,executionMode:e.executionMode}}filterTransformsByGroup(e,r,n){return df(e,r,n)}getTransformsForGroup(e,r,n){return this.filterTransformsByGroup(e.transforms,r,n)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,r,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,r,s.config)}return o}executeInParallel(e,r,n){if(n.length===0)return e;if(n.length===1)return this.executeSequentially(e,r,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 c=i.execute(e,r,s.config);o.push(c)}return o.length===0?e:this.calculateAverageVertices(o)}calculateAverageVertices(e){if(e.length===0)return[];const r=e[0].length;for(const o of e)if(o.length!==r)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const n=[];for(let o=0;o<r;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,r){if(!e||typeof e!="object")return`变换[${r}]必须是对象`;if(!e.type)return`变换[${r}]缺少type字段`;if(!e.config)return`变换[${r}]缺少config字段`;const n=this.registry.get(e.type);if(!n)return`变换[${r}]不支持的变换类型: ${e.type}`;const o=n.validate(e.config);if(!o.isValid)return`变换[${r}]配置验证失败: ${o.errors?.join(", ")}`}createValidationResult(e,r,n){return{isValid:e,errors:r?.filter(Boolean),warnings:n?.filter(Boolean)}}getDefaultRegistry(){return Fi()}}class ff{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new uf(this.registry)}executeShapeTransform(e,r,n){const o=this.getEffectiveTransform(e,n);return o?this.executeTransform(e.vertices,r,o,e.metadata):e.vertices}executeTransform(e,r,n,o){if(!n)return e;const s=to.extractGroupId(o,"rotationGroup");return ir(n)?this.executeSingleTransform(e,r,n,o,s):ar(n)?this.compositor.execute(e,r,n,s,o):(console.error("未知的变换类型:",n),e)}getEffectiveTransform(e,r){return e.transform?e.transform:r}getTransformInfo(e){return e?ir(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:ar(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?ir(e)?this.validateSingleTransform(e):ar(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?ir(e)?!1:ar(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,r,n){return e.map(o=>({...o,vertices:this.executeShapeTransform(o,r,n)}))}executeSingleTransform(e,r,n,o,s){if(!to.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 c=a.validate(n.config);return c.isValid?a.execute(e,r,n.config):(console.error("变换配置验证失败:",c.errors),e)}validateSingleTransform(e){const r=this.registry.get(e.type);return r?r.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return Fi()}}const gf=()=>{const t=x.useRef(null),e=x.useCallback((o,s,i=50)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{s&&s(o)},i)},[]),r=x.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=x.useCallback(()=>(t.current&&(clearTimeout(t.current),t.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:tf,getProgressLabel:r,resetProgress:n}},mf=()=>{const t=x.useCallback((r,n,o=.05)=>{let s=n;switch(r.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 r.preventDefault(),s},[]),e=x.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
12
- `),[]);return{handleKeyDown:t,getNavigationInstructions:e}},ms=Ms.JSXGraph,pf=t=>{const{base:e,height:r,unit:n,layoutDensity:o="default",boardHeight:s,shapes:i,transform:a,animation:c,boardConfig:l={},theme:d="light",className:g="",enableRigidityVerification:p=!1,enableKeyboardNavigation:f=!0,autoCompleteThreshold:m=.95,boardWidth:h,onTransformStart:y,onTransformChange:b,onTransformComplete:_,onError:w}=t,[C,v]=x.useState(0),[k,S]=x.useState(null),[E,N]=x.useState(0),[I,Y]=x.useState(null),[K,L]=x.useState({width:800,height:560}),O=x.useMemo(()=>new ff,[]),U=x.useMemo(()=>zt(a),[a]),T=x.useRef(null),q=x.useRef({}),$=x.useRef(null),{handleProgressChange:ee,shouldAutoComplete:de,resetProgress:re}=gf(),{handleKeyDown:te,getNavigationInstructions:G}=mf();x.useEffect(()=>{const F=()=>{if($.current){const{clientWidth:A}=$.current;if(A>0){const se=l.boundingBox||[0,7,10,0],ue=se[2]-se[0],V=se[1]-se[3];let X;s?X=s:X=Math.round(A*(V/ue)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:se,ratio:`${V}:${ue}`,containerWidth:A,calculatedHeight:X,isCustomHeight:!!s}),L({width:A,height:X})}}};F(),window.addEventListener("resize",F);const M=new ResizeObserver(F);return $.current&&M.observe($.current),()=>{window.removeEventListener("resize",F),M.disconnect()}},[l.boundingBox,s]);const Z={width:h??`${K.width}px`,height:`${K.height}px`},ge=x.useCallback((F,M)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:F.metadata?.id,shapeType:F.type,progress:M,hasMetadata:!!F.metadata,hasDynamicAppearance:!!F.metadata?.dynamicAppearance,dynamicAppearance:F.metadata?.dynamicAppearance});const A=F.metadata?.dynamicAppearance,se=F.style||{};let ue;if(F.transform?.type==="fillcolor_set"&&F.transform.fillColorSet){const fe=F.transform.fillColorSet,{targetColor:xe,startAt:Se=0,endAt:Ee=1,easing:Le="linear",fromColor:Je}=fe;if(Zr(xe)&&(!Je||Zr(Je))){let Ge=M;M<Se?Ge=0:M>Ee?Ge=1:Ge=(M-Se)/(Ee-Se);const Qt=Je||se.fillColor||"#FFFFFF";ue=Ii(Qt,xe,Ge,Le),console.log("🎨 fillcolor_set applied:",{shapeId:F.metadata?.id,progress:M,effectiveProgress:Ge,startColor:Qt,targetColor:xe,resultColor:ue})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:xe,fromColor:Je})}if(!A)return console.log("📝 No dynamicAppearance, returning base style"),ue?{...se,fillColor:ue}:se;const V=fe=>{if(!fe)return 1;const xe=fe.threshold??.5,Se=fe.startValue??0,Ee=fe.endValue??1,Le=fe.type??"step";if(Le==="step")return M>=xe?Ee:Se;if(Le==="fade"){if(M<xe)return Se;{const Je=Math.min((M-xe)/(1-xe),1);return Se+(Ee-Se)*Je}}return 1},X={...se};let wt=!0;const Xe=V(A.visibility),vt=V(A.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:F.metadata?.id,progress:M,visibilityValue:Xe,labelVisibilityValue:vt,hasVisibility:!!A.visibility,hasLabelVisibility:!!A.labelVisibility}),A.visibility&&(X.fillOpacity===void 0&&(X.fillOpacity=1),X.fillOpacity*=Xe,Xe===0&&(X.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),X.strokeColor,wt=Xe>0,console.log("👁️ Shape visibility:",{shapeId:F.metadata?.id,visible:wt,visibilityValue:Xe})),A.labelVisibility){const fe=vt>0;X.labelVisible=fe,console.log("🏷️ Label visibility:",{shapeId:F.metadata?.id,labelVisible:fe,labelVisibilityValue:vt,hasLabel:!!F.metadata?.label})}if(A.opacity){const fe=A.opacity,xe=fe.startAt??0,Se=fe.endAt??1,Ee=fe.from??1,Le=fe.to??1,Je=fe.type??"linear";let Ge=Ee;if(M<xe)Ge=Ee;else if(M>Se)Ge=Le;else{const Qt=(M-xe)/(Se-xe);Ge=Ee+(Le-Ee)*Qt}X.fillOpacity=Ge}if(ue)X.fillColor=ue,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:F.metadata?.id,transformColor:ue});else if(A.color){const fe=A.color,xe=fe.startAt??0,Se=fe.endAt??1,Ee=fe.from??X.fillColor,Le=fe.to??X.fillColor,Je=fe.type??"gradient";if(Ee&&Le)if(M<xe)X.fillColor=Ee;else if(M>Se)X.fillColor=Le;else{const Ge=(M-xe)/(Se-xe);Je==="gradient"?X.fillColor=Le:X.fillColor=Ge>=.5?Le:Ee}}return X.visible=wt,X.labelVisible===void 0&&(X.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:F.metadata?.id,visible:X.visible,labelVisible:X.labelVisible,fillOpacity:X.fillOpacity,strokeWidth:X.strokeWidth}),X},[]),Ce=x.useCallback((F,M,A=!1,se=0)=>{console.log("🎨 createShape called:",{shapeId:M.metadata?.id,shapeType:M.type,isStatic:A,progress:se,verticesLength:M.vertices?.length,hasMetadata:!!M.metadata,hasDynamicAppearance:!!M.metadata?.dynamicAppearance});const ue=M.type==="point"?1:2;if(!F||!M.vertices||M.vertices.length<ue)return console.warn(`⚠️ createShape: invalid board or vertices for ${M.type}`,{shapeId:M.metadata?.id,shapeType:M.type,verticesLength:M.vertices?.length,minVertices:ue}),null;const V=ge(M,se);let X;switch(M.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const wt=V.labelVisible!==void 0?V.labelVisible:M.style?.labelVisible!==void 0?M.style.labelVisible:!1,Xe=M.metadata?.label||M.metadata?.id||"";X=F.create("polygon",M.vertices,{name:Xe,fillColor:V.fillColor!==void 0?V.fillColor:A?"#8ec5fc":"#6a5acd",fillOpacity:V.fillOpacity!==void 0?V.fillOpacity:A?.3:.7,strokeColor:V.strokeColor!==void 0?V.strokeColor:A?"#0074d9":"#4b0082",strokeWidth:V.strokeWidth!==void 0?V.strokeWidth:A?1:2,dash:V.dashStyle!==void 0?V.dashStyle:0,fixed:A,highlight:!A,withLabel:wt,visible:V.visible!==void 0?V.visible:!0});break;case"circle":if(M.vertices.length>=2){const[vt,fe]=M.vertices,xe=V.labelVisible!==void 0?V.labelVisible:M.style?.labelVisible!==void 0?M.style.labelVisible:!1,Se=M.metadata?.label||M.metadata?.id||"";X=F.create("circle",[vt,fe],{name:Se,fillColor:V.fillColor!==void 0?V.fillColor:A?"#8ec5fc":"#6a5acd",fillOpacity:V.fillOpacity!==void 0?V.fillOpacity:A?.3:.7,strokeColor:V.strokeColor!==void 0?V.strokeColor:A?"#0074d9":"#4b0082",strokeWidth:V.strokeWidth!==void 0?V.strokeWidth:A?1:2,dash:V.dashStyle!==void 0?V.dashStyle:0,fixed:A,highlight:!A,withLabel:xe})}break;case"point":if(M.vertices.length>=1){const[vt,fe]=M.vertices[0],xe=V.labelVisible!==void 0?V.labelVisible:M.style?.labelVisible!==void 0?M.style.labelVisible:!1,Se=M.metadata?.label||M.metadata?.id||"";X=F.create("point",[vt,fe],{name:Se,withLabel:xe,fixed:A,size:4,strokeColor:V.strokeColor!==void 0?V.strokeColor:A?"#0074d9":"#4b0082",fillColor:V.fillColor!==void 0?V.fillColor:A?"#8ec5fc":"#6a5acd",visible:V.visible!==void 0?V.visible:!0,highlight:!A})}break;default:return console.warn(`Unsupported shape type: ${M.type}`),null}return console.log("✅ createShape finished:",{shapeId:M.metadata?.id,elementType:X?.type,elementName:X?.name,fillOpacity:X?.getAttribute?.("fillOpacity"),strokeWidth:X?.getAttribute?.("strokeWidth"),labelVisible:V.labelVisible,hasLabel:!!M.metadata?.label,withLabel:!!M.metadata?.label&&V.labelVisible}),X},[ge]);x.useEffect(()=>{if(!(e>0&&r>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:r,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:r>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig});const M=Ju(t);console.log("🔍 GeometryTransform: 验证结果 =",M),S(M),M&&w&&w(M)},[e,r,i,a,c,l,w,t]),x.useEffect(()=>{if(T.current){try{const F=l.boundingBox||[0,7,10,0],M=d==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",l.boundingBox),console.warn(" - Container dimensions:",K.width,"x",K.height),console.warn(" - Container actual dimensions:",T.current.clientWidth,"x",T.current.clientHeight);const A=ms.initBoard(T.current,{boundingbox:F,keepaspectratio:l.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:l.showAxis??!0,grid:l.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),se=l.axisColor||(M?"#ffffff":"#000000"),ue=l.gridColor||(M?"#444444":"#dddddd");A.defaultAxes?.x&&A.defaultAxes.x.setAttribute({strokeColor:se}),A.defaultAxes?.y&&A.defaultAxes.y.setAttribute({strokeColor:se}),A.defaultGrid&&A.defaultGrid.setAttribute({strokeColor:ue}),Y(A)}catch(F){const M={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:F,timestamp:new Date().toISOString()};S(M),w?.(M)}return()=>{if(I)try{ms.freeBoard(I)}catch(F){F instanceof Error&&F.name!=="AbortError"&&console.warn("Board cleanup warning:",F)}}}},[K]),x.useEffect(()=>{if(I)try{I.suspendUpdate(),Object.values(q.current).forEach(F=>{if(F&&I.removeObject)try{I.removeObject(F)}catch{}}),q.current={},i.static.forEach((F,M)=>{const A=F.metadata?.id||`static-${M}`,se=Ce(I,F,!0,0);se&&(q.current[A]=se)}),i.animated.forEach((F,M)=>{const A=F.metadata?.id||`animated-${M}`,se=Ce(I,F,!1,0);se&&(q.current[A]=se)}),I.unsuspendUpdate(),y&&y()}catch(F){const M={code:"RENDER_ERROR",message:"图形渲染失败",details:F,timestamp:new Date().toISOString()};S(M),w?.(M)}},[I,i,e,r]),x.useEffect(()=>{if(I){I.suspendUpdate();try{i.animated.forEach((A,se)=>{const ue=A.metadata?.id||`animated-${se}`,V=q.current[ue];if(V){try{I.removeObject(V)}catch{}delete q.current[ue]}}),i.animated.forEach((A,se)=>{const ue=A.metadata?.id||`animated-${se}`,V=A.transform?{...A,transform:zt(A.transform)}:A,X=O.executeShapeTransform(V,C,U),wt={...A,vertices:X,metadata:{...A.metadata,id:ue,transformSource:A.transform?"shape":"global"}},Xe=Ce(I,wt,!1,C);Xe&&(q.current[ue]=Xe)});const F=c.progressIndicator?.stages||1,M=Math.min(Math.floor(C*F),F-1);N(M)}catch(F){if(F instanceof Error&&F.name==="AbortError")return;console.warn("Transform update failed:",F)}finally{try{I.unsuspendUpdate()}catch{}}}},[I,C,i,a,c,Ce,U,O]);const ce=x.useCallback(F=>{const M=Array.isArray(F)?F[0]:F;v(M),ee(M,A=>{b?.(A)}),de(M,m)&&(v(1),_?.())},[b,_,m,ee,de]);x.useEffect(()=>{if(!f)return;const F=M=>{const A=te(M,C);A!==null&&A!==C&&ce(A)};return window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",F)}},[f,C,ce,te]),x.useCallback(()=>{v(0),N(0),re()},[re]);const ft=x.useCallback(()=>{S(null),v(0),N(0),re()},[re]);return e>0&&r>0&&i?.animated?.length>0?k?u.jsx(Ue.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${g}`,children:u.jsx(Ue.CardBody,{"data-testid":"card-body",children:u.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[u.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:u.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),u.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),u.jsx("h3",{children:"几何变换演示加载失败"}),u.jsx("p",{children:k.message}),k.details&&u.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[u.jsx("summary",{children:"查看错误详情"}),u.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(k.details,null,2)})]}),u.jsx("div",{className:"geometry-transform__error-actions",children:u.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:ft,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):u.jsx(Ue.Card,{"data-testid":"card",className:`geometry-transform ${o==="compact"?"geometry-transform--compact":""} ${d==="dark"?"geometry-transform--dark":""} ${g}`,children:u.jsxs(Ue.CardBody,{"data-testid":"card-body",children:[u.jsxs("div",{ref:$,className:"geometry-transform__board-container",children:[u.jsx("div",{ref:T,id:"geometry-board",className:"geometry-transform__board",style:Z,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),u.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),u.jsxs("div",{className:"geometry-transform__controls",children:[u.jsx("div",{className:"geometry-transform__slider-group",children:u.jsx(Ue.Slider,{id:"transform-slider","data-testid":"slider",value:C,onChange:ce,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),f&&u.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:u.jsxs("details",{children:[u.jsx("summary",{children:"键盘导航说明"}),u.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:G()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:r,shapesAnimatedLength:i?.animated?.length,error:k}),u.jsx(Ue.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${g}`,children:u.jsx(Ue.CardBody,{"data-testid":"card-body",children:u.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},ji=x.memo(pf,(t,e)=>{if(t.base!==e.base||t.height!==e.height||t.unit!==e.unit||t.theme!==e.theme||t.className!==e.className||t.enableRigidityVerification!==e.enableRigidityVerification||t.enableKeyboardNavigation!==e.enableKeyboardNavigation||t.autoCompleteThreshold!==e.autoCompleteThreshold||t.onTransformStart!==e.onTransformStart||t.onTransformChange!==e.onTransformChange||t.onTransformComplete!==e.onTransformComplete||t.onError!==e.onError)return!1;const r=JSON.stringify({shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig}),n=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return r===n}),So=gr.create((t,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:r=>{t({internalValue:Math.max(0,Math.min(1,r))})},startDrag:r=>{t({isDragging:!0,dragState:{isDragging:!0,startIndex:r,currentIndex:r,direction:null}})},updateDrag:r=>{const{dragState:n}=e();let o=null;if(n.startIndex!==-1&&r!==-1){const s=Math.floor(n.startIndex/10),i=n.startIndex%10,a=Math.floor(r/10),c=r%10;a===s?o=c>i?"ltr":"rtl":c===i&&(o=a>s?"ttb":"btt")}t({dragState:{...n,currentIndex:r,direction:o}})},endDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Pi=()=>So(Os.useShallow(t=>({internalValue:t.internalValue,setInternalValue:t.setInternalValue}))),Di=()=>So(Os.useShallow(t=>({isDragging:t.isDragging,dragState:t.dragState,startDrag:t.startDrag,updateDrag:t.updateDrag,endDrag:t.endDrag,resetDrag:t.resetDrag}))),Li=t=>{const{totalCells:e,fillRatio:r,direction:n,rows:o,cols:s}=t,i=Math.round(e*r),a=[];if(n==="ltr")for(let c=0;c<i;c++)a.push(c);else for(let c=0;c<o;c++)for(let l=0;l<s;l++){const d=c*s+l;a.length<i&&a.push(d)}return{filledCells:a,filledCount:i,actualRatio:i/e}},Gi=(t,e,r,n)=>{const o=[];for(let s=0;s<t;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*r,y:s*r})}return o},Ui=(t,e,r,n,o)=>{if(t===-1||e===-1||!r)return[];const s=Math.floor(t/o),i=t%o,a=Math.floor(e/o),c=e%o,l=[];switch(r){case"ltr":for(let d=i;d<=c;d++)l.push(s*o+d);break;case"rtl":for(let d=i;d>=c;d--)l.push(s*o+d);break;case"ttb":for(let d=s;d<=a;d++)l.push(d*o+i);break;case"btt":for(let d=s;d>=a;d--)l.push(d*o+i);break}return l},Vi=(t,e)=>Math.max(0,Math.min(1,t.length/e)),Vr=t=>Math.max(0,Math.min(1,t)),hf=t=>`${Math.round(t*100)}%`;function yf(t,e,r,n,o){if(e&&e.length>0)for(let s=e.length-1;s>=0;s--){const i=e[s];if(i.cells.includes(t))return i.color}return r?n:o}const Ro=({value:t,defaultValue:e=0,mode:r="readonly",onChange:n,rows:o=10,cols:s=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:c="#f3f4f6",strokeColor:l="#d1d5db",shadingDirection:d="ltr",hasShadow:g=!0,className:p="",showNumbers:f=!1,highlightGroups:m,numberFontSize:h=10,numberColor:y="#374151"})=>{const{internalValue:b,setInternalValue:_}=Pi(),{isDragging:w,dragState:C,startDrag:v,updateDrag:k,endDrag:S}=Di(),E=t!==void 0,N=E?Vr(t):b,[I,Y]=x.useState(!1);!I&&!E&&(_(Vr(e)),Y(!0));const K=x.useMemo(()=>{const Z={totalCells:o*s,fillRatio:N,direction:d,rows:o,cols:s};return Li(Z).filledCells},[N,o,s,d]),L=x.useMemo(()=>Gi(o,s,i,K),[o,s,i,K]),O=x.useMemo(()=>!w||C.startIndex===-1||C.currentIndex===-1?[]:Ui(C.startIndex,C.currentIndex,C.direction,o,s),[w,C,o,s]),U=x.useCallback(G=>{if(r!=="edit")return;const Z=Vr((G+1)/(o*s));E||_(Z),n?.(Z)},[r,o,s,E,n,_]),T=x.useCallback(G=>{r==="edit"&&v(G)},[r,v]),q=x.useCallback(G=>{r!=="edit"||!w||k(G)},[r,w,k]),$=x.useCallback(()=>{if(!(r!=="edit"||!w)){if(O.length>0){const G=Vi(O,o*s);E||_(G),n?.(G)}S()}},[r,w,O,o,s,E,n,_,S]),ee=s*i,de=o*i,re=["hundred-chart-container",`hundred-chart--${r}`,g&&"hundred-chart--has-shadow",p].filter(Boolean).join(" "),te=Math.round(N*100);return u.jsx("div",{className:re,"data-testid":"hundred-chart-container",children:u.jsx("svg",{width:ee,height:de,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${te}% 已填充`,children:L.map(G=>{const Z=K.includes(G.index),ge=O.includes(G.index),Ce=Z||ge,ce=G.index+1,ft=yf(ce,m,Ce,a,c);return u.jsxs("g",{"data-testid":"hundred-chart-cell-group",className:"hundred-chart-cell-group",children:[u.jsx("rect",{x:G.x,y:G.y,width:i,height:i,fill:ft,stroke:l,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":Z,"data-drag":ge,"aria-label":`第${G.row+1}行第${G.col+1}列,数字${ce},${Ce?"已填充":"未填充"}`,tabIndex:r==="edit"?0:-1,onClick:()=>U(G.index),onMouseDown:()=>T(G.index),onMouseEnter:()=>q(G.index),onMouseUp:$,onKeyDown:st=>{r==="edit"&&st.key==="Enter"&&U(G.index)}}),f&&u.jsx("text",{x:G.x+i/2,y:G.y+i/2,textAnchor:"middle",dominantBaseline:"middle",fontSize:h,fill:y,className:"hundred-chart-cell-text",pointerEvents:"none","aria-hidden":"true",children:ce})]},G.index)})})})},bf=x.createContext(void 0),zi=(t,e)=>x.useMemo(()=>{const r=t.scenes?.[e];return{...t,content:r?.content||t.content,layout:r?.layout||t.layout,renderer:r?.renderer||t.renderer}},[t,e]),Bi=({children:t,padding:e,shadow:r=!0,border:n=!0,theme:o="light",className:s=""})=>{const i=o==="dark"?"theme-dark":"",a=r?"with-shadow":"",c=n?"with-border":"",l=e?{"--mc-card-padding":e}:void 0;return u.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${c} ${s}`,style:l,"data-testid":"mathcard-v2-container",children:t})},Hi=({children:t,columns:e,gap:r,responsive:n=!0,className:o=""})=>{const s={"--grid-columns":e,"--grid-gap":r},i=n?"mathcard-v2-grid-responsive":"";return u.jsx("div",{style:s,className:`mathcard-v2-grid ${i} ${o}`,"data-testid":"grid-layout",children:t})},qi=({children:t,direction:e="vertical",gap:r,wrap:n=!1,className:o=""})=>{const s={"--flow-gap":r,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":n?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=n?"wrap":"";return u.jsx("div",{style:s,className:`mathcard-v2-flow ${i} ${a} ${o}`,"data-testid":"flow-layout",children:t})},Wi=({content:t,style:e={},onInteraction:r,className:n=""})=>u.jsx("div",{className:`mathcard-v2-text ${n}`,style:e,onClick:()=>r?.({type:"click",content:t}),"data-testid":"text-content",children:t}),Yi=({parts:t,children:e,displayMode:r=!1,style:n={},className:o=""})=>u.jsx("div",{className:`mathcard-v2-formula ${o}`,style:n,"data-testid":"equation-render",children:u.jsx(Kt,{parts:t,children:e,displayMode:r})});class xf extends x.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,r){console.error("MathGraph Error:",e,r.componentStack)}render(){return this.state.hasError?u.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[u.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),u.jsx("p",{className:"text-red-700",children:this.state.error?.message}),u.jsx("button",{className:"mt-2 px-3 py-1 bg-red-100 hover:bg-red-200 rounded",onClick:()=>this.setState({hasError:!1}),children:"重试"})]}):this.props.children}}function wf(t){if(typeof t!="string")throw new Error(`parseFunctionString expects a string, got ${typeof t}`);const e=t.trim(),r=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(r){const n=(r[3]||r[4]||"").trim();if(!n)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return vf(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 vf(t){const e=t.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 r=/^progress\s*\*\s*([0-9.]+)$/,n=e.match(r);if(n){const c=parseFloat(n[1]);return l=>l*c}const o=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,s=e.match(o);if(s){const c=parseFloat(s[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()),_f(l)})}function _f(t){const e=t.replace(/\s/g,"");function r(n){for(;n.includes("(");){const a=n.match(/\(([^()]+)\)/);if(!a)break;const c=r(a[1]);n=n.replace(a[0],c.toString())}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()),r(n)}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()),r(n)}const i=parseFloat(n);if(isNaN(i))throw new Error(`Invalid expression: ${n}`);return i}return r(e)}function Sf(t){return typeof t=="string"&&(t.includes("=>")||t.includes("progress"))}function $e(t,e=0){return typeof t=="function"?t(e):t}function Mn(t,e,r){switch(t.params.type){case"translate":{const n=t.params,o=typeof n.x=="function"&&r?function(){const i=r.Value();return n.x(i)}:$e(n.x,e),s=typeof n.y=="function"&&r?function(){const i=r.Value();return n.y(i)}:$e(n.y,e);return[o,s]}case"rotate":{const n=t.params,o=n.center||[0,0];return typeof n.angle=="function"&&r?[function(){const i=r.Value();return n.angle(i)},o[0],o[1]]:[$e(n.angle,e),o[0],o[1]]}case"scale":{const n=t.params,o=typeof n.scaleX=="function"&&r?function(){const i=r.Value();return n.scaleX(i)}:$e(n.scaleX,e),s=typeof n.scaleY=="function"&&r?function(){const i=r.Value();return n.scaleY(i)}:$e(n.scaleY,e);return[o,s]}case"reflect":{const n=t.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:
11
+ 更多详情请参考组件库文档。`))},[]);const i=b.useMemo(()=>t.length===0?[]:t.map((u,g)=>{try{return Ul.renderToString(u,{displayMode:o,throwOnError:!1,errorColor:"#ff0000"})}catch(m){return console.error(`KaTeX rendering error in part ${g}:`,m),'<span style="color: red;">KaTeX Error</span>'}}),[t,o]);if(t.length===0)return null;const a=o?"div":"span",c=b.Children.toArray(e),l=[];return i.forEach((u,g)=>{l.push(d.jsx("span",{dangerouslySetInnerHTML:{__html:u},style:{display:"inline-block"}},`part-${g}`)),g<c.length&&g<t.length-1&&l.push(d.jsx("span",{style:{display:"inline-block"},children:c[g]},`slot-${g}`))}),d.jsx(a,{className:`equation-render ${s}`.trim(),style:{fontSize:r,color:n,display:"flex",alignItems:"center",gap:"0.3em",...o?{justifyContent:"center",margin:"1em 0"}:{}},children:l})});function cr(t){return t.type!=="composite"}function dr(t){return t.type==="composite"}function Tf(){return{type:"translation",config:{direction:"horizontal",distance:0}}}function Ht(t){if(!t)return Tf();if(t.type==="composite"&&Array.isArray(t.transforms))return{type:"composite",transforms:t.transforms.map(s=>Ht(s)),executionMode:t.executionMode||"sequential"};if(t.type&&t.config)return t;const e=t;if(e.type==="composite"&&Array.isArray(e.composite))return{type:"composite",transforms:e.composite.map((s,i)=>Ht(s)),executionMode:"sequential"};let r,n="translation";return e.rotation?(n="rotation",r=e.rotation):e.translation?(n="translation",r=e.translation):e.scale?(n="scale",r=e.scale):(n="translation",r={direction:"horizontal",distance:0}),{type:n,config:r,targetGroup:e.targetGroup}}const fn=t=>{if(t.length===0)return[0,0];let e=0,r=0;for(const[n,o]of t)e+=n,r+=o;return[e/t.length,r/t.length]},ro=t=>{if(cr(t)){const e=t;if(!e.config)return`${e.type}变换缺少配置`;switch(e.type){case"translation":if(e.config.distance<=0)return"平移距离必须大于0";break;case"rotation":if(e.config.startAngle===e.config.endAngle)return"旋转起始角度和结束角度不能相同";break;case"scale":const r=e.config;if(r.startScale<=0||r.endScale<=0)return"缩放比例必须大于0";break}return null}if(dr(t)){const e=t;if(!e.transforms)return"复合变换缺少transforms字段";for(const r of e.transforms){const n=ro(r);if(n)return`复合变换子配置错误: ${n}`}return null}return"未知的变换配置类型"},$f=(t,e,r,n)=>{if(t<=0)return"底边长度必须大于0";if(e<=0)return"高度必须大于0";if(r.animated.length===0)return"至少需要一个动画图形";const o=ro(n);if(o)return`全局变换配置错误: ${o}`;for(const s of r.animated)if(s.transform){const i=Ht(s.transform),a=ro(i);if(a)return`形状"${s.metadata?.id||"未知"}"专属变换配置错误: ${a}`}for(const s of[...r.static,...r.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,c]=i;if(typeof a!="number"||typeof c!="number"||!isFinite(a)||!isFinite(c))return`形状"${s.metadata?.id||"未知"}"顶点坐标无效`}}return null},kf=t=>{const{base:e,height:r,shapes:n,transform:o}=t,s=Ht(o),i=$f(e,r,n,s);return i?{code:"INVALID_CONFIG",message:i,timestamp:new Date().toISOString()}:null},jf=t=>{if(t.slider){const{slider:e}=t;if(e.length<=0)return"滑块长度必须大于0";if(e.min!==void 0&&e.max!==void 0&&e.min>=e.max)return"滑块最小值必须小于最大值";if(e.step!==void 0&&e.step<=0)return"滑块步长必须大于0"}return null},If=t=>{if(!t)return null;if(t.boundingBox){const[e,r,n,o]=t.boundingBox;if(e>=n||r<=o)return"画板边界框配置无效:left < right 且 top > bottom"}return t.gridSize!==void 0&&t.gridSize<=0?"网格大小必须大于0":null},Mf=t=>{const e=kf({base:t.base,height:t.height,shapes:t.shapes,transform:t.transform});if(e)return e;const r=jf(t.animation);if(r)return{code:"INVALID_CONFIG",message:r,timestamp:new Date().toISOString()};const n=If(t.boardConfig);return n?{code:"INVALID_CONFIG",message:n,timestamp:new Date().toISOString()}:t.autoCompleteThreshold!==void 0&&(t.autoCompleteThreshold<0||t.autoCompleteThreshold>1)?{code:"INVALID_CONFIG",message:"自动完成阈值必须在0到1之间",timestamp:new Date().toISOString()}:null};class gn{validateNumber(e,r,n,o){if(typeof e!="number"||isNaN(e))return`${r}必须是有效的数字`;if(n!==void 0&&e<n)return`${r}不能小于${n}`;if(o!==void 0&&e>o)return`${r}不能大于${o}`}validateArray(e,r,n){if(!Array.isArray(e))return`${r}必须是数组`;if(n!==void 0&&e.length!==n)return`${r}必须是长度为${n}的数组`}validateString(e,r,n){if(typeof e!="string")return`${r}必须是字符串`;if(n!==void 0&&!n.includes(e))return`${r}必须是以下值之一: ${n.join(", ")}`}createValidationResult(e,r,n){return{isValid:e,errors:r?.filter(Boolean),warnings:n?.filter(Boolean)}}validateVertices(e){if(!Array.isArray(e)||e.length===0)return"顶点数组不能为空";for(let r=0;r<e.length;r++){const n=e[r],o=this.validateArray(n,`顶点[${r}]`,2);if(o)return o;const[s,i]=n,a=this.validateNumber(s,`顶点[${r}].x`),c=this.validateNumber(i,`顶点[${r}].y`);if(a||c)return`${a||c} (顶点[${r}])`}}}const Of=(t,e,r)=>{process.env.NODE_ENV==="development"&&console.log("🔧 [calculateTranslation] 调试信息:",{vertices:t,progress:e,config:r,distance:r.distance,distanceType:typeof r.distance,direction:r.direction,directionType:typeof r.direction,configType:typeof r,configKeys:Object.keys(r)});let n;r.direction==="horizontal"?n=[r.distance,0]:r.direction==="vertical"?n=[0,r.distance]:n=[r.direction[0]*r.distance,r.direction[1]*r.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:t[0],firstVertexTransformed:[t[0][0]+o,t[0][1]+s]}),t.map(([i,a])=>[i+o,a+s])},Ff=(t,e,r)=>{const n=r.center==="auto"?fn(t):r.center,[o,s]=n,i=r.endAngle-r.startAngle,a=r.direction==="clockwise"?-1:1,c=r.startAngle+i*e*a;return t.map(([l,u])=>{const g=l-o,m=u-s,f=Math.cos(c),p=Math.sin(c);return[o+g*f-m*p,s+g*p+m*f]})},Pf=(t,e,r)=>{const n=r.center==="centroid"?fn(t):r.center,[o,s]=n,i=r.endScale-r.startScale,a=r.startScale+i*e;return t.map(([c,l])=>{const u=c-o,g=l-s;return[o+u*a,s+g*a]})},Df=(t,e=.95)=>t>=e;class Lf extends gn{type="translation";getDisplayName(){return"平移变换"}getDescription(){return"将图形沿着指定方向移动一定距离"}getDefaultConfig(){return{direction:"horizontal",distance:5,startOffset:0}}execute(e,r,n){return Of(e,r,n)}validate(e){const r=[],n=[];if(typeof e.direction=="string"){const s=this.validateString(e.direction,"direction",["horizontal","vertical"]);s&&r.push(s)}else if(Array.isArray(e.direction)){const s=this.validateArray(e.direction,"direction",2);if(s)r.push(s);else{const[i,a]=e.direction,c=this.validateNumber(i,"direction[0]"),l=this.validateNumber(a,"direction[1]");c&&r.push(c),l&&r.push(l)}}else r.push("direction必须是字符串或数组");const o=this.validateNumber(e.distance,"distance",0);if(o&&r.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(r.length===0,r,n)}getDirectionVector(e){return e.direction==="horizontal"?[1,0]:e.direction==="vertical"?[0,1]:e.direction}calculateMovementVector(e,r){const n=this.getDirectionVector(e),o=e.startOffset||0,s=Math.max(0,Math.min(1,r-o))/(1-o);return[n[0]*e.distance*s,n[1]*e.distance*s]}}class Gf extends gn{type="rotation";getDisplayName(){return"旋转变换"}getDescription(){return"将图形围绕指定中心旋转一定角度"}getDefaultConfig(){return{center:"auto",startAngle:0,endAngle:Math.PI,direction:"clockwise"}}execute(e,r,n){return Ff(e,r,n)}validate(e){const r=[],n=[];if(e.center!=="auto")if(Array.isArray(e.center)){const a=this.validateArray(e.center,"center",2);if(a)r.push(a);else{const[c,l]=e.center,u=this.validateNumber(c,"center[0]"),g=this.validateNumber(l,"center[1]");u&&r.push(u),g&&r.push(g)}}else r.push('center必须是"auto"或数组[x, y]');const o=this.validateNumber(e.startAngle,"startAngle");o&&r.push(o);const s=this.validateNumber(e.endAngle,"endAngle");if(s&&r.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&&r.push(i),this.createValidationResult(r.length===0,r,n)}_calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let r=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,c]=e[i];r=Math.min(r,a),n=Math.max(n,a),o=Math.min(o,c),s=Math.max(s,c)}return{minX:r,maxX:n,minY:o,maxY:s}}getActualCenter(e,r){return r.center==="auto"?fn(e):r.center}calculateCurrentAngle(e,r){const n=e.endAngle-e.startAngle,o=e.direction==="clockwise"?-1:1;return e.startAngle+n*r*o}}class Vf extends gn{type="scale";getDisplayName(){return"缩放变换"}getDescription(){return"将图形以指定中心进行缩放"}getDefaultConfig(){return{center:"centroid",startScale:1,endScale:2,uniform:!0}}execute(e,r,n){return Pf(e,r,n)}validate(e){const r=[],n=[];if(e.center!=="centroid")if(Array.isArray(e.center)){const i=this.validateArray(e.center,"center",2);if(i)r.push(i);else{const[a,c]=e.center,l=this.validateNumber(a,"center[0]"),u=this.validateNumber(c,"center[1]");l&&r.push(l),u&&r.push(u)}}else r.push('center必须是"centroid"或数组[x, y]');const o=this.validateNumber(e.startScale,"startScale",.01);o&&r.push(o);const s=this.validateNumber(e.endScale,"endScale",.01);if(s&&r.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"?r.push("uniform必须是布尔值"):e.uniform||n.push("非均匀缩放可能导致图形变形"),this.createValidationResult(r.length===0,r,n)}getActualCenter(e,r){return r.center==="centroid"?fn(e):r.center}calculateCurrentScale(e,r){const n=e.endScale-e.startScale;return e.startScale+n*r}calculateSizeChange(e,r,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,c=this.calculateCurrentScale(r,n),l=(r.uniform,c),u=s*l,g=i*l,m=u*g;return{widthChange:(u-s)/s,heightChange:(g-i)/i,areaChange:(m-a)/a}}calculateBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let r=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,c]=e[i];r=Math.min(r,a),n=Math.max(n,a),o=Math.min(o,c),s=Math.max(s,c)}return{minX:r,maxX:n,minY:o,maxY:s}}}function Cs(t){let e=t.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(`无效的十六进制颜色格式: ${t}`);const r=parseInt(e.substring(0,2),16),n=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16);if(isNaN(r)||isNaN(n)||isNaN(o))throw new Error(`无效的十六进制颜色值: ${t}`);return[r,n,o]}function zf(t,e,r){const n=a=>Math.max(0,Math.min(255,Math.round(a))),o=n(t).toString(16).padStart(2,"0"),s=n(e).toString(16).padStart(2,"0"),i=n(r).toString(16).padStart(2,"0");return`#${o}${s}${i}`.toUpperCase()}function no(t){const e=t.trim();if(e.startsWith("#"))return Cs(e);const r=e.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)$/i);if(r){const s=parseInt(r[1],10),i=parseInt(r[2],10),a=parseInt(r[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]:Cs(n[o]);throw new Error(`无法解析的颜色格式: ${t}`)}function tn(t){try{return no(t),!0}catch{return!1}}function Uf(t,e,r){if(r<=0)return t;if(r>=1)return e;try{const n=no(t),o=no(e),s=n[0]+(o[0]-n[0])*r,i=n[1]+(o[1]-n[1])*r,a=n[2]+(o[2]-n[2])*r;return zf(s,i,a)}catch(n){return console.warn("颜色插值失败,返回起始颜色:",n),t}}function Bi(t,e,r,n="linear"){let o=r;switch(n){case"ease-in":o=r*r;break;case"ease-out":o=1-(1-r)*(1-r);break;case"ease-in-out":o=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2;break;case"step":o=r>=1?1:0;break}return Uf(t,e,o)}class Bf extends gn{type="fillcolor_set";getDisplayName(){return"颜色变换"}getDescription(){return"将图形的填充颜色从起始颜色渐变到目标颜色"}getDefaultConfig(){return{targetColor:"#000000",startAt:0,endAt:1,easing:"linear",fromColor:void 0}}execute(e,r,n){return e}validate(e){const r=[],n=[];if(!e.targetColor||typeof e.targetColor!="string"?r.push("targetColor 是必需的且必须是字符串"):tn(e.targetColor)||r.push(`targetColor 格式无效: ${e.targetColor}`),e.fromColor!==void 0&&(typeof e.fromColor!="string"?r.push("fromColor 必须是字符串"):tn(e.fromColor)||r.push(`fromColor 格式无效: ${e.fromColor}`)),e.startAt!==void 0){const o=this.validateNumber(e.startAt,"startAt",0,1);o&&r.push(o)}if(e.endAt!==void 0){const o=this.validateNumber(e.endAt,"endAt",0,1);o&&r.push(o)}if(e.startAt!==void 0&&e.endAt!==void 0&&e.startAt>=e.endAt&&r.push("startAt 必须小于 endAt"),e.easing!==void 0){const o=this.validateString(e.easing,"easing",["linear","ease-in","ease-out","ease-in-out","step"]);o&&r.push(o)}return e.targetColor&&e.fromColor,this.createValidationResult(r.length===0,r,n)}calculateCurrentColor(e,r,n){const o=r.fromColor||n,s=r.targetColor,i=this.calculateEffectiveProgress(e,r);return Bi(o,s,i,r.easing)}calculateEffectiveProgress(e,r){const n=r.startAt??0,o=r.endAt??1;return e<=n?0:e>=o?1:(e-n)/(o-n)}isActive(e,r){const n=r.startAt??0,o=r.endAt??1;return e>=n&&e<=o}}class Hf{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[r,n]of this.executors)e[r]=n.getDisplayName();return e}validateConfig(e,r){const n=this.get(e);return n?n.validate(r):{isValid:!1,errors:[`不支持变换类型: ${e}`]}}executeTransform(e,r,n,o){const s=this.get(e);if(!s)return console.error(`不支持变换类型: ${e}`),r;const i=s.validate(o);return i.isValid?s.execute(r,n,o):(console.error("配置验证失败:",i.errors),r)}executeTransforms(e,r,n){let o=r;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 _t=null;function Hi(){return _t||(_t=new Hf,_t.register(new Lf),_t.register(new Gf),_t.register(new Vf),_t.register(new Bf)),_t}class oo{static matchesShape(e,r,n){if(!r)return!n||this.extractGroupId(e)===n;if("targetGroup"in r&&r.targetGroup)return this.matchesSimpleGroup(e,r.targetGroup,r.metadataField);if("pattern"in r){if(r.strategy==="any")return this.matchesWithConfig(e,r);if(r.pattern)return this.matchesWithConfig(e,r)}return!1}static matchesSimpleGroup(e,r,n){const o=this.extractGroupId(e,n);if(!o)return!1;if(r.includes("*")){const s=r.replace(/\*/g,".*");return new RegExp(`^${s}$`).test(o)}return o===r}static matchesWithConfig(e,r){const n=this.extractGroupId(e,r.metadataField);if(!n)return!1;const o=r.pattern,s=r.strategy||"exact",i=r.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(u=>this.matchesSimpleGroup(e,u,r.metadataField));case"any":return!0;default:return!1}}static extractGroupId(e,r="rotationGroup"){if(!e)return;const n=r.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 r=[],n=[];if(!e||typeof e!="object")return r.push("配置必须是对象"),{isValid:!1,errors:r,warnings:n};switch(e.pattern||r.push("pattern不能为空"),e.strategy){case"exact":case"wildcard":typeof e.pattern!="string"&&r.push(`${e.strategy}策略的pattern必须是字符串`);break;case"regex":!(e.pattern instanceof RegExp)&&typeof e.pattern!="string"&&r.push("regex策略的pattern必须是RegExp对象或字符串");break;case"multiple":!Array.isArray(e.pattern)&&typeof e.pattern!="string"&&r.push("multiple策略的pattern必须是数组或逗号分隔的字符串");break;case"any":break;default:r.push(`未知的匹配策略: ${e.strategy}`)}return e.metadataField!==void 0&&typeof e.metadataField!="string"&&r.push("metadataField必须是字符串"),e.caseSensitive!==void 0&&typeof e.caseSensitive!="boolean"&&r.push("caseSensitive必须是布尔值"),e.strategy==="regex"&&n.push("正则表达式匹配可能影响性能,请确保模式简单高效"),{isValid:r.length===0,errors:r,warnings:n}}static convertToGroupMatchConfig(e,r){if(!e)return;const n=e.includes("*")?"wildcard":"exact";return{pattern:e,strategy:n,metadataField:r}}}function qf(t,e,r){return!e&&!r?t.filter(n=>!n.targetGroup&&!n.groupMatch):t.filter(n=>{if(n.groupMatch&&r)return oo.matchesShape(r,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 Wf{registry;constructor(e){this.registry=e||this.getDefaultRegistry()}execute(e,r,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,r,a);case"parallel":return this.executeInParallel(e,r,a);default:return console.warn(`未知的执行模式: ${n.executionMode},使用顺序执行`),this.executeSequentially(e,r,a)}}validate(e){const r=[],n=[];if(!e||e.type!=="composite")return r.push("配置必须是复合变换类型"),this.createValidationResult(!1,r,n);if(!Array.isArray(e.transforms))return r.push("transforms必须是数组"),this.createValidationResult(!1,r,n);e.transforms.length===0&&n.push("复合变换没有子变换,这可能表示配置为空"),e.executionMode!=="sequential"&&e.executionMode!=="parallel"&&r.push('executionMode必须是"sequential"或"parallel"');for(let i=0;i<e.transforms.length;i++){const a=e.transforms[i],c=this.validateSingleTransform(a,i);c&&r.push(c)}const o=e.transforms.map(i=>i.id).filter(Boolean),s=new Set(o);return o.length!==s.size&&n.push("发现重复的变换ID,可能导致不可预测的行为"),this.createValidationResult(r.length===0,r,n)}getTransformInfo(e){const r=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:r,groups:n,executionMode:e.executionMode}}filterTransformsByGroup(e,r,n){return qf(e,r,n)}getTransformsForGroup(e,r,n){return this.filterTransformsByGroup(e.transforms,r,n)}isEmpty(e){return e.transforms.length===0}executeSequentially(e,r,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,r,s.config)}return o}executeInParallel(e,r,n){if(n.length===0)return e;if(n.length===1)return this.executeSequentially(e,r,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 c=i.execute(e,r,s.config);o.push(c)}return o.length===0?e:this.calculateAverageVertices(o)}calculateAverageVertices(e){if(e.length===0)return[];const r=e[0].length;for(const o of e)if(o.length!==r)return console.error("顶点数组长度不一致,无法计算平均值"),e[0];const n=[];for(let o=0;o<r;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,r){if(!e||typeof e!="object")return`变换[${r}]必须是对象`;if(!e.type)return`变换[${r}]缺少type字段`;if(!e.config)return`变换[${r}]缺少config字段`;const n=this.registry.get(e.type);if(!n)return`变换[${r}]不支持的变换类型: ${e.type}`;const o=n.validate(e.config);if(!o.isValid)return`变换[${r}]配置验证失败: ${o.errors?.join(", ")}`}createValidationResult(e,r,n){return{isValid:e,errors:r?.filter(Boolean),warnings:n?.filter(Boolean)}}getDefaultRegistry(){return Hi()}}class Yf{registry;compositor;constructor(e){this.registry=e||this.getDefaultRegistry(),this.compositor=new Wf(this.registry)}executeShapeTransform(e,r,n){const o=this.getEffectiveTransform(e,n);return o?this.executeTransform(e.vertices,r,o,e.metadata):e.vertices}executeTransform(e,r,n,o){if(!n)return e;const s=oo.extractGroupId(o,"rotationGroup");return cr(n)?this.executeSingleTransform(e,r,n,o,s):dr(n)?this.compositor.execute(e,r,n,s,o):(console.error("未知的变换类型:",n),e)}getEffectiveTransform(e,r){return e.transform?e.transform:r}getTransformInfo(e){return e?cr(e)?{count:1,types:[e.type],groups:e.targetGroup?[e.targetGroup]:[],hasTransform:!0}:dr(e)?{...this.compositor.getTransformInfo(e),hasTransform:!0}:{count:0,types:[],groups:[],hasTransform:!1}:{count:0,types:[],groups:[],hasTransform:!1}}validateTransform(e){return e?cr(e)?this.validateSingleTransform(e):dr(e)?this.compositor.validate(e):{isValid:!1,errors:["未知的变换类型"],warnings:[]}:{isValid:!0,errors:[],warnings:["变换配置为空"]}}isEmptyTransform(e){return e?cr(e)?!1:dr(e)?this.compositor.isEmpty(e):!0:!0}executeBatchTransform(e,r,n){return e.map(o=>({...o,vertices:this.executeShapeTransform(o,r,n)}))}executeSingleTransform(e,r,n,o,s){if(!oo.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 c=a.validate(n.config);return c.isValid?a.execute(e,r,n.config):(console.error("变换配置验证失败:",c.errors),e)}validateSingleTransform(e){const r=this.registry.get(e.type);return r?r.validate(e.config):{isValid:!1,errors:[`不支持变换类型: ${e.type}`],warnings:[]}}getDefaultRegistry(){return Hi()}}const Kf=()=>{const t=b.useRef(null),e=b.useCallback((o,s,i=50)=>{t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{s&&s(o)},i)},[]),r=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(()=>(t.current&&(clearTimeout(t.current),t.current=null),0),[]);return{handleProgressChange:e,shouldAutoComplete:Df,getProgressLabel:r,resetProgress:n}},Xf=()=>{const t=b.useCallback((r,n,o=.05)=>{let s=n;switch(r.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 r.preventDefault(),s},[]),e=b.useCallback(()=>["键盘导航说明:","←/→ 或 ↑/↓: 调整进度 (±5%)","Home/End: 跳转到开始/结束","Page Up/Down: 快速调整 (±10%)","空格/回车: 切换完成状态","Esc: 重置进度"].join(`
12
+ `),[]);return{handleKeyDown:t,getNavigationInstructions:e}},Ss=Us.JSXGraph,Jf=t=>{const{base:e,height:r,unit:n,layoutDensity:o="default",boardHeight:s,shapes:i,transform:a,animation:c,boardConfig:l={},theme:u="light",className:g="",enableRigidityVerification:m=!1,enableKeyboardNavigation:f=!0,autoCompleteThreshold:p=.95,boardWidth:h,onTransformStart:y,onTransformChange:x,onTransformComplete:v,onError:w}=t,[S,C]=b.useState(0),[E,_]=b.useState(null),[A,T]=b.useState(0),[j,U]=b.useState(null),[z,O]=b.useState({width:800,height:560}),M=b.useMemo(()=>new Yf,[]),F=b.useMemo(()=>Ht(a),[a]),$=b.useRef(null),B=b.useRef({}),k=b.useRef(null),{handleProgressChange:te,shouldAutoComplete:ue,resetProgress:ne}=Kf(),{handleKeyDown:re,getNavigationInstructions:V}=Xf();b.useEffect(()=>{const P=()=>{if(k.current){const{clientWidth:N}=k.current;if(N>0){const ie=l.boundingBox||[0,7,10,0],fe=ie[2]-ie[0],H=ie[1]-ie[3];let J;s?J=s:J=Math.round(N*(H/fe)),console.log("🎯 GeometryTransform 容器尺寸更新:",{boundingBox:ie,ratio:`${H}:${fe}`,containerWidth:N,calculatedHeight:J,isCustomHeight:!!s}),O({width:N,height:J})}}};P(),window.addEventListener("resize",P);const I=new ResizeObserver(P);return k.current&&I.observe(k.current),()=>{window.removeEventListener("resize",P),I.disconnect()}},[l.boundingBox,s]);const Q={width:h??`${z.width}px`,height:`${z.height}px`},me=b.useCallback((P,I)=>{console.log("🔍 computeDynamicAppearance called:",{shapeId:P.metadata?.id,shapeType:P.type,progress:I,hasMetadata:!!P.metadata,hasDynamicAppearance:!!P.metadata?.dynamicAppearance,dynamicAppearance:P.metadata?.dynamicAppearance});const N=P.metadata?.dynamicAppearance,ie=P.style||{};let fe;if(P.transform?.type==="fillcolor_set"&&P.transform.fillColorSet){const ge=P.transform.fillColorSet,{targetColor:ve,startAt:Re=0,endAt:Te=1,easing:Ve="linear",fromColor:Ze}=ge;if(tn(ve)&&(!Ze||tn(Ze))){let ze=I;I<Re?ze=0:I>Te?ze=1:ze=(I-Re)/(Te-Re);const rr=Ze||ie.fillColor||"#FFFFFF";fe=Bi(rr,ve,ze,Ve),console.log("🎨 fillcolor_set applied:",{shapeId:P.metadata?.id,progress:I,effectiveProgress:ze,startColor:rr,targetColor:ve,resultColor:fe})}else console.warn("⚠️ fillcolor_set: 颜色格式无效",{targetColor:ve,fromColor:Ze})}if(!N)return console.log("📝 No dynamicAppearance, returning base style"),fe?{...ie,fillColor:fe}:ie;const H=ge=>{if(!ge)return 1;const ve=ge.threshold??.5,Re=ge.startValue??0,Te=ge.endValue??1,Ve=ge.type??"step";if(Ve==="step")return I>=ve?Te:Re;if(Ve==="fade"){if(I<ve)return Re;{const Ze=Math.min((I-ve)/(1-ve),1);return Re+(Te-Re)*Ze}}return 1},J={...ie};let vt=!0;const Je=H(N.visibility),Ct=H(N.labelVisibility);if(console.log("📊 Visibility values:",{shapeId:P.metadata?.id,progress:I,visibilityValue:Je,labelVisibilityValue:Ct,hasVisibility:!!N.visibility,hasLabelVisibility:!!N.labelVisibility}),N.visibility&&(J.fillOpacity===void 0&&(J.fillOpacity=1),J.fillOpacity*=Je,Je===0&&(J.strokeWidth=0,console.log("👁️ Shape hidden, strokeWidth set to 0")),J.strokeColor,vt=Je>0,console.log("👁️ Shape visibility:",{shapeId:P.metadata?.id,visible:vt,visibilityValue:Je})),N.labelVisibility){const ge=Ct>0;J.labelVisible=ge,console.log("🏷️ Label visibility:",{shapeId:P.metadata?.id,labelVisible:ge,labelVisibilityValue:Ct,hasLabel:!!P.metadata?.label})}if(N.opacity){const ge=N.opacity,ve=ge.startAt??0,Re=ge.endAt??1,Te=ge.from??1,Ve=ge.to??1,Ze=ge.type??"linear";let ze=Te;if(I<ve)ze=Te;else if(I>Re)ze=Ve;else{const rr=(I-ve)/(Re-ve);ze=Te+(Ve-Te)*rr}J.fillOpacity=ze}if(fe)J.fillColor=fe,console.log("🎨 Using transform color instead of dynamicAppearance.color:",{shapeId:P.metadata?.id,transformColor:fe});else if(N.color){const ge=N.color,ve=ge.startAt??0,Re=ge.endAt??1,Te=ge.from??J.fillColor,Ve=ge.to??J.fillColor,Ze=ge.type??"gradient";if(Te&&Ve)if(I<ve)J.fillColor=Te;else if(I>Re)J.fillColor=Ve;else{const ze=(I-ve)/(Re-ve);Ze==="gradient"?J.fillColor=Ve:J.fillColor=ze>=.5?Ve:Te}}return J.visible=vt,J.labelVisible===void 0&&(J.labelVisible=!1),console.log("📋 Final computed style:",{shapeId:P.metadata?.id,visible:J.visible,labelVisible:J.labelVisible,fillOpacity:J.fillOpacity,strokeWidth:J.strokeWidth}),J},[]),Ee=b.useCallback((P,I,N=!1,ie=0)=>{console.log("🎨 createShape called:",{shapeId:I.metadata?.id,shapeType:I.type,isStatic:N,progress:ie,verticesLength:I.vertices?.length,hasMetadata:!!I.metadata,hasDynamicAppearance:!!I.metadata?.dynamicAppearance});const fe=I.type==="point"?1:2;if(!P||!I.vertices||I.vertices.length<fe)return console.warn(`⚠️ createShape: invalid board or vertices for ${I.type}`,{shapeId:I.metadata?.id,shapeType:I.type,verticesLength:I.vertices?.length,minVertices:fe}),null;const H=me(I,ie);let J;switch(I.type){case"triangle":case"rectangle":case"parallelogram":case"trapezoid":case"polygon":const vt=H.labelVisible!==void 0?H.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,Je=I.metadata?.label||I.metadata?.id||"";J=P.create("polygon",I.vertices,{name:Je,fillColor:H.fillColor!==void 0?H.fillColor:N?"#8ec5fc":"#6a5acd",fillOpacity:H.fillOpacity!==void 0?H.fillOpacity:N?.3:.7,strokeColor:H.strokeColor!==void 0?H.strokeColor:N?"#0074d9":"#4b0082",strokeWidth:H.strokeWidth!==void 0?H.strokeWidth:N?1:2,dash:H.dashStyle!==void 0?H.dashStyle:0,fixed:N,highlight:!N,withLabel:vt,visible:H.visible!==void 0?H.visible:!0});break;case"circle":if(I.vertices.length>=2){const[Ct,ge]=I.vertices,ve=H.labelVisible!==void 0?H.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,Re=I.metadata?.label||I.metadata?.id||"";J=P.create("circle",[Ct,ge],{name:Re,fillColor:H.fillColor!==void 0?H.fillColor:N?"#8ec5fc":"#6a5acd",fillOpacity:H.fillOpacity!==void 0?H.fillOpacity:N?.3:.7,strokeColor:H.strokeColor!==void 0?H.strokeColor:N?"#0074d9":"#4b0082",strokeWidth:H.strokeWidth!==void 0?H.strokeWidth:N?1:2,dash:H.dashStyle!==void 0?H.dashStyle:0,fixed:N,highlight:!N,withLabel:ve})}break;case"point":if(I.vertices.length>=1){const[Ct,ge]=I.vertices[0],ve=H.labelVisible!==void 0?H.labelVisible:I.style?.labelVisible!==void 0?I.style.labelVisible:!1,Re=I.metadata?.label||I.metadata?.id||"";J=P.create("point",[Ct,ge],{name:Re,withLabel:ve,fixed:N,size:4,strokeColor:H.strokeColor!==void 0?H.strokeColor:N?"#0074d9":"#4b0082",fillColor:H.fillColor!==void 0?H.fillColor:N?"#8ec5fc":"#6a5acd",visible:H.visible!==void 0?H.visible:!0,highlight:!N})}break;default:return console.warn(`Unsupported shape type: ${I.type}`),null}return console.log("✅ createShape finished:",{shapeId:I.metadata?.id,elementType:J?.type,elementName:J?.name,fillOpacity:J?.getAttribute?.("fillOpacity"),strokeWidth:J?.getAttribute?.("strokeWidth"),labelVisible:H.labelVisible,hasLabel:!!I.metadata?.label,withLabel:!!I.metadata?.label&&H.labelVisible}),J},[me]);b.useEffect(()=>{if(!(e>0&&r>0&&i?.animated?.length>0)){console.log("🔍 GeometryTransform: 数据未就绪,跳过验证",{base:e,height:r,shapesAnimatedLength:i?.animated?.length,isBaseValid:e>0,isHeightValid:r>0,hasAnimatedShapes:i?.animated?.length>0});return}console.log("🔍 GeometryTransform: 验证配置,props =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig});const I=Mf(t);console.log("🔍 GeometryTransform: 验证结果 =",I),_(I),I&&w&&w(I)},[e,r,i,a,c,l,w,t]),b.useEffect(()=>{if($.current){try{const P=l.boundingBox||[0,7,10,0],I=u==="dark";console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",l.boundingBox),console.warn(" - Container dimensions:",z.width,"x",z.height),console.warn(" - Container actual dimensions:",$.current.clientWidth,"x",$.current.clientHeight);const N=Ss.initBoard($.current,{boundingbox:P,keepaspectratio:l.keepAspectRatio??!0,showCopyright:!1,showNavigation:!1,axis:l.showAxis??!0,grid:l.showGrid??!0,pan:{enabled:!1},zoom:{enabled:!1}}),ie=l.axisColor||(I?"#ffffff":"#000000"),fe=l.gridColor||(I?"#444444":"#dddddd");N.defaultAxes?.x&&N.defaultAxes.x.setAttribute({strokeColor:ie}),N.defaultAxes?.y&&N.defaultAxes.y.setAttribute({strokeColor:ie}),N.defaultGrid&&N.defaultGrid.setAttribute({strokeColor:fe}),U(N)}catch(P){const I={code:"JSXGRAPH_ERROR",message:"JSXGraph 画板初始化失败",details:P,timestamp:new Date().toISOString()};_(I),w?.(I)}return()=>{if(j)try{Ss.freeBoard(j)}catch(P){P instanceof Error&&P.name!=="AbortError"&&console.warn("Board cleanup warning:",P)}}}},[z]),b.useEffect(()=>{if(j)try{j.suspendUpdate(),Object.values(B.current).forEach(P=>{if(P&&j.removeObject)try{j.removeObject(P)}catch{}}),B.current={},i.static.forEach((P,I)=>{const N=P.metadata?.id||`static-${I}`,ie=Ee(j,P,!0,0);ie&&(B.current[N]=ie)}),i.animated.forEach((P,I)=>{const N=P.metadata?.id||`animated-${I}`,ie=Ee(j,P,!1,0);ie&&(B.current[N]=ie)}),j.unsuspendUpdate(),y&&y()}catch(P){const I={code:"RENDER_ERROR",message:"图形渲染失败",details:P,timestamp:new Date().toISOString()};_(I),w?.(I)}},[j,i,e,r]),b.useEffect(()=>{if(j){j.suspendUpdate();try{i.animated.forEach((N,ie)=>{const fe=N.metadata?.id||`animated-${ie}`,H=B.current[fe];if(H){try{j.removeObject(H)}catch{}delete B.current[fe]}}),i.animated.forEach((N,ie)=>{const fe=N.metadata?.id||`animated-${ie}`,H=N.transform?{...N,transform:Ht(N.transform)}:N,J=M.executeShapeTransform(H,S,F),vt={...N,vertices:J,metadata:{...N.metadata,id:fe,transformSource:N.transform?"shape":"global"}},Je=Ee(j,vt,!1,S);Je&&(B.current[fe]=Je)});const P=c.progressIndicator?.stages||1,I=Math.min(Math.floor(S*P),P-1);T(I)}catch(P){if(P instanceof Error&&P.name==="AbortError")return;console.warn("Transform update failed:",P)}finally{try{j.unsuspendUpdate()}catch{}}}},[j,S,i,a,c,Ee,F,M]);const de=b.useCallback(P=>{const I=Array.isArray(P)?P[0]:P;C(I),te(I,N=>{x?.(N)}),ue(I,p)&&(C(1),v?.())},[x,v,p,te,ue]);b.useEffect(()=>{if(!f)return;const P=I=>{const N=re(I,S);N!==null&&N!==S&&de(N)};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[f,S,de,re]),b.useCallback(()=>{C(0),T(0),ne()},[ne]);const gt=b.useCallback(()=>{_(null),C(0),T(0),ne()},[ne]);return e>0&&r>0&&i?.animated?.length>0?E?d.jsx(X.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__error ${g}`,children:d.jsx(X.CardBody,{"data-testid":"card-body",children:d.jsxs("div",{className:"geometry-transform__error-message",role:"alert","aria-live":"assertive","aria-atomic":"true",children:[d.jsx("div",{className:"geometry-transform__error-icon","aria-hidden":"true",children:d.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),d.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),d.jsx("h3",{children:"几何变换演示加载失败"}),d.jsx("p",{children:E.message}),E.details&&d.jsxs("details",{className:"geometry-transform__error-details-wrapper",children:[d.jsx("summary",{children:"查看错误详情"}),d.jsx("pre",{className:"geometry-transform__error-details",children:JSON.stringify(E.details,null,2)})]}),d.jsx("div",{className:"geometry-transform__error-actions",children:d.jsx("button",{type:"button",className:"geometry-transform__retry-button",onClick:gt,"aria-label":"重试加载几何变换演示",children:"重试加载"})})]})})}):d.jsx(X.Card,{"data-testid":"card",className:`geometry-transform ${o==="compact"?"geometry-transform--compact":""} ${u==="dark"?"geometry-transform--dark":""} ${g}`,children:d.jsxs(X.CardBody,{"data-testid":"card-body",children:[d.jsxs("div",{ref:k,className:"geometry-transform__board-container",children:[d.jsx("div",{ref:$,id:"geometry-board",className:"geometry-transform__board",style:Q,"data-testid":"geometry-board",role:"application","aria-label":"几何变换演示画板","aria-describedby":"geometry-board-description"}),d.jsx("div",{id:"geometry-board-description",className:"sr-only",children:"交互式几何变换画板,显示几何图形及其变换过程。 使用滑块控制变换进度,支持键盘导航。"})]}),d.jsxs("div",{className:"geometry-transform__controls",children:[d.jsx("div",{className:"geometry-transform__slider-group",children:d.jsx(X.Slider,{id:"transform-slider","data-testid":"slider",value:S,onChange:de,minValue:0,maxValue:1,step:.01,size:"lg",color:"primary",className:"geometry-transform__slider",label:"变换进度",showTooltip:!1,formatOptions:{style:"percent"},"aria-label":"几何变换进度控制"})}),f&&d.jsx("div",{className:"geometry-transform__keyboard-hint",role:"note","aria-label":"键盘导航提示",children:d.jsxs("details",{children:[d.jsx("summary",{children:"键盘导航说明"}),d.jsx("pre",{className:"geometry-transform__keyboard-instructions",children:V()})]})})]})]})}):(console.log("🔍 GeometryTransform: 数据未就绪,显示加载状态",{base:e,height:r,shapesAnimatedLength:i?.animated?.length,error:E}),d.jsx(X.Card,{"data-testid":"card",className:`geometry-transform geometry-transform__loading ${g}`,children:d.jsx(X.CardBody,{"data-testid":"card-body",children:d.jsx("div",{className:"geometry-transform__loading-message",children:"正在加载几何变换演示..."})})}))},qi=b.memo(Jf,(t,e)=>{if(t.base!==e.base||t.height!==e.height||t.unit!==e.unit||t.theme!==e.theme||t.className!==e.className||t.enableRigidityVerification!==e.enableRigidityVerification||t.enableKeyboardNavigation!==e.enableKeyboardNavigation||t.autoCompleteThreshold!==e.autoCompleteThreshold||t.onTransformStart!==e.onTransformStart||t.onTransformChange!==e.onTransformChange||t.onTransformComplete!==e.onTransformComplete||t.onError!==e.onError)return!1;const r=JSON.stringify({shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig}),n=JSON.stringify({shapes:e.shapes,transform:e.transform,animation:e.animation,boardConfig:e.boardConfig});return r===n}),Ao=Yt.create((t,e)=>({internalValue:0,isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null},setInternalValue:r=>{t({internalValue:Math.max(0,Math.min(1,r))})},startDrag:r=>{t({isDragging:!0,dragState:{isDragging:!0,startIndex:r,currentIndex:r,direction:null}})},updateDrag:r=>{const{dragState:n}=e();let o=null;if(n.startIndex!==-1&&r!==-1){const s=Math.floor(n.startIndex/10),i=n.startIndex%10,a=Math.floor(r/10),c=r%10;a===s?o=c>i?"ltr":"rtl":c===i&&(o=a>s?"ttb":"btt")}t({dragState:{...n,currentIndex:r,direction:o}})},endDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})},resetDrag:()=>{t({isDragging:!1,dragState:{isDragging:!1,startIndex:-1,currentIndex:-1,direction:null}})}})),Wi=()=>Ao(Bs.useShallow(t=>({internalValue:t.internalValue,setInternalValue:t.setInternalValue}))),Yi=()=>Ao(Bs.useShallow(t=>({isDragging:t.isDragging,dragState:t.dragState,startDrag:t.startDrag,updateDrag:t.updateDrag,endDrag:t.endDrag,resetDrag:t.resetDrag}))),Ki=t=>{const{totalCells:e,fillRatio:r,direction:n,rows:o,cols:s}=t,i=Math.round(e*r),a=[];if(n==="ltr")for(let c=0;c<i;c++)a.push(c);else for(let c=0;c<o;c++)for(let l=0;l<s;l++){const u=c*s+l;a.length<i&&a.push(u)}return{filledCells:a,filledCount:i,actualRatio:i/e}},Xi=(t,e,r,n)=>{const o=[];for(let s=0;s<t;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*r,y:s*r})}return o},Ji=(t,e,r,n,o)=>{if(t===-1||e===-1||!r)return[];const s=Math.floor(t/o),i=t%o,a=Math.floor(e/o),c=e%o,l=[];switch(r){case"ltr":for(let u=i;u<=c;u++)l.push(s*o+u);break;case"rtl":for(let u=i;u>=c;u--)l.push(s*o+u);break;case"ttb":for(let u=s;u<=a;u++)l.push(u*o+i);break;case"btt":for(let u=s;u>=a;u--)l.push(u*o+i);break}return l},Zi=(t,e)=>Math.max(0,Math.min(1,t.length/e)),Hr=t=>Math.max(0,Math.min(1,t)),Zf=t=>`${Math.round(t*100)}%`;function Qf(t,e,r,n,o){if(e&&e.length>0)for(let s=e.length-1;s>=0;s--){const i=e[s];if(i.cells.includes(t))return i.color}return r?n:o}const Eo=({value:t,defaultValue:e=0,mode:r="readonly",onChange:n,rows:o=10,cols:s=10,cellSize:i=12,fillColor:a="#3b82f6",baseColor:c="#f3f4f6",strokeColor:l="#d1d5db",shadingDirection:u="ltr",hasShadow:g=!0,className:m="",showNumbers:f=!1,highlightGroups:p,numberFontSize:h=10,numberColor:y="#374151"})=>{const{internalValue:x,setInternalValue:v}=Wi(),{isDragging:w,dragState:S,startDrag:C,updateDrag:E,endDrag:_}=Yi(),A=t!==void 0,T=A?Hr(t):x,[j,U]=b.useState(!1);!j&&!A&&(v(Hr(e)),U(!0));const z=b.useMemo(()=>{const Q={totalCells:o*s,fillRatio:T,direction:u,rows:o,cols:s};return Ki(Q).filledCells},[T,o,s,u]),O=b.useMemo(()=>Xi(o,s,i,z),[o,s,i,z]),M=b.useMemo(()=>!w||S.startIndex===-1||S.currentIndex===-1?[]:Ji(S.startIndex,S.currentIndex,S.direction,o,s),[w,S,o,s]),F=b.useCallback(V=>{if(r!=="edit")return;const Q=Hr((V+1)/(o*s));A||v(Q),n?.(Q)},[r,o,s,A,n,v]),$=b.useCallback(V=>{r==="edit"&&C(V)},[r,C]),B=b.useCallback(V=>{r!=="edit"||!w||E(V)},[r,w,E]),k=b.useCallback(()=>{if(!(r!=="edit"||!w)){if(M.length>0){const V=Zi(M,o*s);A||v(V),n?.(V)}_()}},[r,w,M,o,s,A,n,v,_]),te=s*i,ue=o*i,ne=["hundred-chart-container",`hundred-chart--${r}`,g&&"hundred-chart--has-shadow",m].filter(Boolean).join(" "),re=Math.round(T*100);return d.jsx("div",{className:ne,"data-testid":"hundred-chart-container",children:d.jsx("svg",{width:te,height:ue,className:"hundred-chart-svg","data-testid":"hundred-chart-svg",role:"img","aria-label":`百格图 - ${re}% 已填充`,children:O.map(V=>{const Q=z.includes(V.index),me=M.includes(V.index),Ee=Q||me,de=V.index+1,gt=Qf(de,p,Ee,a,c);return d.jsxs("g",{"data-testid":"hundred-chart-cell-group",className:"hundred-chart-cell-group",children:[d.jsx("rect",{x:V.x,y:V.y,width:i,height:i,fill:gt,stroke:l,strokeWidth:1,className:"hundred-chart-cell","data-testid":"hundred-chart-cell","data-filled":Q,"data-drag":me,"aria-label":`第${V.row+1}行第${V.col+1}列,数字${de},${Ee?"已填充":"未填充"}`,tabIndex:r==="edit"?0:-1,onClick:()=>F(V.index),onMouseDown:()=>$(V.index),onMouseEnter:()=>B(V.index),onMouseUp:k,onKeyDown:it=>{r==="edit"&&it.key==="Enter"&&F(V.index)}}),f&&d.jsx("text",{x:V.x+i/2,y:V.y+i/2,textAnchor:"middle",dominantBaseline:"middle",fontSize:h,fill:y,className:"hundred-chart-cell-text",pointerEvents:"none","aria-hidden":"true",children:de})]},V.index)})})})},eg=b.createContext(void 0),Qi=(t,e)=>b.useMemo(()=>{const r=t.scenes?.[e];return{...t,content:r?.content||t.content,layout:r?.layout||t.layout,renderer:r?.renderer||t.renderer}},[t,e]),ea=({children:t,padding:e,shadow:r=!0,border:n=!0,theme:o="light",className:s=""})=>{const i=o==="dark"?"theme-dark":"",a=r?"with-shadow":"",c=n?"with-border":"",l=e?{"--mc-card-padding":e}:void 0;return d.jsx("div",{className:`mathcard-v2-card ${i} ${a} ${c} ${s}`,style:l,"data-testid":"mathcard-v2-container",children:t})},ta=({children:t,columns:e,gap:r,responsive:n=!0,className:o=""})=>{const s={"--grid-columns":e,"--grid-gap":r},i=n?"mathcard-v2-grid-responsive":"";return d.jsx("div",{style:s,className:`mathcard-v2-grid ${i} ${o}`,"data-testid":"grid-layout",children:t})},ra=({children:t,direction:e="vertical",gap:r,wrap:n=!1,className:o=""})=>{const s={"--flow-gap":r,"--flow-direction":e==="horizontal"?"row":"column","--flow-wrap":n?"wrap":"nowrap"},i=e==="horizontal"?"horizontal":"",a=n?"wrap":"";return d.jsx("div",{style:s,className:`mathcard-v2-flow ${i} ${a} ${o}`,"data-testid":"flow-layout",children:t})},na=({content:t,style:e={},onInteraction:r,className:n=""})=>d.jsx("div",{className:`mathcard-v2-text ${n}`,style:e,onClick:()=>r?.({type:"click",content:t}),"data-testid":"text-content",children:t}),oa=({parts:t,children:e,displayMode:r=!1,style:n={},className:o=""})=>d.jsx("div",{className:`mathcard-v2-formula ${o}`,style:n,"data-testid":"equation-render",children:d.jsx(Zt,{parts:t,children:e,displayMode:r})});class tg extends b.Component{state={hasError:!1,error:null};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,r){console.error("MathGraph Error:",e,r.componentStack)}render(){return this.state.hasError?d.jsxs("div",{className:"border border-red-200 rounded-lg p-4 bg-red-50",children:[d.jsx("h3",{className:"font-bold text-red-800",children:"绘图组件加载失败"}),d.jsx("p",{className:"text-red-700",children:this.state.error?.message}),d.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 rg(t){if(typeof t!="string")throw new Error(`parseFunctionString expects a string, got ${typeof t}`);const e=t.trim(),r=e.match(/^(?:\(\s*\)\s*=\>|\(\s*([^,)]+)\s*\)\s*=\>|([^=]+)\s*=\>)\s*(?:\{?\s*return\s+([^;]+);?\s*\}?|(.+))$/);if(r){const n=(r[3]||r[4]||"").trim();if(!n)throw new Error(`Invalid function string: no expression found in "${e}"`);try{return ng(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 ng(t){const e=t.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 r=/^progress\s*\*\s*([0-9.]+)$/,n=e.match(r);if(n){const c=parseFloat(n[1]);return l=>l*c}const o=/^progress\s*\*\s*Math\.PI\s*\*\s*([0-9.]+)$/,s=e.match(o);if(s){const c=parseFloat(s[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()),og(l)})}function og(t){const e=t.replace(/\s/g,"");function r(n){for(;n.includes("(");){const a=n.match(/\(([^()]+)\)/);if(!a)break;const c=r(a[1]);n=n.replace(a[0],c.toString())}const o=n.match(/(-?\d+\.?\d*)([*/])(-?\d+\.?\d*)/);if(o){const a=parseFloat(o[1]),c=o[2],l=parseFloat(o[3]),u=c==="*"?a*l:a/l;return n=n.replace(o[0],u.toString()),r(n)}const s=n.match(/(-?\d+\.?\d*)([+\-])(-?\d+\.?\d*)/);if(s){const a=parseFloat(s[1]),c=s[2],l=parseFloat(s[3]),u=c==="+"?a+l:a-l;return n=n.replace(s[0],u.toString()),r(n)}const i=parseFloat(n);if(isNaN(i))throw new Error(`Invalid expression: ${n}`);return i}return r(e)}function sg(t){return typeof t=="string"&&(t.includes("=>")||t.includes("progress"))}function ke(t,e=0){return typeof t=="function"?t(e):t}function Fn(t,e,r){switch(t.params.type){case"translate":{const n=t.params,o=typeof n.x=="function"&&r?function(){const i=r.Value();return n.x(i)}:ke(n.x,e),s=typeof n.y=="function"&&r?function(){const i=r.Value();return n.y(i)}:ke(n.y,e);return[o,s]}case"rotate":{const n=t.params,o=n.center||[0,0];return typeof n.angle=="function"&&r?[function(){const i=r.Value();return n.angle(i)},o[0],o[1]]:[ke(n.angle,e),o[0],o[1]]}case"scale":{const n=t.params,o=typeof n.scaleX=="function"&&r?function(){const i=r.Value();return n.scaleX(i)}:ke(n.scaleX,e),s=typeof n.scaleY=="function"&&r?function(){const i=r.Value();return n.scaleY(i)}:ke(n.scaleY,e);return[o,s]}case"reflect":{const n=t.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:
13
13
  1. line ID (string)
14
14
  2. point1 + point2 IDs
15
15
  3. p1 + p2 coordinates
16
- Received: ${JSON.stringify(n)}`)}case"shear":{const n=t.params,o=$e(n.shearX,e),s=$e(n.shearY,e);return[o,s]}case"generic":{const n=t.params;return[$e(n.a,e),$e(n.b,e),$e(n.c,e),$e(n.d,e),$e(n.e,e),$e(n.f,e),$e(n.g,e),$e(n.h,e),$e(n.i,e)]}case"matrix":{const n=t.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: ${t.params.type}`)}}function Rf(t){const e={};return Object.entries(t).forEach(([r,n])=>{if(typeof n=="string"&&Sf(n))try{e[r]=wf(n)}catch(o){console.warn(`Failed to parse function string for ${r}: ${n}`,o),e[r]=()=>0}else e[r]=n}),e}function Cf(t){if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!t.id||typeof t.id!="string"||t.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(t.transforms)?t.transforms.forEach((r,n)=>{(!r.id||typeof r.id!="string")&&e.push(`Transform at index ${n} must have a valid id`),(!r.type||typeof r.type!="string")&&e.push(`Transform at index ${n} must have a valid type`),(!r.params||typeof r.params!="object")&&e.push(`Transform at index ${n} must have valid params`),Array.isArray(r.targetShapes)?r.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 ps=Ms.JSXGraph,Ki=t=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!t.animation,animationId:t.animation?.id,hasControl:!!t.animation?.control,controlConfig:t.animation?.control,animationProgress:t.animationProgress});const e=x.useRef(null),[r,n]=x.useState(null),[,o]=x.useState({}),[s,i]=x.useState(!1),a=x.useRef({}),c=x.useRef({}),l=x.useRef(null),d=x.useRef({}),g=x.useCallback((f,m)=>{t.onShapeChange},[t.onShapeChange]),p=x.useCallback(f=>{t.onSelectionChange&&t.onSelectionChange(f?[f]:[])},[t.onSelectionChange]);return x.useEffect(()=>{if(e.current){try{const f=t.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",f),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const m=ps.initBoard(e.current,{boundingbox:f,axis:t.showAxis??!0,grid:t.showGrid??!0,showNavigation:!1,pan:{enabled:t.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",m.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",f),console.warn(" * 实际边界框:",m.getBoundingBox()),console.warn(" * 实际显示范围:",{left:m.getBoundingBox()[0],top:m.getBoundingBox()[1],right:m.getBoundingBox()[2],bottom:m.getBoundingBox()[3]})},100),n(m)}catch(f){console.error("JSXGraph initialization failed:",f)}return()=>{r&&ps.freeBoard(r)}}},[]),x.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!r,hasAnimation:!!t.animation,hasControl:!!t.animation?.control,animationId:t.animation?.id,controlType:t.animation?.control?.type,controlPosition:t.animation?.control?.position,controlRange:t.animation?.control?.range}),!r||!t.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!r+", control="+!!t.animation?.control),l.current){try{l.current.remove&&l.current.remove()}catch(m){console.warn("Failed to remove control:",m)}l.current=null}return}const f=t.animation.control;console.warn("✨ Creating Control Component:",{type:f.type,config:f,position:f.position,range:f.range});try{if(f.type==="slider"){const m=f.position[0]+(f.length||5);console.warn("📐 Slider creation parameters:",{startPoint:f.position,endPoint:[m,f.position[1]],values:[f.range[0],f.initial||0,f.range[1]],label:f.label,snapWidth:f.snapWidth||.01});const h=r.create("slider",[f.position,[m,f.position[1]],[f.range[0],f.initial||0,f.range[1]]],{name:f.label||"control",snapWidth:f.snapWidth||.01,withLabel:f.showLabel!==void 0?f.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});l.current=h,console.warn("✅ Slider created:",{id:h.id,name:h.name,initialValue:h.Value(),startPoint:f.position,endPoint:[m,f.position[1]],boundingBox:r.getBoundingBox(),visProp:h.visProp});const y=r.objectsList.map(_=>({id:_.id,type:_.elType,name:_.name,visible:_.visProp?.visible})),b=y.find(_=>_.id===h.id);if(console.warn("📊 Slider in board.objectsList:",!!b,b),console.warn("📊 All board objects count:",y.length),t.onAnimationChange){let _=!1;h.on("drag",()=>{if(_)return;_=!0;const C=(h.Value()-f.range[0])/(f.range[1]-f.range[0]);t.onAnimationChange?.(C),_=!1})}}else if(f.type==="glider"){const m=r.select(f.line,!0);if(m){const h=r.create("glider",[f.initial||0,0,m],{name:f.label||"control",snapWidth:f.snapWidth||.01});if(l.current=h,console.warn("✅ Glider created:",{id:h.id,name:h.name}),t.onAnimationChange){let y=!1;h.on("drag",()=>{if(y)return;y=!0;const b=h.Value();t.onAnimationChange?.(b),y=!1})}}else console.warn(`Reference line not found for glider: ${f.line}`)}}catch(m){console.error("Failed to create control component:",m)}return()=>{if(l.current){try{l.current.remove()}catch(m){console.warn("Failed to remove control on cleanup:",m)}l.current=null}}},[r,t.animation?.control]),x.useEffect(()=>{if(!r||!t.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:t.animation.id,transformCount:t.animation.transforms.length}),Object.values(a.current).forEach(h=>{try{h&&h.remove&&h.remove()}catch(y){console.warn("Failed to remove transform:",y)}}),a.current={};const f={},m=t.animationProgress??0;t.animation.transforms.forEach(h=>{try{let y,b;const _=h.usesControl||!1;if(l.current&&_){y=Mn(h,m,l.current),console.warn(`🔧 Creating transform ${h.id} (with dynamic params):`,{type:h.type,paramsTypes:y.map(C=>typeof C),targetShapes:h.targetShapes,controlValue:l.current.Value()}),b=r.create("transform",y,{type:h.type,id:`transform_${h.id}`});const w=()=>{if(!l.current)return;r.update();const C=l.current.Value();if(console.warn(`🎯 Slider drag - transform ${h.id} auto-updated (controlValue: ${C})`),t.onAnimationChange){const v=t.animation?.control?.range||[0,1],k=(C-v[0])/(v[1]-v[0]);t.onAnimationChange(k)}};l.current.on("drag",w),d.current[h.id]=w,console.warn(`🔗 Slider listener attached for transform ${h.id} (auto-update mode)`)}else y=Mn(h,m),console.warn(`🔧 Creating transform ${h.id} (with progress ${m}):`,{type:h.type,params:y,targetShapes:h.targetShapes}),b=r.create("transform",y,{type:h.type,id:`transform_${h.id}`});f[h.id]=b,console.warn(`📝 Transform ${h.id} created:`,{type:h.type,paramsTypes:y.map(w=>typeof w),transformMethods:Object.keys(b).filter(w=>typeof b[w]=="function")})}catch(y){console.error(`Failed to create transform ${h.id}:`,y)}}),a.current=f}catch(f){console.error("Transform setup failed:",f)}},[r,t.animation]),x.useEffect(()=>{if(!s||!r||!t.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${s}, board=${!!r}, animation=${!!t.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(([f,m])=>{const h=t.animation?.transforms.find(b=>b.id===f);if(!h)return;console.warn(`🔍 Binding transform ${f} (type: ${h.type}) to shapes:`,h.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(c.current));const y=h.targetShapes.map(b=>{const _=c.current[b];return _?console.warn(`✅ Found shape ${b}:`,_):(console.warn(`❌ Shape not found for transform binding: ${b}`),console.warn(" Available IDs:",Object.keys(c.current))),_}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",y.length),y.length>0)try{console.warn(`🔗 Attempting to bind transform ${f} to ${y.length} shapes`),m.bindTo(y),console.warn(`✅ Successfully bound transform ${f} to ${y.length} shapes`),console.warn(" Transform object:",m),console.warn(" Target elements:",y.map(b=>({id:b.id,name:b.name,type:b.elementClass})))}catch(b){console.error(`❌ Failed to bind transform ${f}:`,b),console.error(" Transform:",m),console.error(" TargetElements:",y)}else console.warn(`⚠️ No valid target elements for transform ${f}`)}),r.update(),console.warn("✅ All transforms bound and board updated")},[s,r,t.animation]),x.useEffect(()=>{if(!r||Object.keys(a.current).length===0)return;const f=t.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${f}`);try{Object.entries(a.current).forEach(([m,h])=>{const y=t.animation?.transforms.find(_=>_.id===m);if(!y)return;const b=Mn(y,f);console.warn(`🔄 Attempting to update transform ${m} with params:`,b),h.update?(console.warn(" Using transform.update(params)"),h.update(b)):h.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),h.setMatrix(r,y.type,b)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(h).filter(_=>typeof h[_]=="function")))}),r.update()}catch(m){console.error("Transform update failed:",m)}},[r,t.animationProgress]),x.useEffect(()=>{if(r)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:t.shapes.length,shapes:t.shapes.map(h=>({id:h.id,type:h.type,hasVertices:"vertices"in h,verticesCount:"vertices"in h&&h.vertices?h.vertices.length:"undefined",hasPosition:"position"in h,hasGeometryRef:"geometryRef"in h,geometryRef:"geometryRef"in h?h.geometryRef:void 0}))}),r.suspendUpdate(),[...r.objectsList].forEach(h=>{r.removeObject(h)});const m={};c.current={},t.shapes.forEach(h=>{if(h.type==="point")try{const y=On(r,h,t.mode,g,p);y&&(m[h.id]=y)}catch(y){console.warn(`Failed to create point shape ${h.id}:`,y)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",r.objectsList.map(h=>({id:h.id,name:h.name,type:h.elementClass}))),t.shapes.forEach(h=>{if(h.type==="line"||h.type==="circle"||h.type==="polygon")try{const y=On(r,h,t.mode,g,p);y&&(m[h.id]=y)}catch(y){console.warn(`Failed to create shape ${h.id}:`,y)}}),console.warn("📝 Starting phase 3: creating text labels"),t.shapes.forEach(h=>{if(h.type==="text")try{const y=On(r,h,t.mode,g,p);y&&(m[h.id]=y)}catch(y){console.warn(`Failed to create text ${h.id}:`,y)}}),o(m),c.current=m,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(m).length} shapes created`),r.unsuspendUpdate()}catch(f){console.error("Shape rendering failed:",f)}},[r,t.shapes,t.mode,g,p]),x.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),l.current&&Object.entries(d.current).forEach(([f,m])=>{try{l.current.off("drag",m),console.warn(` Removed drag listener for transform ${f}`)}catch(h){console.warn(`Failed to remove drag listener for ${f}:`,h)}}),d.current={},Object.values(a.current).forEach(f=>{try{f&&f.remove&&f.remove()}catch(m){console.warn("Failed to remove transform during cleanup:",m)}}),a.current={},c.current={},i(!1),console.warn("✅ Cleanup complete")},[]),u.jsx("div",{ref:e,className:"w-full h-full"})};function On(t,e,r,n,o){const s=r==="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 g=t.create("point",[l,d],{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:g.id,pointName:g.name,hasIdProperty:"id"in g}),s&&(t.on("drag",()=>{n(e.id,{x:g.X(),y:g.Y()})}),t.on("down",()=>{o(e.id)})),g}catch(l){return console.error(`Failed to create point ${e.id}:`,l),null}case"line":const i=Mr(e.start,t),a=Mr(e.end,t);if(i&&a)try{const l=t.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&&t.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 c=Mr(e.center,t);if(c){let l;if(e.through){const d=Mr(e.through,t);d&&(l=t.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:!s,visible:e.visible??!0}))}else e.radius!==void 0&&(l=t.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:!s,visible:e.visible??!0}));return l&&s&&t.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((d,g)=>{const p=e.verticesConfig?e.verticesConfig[g]:null;return Af(d,t,p)});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:!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 p={};e.verticesConfig.withLabel!==void 0?p.withLabel=e.verticesConfig.withLabel:p.withLabel=!0;const f={};let m=!1;e.verticesConfig.offset&&(f.offset=e.verticesConfig.offset,m=!0),e.verticesConfig.fontSize&&(f.fontSize=e.verticesConfig.fontSize,m=!0),e.verticesConfig.color&&(f.color=e.verticesConfig.color,m=!0),e.verticesConfig.anchorX&&(f.anchorX=e.verticesConfig.anchorX,m=!0),e.verticesConfig.anchorY&&(f.anchorY=e.verticesConfig.anchorY,m=!0),m&&(p.label=f),d.vertices=p,console.warn("🔧 Using JSXGraph vertices config:",p)}else d.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",d);const g=t.create("polygon",l,d);return console.warn("🔧 Polygon created:",g),console.warn("🔧 Polygon vertices:",g.vertices),console.warn("🔧 Polygon vertices names:",g.vertices?g.vertices.map(p=>p.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",g.vertices?g.vertices.map(p=>p.hasLabel?p.label:"no label"):"no vertices"),s&&t.on("down",()=>{o(e.id)}),g}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)}),t.create("text",[e.position.x,e.position.y,e.content],{color:e.color||"black",fontSize:e.fontSize??14,fixed:!0,visible:e.visible??!0})}catch(l){console.error(`Failed to create text ${e.id}:`,l)}break}return null}function Mr(t,e){if(Array.isArray(t)&&t.length>=2)return t;if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return[t.x,t.y];if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const n=e.objects[t.$ref];if(n)return n}const r=e.objectsList.find(n=>n.id===t.$ref);if(r)return console.warn(`✅ Found referenced point ${t.$ref}:`,r),r;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(r){console.warn(`Failed to resolve point reference ${t.$ref}:`,r)}}return null}function Af(t,e,r){if(Array.isArray(t)&&t.length>=2){if(r&&r.name){const n=e.create("point",t,{name:r.name});return console.warn(`🔧 Created point with name ${r.name} at`,t),n}return t}if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t){const n=[t.x,t.y];if(r&&r.name){const o=e.create("point",n,{name:r.name});return console.warn(`🔧 Created point with name ${r.name} at`,n),o}return n}if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const o=e.objects[t.$ref];if(o)return r&&r.name&&o.setName&&(o.setName(r.name),console.warn(`🔧 Updated point ${t.$ref} name to ${r.name}`)),o}const n=e.objectsList.find(o=>o.id===t.$ref);if(n)return console.warn(`✅ Found referenced point ${t.$ref}:`,n),r&&r.name&&n.setName&&(n.setName(r.name),console.warn(`🔧 Updated point ${t.$ref} name to ${r.name}`)),n;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${t.$ref}:`,n)}}return null}function Co(t,e={}){const{padding:r=.2,margin:n=1,minSize:o=4}=e,s=[];if(t.forEach(S=>{switch(S.type){case"point":s.push(S.position);break;case"line":const E=jt(S.start,t),N=jt(S.end,t);E&&s.push(E),N&&s.push(N);break;case"circle":const I=jt(S.center,t);if(I&&(s.push(I),S.radius!==void 0&&s.push({x:I.x+S.radius,y:I.y},{x:I.x-S.radius,y:I.y},{x:I.x,y:I.y+S.radius},{x:I.x,y:I.y-S.radius})),S.through){const L=jt(S.through,t);L&&s.push(L)}break;case"polygon":S.vertices.forEach(L=>{const O=jt(L,t);O&&s.push(O)});break;case"text":s.push(S.position);const Y=S.content.length*(S.fontSize||14)/20,K=(S.fontSize||14)/10;s.push({x:S.position.x+Y,y:S.position.y},{x:S.position.x-Y,y:S.position.y},{x:S.position.x,y:S.position.y+K},{x:S.position.x,y:S.position.y-K});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(S=>S.x)),a=Math.max(...s.map(S=>S.x)),c=Math.min(...s.map(S=>S.y)),l=Math.max(...s.map(S=>S.y)),d=(i+a)/2,g=(c+l)/2;let p=Math.max(a-i,o),f=Math.max(l-c,o);const m=800/500,h=p/f;Math.abs(h-m)>.1&&(h>m?f=p/m:p=f*m);const y=p*(1+r)+n*2,b=f*(1+r)+n*2,_=d-y/2,w=g+b/2,C=d+y/2,v=g-b/2,k=[_,w,C,v];if(process.env.NODE_ENV==="development"){const E=s.map(N=>({x:N.x,y:N.y,insideX:N.x>=_&&N.x<=C,insideY:N.y<=w&&N.y>=v,inside:N.x>=_&&N.x<=C&&N.y<=w&&N.y>=v})).filter(N=>!N.inside);E.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:k,outsidePoints:E.slice(0,5),totalOutside:E.length})}return{boundingBox:k,center:{x:d,y:g},width:y,height:b}}function jt(t,e=[]){if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return{x:t.x,y:t.y};if("$ref"in t){const r=e.find(n=>n.id===t.$ref&&n.type==="point");if(r)return r.position}}return null}function Ef(t,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const r=[];if(t.forEach(o=>{switch(o.type){case"point":r.push({x:o.position.x,y:o.position.y,source:`point:${o.id}`});break;case"text":r.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;r.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,c)=>{const l=jt(a,t);l&&r.push({x:l.x,y:l.y,source:`polygon:${o.id}:vertex${c}`})});break}}),console.log("📊 收集到的坐标点:",r),r.length>0){const o=Math.min(...r.map(c=>c.x)),s=Math.max(...r.map(c=>c.x)),i=Math.min(...r.map(c=>c.y)),a=Math.max(...r.map(c=>c.y));console.log("📐 原始包围盒:",{minX:o,maxX:s,minY:i,maxY:a,width:s-o,height:a-i})}const n=Co(t,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",n),console.groupEnd(),n}const xr=t=>{const{shapes:e,mode:r,onShapeChange:n,onSelectionChange:o,width:s=600,height:i=400,showGrid:a=!0,showAxis:c=!0,className:l="",boundingBox:d,autoBoundingBox:g=!0,boundingBoxOptions:p,animation:f,animationProgress:m,onAnimationChange:h,showAnimationControls:y}=t,b=x.useMemo(()=>{if(d)return d;if(g&&e.length>0)try{process.env.NODE_ENV==="development"&&Ef(e,"MathGraph Auto BoundingBox");const w=Co(e,p);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",w.boundingBox),console.log(" - Center:",w.center),console.log(" - Width:",w.width),console.log(" - Height:",w.height),console.log(" - Options used:",p),w.boundingBox}catch(w){return console.warn("Failed to calculate auto bounding box, using default:",w),[-10,10,10,-10]}return[-10,10,10,-10]},[d,g,e,p]),_=x.useMemo(()=>({width:typeof s=="number"?`${s}px`:s,height:typeof i=="number"?`${i}px`:i}),[s,i]);return u.jsx(xf,{children:u.jsx("div",{className:`bg-white overflow-hidden ${l}`,style:_,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:u.jsx(Ki,{shapes:e,mode:r,onShapeChange:n,onSelectionChange:o,boundingBox:b,showGrid:a,showAxis:c,animation:f,animationProgress:m,onAnimationChange:h})})})},Xi=({shapes:t,width:e,height:r,showGrid:n=!0,showAxis:o=!0,boundingBox:s,autoBoundingBox:i,onShapeChange:a,className:c="",animation:l,animationProgress:d,showAnimationControls:g,onAnimationChange:p})=>{const f=x.useRef(null),[m,h]=x.useState({width:600,height:400});x.useEffect(()=>{const b=()=>{if(f.current){const{clientWidth:w,clientHeight:C}=f.current;w>0&&C>0&&h({width:w,height:C})}};b(),window.addEventListener("resize",b);const _=new ResizeObserver(b);return f.current&&_.observe(f.current),()=>{window.removeEventListener("resize",b),_.disconnect()}},[]);const y={width:e?typeof e=="string"?e:`${e}px`:"100%",height:r?typeof r=="string"?r:`${r}px`:"100%"};return u.jsx("div",{ref:f,className:`mathcard-v2-graph ${c}`,style:y,children:u.jsx(xr,{shapes:t,width:m.width,height:m.height,showGrid:n,showAxis:o,boundingBox:s,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:l,animationProgress:d,showAnimationControls:g,onAnimationChange:p})})},Ao=({config:t,onTransformChange:e,onTransformComplete:r,onError:n,layoutDensity:o,boardHeight:s,boardWidth:i,className:a=""})=>{const c=o??t.ui?.layoutDensity??"default",l=s??t.ui?.boardHeight??300,d=i??t.ui?.boardWidth??400,g=m=>{e?.(m)},p=()=>{r?.()},f=m=>{n?.(m)};return console.error("🔍 GeometryTransformContent: config =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,boardConfigKeys:t.boardConfig?Object.keys(t.boardConfig):[],boardConfigBoundingBox:t.boardConfig?.boundingBox,boardConfigOriginX:t.boardConfig?.originX,boardConfigOriginY:t.boardConfig?.originY,configKeys:Object.keys(t)}),u.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:u.jsx(ji,{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,onTransformChange:g,onTransformComplete:p,onError:f,layoutDensity:c,boardHeight:l,boardWidth:d,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})};function Tf(t){switch(t.contentType){case"formula":return u.jsx(Kt,{parts:[t.content],children:null});case"graph":return u.jsx(xr,{mode:"view",shapes:t.graphConfig?.shapes||[],boundingBox:t.graphConfig?.boundingBox,showGrid:t.graphConfig?.showGrid,showAxis:t.graphConfig?.showAxis});case"image":return u.jsx("img",{src:t.content,alt:"选项图片",className:"max-w-full"});default:return u.jsx("span",{children:t.content})}}const $f=({options:t,correctAnswers:e,answerType:r,layout:n="vertical",variant:o="default",value:s=[],onChange:i,showResult:a=!1,disabled:c=!1,className:l})=>{const d=x.useMemo(()=>t.map(p=>({id:p.id,label:Tf(p),rawContent:p.content,contentType:p.contentType||"text"})),[t]),g=x.useCallback(p=>{i?.(p)},[i]);return u.jsx(bo,{type:r,options:d,value:s,onChange:g,correctAnswers:e,showResult:a,disabled:c,layout:n,variant:o,className:l})},Nf=({headers:t,values:e,colors:r={}})=>{const{headerBg:n="#f1f5f9",valueBg:o="#ffffff",borderColor:s="#e2e8f0"}=r;return t.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):u.jsxs("div",{className:"place-value-chart",style:{display:"inline-block",border:`1px solid ${s}`,borderRadius:"8px",overflow:"hidden",fontFamily:"system-ui, sans-serif",fontSize:"14px",lineHeight:"1.4"},children:[u.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${s}`},children:t.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:n,fontWeight:"600",textAlign:"center",borderRight:a<t.length-1?`1px solid ${s}`:"none",color:"#1e293b"},children:i},a))}),u.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>u.jsx("div",{style:{flex:1,padding:"12px",backgroundColor:o,textAlign:"center",borderRight:a<e.length-1?`1px solid ${s}`:"none",color:"#0f172a",fontSize:"16px",fontWeight:"500"},children:i},a))})]})},Ji=({content:t,onInteraction:e,interactionValues:r={}})=>{const n=(o,s)=>{if(o.enabled===!1)return null;const i=`${o.type}-${s}`,a=c=>{e?.(i,c)};switch(o.type){case"text":return u.jsx(Wi,{content:o.content,style:o.style,onInteraction:a},i);case"formula":const c=o;return u.jsx(Yi,{parts:c.parts||[],displayMode:c.displayMode,style:o.style},i);case"graph":const l=o;return u.jsx(Xi,{shapes:l.shapes||[],width:l.width,height:l.height,showGrid:l.showGrid,showAxis:l.showAxis,boundingBox:l.boardConfig?.boundingBox,autoBoundingBox:!l.boardConfig?.boundingBox,animation:l.animation,animationProgress:l.animationProgress,showAnimationControls:l.showAnimationControls,onAnimationChange:l.onAnimationChange},i);case"hundredGrid":const d=o;return u.jsx(Ro,{...d.props},i);case"placeValueChart":const g=o;return u.jsx(Nf,{...g.props},i);case"geometryTransform":const p=o;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:p.metadata,config:p.metadata?.config,hasConfig:!!p.metadata?.config,configKeys:p.metadata?.config?Object.keys(p.metadata.config):[],configShapes:p.metadata?.config?.shapes,configShapesAnimatedLength:p.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:p.metadata?.config?.shapes?.static?.length,configBase:p.metadata?.config?.base,configHeight:p.metadata?.config?.height,configUnit:p.metadata?.config?.unit,configTransform:p.metadata?.config?.transform}),u.jsx(Ao,{config:p.metadata.config,onTransformChange:h=>a({type:"transformChange",progress:h}),onTransformComplete:()=>a({type:"transformComplete"}),onError:h=>a({type:"error",error:h})},i);case"optionGroup":const f=o,m=f.metadata?.optionGroupId;return u.jsx($f,{options:f.options,correctAnswers:f.correctAnswers,answerType:f.answerType,layout:f.layout,variant:f.variant,value:r[m]??[],onChange:h=>a({type:"optionChange",value:h,optionGroupId:m})},i);default:return u.jsx("div",{onClick:()=>a({type:"click"}),children:o.content},i)}};return u.jsx(u.Fragment,{children:t.map(n)})},Oe=({data:t,scene:e="question",layout:r={type:"card"},renderer:n={mode:"default"},theme:o="light",onContentInteraction:s,interactionValues:i,className:a="",children:c})=>{const l=zi(t,e),d={data:l,scene:e,layout:l.layout||r,renderer:l.renderer||n,theme:o,onContentInteraction:s},g=l.layout||r,p=(()=>{switch(g.type){case"grid":return Hi;case"flow":return qi;default:return Bi}})(),f=(()=>{const m={className:a,theme:o,"data-testid":"mathcard-v2-container"};switch(g.type){case"grid":return{...m,columns:g.columns||2,gap:g.gap||"16px",responsive:g.responsive!==!1};case"flow":return{...m,direction:g.direction||"vertical",gap:g.gap||"16px",wrap:g.wrap!==!1};default:return{...m,padding:g.padding||"24px",shadow:g.shadow!==!1,border:g.border!==!1}}})();return u.jsx(bf.Provider,{value:d,children:u.jsx(p,{...f,children:c||u.jsx(Ji,{content:l.content,layout:l.layout||r,onInteraction:s,interactionValues:i})})})};Oe.CardLayout=Bi;Oe.GridLayout=Hi;Oe.FlowLayout=qi;Oe.TextContent=Wi;Oe.FormulaContent=Yi;Oe.GraphContent=Xi;Oe.GeometryTransformContent=Ao;Oe.ContentRenderer=Ji;const Zi=t=>{const{ixlConfig:e,enableIXLStyle:r,isMobile:n}=t,o=x.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),s=x.useMemo(()=>{if(e.tagColor)return e.tagColor;const d={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return d[e.type]||d.remember},[e.tagColor,e.type]),i=x.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=x.useMemo(()=>{if(!r)return{};const d={backgroundColor:s,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},[r,s,i,n]),c=x.useMemo(()=>!r||n?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[r,n]);return{ixlClassName:x.useMemo(()=>{if(!r)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(" ")},[r,e.type,n]),tagStyle:a,contentStyle:c,tagText:o,tagColor:s,tagTextColor:i}},kf=(t,e)=>{let r=null;return(...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n)},e)}},Qi=(t={})=>{const e=typeof t=="number"?t:t.breakpoint||768,r=typeof t=="number"?!0:t.enabled!==!1,[n,o]=x.useState(()=>typeof window<"u"?window.innerWidth:1024),[s,i]=x.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=x.useRef(new Set),c=x.useCallback(()=>{if(typeof window>"u")return;const p=window.innerWidth,f=p<e;o(p),i(f),a.current.forEach(m=>{try{m()}catch(h){console.error("Error in resize listener:",h)}})},[e]),l=x.useCallback(kf(c,150),[c]);x.useEffect(()=>{if(!(!r||typeof window>"u"))return c(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l)}},[r,l,c]);const d=x.useCallback(p=>(a.current.add(p),()=>{a.current.delete(p)}),[]),g=x.useCallback(p=>{a.current.delete(p)},[]);return{isMobile:s,viewportWidth:n,addResizeListener:d,removeResizeListener:g}},Bt=({cardProps:t,ixlConfig:e,enableIXLStyle:r=!0,wrapperMode:n="mathcard",mobileBreakpoint:o=768,className:s="",style:i,children:a,onResponsiveChange:c})=>{const l=Qi(o),d=Zi({ixlConfig:e,enableIXLStyle:r,isMobile:l.isMobile});x.useEffect(()=>{c?.(l.isMobile)},[l.isMobile,c]);const g=x.useMemo(()=>{const m=["ixl-style-card-container"];return r&&m.push(d.ixlClassName),s&&m.push(s),l.isMobile?m.push("ixl-mobile"):m.push("ixl-desktop"),m.join(" ")},[r,d.ixlClassName,s,l.isMobile]),p=x.useMemo(()=>{const m={...i};return r&&!l.isMobile?{...m,paddingLeft:d.contentStyle.paddingLeft}:m},[r,l.isMobile,d.contentStyle,i]),f=x.useMemo(()=>{if(n!=="mathcard"||!t)return"";const m=[t.className||""];return r&&m.push("ixl-adjusted"),m.filter(Boolean).join(" ")},[n,t?.className,r]);return u.jsxs("div",{className:g,style:p,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":r,"data-responsive-mode":l.isMobile?"mobile":"desktop",children:[r&&e.showTag!==!1&&u.jsx("div",{className:"ixl-tag",style:d.tagStyle,"data-testid":"ixl-tag",children:u.jsx("span",{className:"ixl-tag-text",children:d.tagText})}),n==="mathcard"&&t?u.jsx(Oe,{...t,className:f}):a]})};Bt.displayName="IXLStyleCard";const Mf={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},Of={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},If={remember:"速记",review:"回顾",solve:"解答"},Ff=({grades:t,onGradeSelect:e,selectedGrade:r})=>u.jsxs("div",{className:"grade-navigation",children:[u.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),u.jsx("div",{className:"grade-navigation__grid",children:t.map(n=>u.jsxs("div",{className:`grade-card ${r===n.id?"grade-card--selected":""}`,style:{borderLeftColor:n.color},onClick:()=>e?.(n.id),children:[u.jsx("div",{className:"grade-card__level",children:n.level}),u.jsx("div",{className:"grade-card__name",children:n.name}),u.jsx("div",{className:"grade-card__description",children:n.description})]},n.id))})]}),ea=({abilities:t,width:e=400,height:r=400})=>{const n=()=>t.length===0?"":t.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*t.indexOf(i)/t.length,c=i.score/i.maxScore*40+10,l=50+c*Math.sin(a),d=50-c*Math.cos(a);return`${l},${d}`}).join(" "),o=i=>{const a=Math.PI*2*i/Math.max(t.length,1),c=50+40*Math.sin(a),l=50-40*Math.cos(a);return{x2:c,y2:l}},s=i=>{const a=Math.PI*2*i/Math.max(t.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 u.jsxs("svg",{"data-testid":"radar-chart",width:e,height:r,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[u.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),t.map((i,a)=>{const{x2:c,y2:l}=o(a);return u.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:c,y2:l,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),t.length>2&&u.jsx("polygon",{"data-testid":"radar-polygon",points:n(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),t.map((i,a)=>{let c,l;if(i.svgPoint)c=i.svgPoint.x,l=i.svgPoint.y;else{const d=Math.PI*2*a/t.length,g=i.score/i.maxScore*40+10;c=50+g*Math.sin(d),l=50-g*Math.cos(d)}return u.jsx("circle",{"data-testid":"data-point",cx:c,cy:l,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),t.map((i,a)=>{const{x:c,y:l,textAnchor:d}=s(a);return u.jsx("text",{x:c,y:l,textAnchor:d,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},hs={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 jf{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),hs):(await he.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 hs}}static async submitFeedback(e){try{await he.post(`${this.API_BASE_URL}/feedback`,e)}catch(r){throw console.error("Failed to submit feedback:",r),new Error("提交反馈失败")}}}const Pf=gr.create((t,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){t({loading:!0,error:null});try{const r=await jf.fetchRadarAbilityData();t({data:r,loading:!1})}catch(r){const n=r instanceof Error?r.message:"获取数据失败";t({error:n,loading:!1})}}},setData:r=>{t({data:r,error:null,loading:!1})},setError:r=>{t({error:r,loading:!1})},reset:()=>{t({data:null,loading:!1,error:null})}})),ta=({ability:t})=>{const e=t.score/t.maxScore*100;return u.jsxs("div",{className:"ability-progress-bar-item","data-ability":t.name,"data-testid":"progress-bar-container",children:[u.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[u.jsx("span",{className:"text-gray-700 font-medium",children:t.name}),u.jsxs("span",{className:"text-gray-600",children:[t.score,"/",t.maxScore]})]}),u.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:u.jsx("div",{className:`${t.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":t.score,"aria-valuemin":0,"aria-valuemax":t.maxScore,"aria-label":`${t.name} progress: ${t.score} out of ${t.maxScore}`})})]})},ra=({generalRecommendation:t})=>u.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:u.jsxs("div",{className:"flex items-start",children:[u.jsx("div",{className:"flex-shrink-0",children:u.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),u.jsxs("div",{className:"ml-3",children:[u.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),u.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:t})]})]})}),na=({ability:t,customLinkTexts:e={}})=>{const r=n=>{const o={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[n]||o[n]||"开始挑战"};return u.jsx(Ue.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":t.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:u.jsx(Ue.CardBody,{className:"p-5",children:u.jsxs("div",{className:"flex flex-col gap-3",children:[u.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[t.name,": 专项提高"]}),u.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:t.recommendation}),u.jsx(Ue.Button,{as:"a",href:t.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:u.jsx(Ln.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${t.name}专项提高页面`,children:r(t.name)})]})})})},Df="_dashboardLayout_10wqn_5",Lf="_upperSection_10wqn_19",Gf="_lowerSection_10wqn_33",Uf="_radarChartArea_10wqn_51",Or={dashboardLayout:Df,upperSection:Lf,lowerSection:Gf,radarChartArea:Uf},Vf=()=>{const{data:t,loading:e,error:r,fetchData:n}=Pf();return x.useEffect(()=>{n()},[n]),e?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),u.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):r?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[u.jsx("div",{className:"text-red-500 mb-4",children:u.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),u.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),u.jsx("p",{className:"text-gray-600 mb-4",children:r}),u.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:"重试"})]}):t?u.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 animate-fade-in","data-component":"AbilityAssessmentDashboard",role:"main","aria-label":"能力评估雷达图展示",children:[u.jsxs("div",{className:"flex justify-between items-center mb-6",children:[u.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),u.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${t.overallRating}`,children:["综合评级: ",t.overallRating]})]}),u.jsxs("div",{className:Or.dashboardLayout,children:[u.jsxs("div",{className:Or.upperSection,children:[u.jsx("div",{className:Or.radarChartArea,children:u.jsx(ea,{abilities:t.abilities})}),u.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:t.abilities.map(o=>u.jsx(ta,{ability:o},o.name))})]}),u.jsxs("div",{className:Or.lowerSection,children:[u.jsx(ra,{generalRecommendation:t.generalRecommendation}),u.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.abilities.map(o=>u.jsx(na,{ability:o},o.name))})]})]})]}):u.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:u.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},cr={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},zf={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},Bf={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},wr={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},Hf=[{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")}],qf="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",be={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:""}]}]}]},Wf=Hf,Yf=wr;class Kf{baseURL;token;constructor(e="/api/v1",r=qf){this.baseURL=e,this.token=r}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,r={}){const n=await fetch(e,{...r,headers:{...this.getAuthHeaders(),...r.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 r=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(r)).json()}async getUnitProgress(e,r){const n=r?`${this.baseURL}/content/courses/${e}/units/${r}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(n)).json()}async batchUpdateLessonProgress(e,r){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(r)})).json()}async updateLessonProgress(e,r,n,o){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${r}/lessons/${n}/progress`,{method:"POST",body:JSON.stringify({status:o})})}setToken(e){this.token=e}getToken(){return this.token}}const Ir=new Kf;class rt extends Error{constructor(e,r,n){super(e),this.code=r,this.originalError=n,this.name="DataSourceError"}}class Xf{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},Ir.setToken(this.config.token)}async getUserGradeUnitsNav(e,r){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${r}`),await this.withRetry(()=>Ir.getUserGradeUnitsNav(e))}catch(n){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",n),new rt(`获取年级单元导航数据失败: ${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(r){throw console.error("[ApiDataSource] 获取用户个人信息失败:",r),new rt(`获取用户个人信息失败: ${r instanceof Error?r.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",r instanceof Error?r: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 rt(`获取探索菜单数据失败: ${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(()=>Ir.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(r){throw console.error("[ApiDataSource] 更新课时进度失败:",r),new rt(`更新课时进度失败: ${r instanceof Error?r.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",r instanceof Error?r:void 0)}}async batchUpdateLessonProgress(e,r){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,r),await this.withRetry(()=>Ir.batchUpdateLessonProgress(e,r))}catch(n){throw console.error("[ApiDataSource] 批量更新课时进度失败:",n),new rt(`批量更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async withRetry(e){let r;for(let n=1;n<=this.config.retryCount;n++)try{return await e()}catch(o){r=o instanceof Error?o:new Error(String(o)),n<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${n}次重试...`,r.message),await this.delay(this.config.retryDelay))}throw r}delay(e){return new Promise(r=>setTimeout(r,e))}getConfig(){return{...this.config}}}class Jf{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,r){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${r}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${r}`),new rt("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${r}`),{userId:r,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:be.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:be.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:cr[o.moduleCategory]||cr.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new rt("模拟数据源:获取用户个人信息失败","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 rt("模拟数据源:获取探索菜单数据失败","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 rt("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,r){if(await this.simulateDelay(),this.shouldSimulateError())throw new rt("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,r),{success:!0,results:r.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 be}getLessonsData(){const e={};return be.units.forEach(r=>{e[r.id]=r.lessons.map(n=>({id:n.id,title:n.title,duration:n.duration,knowledgeItems:n.knowledgeItems.map(o=>({...o,progress:0}))}))}),e}}class Zf{static instances=new Map;static createDataSource(e){const{type:r,config:n,customDataSourceClass:o}=e,s=this.getInstanceKey(r,n);if(this.instances.has(s))return this.instances.get(s);let i;switch(r){case"api":i=new Xf(n);break;case"mock":i=new Jf(n);break;case"custom":if(!o)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new o(n);break;default:throw new Error(`不支持的数据源类型: ${r}`)}return this.instances.set(s,i),console.log(`[DataSourceFactory] 创建数据源: type=${r}, 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 r=!1,n=!1,o=!1;try{typeof process<"u"&&process.env?(r=process.env.NODE_ENV==="development",n=process.env.NODE_ENV==="test",o=process.env.REACT_APP_USE_MOCK==="true"):(r=!0,o=!0)}catch(s){console.warn("无法检测环境变量,使用默认配置:",s),r=!0,o=!0}return r||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,r){return`${e}:${r.name}:${JSON.stringify(r)}`}}function Qf(){return Zf.createDefaultDataSource()}function eg(t={}){const{dataSource:e=Qf(),fallbackStrategy:r="mock",errorHandling:n={},performance:o={},theme:s={},debug:i=!1,enableDevTools:a=!1}=t;return{dataSource:e,fallbackStrategy:r,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 tg(t,e){return{...t,...e,errorHandling:{...t.errorHandling,...e.errorHandling},performance:{...t.performance,...e.performance},theme:{...t.theme,...e.theme}}}const oa=x.createContext(null),sa=()=>{const t=x.useContext(oa);if(!t)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return t},ia=({children:t,config:e})=>{const[r,n]=x.useState(()=>eg(e)),[o,s]=x.useState(null),[i,a]=x.useState([]),[c,l]=x.useState(null),[d,g]=x.useState({}),[p,f]=x.useState(!1),[m,h]=x.useState(null),[y,b]=x.useState(null),[_,w]=x.useState([]),C=x.useCallback(async(N,I)=>{f(!0),h(null);try{process.env.NODE_ENV!=="test"&&await new Promise(L=>setTimeout(L,100));const Y=await r.dataSource.getUserGradeUnitsNav(N,I);l(Y);const K={};be.units.forEach(L=>{K[L.id]=L.lessons.map(O=>({id:O.id,title:O.title,duration:O.duration,knowledgeItems:O.knowledgeItems.map(U=>({...U,progress:0}))}))}),console.log("Lessons data loaded:",K),g(K);try{const L=await r.dataSource.getUserProfile(I);s(L)}catch(L){console.warn("获取用户信息失败,使用默认数据:",L),s({id:I,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const L=await r.dataSource.getExploreMenu();a(L)}catch(L){console.warn("获取探索菜单失败,使用默认数据:",L),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(Y){if(console.error("数据加载错误:",Y),r.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const K={userId:I,courseId:N,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:be.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:be.units.map((O,U)=>({unitId:O.id,title:O.title,description:O.description,moduleCategory:O.moduleCategory,estimatedDuration:O.estimatedDuration,totalLessons:O.lessons.length,completedLessons:U<2?Math.floor(O.lessons.length*.5):0,progressPercentage:U<2?50:0,status:U<2?"in-progress":"not-started",lastAccessed:U<2?new Date().toISOString():void 0,isActive:U===0,route:`/math/grade-5/unit/${O.id}`,icon:cr[O.moduleCategory]||cr.Default}))};l(K);const L={};be.units.forEach(O=>{L[O.id]=O.lessons.map(U=>({id:U.id,title:U.title,duration:U.duration,knowledgeItems:U.knowledgeItems.map(T=>({...T,progress:0}))}))}),g(L),s({id:I,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else h(Y instanceof Error?Y.message:"数据加载失败"),l(null)}finally{f(!1)}},[r]),v=x.useCallback(N=>{w(I=>I.includes(N)?I.filter(Y=>Y!==N):[...I,N])},[]),k=x.useCallback(N=>{b(N)},[]),S=x.useCallback(N=>{n(I=>tg(I,N))},[]);x.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 N=c.units.find(Y=>Y.isActive);console.log("Found active unit:",N);const I=N?.unitId||c.units[0].unitId;console.log("Setting default active unit:",I),b(I),console.log("Default active unit set after state update:",I)}else console.log("No units data available for setting default active unit")},[c]);const E={userInfo:o,exploreMenu:i,unitsData:c,lessons:d,loading:p,error:m,activeUnitId:y,activeLessonIds:_,config:r,theme:r.theme,enableVirtualization:r.performance?.enableVirtualization,setLoading:f,setError:h,setActiveUnit:k,toggleLesson:v,loadPageData:C,updateConfig:S};return u.jsx(oa.Provider,{value:E,children:t})},rg=({gradeId:t,userId:e,onLearnAction:r,className:n,userInfo:o,exploreMenu:s})=>{const{userInfo:i,exploreMenu:a,unitsData:c,lessons:l,loading:d,error:g,activeUnitId:p,activeLessonIds:f,setActiveUnit:m,toggleLesson:h,loadPageData:y}=sa(),b=o??i,_=s??a;x.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",t,"userId:",e),y(t,e)},[t,e,y]),x.useEffect(()=>{console.log("activeUnitId from context:",p),console.log("lessons from context:",l);const v=c?.units?.find(S=>S.unitId===p)||null,k=v&&p&&l[p]?{id:v.unitId,title:v.title,description:v.description,estimatedDuration:v.estimatedDuration,totalLessons:v.totalLessons,moduleCategory:v.moduleCategory,lessons:l[p]}:null;console.log("activeUnit computed:",k)},[p,l,c]);const w=c?.units?.find(v=>v.unitId===p)||null,C=w&&p&&l[p]?{id:w.unitId,title:w.title,description:w.description,estimatedDuration:w.estimatedDuration,totalLessons:w.totalLessons,moduleCategory:w.moduleCategory,lessons:l[p]}:null;return d?u.jsx("div",{className:`grade-unit-browser-page loading ${n||""}`,"data-testid":"grade-unit-browser-page",children:u.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):g?u.jsxs("div",{className:`grade-unit-browser-page error ${n||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"error-message","data-testid":"error-message",children:g}),u.jsx(ut,{onClick:()=>y(t,e),intent:"retry",useNewClassName:!0,className:"retry-button",children:"重试"})]}):u.jsxs("div",{className:`grade-unit-browser-page ${n||""}`,"data-testid":"grade-unit-browser-page",children:[u.jsx("div",{className:"header-area",children:u.jsx(si,{userData:b||void 0,exploreItems:_})}),u.jsx("div",{className:"sidebar-area",children:u.jsx(Fs,{data:c,activeUnitId:p,onUnitSelect:m,loading:d})}),u.jsx("div",{className:"content-area",children:u.jsx(Is,{unit:C,activeLessonIds:f,onToggleLesson:h,onLearnAction:r||(()=>{}),loading:d})})]})},ng=t=>u.jsx(ia,{config:t.config,children:u.jsx(rg,{...t})});function og(t){return t.steps!==void 0}function sg(t){if(og(t))return t;if(Array.isArray(t)){if(t.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=t[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=t.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:t,total_steps:t.length,strategy:"step_by_step",estimated_time:t.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}function aa(t){return Array.isArray(t)}const ig=(t,e,r=.1)=>{if(!t.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const n=parseFloat(t);if(isNaN(n))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(n<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const s=Math.abs(n-e)<=r;return{isValid:!0,isCorrect:s,errorMessage:s?void 0:"答案不正确,请再试一次"}},ag=()=>gr.create((t,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:r=>{t({problemData:r,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:r=>{t({userAnswer:r,validationError:null})},updateChoiceAnswer:r=>{t({userAnswer:r,validationError:null})},submitAnswer:r=>{const n=e();if(!n.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}let o=n.userAnswer;if((Array.isArray(r)||r!==void 0)&&(o=r),aa(o)){const d=o.map(f=>f.id),g=n.problemData.answer_info?.correctAnswers||[];process.env.NODE_ENV==="development"&&console.log("[答案验证]",{selectedIds:d,correctAnswers:g,answerInfo:n.problemData.answer_info});const p=d.length===g.length&&d.every(f=>g.includes(f));t({isCorrect:p,showAnswerForm:!1,validationError:null,currentScene:p?"success":"explanation"});return}const s=typeof o=="string"?o:"",i=n.problemData.answer_info?.value??n.problemData.answer.value,a=Number(i),c=n.problemData.answer_info?.tolerance??.1,l=ig(s,a,c);if(!l.isValid){t({userAnswer:o,validationError:l.errorMessage||"答案格式错误"});return}t({userAnswer:o,isCorrect:l.isCorrect,showAnswerForm:!1,validationError:null,currentScene:l.isCorrect?"success":"explanation"})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),xt=ag(),Eo=()=>xt(t=>t.currentScene),To=()=>xt(t=>t.userAnswer),lg=()=>xt(t=>t.isCorrect),$o=()=>xt(t=>t.showAnswerForm),la=()=>xt(t=>t.validationError),cg=()=>xt(t=>t.problemData),No=()=>xt(lo.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,updateChoiceAnswer:t.updateChoiceAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),dg=x.createContext(null),vr=()=>{const t=x.useContext(dg);if(!t)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return t},ug=()=>{const t=vr(),e=x.useCallback(r=>r.currentScene,[]);return t(e)},fg=()=>{const t=vr(),e=x.useCallback(r=>r.userAnswer,[]);return t(e)},gg=()=>{const t=vr(),e=x.useCallback(r=>r.showAnswerForm,[]);return t(e)},mg=()=>{const t=vr(),e=x.useCallback(r=>r.validationError,[]);return t(e)},pg=()=>vr()(lo.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,updateChoiceAnswer:e.updateChoiceAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),dn=()=>{try{return ug()}catch{return Eo()}},un=()=>{try{return fg()}catch{return To()}},fn=()=>{try{return gg()}catch{return $o()}},gn=()=>{try{return mg()}catch{return la()}},mn=()=>{try{return pg()}catch{return No()}},Mt=({problemData:t,userAnswer:e,showAnswerForm:r,onAnswerSubmit:n,onAnswerChange:o,validationError:s,noBorder:i=!1})=>{const a=x.useCallback((p,f)=>{f.type==="optionChange"&&o(f.value)},[o]),c=x.useMemo(()=>Array.isArray(e)?(t.scenes?.question?.items??[]).reduce((f,m)=>(m.type==="optionGroup"&&m.metadata?.optionGroupId&&(f[m.metadata.optionGroupId]=e),f),{}):{},[e,t]),l=Array.isArray(e)||t.scenes?.question?.items?.some(p=>p.type==="optionGroup"),d=p=>{p.preventDefault(),n(e)},g=p=>{o(p)};return u.jsx("div",{className:"question-scene-container",children:u.jsxs("div",{className:"question-scene-card",children:[u.jsx("div",{className:"question-display-area",children:u.jsx(Oe,{data:{id:t.id,grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1},onContentInteraction:a,interactionValues:c})}),r&&u.jsxs("div",{className:"answer-form-container",children:[u.jsxs("form",{onSubmit:d,className:"answer-form",children:[!l&&u.jsxs(u.Fragment,{children:[u.jsx("label",{className:"answer-label",children:"答案"}),u.jsx("input",{type:"number",value:typeof e=="string"?e:"",onChange:p=>g(p.target.value),className:`answer-input ${s?"error":"normal"}`,placeholder:"?",required:!0}),u.jsx("span",{className:"answer-unit",children:t.basicInfo.answerUnit||t.basicInfo.areaUnit})]}),u.jsx(ut,{type:"submit",size:"lg",intent:"submit",useNewClassName:!0,className:"submit-button",children:"提交答案"})]}),s&&u.jsxs("div",{className:"validation-error",children:[u.jsx("span",{children:"⚠️"}),u.jsx("span",{children:s})]})]})]})})},ca=({problemData:t,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",t),console.log("🔍 RememberModule scenes.remember:",t?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",t?.scenes?.remember?.content);const n=(()=>{const s=t.scenes?.review?.items;if(s&&Array.isArray(s)&&s.length>0)return console.log("🔍 RememberModule 使用 review.items"),s;const i=t.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=t.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const c=t.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 s=u.jsx("div",{className:"remember-module-content",children:u.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?u.jsx(Bt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})}const o=u.jsx("div",{className:"remember-module-content",children:n.map((s,i)=>{const{type:a,content:c,style:l,parts:d}=s;switch(a){case"text":return u.jsx("p",{className:"remember-module-text-block",style:l,children:c},i);case"formula":return u.jsx("div",{className:"remember-module-formula-block",children:u.jsx(Oe,{data:{id:`formula-${i}`,grade:t.grade,unit:t.unit,content:[{type:"formula",content:c,parts:d||[c]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return u.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?u.jsx(Bt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):u.jsxs("div",{className:"remember-module-container",children:[u.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})},ko=({problemData:t,userAnswer:e,enableIXLStyle:r=!0})=>{const n=x.useMemo(()=>aa(e)?e.length===0?"未选择":e.map(i=>i.contentType==="formula"?i.content:i.content||i.id).join("、"):e||"--",[e]),o=u.jsxs("div",{className:"review-module-content",children:[u.jsx("p",{className:"review-module-question",children:t.basicInfo.question}),u.jsx("div",{className:"review-module-graph",children:u.jsx(Oe,{data:{id:"review-problem",grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:r?"ixl-adjusted":""})}),u.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",u.jsx("span",{className:"review-module-user-answer-value",children:n})]})]});return r?u.jsx(Bt,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:o}):u.jsxs("div",{className:"review-module-container",children:[u.jsx("h4",{className:"review-module-title",children:"复习"}),o]})},hg=t=>[{color:"var(--mc-step-color-ident)",bg:"var(--mc-step-bg-ident)"},{color:"var(--mc-step-color-calc)",bg:"var(--mc-step-bg-calc)"},{color:"var(--mc-step-color-res)",bg:"var(--mc-step-bg-res)"}][t%3],yg=({step:t,problemData:e,stepNumber:r})=>{const{title:n,description:o,chartConfig:s}=t.content,i=!!s,a=hg(r-1),c=[{type:"text",content:o.replace(/<br>/g,`
17
- `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return u.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[u.jsxs("h3",{className:"explanation-step-title",children:[u.jsx("span",{className:"explanation-step-number",children:r}),u.jsx("span",{children:n})]}),u.jsxs("div",{className:"explanation-step-content",children:[u.jsx(Oe,{data:{id:`${t.id}-description`,grade:e.grade,unit:e.unit,content:c},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&s.type&&u.jsx("div",{className:"explanation-step-chart-container",children:s.type==="hundredGrid"?u.jsx(Ro,{rows:s.rows||2,cols:s.cols||6,cellSize:s.cellSize||36,mode:s.mode||"readonly",value:s.value,fillColor:s.fillColor,baseColor:s.baseColor,className:"mathwiz-hundredgrid-explanation"}):s.type==="geometryTransform"&&(s.config||s.metadata?.config)?u.jsx(Ao,{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)}):s.shapes&&s.shapes.length>0?u.jsx(xr,{shapes:s.shapes,width:s.width||400,height:s.height||300,boundingBox:s.boundingBox||[-10,10,10,-10],showGrid:s.showGrid||!1,showAxis:s.showAxis||!1,mode:"view",className:"mx-auto"}):null})]})]})},Mo=({problemData:t,enableIXLStyle:e=!0})=>{const[r,n]=x.useState(!1),o=t?.scenes?.solve?.items||t?.scenes?.solve?.content,s=Array.isArray(o)&&o.length>0,i=x.useMemo(()=>o&&o.map(g=>g.type==="geometryTransform"&&g.metadata?.config&&!g.config?{...g,config:g.metadata.config}:g),[o]),a=x.useMemo(()=>sg(t.explanation),[t.explanation]),c=a.steps.length>0,l=x.useMemo(()=>c?a.steps.map(g=>({...g,content:{title:g.title,description:g.description,chartConfig:g.chartConfig?{...g.chartConfig,boundingBox:g.chartConfig.type==="graph"&&Array.isArray(g.chartConfig.boundingBox)&&g.chartConfig.boundingBox.length===4?[g.chartConfig.boundingBox[0],g.chartConfig.boundingBox[1],g.chartConfig.boundingBox[2],g.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[c,a.steps]),d=u.jsxs("div",{className:"solve-module-content",children:[s?u.jsxs(u.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",o),o?.forEach?.((g,p)=>{if(g.type==="geometryTransform"){const f=i?.[p];console.log(`🔍 SolveModule: geometryTransform block [${p}] =`,{type:g.type,hasMetadata:!!g.metadata,metadata:g.metadata,hasMetadataConfig:!!g.metadata?.config,metadataConfig:g.metadata?.config,hasConfig:!!g.config,config:g.config,hasShapes:!!g.shapes,shapes:g.shapes,hasTransform:!!g.transform,transform:g.transform,fixedBlockHasConfig:!!f?.config,fixedBlockConfig:f?.config,fixedBlockHasMetadataConfig:!!f?.metadata?.config,fixedBlockMetadataConfig:f?.metadata?.config,isConfigFixed:!g.config&&!!f?.config})}}),u.jsx(Oe,{data:{id:"solve-steps",grade:t.grade,unit:t.unit,content:i},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):u.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),u.jsx("div",{className:"solve-module-button-container",children:u.jsx(ut,{intent:"solve",variant:"light",useNewClassName:!0,onClick:()=>n(g=>!g),className:"solve-module-button",children:r?"收起详细解题步骤":"查看详细解题步骤"})}),r&&u.jsxs("div",{className:"solve-module-detailed-container",children:[u.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),c?u.jsx("div",{className:"solve-module-detailed-list",children:l.map((g,p)=>u.jsx(yg,{step:g,problemData:t,stepNumber:p+1},g.id))}):u.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?u.jsx(Bt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:d}):u.jsxs("div",{className:"solve-module-container",children:[u.jsx("h4",{className:"solve-module-title",children:"解题"}),d]})},bg=t=>{if(t.answer_info?.displayValue)return t.answer_info.displayValue;const e=t.answer_info?.value;if(e!=null)return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e);const r=t.answer?.value;return r!=null?String(r):"--"},Xt=({problemData:t,userAnswer:e,onNextQuestion:r})=>{console.log("🔍 ExplanationScene problemData:",t),console.log("🔍 ExplanationScene scenes.remember:",t?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",t?.scenes?.remember?.content);const n=x.useMemo(()=>bg(t),[t]);return u.jsxs("div",{children:[u.jsx("div",{className:"explanation-error-banner",children:u.jsxs("div",{className:"explanation-inner-container",children:[u.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),u.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[u.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),u.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[u.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),u.jsx("div",{className:"correct-answer-value-container",children:u.jsx("span",{className:"correct-answer-value",children:u.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:n})})})]})]}),u.jsx("div",{className:"explanation-button-container",children:u.jsx(ut,{onClick:r,size:"lg",intent:"next",useNewClassName:!0,className:"explanation-next-button",children:"明白了"})})]})}),u.jsxs("div",{className:"explanation-content-area",children:[u.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),u.jsx(ko,{problemData:t,userAnswer:e}),u.jsx(ca,{problemData:t}),u.jsx(Mo,{problemData:t})]}),u.jsx("div",{className:"explanation-bottom-area",children:u.jsx(ut,{onClick:r,size:"md",intent:"next",useNewClassName:!0,children:"明白了"})})]})},Ot=({problemData:t,onNextQuestion:e})=>u.jsxs("div",{className:"success-scene-container",children:[u.jsx("h3",{className:"success-message-title",children:"正确!"}),u.jsx("p",{className:"success-message-description",children:"你做得很好!"}),u.jsx("div",{className:"concept-review-container",children:u.jsx(Oe,{data:{id:"review-concepts",grade:t.grade,unit:t.unit,content:t.scenes?.review?.items||t.scenes?.review?.content||t.scenes?.remember?.items||t.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),u.jsx(ut,{onClick:e,size:"lg",intent:"next",useNewClassName:!0,className:"next-button",children:"下一题"})]}),dt={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};let Gt=class extends Error{code;details;constructor(e,r,n){super(r),this.name="AdapterError",this.code=e,this.details=n}};const xg={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},wg={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},le={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"},Q={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 we extends Error{code;details;constructor(e,r,n){super(r),this.name="AdapterError",this.code=e,this.details=n}}const zr={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"}},ys={[Q.INVALID_INPUT]:"输入数据无效",[Q.MISSING_REQUIRED_FIELD]:"缺少必需字段",[Q.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[Q.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[Q.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[Q.STYLE_REF_NOT_FOUND]:"样式引用未找到",[Q.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[Q.BOARD_REF_NOT_FOUND]:"画板引用未找到",[Q.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[Q.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[Q.TRANSFORMATION_FAILED]:"数据转换失败",[Q.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},Rt={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},In={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"]},da=["question","solve","review","remember"],me={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_]*)$/},Re={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},ua={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.5rem",heading_normal:"1.25rem",body:"1.2rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},fa={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_secondary",fontSize:"$fonts.heading_normal",fontWeight:"600",lineHeight:1.5,letterSpacing:"0.01em"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"},hundredGrid_primary:{id:"hundredGrid_primary",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.primary",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_highlight:{id:"hundredGrid_highlight",baseColor:"$colors.background_lighter",borderColor:"$colors.primary",selectedColor:"$colors.success",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_solve:{id:"hundredGrid_solve",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.highlight_yellow",textColor:"$colors.text_primary",fontSize:"$fonts.body"}}},ga={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:"左三角形模板"}}},ma={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"}}},pa={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:"缩放变换"}}},Dt={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:"垂直滑块动画"}}},ha={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:"扩展画板配置(带网格和坐标轴)"}}},Et={designTokens:ua.design_tokens,stylePresets:fa.style_presets,geometryPresets:ga.geometry_presets,layoutPresets:ma.layout_presets,transformDefinitions:pa.transform_definitions,animationDefinitions:Dt.slider_definitions,animationConfigs:Dt.slider_definitions,boardDefinitions:ha.board_definitions};function ya(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!Dt,sliderDefinitionsKeys:Dt.slider_definitions?Object.keys(Dt.slider_definitions):[]});const t=Dt.slider_definitions;return{designTokens:ua.design_tokens,stylePresets:fa.style_presets,geometryPresets:ga.geometry_presets,layoutPresets:ma.layout_presets,transformDefinitions:pa.transform_definitions,animationDefinitions:t,animationConfigs:t,boardDefinitions:ha.board_definitions}}class ze{static canResolve(e){return me.DESIGN_TOKEN.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,r.designTokens)}static resolvePath(e,r){const n=e.split(".");let o=r;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,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`设计令牌解析失败: ${o}`,s)}return n}static extractDesignTokenRefs(e){const r=[],n=o=>{typeof o=="string"?this.canResolve(o)&&r.push(o):Array.isArray(o)?o.forEach(n):typeof o=="object"&&o!==null&&Object.values(o).forEach(n)};return n(e),r}static replaceDesignTokenRefs(e,r,n){const o=s=>{if(typeof s=="string"){if(this.canResolve(s))try{return this.resolve(s,r)}catch(d){if(n)return n(s);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(s))!==null;){a.index>c&&l.push(s.substring(c,a.index));const d=a[0];try{const g=this.resolve(d,r);l.push(String(g))}catch{n?l.push(String(n(d))):l.push(d)}c=a.index+d.length}return c<s.length&&l.push(s.substring(c)),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,c]of Object.entries(s))i[a]=o(c);return i}}return s};return o(e)}}function vg(){return{type:le.DESIGN_TOKEN,canResolve:ze.canResolve.bind(ze),resolve:ze.resolve.bind(ze)}}class Ze{static canResolve(e,r){if(typeof e!="string"||e.length===0)return!1;if(me.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(r&&r.geometryPresets){let s;const i=e.match(me.GEOMETRY_REF);return i?s=i[1]:s=e,s in r.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,r){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!r.geometryPresets,pointFound:!!r.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(r.geometryPresets&&r.geometryPresets[n]){const o=r.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,r){if(!this.canResolve(e,r))throw new Error(`无法解析的几何引用: ${e}`);let n;const o=e.match(me.GEOMETRY_REF);o?n=o[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(r.geometryPresets||{}));const s=r.geometryPresets[n];if(!s)throw console.error(`❌ Geometry preset not found: ${n} in`,r.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,r):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,r):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,r){if(!this.canResolve(e,r))return!1;let n;const o=e.match(me.GEOMETRY_REF);return o?n=o[1]:n=e,n in r.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,r){const n=this.resolve(e,r);if(n.styleRef&&r.stylePresets[n.styleRef]){const o=r.stylePresets[n.styleRef];return{...n,style:{...o}}}return n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`几何引用解析失败: ${o}`,s)}return n}static extractGeometryRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.geometryRef&&typeof o.geometryRef=="string"&&r.push(o.geometryRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.geometryRef&&typeof s.geometryRef=="string"&&r.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(r)]}}function _g(){return{type:le.GEOMETRY_REF,canResolve:Ze.canResolve.bind(Ze),resolve:Ze.resolve.bind(Ze),validate:Ze.validate.bind(Ze)}}class Fe{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.TRANSFORM_REF.test(e)?!0:/_(rotation|translation|scale|transform|reflection|shear|mirror)$/i.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const o=e.match(me.TRANSFORM_REF);if(o?n=o[1]:n=e,r.transformDefinitions&&r.transformDefinitions[n])return{...r.transformDefinitions[n]};const s=this.createDefaultTransform(n);if(s)return console.warn(`⚠️ 使用智能默认变换: ${n}`,s),s;throw new Error(`变换定义未找到: ${n}`)}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(me.TRANSFORM_REF);return o?n=o[1]:n=e,r.transformDefinitions&&r.transformDefinitions[n]?!0:this.createDefaultTransform(n)!==null}static applyTransform(e,r){if(!r||!e)return e;const n={...e};switch(r.type){case"rotation":n.vertices=this.applyRotation(e.vertices,r.angle,r.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,r.dx,r.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,r.factor,r.origin);break;default:console.warn(`未知的变换类型: ${r.type}`)}return n}static applyRotation(e,r,n){if(!e||!Array.isArray(e))return e;const[o,s]=n,i=r*Math.PI/180,a=Math.cos(i),c=Math.sin(i);return e.map(([l,d])=>{const g=l-o,p=d-s;return[o+g*a-p*c,s+g*c+p*a]})}static applyTranslation(e,r,n){return!e||!Array.isArray(e)?e:e.map(([o,s])=>[o+r,s+n])}static applyScale(e,r,n){if(!e||!Array.isArray(e))return e;const[o,s]=n;return e.map(([i,a])=>{const c=i-o,l=a-s;return[o+c*r,s+l*r]})}static createDefaultTransform(e){const r=e.toLowerCase();if(r.includes("rotation")||r.includes("rotate")){let n=0,o=Math.PI,s="clockwise";return r.includes("left")?(s="clockwise",o=Math.PI):r.includes("right")?(s="counterclockwise",o=Math.PI):r.includes("half")||r.includes("180")?o=Math.PI:r.includes("full")||r.includes("360")?o=2*Math.PI:(r.includes("quarter")||r.includes("90"))&&(o=Math.PI/2),{type:"rotation",config:{center:[0,0],startAngle:n,endAngle:o,direction:s}}}else if(r.includes("translation")||r.includes("translate")||r.includes("move")){let n=[0,0],o=0;return r.includes("left")||r.includes("west")?(n=[-1,0],o=10):r.includes("right")||r.includes("east")?(n=[1,0],o=10):r.includes("up")||r.includes("north")?(n=[0,1],o=10):r.includes("down")||r.includes("south")?(n=[0,-1],o=10):r.includes("horizontal")?(n="horizontal",o=10):r.includes("vertical")&&(n="vertical",o=10),{type:"translation",config:{direction:n,distance:o}}}else if(r.includes("scale")||r.includes("zoom")){let n=1,o=1;return r.includes("enlarge")||r.includes("bigger")||r.includes("up")?o=2:(r.includes("shrink")||r.includes("smaller")||r.includes("down"))&&(o=.5),{type:"scale",config:{center:[0,0],startScale:n,endScale:o,uniform:!0}}}else if(r.includes("transform")||r.includes("main")||r.includes("default")||r.includes("primary"))return{type:"translation",config:{direction:"horizontal",distance:0}};return null}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`变换引用解析失败: ${o}`,s)}return n}static extractTransformRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.transformRef&&typeof o.transformRef=="string"&&r.push(o.transformRef),Array.isArray(o.transformations)&&o.transformations.forEach(s=>{s.transformRef&&typeof s.transformRef=="string"&&r.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(r)]}}function Sg(){return{type:le.TRANSFORM_REF,canResolve:Fe.canResolve.bind(Fe),resolve:Fe.resolve.bind(Fe),validate:Fe.validate.bind(Fe)}}class ke{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.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,r){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const o=e.match(me.STYLE_REF);o?n=o[1]:n=e;const s=r.stylePresets[n];if(!s)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(s,r)}static resolveStylePreset(e,r){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(ze.canResolve(s))try{n[o]=ze.resolve(s,r)}catch(i){console.warn(`样式中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveStylePreset(s,r));return n}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(me.STYLE_REF);return o?n=o[1]:n=e,n in r.stylePresets}static applyStyle(e,r){if(!e||!r)return e;const n={...e};return n.style=n.style?{...n.style,...r}:{...r},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(s=>{r[s]!==void 0&&(n[s]=r[s])}),n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`样式引用解析失败: ${o}`,s)}return n}static extractStyleRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.styleRef&&typeof o.styleRef=="string"&&r.push(o.styleRef),o.style&&typeof o.style=="object"&&o.style.styleRef&&typeof o.style.styleRef=="string"&&r.push(o.style.styleRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.styleRef&&typeof s.styleRef=="string"&&r.push(s.styleRef),s.style&&s.style.styleRef&&typeof s.style.styleRef=="string"&&r.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(r)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Rg(){return{type:le.STYLE_REF,canResolve:ke.canResolve.bind(ke),resolve:ke.resolve.bind(ke),validate:ke.validate.bind(ke)}}class Qe{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const o=e.match(me.LAYOUT_REF);if(o?n=o[1]:n=e,r.layoutPresets&&r.layoutPresets[n]){const i=r.layoutPresets[n];return this.resolveLayoutPreset(i,r)}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,r){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(ze.canResolve(s))try{n[o]=ze.resolve(s,r)}catch(i){console.warn(`布局中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveLayoutPreset(s,r));return n}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(me.LAYOUT_REF);return o?n=o[1]:n=e,r.layoutPresets&&r.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,r){if(!e||!r)return e;const n={...e};return n.layout?n.layout={...n.layout,...r}:n.layout={...r},n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`布局引用解析失败: ${o}`,s)}return n}static extractLayoutRefs(e){const r=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&r.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const o of Object.values(n.layout))typeof o=="string"&&this.isLayoutRef(o)&&r.push(o);return[...new Set(r)]}static isLayoutRef(e){return me.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function Cg(){return{type:le.LAYOUT_REF,canResolve:Qe.canResolve.bind(Qe),resolve:Qe.resolve.bind(Qe),validate:Qe.validate.bind(Qe)}}class Ct{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.ANIMATION_REF.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new we(Q.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(me.ANIMATION_REF);if(!n)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const o=n[1],s=r.animationConfigs?.[o];if(!s)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${o}`);return this.resolveAnimationConfig(o,s,r)}static resolveAnimationConfig(e,r,n){if(!r.transforms||!Array.isArray(r.transforms))throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const o=r.transforms.map((a,c)=>{if(!a.id)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 id 字段`);if(!a.type)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] targetShapes 不能为空`);a.targetShapes.forEach((g,p)=>{if(typeof g!="string"||g.trim()==="")throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}].targetShapes[${p}] 必须是有效的字符串 ID`)});const l=Rf(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:d}}),s={id:e,control:r.control,transforms:o,visualEffects:r.visualEffects||[],progressControl:r.progressControl},i=Cf(s);if(!i.valid)throw new we(Q.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
16
+ Received: ${JSON.stringify(n)}`)}case"shear":{const n=t.params,o=ke(n.shearX,e),s=ke(n.shearY,e);return[o,s]}case"generic":{const n=t.params;return[ke(n.a,e),ke(n.b,e),ke(n.c,e),ke(n.d,e),ke(n.e,e),ke(n.f,e),ke(n.g,e),ke(n.h,e),ke(n.i,e)]}case"matrix":{const n=t.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: ${t.params.type}`)}}function ig(t){const e={};return Object.entries(t).forEach(([r,n])=>{if(typeof n=="string"&&sg(n))try{e[r]=rg(n)}catch(o){console.warn(`Failed to parse function string for ${r}: ${n}`,o),e[r]=()=>0}else e[r]=n}),e}function ag(t){if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!t.id||typeof t.id!="string"||t.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(t.transforms)?t.transforms.forEach((r,n)=>{(!r.id||typeof r.id!="string")&&e.push(`Transform at index ${n} must have a valid id`),(!r.type||typeof r.type!="string")&&e.push(`Transform at index ${n} must have a valid type`),(!r.params||typeof r.params!="object")&&e.push(`Transform at index ${n} must have valid params`),Array.isArray(r.targetShapes)?r.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 _s=Us.JSXGraph,sa=t=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!t.animation,animationId:t.animation?.id,hasControl:!!t.animation?.control,controlConfig:t.animation?.control,animationProgress:t.animationProgress});const e=b.useRef(null),[r,n]=b.useState(null),[,o]=b.useState({}),[s,i]=b.useState(!1),a=b.useRef({}),c=b.useRef({}),l=b.useRef(null),u=b.useRef({}),g=b.useCallback((f,p)=>{t.onShapeChange},[t.onShapeChange]),m=b.useCallback(f=>{t.onSelectionChange&&t.onSelectionChange(f?[f]:[])},[t.onSelectionChange]);return b.useEffect(()=>{if(e.current){try{const f=t.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",f),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const p=_s.initBoard(e.current,{boundingbox:f,axis:t.showAxis??!0,grid:t.showGrid??!0,showNavigation:!1,pan:{enabled:t.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",p.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",f),console.warn(" * 实际边界框:",p.getBoundingBox()),console.warn(" * 实际显示范围:",{left:p.getBoundingBox()[0],top:p.getBoundingBox()[1],right:p.getBoundingBox()[2],bottom:p.getBoundingBox()[3]})},100),n(p)}catch(f){console.error("JSXGraph initialization failed:",f)}return()=>{r&&_s.freeBoard(r)}}},[]),b.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!r,hasAnimation:!!t.animation,hasControl:!!t.animation?.control,animationId:t.animation?.id,controlType:t.animation?.control?.type,controlPosition:t.animation?.control?.position,controlRange:t.animation?.control?.range}),!r||!t.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!r+", control="+!!t.animation?.control),l.current){try{l.current.remove&&l.current.remove()}catch(p){console.warn("Failed to remove control:",p)}l.current=null}return}const f=t.animation.control;console.warn("✨ Creating Control Component:",{type:f.type,config:f,position:f.position,range:f.range});try{if(f.type==="slider"){const p=f.position[0]+(f.length||5);console.warn("📐 Slider creation parameters:",{startPoint:f.position,endPoint:[p,f.position[1]],values:[f.range[0],f.initial||0,f.range[1]],label:f.label,snapWidth:f.snapWidth||.01});const h=r.create("slider",[f.position,[p,f.position[1]],[f.range[0],f.initial||0,f.range[1]]],{name:f.label||"control",snapWidth:f.snapWidth||.01,withLabel:f.showLabel!==void 0?f.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});l.current=h,console.warn("✅ Slider created:",{id:h.id,name:h.name,initialValue:h.Value(),startPoint:f.position,endPoint:[p,f.position[1]],boundingBox:r.getBoundingBox(),visProp:h.visProp});const y=r.objectsList.map(v=>({id:v.id,type:v.elType,name:v.name,visible:v.visProp?.visible})),x=y.find(v=>v.id===h.id);if(console.warn("📊 Slider in board.objectsList:",!!x,x),console.warn("📊 All board objects count:",y.length),t.onAnimationChange){let v=!1;h.on("drag",()=>{if(v)return;v=!0;const S=(h.Value()-f.range[0])/(f.range[1]-f.range[0]);t.onAnimationChange?.(S),v=!1})}}else if(f.type==="glider"){const p=r.select(f.line,!0);if(p){const h=r.create("glider",[f.initial||0,0,p],{name:f.label||"control",snapWidth:f.snapWidth||.01});if(l.current=h,console.warn("✅ Glider created:",{id:h.id,name:h.name}),t.onAnimationChange){let y=!1;h.on("drag",()=>{if(y)return;y=!0;const x=h.Value();t.onAnimationChange?.(x),y=!1})}}else console.warn(`Reference line not found for glider: ${f.line}`)}}catch(p){console.error("Failed to create control component:",p)}return()=>{if(l.current){try{l.current.remove()}catch(p){console.warn("Failed to remove control on cleanup:",p)}l.current=null}}},[r,t.animation?.control]),b.useEffect(()=>{if(!r||!t.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:t.animation.id,transformCount:t.animation.transforms.length}),Object.values(a.current).forEach(h=>{try{h&&h.remove&&h.remove()}catch(y){console.warn("Failed to remove transform:",y)}}),a.current={};const f={},p=t.animationProgress??0;t.animation.transforms.forEach(h=>{try{let y,x;const v=h.usesControl||!1;if(l.current&&v){y=Fn(h,p,l.current),console.warn(`🔧 Creating transform ${h.id} (with dynamic params):`,{type:h.type,paramsTypes:y.map(S=>typeof S),targetShapes:h.targetShapes,controlValue:l.current.Value()}),x=r.create("transform",y,{type:h.type,id:`transform_${h.id}`});const w=()=>{if(!l.current)return;r.update();const S=l.current.Value();if(console.warn(`🎯 Slider drag - transform ${h.id} auto-updated (controlValue: ${S})`),t.onAnimationChange){const C=t.animation?.control?.range||[0,1],E=(S-C[0])/(C[1]-C[0]);t.onAnimationChange(E)}};l.current.on("drag",w),u.current[h.id]=w,console.warn(`🔗 Slider listener attached for transform ${h.id} (auto-update mode)`)}else y=Fn(h,p),console.warn(`🔧 Creating transform ${h.id} (with progress ${p}):`,{type:h.type,params:y,targetShapes:h.targetShapes}),x=r.create("transform",y,{type:h.type,id:`transform_${h.id}`});f[h.id]=x,console.warn(`📝 Transform ${h.id} created:`,{type:h.type,paramsTypes:y.map(w=>typeof w),transformMethods:Object.keys(x).filter(w=>typeof x[w]=="function")})}catch(y){console.error(`Failed to create transform ${h.id}:`,y)}}),a.current=f}catch(f){console.error("Transform setup failed:",f)}},[r,t.animation]),b.useEffect(()=>{if(!s||!r||!t.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${s}, board=${!!r}, animation=${!!t.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(([f,p])=>{const h=t.animation?.transforms.find(x=>x.id===f);if(!h)return;console.warn(`🔍 Binding transform ${f} (type: ${h.type}) to shapes:`,h.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(c.current));const y=h.targetShapes.map(x=>{const v=c.current[x];return v?console.warn(`✅ Found shape ${x}:`,v):(console.warn(`❌ Shape not found for transform binding: ${x}`),console.warn(" Available IDs:",Object.keys(c.current))),v}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",y.length),y.length>0)try{console.warn(`🔗 Attempting to bind transform ${f} to ${y.length} shapes`),p.bindTo(y),console.warn(`✅ Successfully bound transform ${f} to ${y.length} shapes`),console.warn(" Transform object:",p),console.warn(" Target elements:",y.map(x=>({id:x.id,name:x.name,type:x.elementClass})))}catch(x){console.error(`❌ Failed to bind transform ${f}:`,x),console.error(" Transform:",p),console.error(" TargetElements:",y)}else console.warn(`⚠️ No valid target elements for transform ${f}`)}),r.update(),console.warn("✅ All transforms bound and board updated")},[s,r,t.animation]),b.useEffect(()=>{if(!r||Object.keys(a.current).length===0)return;const f=t.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${f}`);try{Object.entries(a.current).forEach(([p,h])=>{const y=t.animation?.transforms.find(v=>v.id===p);if(!y)return;const x=Fn(y,f);console.warn(`🔄 Attempting to update transform ${p} with params:`,x),h.update?(console.warn(" Using transform.update(params)"),h.update(x)):h.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),h.setMatrix(r,y.type,x)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(h).filter(v=>typeof h[v]=="function")))}),r.update()}catch(p){console.error("Transform update failed:",p)}},[r,t.animationProgress]),b.useEffect(()=>{if(r)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:t.shapes.length,shapes:t.shapes.map(h=>({id:h.id,type:h.type,hasVertices:"vertices"in h,verticesCount:"vertices"in h&&h.vertices?h.vertices.length:"undefined",hasPosition:"position"in h,hasGeometryRef:"geometryRef"in h,geometryRef:"geometryRef"in h?h.geometryRef:void 0}))}),r.suspendUpdate(),[...r.objectsList].forEach(h=>{r.removeObject(h)});const p={};c.current={},t.shapes.forEach(h=>{if(h.type==="point")try{const y=Pn(r,h,t.mode,g,m);y&&(p[h.id]=y)}catch(y){console.warn(`Failed to create point shape ${h.id}:`,y)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",r.objectsList.map(h=>({id:h.id,name:h.name,type:h.elementClass}))),t.shapes.forEach(h=>{if(h.type==="line"||h.type==="circle"||h.type==="polygon")try{const y=Pn(r,h,t.mode,g,m);y&&(p[h.id]=y)}catch(y){console.warn(`Failed to create shape ${h.id}:`,y)}}),console.warn("📝 Starting phase 3: creating text labels"),t.shapes.forEach(h=>{if(h.type==="text")try{const y=Pn(r,h,t.mode,g,m);y&&(p[h.id]=y)}catch(y){console.warn(`Failed to create text ${h.id}:`,y)}}),o(p),c.current=p,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(p).length} shapes created`),r.unsuspendUpdate()}catch(f){console.error("Shape rendering failed:",f)}},[r,t.shapes,t.mode,g,m]),b.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),l.current&&Object.entries(u.current).forEach(([f,p])=>{try{l.current.off("drag",p),console.warn(` Removed drag listener for transform ${f}`)}catch(h){console.warn(`Failed to remove drag listener for ${f}:`,h)}}),u.current={},Object.values(a.current).forEach(f=>{try{f&&f.remove&&f.remove()}catch(p){console.warn("Failed to remove transform during cleanup:",p)}}),a.current={},c.current={},i(!1),console.warn("✅ Cleanup complete")},[]),d.jsx("div",{ref:e,className:"w-full h-full"})};function Pn(t,e,r,n,o){const s=r==="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,u;if(e.position.x!==void 0&&e.position.y!==void 0)l=e.position.x,u=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)l=e.position[0],u=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const g=t.create("point",[l,u],{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:g.id,pointName:g.name,hasIdProperty:"id"in g}),s&&(t.on("drag",()=>{n(e.id,{x:g.X(),y:g.Y()})}),t.on("down",()=>{o(e.id)})),g}catch(l){return console.error(`Failed to create point ${e.id}:`,l),null}case"line":const i=Or(e.start,t),a=Or(e.end,t);if(i&&a)try{const l=t.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&&t.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 c=Or(e.center,t);if(c){let l;if(e.through){const u=Or(e.through,t);u&&(l=t.create("circle",[c,u],{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=t.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:!s,visible:e.visible??!0}));return l&&s&&t.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((u,g)=>{const m=e.verticesConfig?e.verticesConfig[g]:null;return lg(u,t,m)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,l),console.warn(`🔧 Polygon ${e.id} vertices types:`,l.map(u=>({type:typeof u,isArray:Array.isArray(u),value:u}))),l.every(u=>u!==null)){const u={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 m={};e.verticesConfig.withLabel!==void 0?m.withLabel=e.verticesConfig.withLabel:m.withLabel=!0;const f={};let p=!1;e.verticesConfig.offset&&(f.offset=e.verticesConfig.offset,p=!0),e.verticesConfig.fontSize&&(f.fontSize=e.verticesConfig.fontSize,p=!0),e.verticesConfig.color&&(f.color=e.verticesConfig.color,p=!0),e.verticesConfig.anchorX&&(f.anchorX=e.verticesConfig.anchorX,p=!0),e.verticesConfig.anchorY&&(f.anchorY=e.verticesConfig.anchorY,p=!0),p&&(m.label=f),u.vertices=m,console.warn("🔧 Using JSXGraph vertices config:",m)}else u.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",u);const g=t.create("polygon",l,u);return console.warn("🔧 Polygon created:",g),console.warn("🔧 Polygon vertices:",g.vertices),console.warn("🔧 Polygon vertices names:",g.vertices?g.vertices.map(m=>m.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",g.vertices?g.vertices.map(m=>m.hasLabel?m.label:"no label"):"no vertices"),s&&t.on("down",()=>{o(e.id)}),g}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)}),t.create("text",[e.position.x,e.position.y,e.content],{color:e.color||"black",fontSize:e.fontSize??14,fixed:!0,visible:e.visible??!0})}catch(l){console.error(`Failed to create text ${e.id}:`,l)}break}return null}function Or(t,e){if(Array.isArray(t)&&t.length>=2)return t;if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return[t.x,t.y];if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const n=e.objects[t.$ref];if(n)return n}const r=e.objectsList.find(n=>n.id===t.$ref);if(r)return console.warn(`✅ Found referenced point ${t.$ref}:`,r),r;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(r){console.warn(`Failed to resolve point reference ${t.$ref}:`,r)}}return null}function lg(t,e,r){if(Array.isArray(t)&&t.length>=2){if(r&&r.name){const n=e.create("point",t,{name:r.name});return console.warn(`🔧 Created point with name ${r.name} at`,t),n}return t}if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t){const n=[t.x,t.y];if(r&&r.name){const o=e.create("point",n,{name:r.name});return console.warn(`🔧 Created point with name ${r.name} at`,n),o}return n}if("$ref"in t)try{if(e.objects&&e.objects[t.$ref]){const o=e.objects[t.$ref];if(o)return r&&r.name&&o.setName&&(o.setName(r.name),console.warn(`🔧 Updated point ${t.$ref} name to ${r.name}`)),o}const n=e.objectsList.find(o=>o.id===t.$ref);if(n)return console.warn(`✅ Found referenced point ${t.$ref}:`,n),r&&r.name&&n.setName&&(n.setName(r.name),console.warn(`🔧 Updated point ${t.$ref} name to ${r.name}`)),n;console.warn(`⚠️ Point reference ${t.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${t.$ref}:`,n)}}return null}function No(t,e={}){const{padding:r=.2,margin:n=1,minSize:o=4}=e,s=[];if(t.forEach(_=>{switch(_.type){case"point":s.push(_.position);break;case"line":const A=Dt(_.start,t),T=Dt(_.end,t);A&&s.push(A),T&&s.push(T);break;case"circle":const j=Dt(_.center,t);if(j&&(s.push(j),_.radius!==void 0&&s.push({x:j.x+_.radius,y:j.y},{x:j.x-_.radius,y:j.y},{x:j.x,y:j.y+_.radius},{x:j.x,y:j.y-_.radius})),_.through){const O=Dt(_.through,t);O&&s.push(O)}break;case"polygon":_.vertices.forEach(O=>{const M=Dt(O,t);M&&s.push(M)});break;case"text":s.push(_.position);const U=_.content.length*(_.fontSize||14)/20,z=(_.fontSize||14)/10;s.push({x:_.position.x+U,y:_.position.y},{x:_.position.x-U,y:_.position.y},{x:_.position.x,y:_.position.y+z},{x:_.position.x,y:_.position.y-z});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(_=>_.x)),a=Math.max(...s.map(_=>_.x)),c=Math.min(...s.map(_=>_.y)),l=Math.max(...s.map(_=>_.y)),u=(i+a)/2,g=(c+l)/2;let m=Math.max(a-i,o),f=Math.max(l-c,o);const p=800/500,h=m/f;Math.abs(h-p)>.1&&(h>p?f=m/p:m=f*p);const y=m*(1+r)+n*2,x=f*(1+r)+n*2,v=u-y/2,w=g+x/2,S=u+y/2,C=g-x/2,E=[v,w,S,C];if(process.env.NODE_ENV==="development"){const A=s.map(T=>({x:T.x,y:T.y,insideX:T.x>=v&&T.x<=S,insideY:T.y<=w&&T.y>=C,inside:T.x>=v&&T.x<=S&&T.y<=w&&T.y>=C})).filter(T=>!T.inside);A.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:E,outsidePoints:A.slice(0,5),totalOutside:A.length})}return{boundingBox:E,center:{x:u,y:g},width:y,height:x}}function Dt(t,e=[]){if(typeof t=="object"&&t!==null){if("x"in t&&"y"in t)return{x:t.x,y:t.y};if("$ref"in t){const r=e.find(n=>n.id===t.$ref&&n.type==="point");if(r)return r.position}}return null}function cg(t,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const r=[];if(t.forEach(o=>{switch(o.type){case"point":r.push({x:o.position.x,y:o.position.y,source:`point:${o.id}`});break;case"text":r.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;r.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,c)=>{const l=Dt(a,t);l&&r.push({x:l.x,y:l.y,source:`polygon:${o.id}:vertex${c}`})});break}}),console.log("📊 收集到的坐标点:",r),r.length>0){const o=Math.min(...r.map(c=>c.x)),s=Math.max(...r.map(c=>c.x)),i=Math.min(...r.map(c=>c.y)),a=Math.max(...r.map(c=>c.y));console.log("📐 原始包围盒:",{minX:o,maxX:s,minY:i,maxY:a,width:s-o,height:a-i})}const n=No(t,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",n),console.groupEnd(),n}const vr=t=>{const{shapes:e,mode:r,onShapeChange:n,onSelectionChange:o,width:s=600,height:i=400,showGrid:a=!0,showAxis:c=!0,className:l="",boundingBox:u,autoBoundingBox:g=!0,boundingBoxOptions:m,animation:f,animationProgress:p,onAnimationChange:h,showAnimationControls:y}=t,x=b.useMemo(()=>{if(u)return u;if(g&&e.length>0)try{process.env.NODE_ENV==="development"&&cg(e,"MathGraph Auto BoundingBox");const w=No(e,m);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",w.boundingBox),console.log(" - Center:",w.center),console.log(" - Width:",w.width),console.log(" - Height:",w.height),console.log(" - Options used:",m),w.boundingBox}catch(w){return console.warn("Failed to calculate auto bounding box, using default:",w),[-10,10,10,-10]}return[-10,10,10,-10]},[u,g,e,m]),v=b.useMemo(()=>({width:typeof s=="number"?`${s}px`:s,height:typeof i=="number"?`${i}px`:i}),[s,i]);return d.jsx(tg,{children:d.jsx("div",{className:`bg-white overflow-hidden ${l}`,style:v,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:d.jsx(sa,{shapes:e,mode:r,onShapeChange:n,onSelectionChange:o,boundingBox:x,showGrid:a,showAxis:c,animation:f,animationProgress:p,onAnimationChange:h})})})},ia=({shapes:t,width:e,height:r,showGrid:n=!0,showAxis:o=!0,boundingBox:s,autoBoundingBox:i,onShapeChange:a,className:c="",animation:l,animationProgress:u,showAnimationControls:g,onAnimationChange:m})=>{const f=b.useRef(null),[p,h]=b.useState({width:600,height:400});b.useEffect(()=>{const x=()=>{if(f.current){const{clientWidth:w,clientHeight:S}=f.current;w>0&&S>0&&h({width:w,height:S})}};x(),window.addEventListener("resize",x);const v=new ResizeObserver(x);return f.current&&v.observe(f.current),()=>{window.removeEventListener("resize",x),v.disconnect()}},[]);const y={width:e?typeof e=="string"?e:`${e}px`:"100%",height:r?typeof r=="string"?r:`${r}px`:"100%"};return d.jsx("div",{ref:f,className:`mathcard-v2-graph ${c}`,style:y,children:d.jsx(vr,{shapes:t,width:p.width,height:p.height,showGrid:n,showAxis:o,boundingBox:s,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:l,animationProgress:u,showAnimationControls:g,onAnimationChange:m})})},To=({config:t,onTransformChange:e,onTransformComplete:r,onError:n,layoutDensity:o,boardHeight:s,boardWidth:i,className:a=""})=>{const c=o??t.ui?.layoutDensity??"default",l=s??t.ui?.boardHeight??300,u=i??t.ui?.boardWidth??400,g=p=>{e?.(p)},m=()=>{r?.()},f=p=>{n?.(p)};return console.error("🔍 GeometryTransformContent: config =",{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,shapesAnimatedLength:t.shapes?.animated?.length,shapesStaticLength:t.shapes?.static?.length,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,boardConfigKeys:t.boardConfig?Object.keys(t.boardConfig):[],boardConfigBoundingBox:t.boardConfig?.boundingBox,boardConfigOriginX:t.boardConfig?.originX,boardConfigOriginY:t.boardConfig?.originY,configKeys:Object.keys(t)}),d.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:d.jsx(qi,{base:t.base,height:t.height,unit:t.unit,shapes:t.shapes,transform:t.transform,animation:t.animation,boardConfig:t.boardConfig,onTransformChange:g,onTransformComplete:m,onError:f,layoutDensity:c,boardHeight:l,boardWidth:u,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})};function dg(t){switch(t.contentType){case"formula":return d.jsx(Zt,{parts:[t.content],children:null});case"graph":return d.jsx(vr,{mode:"view",shapes:t.graphConfig?.shapes||[],boundingBox:t.graphConfig?.boundingBox,showGrid:t.graphConfig?.showGrid,showAxis:t.graphConfig?.showAxis});case"image":return d.jsx("img",{src:t.content,alt:"选项图片",className:"max-w-full"});default:return d.jsx("span",{children:t.content})}}const ug=({options:t,correctAnswers:e,answerType:r,layout:n="vertical",variant:o="default",value:s=[],onChange:i,showResult:a=!1,disabled:c=!1,className:l})=>{const u=b.useMemo(()=>t.map(m=>({id:m.id,label:dg(m),rawContent:m.content,contentType:m.contentType||"text"})),[t]),g=b.useCallback(m=>{i?.(m)},[i]);return d.jsx(vo,{type:r,options:u,value:s,onChange:g,correctAnswers:e,showResult:a,disabled:c,layout:n,variant:o,className:l})},fg={FACTOR_TABLE:"factorTable",SHORT_DIVISION:"shortDivision",VERTICAL_MULTIPLICATION:"verticalMultiplication",LONG_DIVISION:"longDivision"},gg={EDIT:"edit",REVIEW:"review",SOLUTION:"solution"},mg={CORRECT:"correct",INCORRECT:"incorrect",PENDING:"pending"};function aa(t){const{config:e,initialAnswers:r={},onAnswerChange:n,onValidationChange:o}=t,{number:s,rows:i}=e,a=b.useRef(r),c=b.useRef({}),[l,u]=b.useState(r),[g,m]=b.useState({});b.useEffect(()=>{a.current=l},[l]),b.useEffect(()=>{c.current=g},[g]);const f=b.useCallback((v,w)=>v===null||w===null?"pending":v*w===s?"correct":"incorrect",[s]),p=b.useCallback((v,w)=>{const S=a.current,C=c.current,E={value:w,status:"pending"},_={...S,[v]:E};a.current=_,u(_),n?.(_);const A=v.split("_");if(A.length!==3)return;const T=parseInt(A[1],10),j=parseInt(A[2],10);if(isNaN(T)||isNaN(j))return;const z=`factor_${T}_${j===0?1:0}`,O=_[z];if(w!==null&&O?.value!=null){const M=j===0?w:O.value,F=j===0?O.value:w,$=f(M,F),B={...C,[v]:$,[z]:$};c.current=B,m(B),o?.(B)}},[f,n,o]),h=b.useCallback(v=>g[v]||l[v]?.status||"pending",[g,l]),y=b.useMemo(()=>{const v=i*2;return Object.values(l).filter(S=>S.value!==null).length===v},[l,i]),x=b.useCallback(()=>{u({}),m({}),a.current={},c.current={}},[]);return{answers:l,updateAnswer:p,getCellStatus:h,validation:g,isComplete:y,reset:x}}function la(t){const{config:e,initialAnswers:r={},onAnswerChange:n}=t,{dividend:o,divisor:s,steps:i}=e,a=b.useRef(r),[c,l]=b.useState(r),[u,g]=b.useState({});b.useEffect(()=>{a.current=c},[c]);const m=b.useCallback(v=>{const w=o.toString();if(v===0)return parseInt(w[0],10);const S=u[v-1]?.remainder??0,C=parseInt(w[v],10);return S*10+C},[o,u]),f=b.useCallback(v=>{const w=m(v);return{quotient:Math.floor(w/s),remainder:w%s}},[m,s]),p=b.useCallback((v,w)=>{const S=a.current,C={value:w,status:"pending"},E={...S,[v]:C};a.current=E,l(E),n?.(E);const _=v.split("_");if(_.length!==2)return;const A=_[0],T=parseInt(_[1],10);if(isNaN(T)||T<0||T>=i)return;const j=f(T);g(M=>({...M,[T]:j}));let U=!1;w!==null&&(A==="quotient"?U=w===j.quotient:A==="remainder"&&(U=w===j.remainder));const z={value:w,status:w===null?"pending":U?"correct":"incorrect"},O={...E,[v]:z};a.current=O,l(O)},[f,i,n]),h=b.useCallback(v=>c[v]?.status||"pending",[c]),y=b.useMemo(()=>{const v=i*2;return Object.values(c).filter(S=>S.value!==null).length===v},[c,i]),x=b.useCallback(()=>{l({}),g({}),a.current={}},[]);return{answers:c,updateAnswer:p,getCellStatus:h,stepResults:u,isComplete:y,reset:x}}function pg(t,e){return e.toString().split("").reverse().map(Number).map((n,o)=>({digit:n,partial:t*n*Math.pow(10,o),rowIndex:o}))}function hg(t,e){return t.reduce((n,o)=>n+o.partial.toString().length,0)+e.toString().length}function yg(t,e,r){const n=t.split("_"),o=n[0];if(o==="partial"&&n.length===3){const s=parseInt(n[1],10),i=parseInt(n[2],10);if(isNaN(s)||isNaN(i))return null;const a=e[s]?.partial;if(a===void 0)return null;const c=a.toString().split("").reverse();return c[i]!==void 0?parseInt(c[i],10):null}if(o==="product"&&n.length===2){const s=parseInt(n[1],10);if(isNaN(s))return null;const i=r.toString().split("").reverse();return i[s]!==void 0?parseInt(i[s],10):null}return null}function bg(t,e){return Object.values(t).filter(n=>n.value!==null).length===e&&e>0}function ca(t){const{config:e,initialAnswers:r={},onAnswerChange:n}=t,{multiplicand:o,multiplier:s}=e,i=b.useRef(r),[a,c]=b.useState(r);b.useEffect(()=>{i.current=a},[a]);const l=b.useMemo(()=>o*s,[o,s]),u=b.useMemo(()=>pg(o,s),[o,s]),g=b.useMemo(()=>hg(u,l),[u,l]),m=b.useCallback((y,x)=>{const v=i.current,w=yg(y,u,l),C={value:x,status:x===null?"pending":x!==null&&x===w?"correct":"incorrect"},E={...v,[y]:C};i.current=E,c(E),n?.(E)},[u,l,n]),f=b.useCallback(y=>a[y]?.status||"pending",[a]),p=b.useMemo(()=>bg(a,g),[a,g]),h=b.useCallback(()=>{c({}),i.current={}},[]);return{answers:a,updateAnswer:m,getCellStatus:f,partialProducts:u,correctProduct:l,isComplete:p,reset:h}}function xg(t,e){if(t===0)return[{index:0,dividend:0,quotient:0,remainder:0,product:0}];const r=t.toString(),n=[];let o=0;for(let s=0;s<r.length;s++){o=o*10+parseInt(r[s],10);const i=Math.floor(o/e),a=o%e,c=i*e;n.push({index:s,dividend:o,quotient:i,remainder:a,product:c}),o=a}return n}function da(t){const{config:e,initialAnswers:r={},onAnswerChange:n}=t,{dividend:o,divisor:s}=e,i=b.useRef(r),[a,c]=b.useState(r),l=b.useMemo(()=>Math.floor(o/s),[o,s]),u=b.useMemo(()=>o%s,[o,s]),g=b.useMemo(()=>xg(o,s),[o,s]);b.useEffect(()=>{i.current=a},[a]);const m=(x,v)=>{if(x<0)return null;const w=x.toString();return v>=w.length?null:parseInt(w[w.length-1-v],10)},f=b.useCallback((x,v)=>{const w=i.current,S=x.split("_");if(S.length<2)return;let C=S[0],E;if(x.startsWith("div_q_"))C="quotient",E=parseInt(S[2],10);else if(x.startsWith("div_s")){C="product";const z=S[1].substring(1);E=parseInt(z,10)-1}else E=parseInt(S[1],10);if(isNaN(E)||E<0||E>=g.length)return;const _=g[E];let A=null,T=!1;if(C==="quotient")A=_.quotient,T=v!==null&&v===A;else if(C==="product")if(S.length===3){const z=parseInt(S[2],10);isNaN(z)||(A=m(_.product,z),T=v!==null&&v===A)}else A=_.product,T=v!==null&&v===A;else if(C==="remainder")if(S.length===3){const z=parseInt(S[2],10);isNaN(z)||(A=m(_.remainder,z),T=v!==null&&v===A)}else A=_.remainder,T=v!==null&&v===A;const j={value:v,status:v===null?"pending":T?"correct":"incorrect"},U={...w,[x]:j};i.current=U,c(U),n?.(U)},[g,n]),p=b.useCallback(x=>a[x]?.status||"pending",[a]),h=b.useMemo(()=>{const x=g.length*3;return Object.values(a).filter(w=>w.value!==null).length===x},[a,g]),y=b.useCallback(()=>{c({}),i.current={}},[]);return{answers:a,updateAnswer:f,getCellStatus:p,steps:g,quotient:l,remainder:u,isComplete:h,reset:y}}const ua=b.memo(function(e){const{config:r,answers:n,onCellChange:o,getCellStatus:s,readonly:i=!1}=e,{number:a,rows:c}=r,l=b.useCallback((g,m)=>{const f=m.trim()===""?null:parseInt(m,10);m.trim()!==""&&isNaN(f)||o(g,f)},[o]),u=b.useCallback(g=>{const m=`factor_${g}_0`,f=`factor_${g}_1`,p=n[m],h=n[f],y=s(m),x=s(f),v=w=>{const S="w-16 h-10 text-center border-2 rounded focus:outline-none focus:ring-2";switch(w){case"correct":return`${S} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${S} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${S} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}};return d.jsxs("div",{className:"contents",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:p?.value??"",readOnly:i,onChange:w=>l(m,w.target.value),className:v(y),"aria-label":`第 ${g+1} 行左侧因数`,"data-cell-id":m}),d.jsx("span",{className:"text-gray-500 font-medium select-none",children:"×"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:h?.value??"",readOnly:i,onChange:w=>l(f,w.target.value),className:v(x),"aria-label":`第 ${g+1} 行右侧因数`,"data-cell-id":f}),d.jsx("span",{className:"text-gray-500 font-medium select-none",children:"="}),d.jsx("span",{className:"text-gray-700 font-semibold min-w-[2rem] select-none",children:a})]})]},g)},[n,s,l,i,a]);return d.jsxs("div",{className:"inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`因数表:分解 ${a}`,children:[d.jsx("div",{className:"mb-4 text-center",children:d.jsxs("span",{className:"text-lg font-semibold text-gray-800",children:["找出 ",a," 的所有因数对"]})}),d.jsx("div",{className:"grid grid-cols-2 gap-x-8 gap-y-3",role:"grid","aria-label":`${a} 的因数表`,children:Array.from({length:c},(g,m)=>u(m))})]})});ua.displayName="FactorTableView";const $o=t=>{const{config:e,initialAnswers:r={},onAnswerChange:n,onValidationChange:o,readonly:s=!1}=t,{answers:i,updateAnswer:a,getCellStatus:c,validation:l,isComplete:u,reset:g}=aa({config:e,initialAnswers:r,onAnswerChange:n,onValidationChange:o});b.useEffect(()=>{u&&n&&n(i)},[u,i,n]);const m=s||e.mode!=="edit";return d.jsx(ua,{config:e,answers:i,onCellChange:a,getCellStatus:c,readonly:m})};$o.displayName="FactorTable";const fa=b.memo(function(e){const{config:r,answers:n,onCellChange:o,getCellStatus:s,readonly:i=!1}=e,{dividend:a,divisor:c,steps:l}=r,u=b.useCallback((f,p)=>{const h=p.trim();if(h===""){o(f,null);return}const y=parseInt(h,10);isNaN(y)||o(f,y)},[o]),g=f=>{const p="w-12 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-medium";switch(f){case"correct":return`${p} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${p} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${p} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}},m=b.useCallback(f=>{const p=`quotient_${f}`,h=`remainder_${f}`,y=n[p],x=n[h],v=s(p),w=s(h);return d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:y?.value??"",readOnly:i,onChange:S=>u(p,S.target.value),className:g(v),"aria-label":`第 ${f+1} 步的商`,"data-cell-id":p}),d.jsx("span",{className:"text-gray-400 select-none",children:"..."}),d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:x?.value??"",readOnly:i,onChange:S=>u(h,S.target.value),className:g(w),"aria-label":`第 ${f+1} 步的余数`,"data-cell-id":h})]},f)},[n,s,u,i]);return d.jsx("div",{className:"mathwiz-short-division inline-block p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`短除法:${a} ÷ ${c}`,children:d.jsxs("div",{className:"flex items-start gap-4",children:[d.jsxs("div",{className:"flex flex-col items-center pt-2",children:[d.jsx("span",{className:"text-xl font-bold text-gray-800",children:c}),d.jsx("div",{className:"w-8 h-0.5 bg-gray-400 my-1"})]}),d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsx("div",{className:"text-xl font-bold text-gray-800 text-right border-b-2 border-gray-400 pb-1",children:a}),d.jsx("div",{className:"flex flex-col gap-2 pt-2",children:Array.from({length:l},(f,p)=>m(p))})]})]})})});fa.displayName="ShortDivisionView";const ko=t=>{const{config:e,initialAnswers:r,onAnswerChange:n,readonly:o}=t,{answers:s,updateAnswer:i,getCellStatus:a,stepResults:c,isComplete:l}=la({config:e,initialAnswers:r,onAnswerChange:n});return b.useEffect(()=>{l&&n&&n(s)},[l,s,n]),d.jsx(fa,{config:e,answers:s,onCellChange:i,getCellStatus:a,stepResults:c,readonly:o})};ko.displayName="ShortDivision";function wg(t){const e=t.trim()===""?null:parseInt(t,10);return t.trim()!==""&&isNaN(e)?null:e}function vg(t){const e="w-8 h-10 text-center border-2 rounded focus:outline-none focus:ring-2 text-lg font-semibold";switch(t){case"correct":return`${e} border-green-500 bg-green-50 focus:ring-green-300`;case"incorrect":return`${e} border-red-500 bg-red-50 focus:ring-red-300`;default:return`${e} border-gray-300 focus:border-blue-500 focus:ring-blue-300`}}function Cg(t,e,r){return Math.max(t.toString().length,e.toString().length+1,r.toString().length)}const Rs=({digits:t,prefix:e,className:r=""})=>d.jsxs("div",{className:`flex justify-end items-center gap-1 ${r}`,children:[e,t.map((n,o)=>d.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-800",children:n},o))]}),As=({width:t})=>d.jsx("div",{className:"border-t-2 border-gray-400 my-2",style:{width:t},"aria-hidden":"true"}),ga=({cellId:t,value:e,status:r,readonly:n,ariaLabel:o,onChange:s})=>d.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:e??"",readOnly:n,onChange:i=>s(t,i.target.value),className:vg(r),"aria-label":o,"data-cell-id":t}),Sg=({rowIndex:t,partial:e,maxDigits:r,answers:n,getCellStatus:o,readonly:s,onChange:i})=>{const a=e.toString().split(""),c=r-a.length;return d.jsxs("div",{className:"flex justify-end items-center gap-1 mb-1",children:[Array.from({length:c}).map((l,u)=>d.jsx("span",{className:"w-8"},u)),[...a].reverse().map((l,u)=>{const g=`partial_${t}_${u}`;return d.jsx(ga,{cellId:g,value:n[g]?.value??null,status:o(g),readonly:s,ariaLabel:`第 ${t+1} 行中间积第 ${u+1} 位`,onChange:i},g)})]},`p-${t}`)},_g=({correctProduct:t,maxDigits:e,answers:r,getCellStatus:n,readonly:o,onChange:s})=>{const i=t.toString().split(""),a=e-i.length;return d.jsxs("div",{className:"flex justify-end items-center gap-1",children:[Array.from({length:a}).map((c,l)=>d.jsx("span",{className:"w-8"},l)),[...i].reverse().map((c,l)=>{const u=`product_${l}`;return d.jsx(ga,{cellId:u,value:r[u]?.value??null,status:n(u),readonly:o,ariaLabel:`乘积第 ${l+1} 位`,onChange:s},u)})]})},ma=b.memo(function(e){const{config:r,answers:n,onCellChange:o,getCellStatus:s,partialProducts:i,correctProduct:a,readonly:c=!1}=e,{multiplicand:l,multiplier:u}=r,g=Cg(l,u,a),m=b.useCallback((f,p)=>o(f,wg(p)),[o]);return d.jsx("div",{className:"inline-block p-6 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`乘法竖式:${l} × ${u}`,children:d.jsxs("div",{className:"flex flex-col items-end",children:[d.jsx(Rs,{digits:l.toString().split(""),className:"mb-1"}),d.jsx(Rs,{digits:u.toString().split(""),prefix:d.jsx("span",{className:"w-8 h-10 flex items-center justify-center text-lg font-semibold text-gray-600 select-none",children:"×"}),className:"mb-2"}),d.jsx(As,{width:`${g*2.25}rem`}),i.map((f,p)=>d.jsx(Sg,{rowIndex:p,partial:f.partial,maxDigits:g,answers:n,getCellStatus:s,readonly:c,onChange:m},p)),d.jsx(As,{width:`${g*2.25}rem`}),d.jsx(_g,{correctProduct:a,maxDigits:g,answers:n,getCellStatus:s,readonly:c,onChange:m})]})})});ma.displayName="VerticalMultiplicationView";const jo=t=>{const{config:e,initialAnswers:r,onAnswerChange:n,readonly:o}=t,{answers:s,updateAnswer:i,getCellStatus:a,partialProducts:c,correctProduct:l,isComplete:u}=ca({config:e,initialAnswers:r,onAnswerChange:n});return b.useEffect(()=>{u&&n&&n(s)},[u,s,n]),d.jsx(ma,{config:e,answers:s,onCellChange:i,getCellStatus:a,partialProducts:c,correctProduct:l,readonly:o})};jo.displayName="VerticalMultiplication";const Rg=dn({base:["border rounded text-center font-medium transition-colors duration-150","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent","text-lg"],variants:{size:{digit:"w-10 h-10",standard:"min-w-12 h-10 px-2"},status:{normal:"border-gray-300 bg-white text-gray-900",correct:"border-emerald-500 bg-emerald-50 text-emerald-700",incorrect:"border-red-500 bg-red-50 text-red-700 line-through",idle:"border-dashed border-gray-400 bg-gray-50 text-gray-500"},type:{input:"",label:"font-bold bg-gray-100 cursor-default",result:"font-semibold bg-blue-50",placeholder:"opacity-0 pointer-events-none"},disabled:{true:"cursor-not-allowed opacity-60",false:""},readonly:{true:"cursor-default",false:""}},defaultVariants:{size:"digit",status:"normal",type:"input",disabled:!1,readonly:!1}});dn({base:"inline-flex items-center gap-1"});const Io=b.memo(function(e){const{type:r,value:n,readonly:o=!1,status:s,autoTab:i=!1,place:a,onChange:c,className:l,cellId:u,onAutoTab:g}=e,m=b.useRef(null),[f,p]=b.useState(n?.toString()||"");b.useEffect(()=>{p(n?.toString()||"")},[n]);const h=a===void 0||a!==null,y=b.useMemo(()=>Rg({size:h?"digit":"standard",status:s||"normal",type:r,readonly:o,disabled:o}),[h,s,r,o]),x=b.useCallback(w=>{if(o)return;let S=w.target.value;S=S.replace(/[^0-9]/g,""),h&&(S=S.slice(-1)),p(S);const C=S===""?null:Number(S);c?.(C),h&&i&&S&&u&&g&&g(u,"next")},[o,h,i,u,c,g]),v=b.useCallback(w=>{o||w.key==="Backspace"&&f===""&&u&&g&&g(u,"prev")},[o,f,u,g]);return r==="placeholder"?d.jsx("div",{className:`${y} ${l||""}`,"aria-hidden":"true","data-cell-id":u}):r==="label"||r==="result"||o?d.jsx("div",{className:`${y} ${l||""}`,role:"text","aria-label":u?`单元格 ${u}:${n||""}`:`值:${n||""}`,"aria-readonly":"true","data-cell-id":u,"data-place":a,"data-testid":u?`mathcell-${u}`:"mathcell",children:n||""}):d.jsx("input",{ref:m,type:"text",inputMode:"numeric",pattern:"[0-9]*",value:f,onChange:x,onKeyDown:v,className:`${y} ${l||""}`,disabled:o,"aria-label":u?`输入单元格 ${u}`:"数学输入","aria-invalid":s==="incorrect",maxLength:h?1:void 0,"data-cell-id":u,"data-place":a,"data-testid":u?`mathcell-input-${u}`:"mathcell-input"})});Io.displayName="MathCell";function Ag(t){return{display:"grid",gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${t.rows}, auto)`,gap:"0.1rem",justifyItems:"center",alignItems:"center"}}function Eg(t,e){const{dividend:r,divisor:n}=t,s=r.toString().split("").map(Number);n.toString().split("").map(Number);const a=s.length+1;let c=2;for(let m=0;m<e.length;m++)c+=3;const l=[];for(let m=0;m<e.length;m++){const f=e[m];l.push({id:`div_q_${m}`,type:"quotient",value:f.quotient,place:m,readonly:!1,position:{row:0,col:m+1}})}l.push({id:"divisor",type:"divisor",value:n,readonly:!0,position:{row:1,col:0},className:"text-right pr-2 self-end pb-1"});for(let m=0;m<s.length;m++){const p=m===0?"div-bracket-left pt-2 mt-2":"div-bracket-top pt-2 mt-2";l.push({id:`dividend_${m}`,type:"dividend",value:s[m],readonly:!0,position:{row:1,col:m+1},className:p,dataAttrs:{"data-digit-index":m.toString()}})}let u=2;const g=s.length-e.length;for(let m=0;m<e.length;m++){const f=e[m],p=m+1;f.dividend.toString().split("").map(Number).length;const v=f.product.toString().split("").map(Number),w=v.length,C=f.remainder.toString().split("").map(Number),E=C.length,_=g+m+1,A=_-w+1;for(let T=0;T<w;T++)l.push({id:`div_s${p}_${T}`,type:"product",value:v[T],place:T,readonly:!1,position:{row:u,col:A+T}});if(u++,l.push({id:`hline_${m}`,type:"horizontalLine",value:null,readonly:!0,position:{row:u,col:A,colspan:w},className:"border-t-2 border-neutral-800 my-1"}),u++,m<e.length-1){const U=e[m+1].dividend.toString().split("").map(Number),z=_+1,O=z-E;for(let F=0;F<E;F++)l.push({id:`remainder_${m}_${F}`,type:"remainderWithBringDown",value:C[F],readonly:!0,position:{row:u,col:O+F}});const M=U[U.length-1];l.push({id:`bringdown_${m}`,type:"remainderWithBringDown",value:M,readonly:!0,position:{row:u,col:z}})}else{const T=_-E+1;for(let j=0;j<E;j++)l.push({id:`remainder_${m}_${j}`,type:"remainder",value:C[j],readonly:!0,position:{row:u,col:T+j}})}u+=1}return c=u,{columns:a,rows:c,cells:l,divisorPosition:[1,0],dividendStartPosition:[1,1],quotientStartPosition:[0,1]}}const pa=b.memo(function(e){const{config:r,answers:n,onCellChange:o,getCellStatus:s,steps:i,readonly:a=!1}=e;b.useEffect(()=>{if(document.getElementById("mathwiz-long-division-styles"))return;const m=document.createElement("style");return m.id="mathwiz-long-division-styles",m.textContent=`
17
+ .div-bracket-top {
18
+ border-top: 2px solid #1b2b4c;
19
+ position: relative;
20
+ }
21
+ .div-bracket-top::after {
22
+ content: '';
23
+ position: absolute;
24
+ top: -2px;
25
+ left: -8px;
26
+ width: 8px;
27
+ border-top: 2px solid #1b2b4c;
28
+ }
29
+ .div-bracket-left {
30
+ border-top: 2px solid #1b2b4c;
31
+ position: relative;
32
+ }
33
+ .div-bracket-left::before {
34
+ content: '';
35
+ position: absolute;
36
+ left: -14px;
37
+ top: -2px;
38
+ bottom: 4px;
39
+ width: 14px;
40
+ border-right: 2px solid #1b2b4c;
41
+ border-top-right-radius: 12px 40%;
42
+ border-bottom-right-radius: 12px 40%;
43
+ }
44
+ `,document.head.appendChild(m),()=>{const f=document.getElementById("mathwiz-long-division-styles");f&&f.remove()}},[]);const c=b.useMemo(()=>Eg(r,i),[r,i]),l=(m,f)=>{o(m,f)},u=m=>{switch(m){case"correct":return"correct";case"incorrect":return"incorrect";case"pending":return"idle";default:return"idle"}},g=m=>{const{id:f,type:p,value:h,place:y,readonly:x=!1,position:v,className:w,dataAttrs:S}=m;let C="input",E=a||x;switch(p){case"quotient":case"product":case"remainder":C="input";break;case"dividend":case"divisor":C="label",E=!0;break;case"horizontalLine":C=null,E=!0;break;case"remainderWithBringDown":C="label",E=!0;break;case"placeholder":C="placeholder",E=!0;break;default:C="placeholder",E=!0;break}const _=u(s(f));let A=`${v.row+1}`,T=`${v.col+1}`;v.colspan&&v.colspan>1&&(T=`${v.col+1} / span ${v.colspan}`),v.rowspan&&v.rowspan>1&&(A=`${v.row+1} / span ${v.rowspan}`);const j={gridRow:A,gridColumn:T,...m.type==="horizontalLine"?{justifySelf:"stretch",alignSelf:"center"}:{}};return d.jsx("div",{className:w,style:j,"data-cell-id":f,...S,children:C!==null&&d.jsx(Io,{type:C,value:h!==null?h:void 0,readonly:E,status:_,place:y,onChange:U=>l(f,U),cellId:f,autoTab:!E&&y!==null})},f)};return d.jsxs("div",{className:"mathwiz-long-division p-4 bg-white rounded-lg shadow-sm border border-gray-200",role:"region","aria-label":`长除法:${r.dividend} ÷ ${r.divisor}`,children:[d.jsx("div",{className:"text-lg font-bold text-primary-500 mb-4",children:"长除法竖式"}),d.jsx("div",{className:"long-division-grid",style:{...Ag(c),paddingLeft:"1.5rem",overflow:"visible"},children:c.cells.map(g)})]})});pa.displayName="LongDivisionView";const Mo=t=>{const{config:e,initialAnswers:r,onAnswerChange:n,readonly:o}=t,{answers:s,updateAnswer:i,getCellStatus:a,steps:c,quotient:l,remainder:u,isComplete:g}=da({config:e,initialAnswers:r,onAnswerChange:n});return b.useEffect(()=>{g&&n&&n(s)},[g,s,n]),d.jsx(pa,{config:e,answers:s,onCellChange:i,getCellStatus:a,steps:c,readonly:o})};Mo.displayName="LongDivision";const Ng=({block:t,onInteraction:e})=>{const{containerType:r,config:n,onAnswerChange:o}=t,s=b.useCallback(i=>{e?.({type:"answerChange",answers:i}),o?.(i)},[e,o]);switch(r){case"factorTable":return d.jsx($o,{config:n,onAnswerChange:s});case"shortDivision":return d.jsx(ko,{config:n,onAnswerChange:s});case"verticalMultiplication":return d.jsx(jo,{config:n,onAnswerChange:s});case"longDivision":return d.jsx(Mo,{config:n,onAnswerChange:s});default:return null}},Tg=({headers:t,values:e,colors:r={}})=>{const{headerBg:n="#f1f5f9",valueBg:o="#ffffff",borderColor:s="#e2e8f0"}=r;return t.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):d.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:[d.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${s}`},children:t.map((i,a)=>d.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:n,fontWeight:"600",textAlign:"center",borderRight:a<t.length-1?`1px solid ${s}`:"none",color:"#1e293b"},children:i},a))}),d.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>d.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))})]})},ha=({content:t,onInteraction:e,interactionValues:r={}})=>{const n=(o,s)=>{if(o.enabled===!1)return null;const i=`${o.type}-${s}`,a=c=>{e?.(i,c)};switch(o.type){case"text":return d.jsx(na,{content:o.content,style:o.style,onInteraction:a},i);case"formula":const c=o;return d.jsx(oa,{parts:c.parts||[],displayMode:c.displayMode,style:o.style},i);case"graph":const l=o;return d.jsx(ia,{shapes:l.shapes||[],width:l.width,height:l.height,showGrid:l.showGrid,showAxis:l.showAxis,boundingBox:l.boardConfig?.boundingBox,autoBoundingBox:!l.boardConfig?.boundingBox,animation:l.animation,animationProgress:l.animationProgress,showAnimationControls:l.showAnimationControls,onAnimationChange:l.onAnimationChange},i);case"hundredGrid":const u=o;return d.jsx(Eo,{...u.props},i);case"placeValueChart":const g=o;return d.jsx(Tg,{...g.props},i);case"geometryTransform":const m=o;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:m.metadata,config:m.metadata?.config,hasConfig:!!m.metadata?.config,configKeys:m.metadata?.config?Object.keys(m.metadata.config):[],configShapes:m.metadata?.config?.shapes,configShapesAnimatedLength:m.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:m.metadata?.config?.shapes?.static?.length,configBase:m.metadata?.config?.base,configHeight:m.metadata?.config?.height,configUnit:m.metadata?.config?.unit,configTransform:m.metadata?.config?.transform}),d.jsx(To,{config:m.metadata.config,onTransformChange:y=>a({type:"transformChange",progress:y}),onTransformComplete:()=>a({type:"transformComplete"}),onError:y=>a({type:"error",error:y})},i);case"optionGroup":const f=o,p=f.metadata?.optionGroupId;return d.jsx(ug,{options:f.options,correctAnswers:f.correctAnswers,answerType:f.answerType,layout:f.layout,variant:f.variant,value:r[p]??[],onChange:y=>a({type:"optionChange",value:y,optionGroupId:p})},i);case"mathContainer":const h=o;return d.jsx(Ng,{block:h,onInteraction:a},i);default:return d.jsx("div",{onClick:()=>a({type:"click"}),children:o.content},i)}};return d.jsx(d.Fragment,{children:t.map(n)})},Oe=({data:t,scene:e="question",layout:r={type:"card"},renderer:n={mode:"default"},theme:o="light",onContentInteraction:s,interactionValues:i,className:a="",children:c})=>{const l=Qi(t,e),u={data:l,scene:e,layout:l.layout||r,renderer:l.renderer||n,theme:o,onContentInteraction:s},g=l.layout||r,m=(()=>{switch(g.type){case"grid":return ta;case"flow":return ra;default:return ea}})(),f=(()=>{const p={className:a,theme:o,"data-testid":"mathcard-v2-container"};switch(g.type){case"grid":return{...p,columns:g.columns||2,gap:g.gap||"16px",responsive:g.responsive!==!1};case"flow":return{...p,direction:g.direction||"vertical",gap:g.gap||"16px",wrap:g.wrap!==!1};default:return{...p,padding:g.padding||"24px",shadow:g.shadow!==!1,border:g.border!==!1}}})();return d.jsx(eg.Provider,{value:u,children:d.jsx(m,{...f,children:c||d.jsx(ha,{content:l.content,layout:l.layout||r,onInteraction:s,interactionValues:i})})})};Oe.CardLayout=ea;Oe.GridLayout=ta;Oe.FlowLayout=ra;Oe.TextContent=na;Oe.FormulaContent=oa;Oe.GraphContent=ia;Oe.GeometryTransformContent=To;Oe.ContentRenderer=ha;const ya=t=>{const{ixlConfig:e,enableIXLStyle:r,isMobile:n}=t,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 u={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return u[e.type]||u.remember},[e.tagColor,e.type]),i=b.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=b.useMemo(()=>{if(!r)return{};const u={backgroundColor:s,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return n?Object.assign(u,{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(u,{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)"}),u},[r,s,i,n]),c=b.useMemo(()=>!r||n?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[r,n]);return{ixlClassName:b.useMemo(()=>{if(!r)return"";const u=["ixl-styled"];return u.push(`ixl-type-${e.type}`),n?u.push("ixl-mobile-layout"):u.push("ixl-desktop-layout"),u.join(" ")},[r,e.type,n]),tagStyle:a,contentStyle:c,tagText:o,tagColor:s,tagTextColor:i}},$g=(t,e)=>{let r=null;return(...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n)},e)}},ba=(t={})=>{const e=typeof t=="number"?t:t.breakpoint||768,r=typeof t=="number"?!0:t.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),c=b.useCallback(()=>{if(typeof window>"u")return;const m=window.innerWidth,f=m<e;o(m),i(f),a.current.forEach(p=>{try{p()}catch(h){console.error("Error in resize listener:",h)}})},[e]),l=b.useCallback($g(c,150),[c]);b.useEffect(()=>{if(!(!r||typeof window>"u"))return c(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l)}},[r,l,c]);const u=b.useCallback(m=>(a.current.add(m),()=>{a.current.delete(m)}),[]),g=b.useCallback(m=>{a.current.delete(m)},[]);return{isMobile:s,viewportWidth:n,addResizeListener:u,removeResizeListener:g}},qt=({cardProps:t,ixlConfig:e,enableIXLStyle:r=!0,wrapperMode:n="mathcard",mobileBreakpoint:o=768,className:s="",style:i,children:a,onResponsiveChange:c})=>{const l=ba(o),u=ya({ixlConfig:e,enableIXLStyle:r,isMobile:l.isMobile});b.useEffect(()=>{c?.(l.isMobile)},[l.isMobile,c]);const g=b.useMemo(()=>{const p=["ixl-style-card-container"];return r&&p.push(u.ixlClassName),s&&p.push(s),l.isMobile?p.push("ixl-mobile"):p.push("ixl-desktop"),p.join(" ")},[r,u.ixlClassName,s,l.isMobile]),m=b.useMemo(()=>{const p={...i};return r&&!l.isMobile?{...p,paddingLeft:u.contentStyle.paddingLeft}:p},[r,l.isMobile,u.contentStyle,i]),f=b.useMemo(()=>{if(n!=="mathcard"||!t)return"";const p=[t.className||""];return r&&p.push("ixl-adjusted"),p.filter(Boolean).join(" ")},[n,t?.className,r]);return d.jsxs("div",{className:g,style:m,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":r,"data-responsive-mode":l.isMobile?"mobile":"desktop",children:[r&&e.showTag!==!1&&d.jsx("div",{className:"ixl-tag",style:u.tagStyle,"data-testid":"ixl-tag",children:d.jsx("span",{className:"ixl-tag-text",children:u.tagText})}),n==="mathcard"&&t?d.jsx(Oe,{...t,className:f}):a]})};qt.displayName="IXLStyleCard";const kg={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},jg={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},Ig={remember:"速记",review:"回顾",solve:"解答"},Mg=({grades:t,onGradeSelect:e,selectedGrade:r})=>d.jsxs("div",{className:"grade-navigation",children:[d.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),d.jsx("div",{className:"grade-navigation__grid",children:t.map(n=>d.jsxs("div",{className:`grade-card ${r===n.id?"grade-card--selected":""}`,style:{borderLeftColor:n.color},onClick:()=>e?.(n.id),children:[d.jsx("div",{className:"grade-card__level",children:n.level}),d.jsx("div",{className:"grade-card__name",children:n.name}),d.jsx("div",{className:"grade-card__description",children:n.description})]},n.id))})]}),xa=({abilities:t,width:e=400,height:r=400})=>{const n=()=>t.length===0?"":t.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*t.indexOf(i)/t.length,c=i.score/i.maxScore*40+10,l=50+c*Math.sin(a),u=50-c*Math.cos(a);return`${l},${u}`}).join(" "),o=i=>{const a=Math.PI*2*i/Math.max(t.length,1),c=50+40*Math.sin(a),l=50-40*Math.cos(a);return{x2:c,y2:l}},s=i=>{const a=Math.PI*2*i/Math.max(t.length,1),c=50+45*Math.sin(a),l=50-45*Math.cos(a);let u="middle";return a>Math.PI*.25&&a<Math.PI*.75&&(u="start"),a>Math.PI*1.25&&a<Math.PI*1.75&&(u="end"),{x:c,y:l,textAnchor:u}};return d.jsxs("svg",{"data-testid":"radar-chart",width:e,height:r,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[d.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),t.map((i,a)=>{const{x2:c,y2:l}=o(a);return d.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:c,y2:l,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),t.length>2&&d.jsx("polygon",{"data-testid":"radar-polygon",points:n(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),t.map((i,a)=>{let c,l;if(i.svgPoint)c=i.svgPoint.x,l=i.svgPoint.y;else{const u=Math.PI*2*a/t.length,g=i.score/i.maxScore*40+10;c=50+g*Math.sin(u),l=50-g*Math.cos(u)}return d.jsx("circle",{"data-testid":"data-point",cx:c,cy:l,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),t.map((i,a)=>{const{x:c,y:l,textAnchor:u}=s(a);return d.jsx("text",{x:c,y:l,textAnchor:u,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},Es={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 Og{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),Es):(await ye.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 Es}}static async submitFeedback(e){try{await ye.post(`${this.API_BASE_URL}/feedback`,e)}catch(r){throw console.error("Failed to submit feedback:",r),new Error("提交反馈失败")}}}const Fg=Yt.create((t,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){t({loading:!0,error:null});try{const r=await Og.fetchRadarAbilityData();t({data:r,loading:!1})}catch(r){const n=r instanceof Error?r.message:"获取数据失败";t({error:n,loading:!1})}}},setData:r=>{t({data:r,error:null,loading:!1})},setError:r=>{t({error:r,loading:!1})},reset:()=>{t({data:null,loading:!1,error:null})}})),wa=({ability:t})=>{const e=t.score/t.maxScore*100;return d.jsxs("div",{className:"ability-progress-bar-item","data-ability":t.name,"data-testid":"progress-bar-container",children:[d.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[d.jsx("span",{className:"text-gray-700 font-medium",children:t.name}),d.jsxs("span",{className:"text-gray-600",children:[t.score,"/",t.maxScore]})]}),d.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:d.jsx("div",{className:`${t.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":t.score,"aria-valuemin":0,"aria-valuemax":t.maxScore,"aria-label":`${t.name} progress: ${t.score} out of ${t.maxScore}`})})]})},va=({generalRecommendation:t})=>d.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:d.jsxs("div",{className:"flex items-start",children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),d.jsxs("div",{className:"ml-3",children:[d.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),d.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:t})]})]})}),Ca=({ability:t,customLinkTexts:e={}})=>{const r=n=>{const o={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[n]||o[n]||"开始挑战"};return d.jsx(X.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":t.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:d.jsx(X.CardBody,{className:"p-5",children:d.jsxs("div",{className:"flex flex-col gap-3",children:[d.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[t.name,": 专项提高"]}),d.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:t.recommendation}),d.jsx(X.Button,{as:"a",href:t.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:d.jsx(xe.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${t.name}专项提高页面`,children:r(t.name)})]})})})},Pg="_dashboardLayout_10wqn_5",Dg="_upperSection_10wqn_19",Lg="_lowerSection_10wqn_33",Gg="_radarChartArea_10wqn_51",Fr={dashboardLayout:Pg,upperSection:Dg,lowerSection:Lg,radarChartArea:Gg},Vg=()=>{const{data:t,loading:e,error:r,fetchData:n}=Fg();return b.useEffect(()=>{n()},[n]),e?d.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[d.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),d.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):r?d.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[d.jsx("div",{className:"text-red-500 mb-4",children:d.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),d.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),d.jsx("p",{className:"text-gray-600 mb-4",children:r}),d.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:"重试"})]}):t?d.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:[d.jsxs("div",{className:"flex justify-between items-center mb-6",children:[d.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),d.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${t.overallRating}`,children:["综合评级: ",t.overallRating]})]}),d.jsxs("div",{className:Fr.dashboardLayout,children:[d.jsxs("div",{className:Fr.upperSection,children:[d.jsx("div",{className:Fr.radarChartArea,children:d.jsx(xa,{abilities:t.abilities})}),d.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:t.abilities.map(o=>d.jsx(wa,{ability:o},o.name))})]}),d.jsxs("div",{className:Fr.lowerSection,children:[d.jsx(va,{generalRecommendation:t.generalRecommendation}),d.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),d.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.abilities.map(o=>d.jsx(Ca,{ability:o},o.name))})]})]})]}):d.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:d.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},fr={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},zg={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},Ug={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Cr={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},Bg=[{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")}],Hg="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",we={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:""}]}]}]},qg=Bg,Wg=Cr;class Yg{baseURL;token;constructor(e="/api/v1",r=Hg){this.baseURL=e,this.token=r}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,r={}){const n=await fetch(e,{...r,headers:{...this.getAuthHeaders(),...r.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 r=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(r)).json()}async getUnitProgress(e,r){const n=r?`${this.baseURL}/content/courses/${e}/units/${r}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(n)).json()}async batchUpdateLessonProgress(e,r){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(r)})).json()}async updateLessonProgress(e,r,n,o){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${r}/lessons/${n}/progress`,{method:"POST",body:JSON.stringify({status:o})})}setToken(e){this.token=e}getToken(){return this.token}}const Pr=new Yg;class nt extends Error{constructor(e,r,n){super(e),this.code=r,this.originalError=n,this.name="DataSourceError"}}class Kg{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},Pr.setToken(this.config.token)}async getUserGradeUnitsNav(e,r){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${r}`),await this.withRetry(()=>Pr.getUserGradeUnitsNav(e))}catch(n){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",n),new nt(`获取年级单元导航数据失败: ${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(r){throw console.error("[ApiDataSource] 获取用户个人信息失败:",r),new nt(`获取用户个人信息失败: ${r instanceof Error?r.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",r instanceof Error?r: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 nt(`获取探索菜单数据失败: ${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(()=>Pr.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(r){throw console.error("[ApiDataSource] 更新课时进度失败:",r),new nt(`更新课时进度失败: ${r instanceof Error?r.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",r instanceof Error?r:void 0)}}async batchUpdateLessonProgress(e,r){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,r),await this.withRetry(()=>Pr.batchUpdateLessonProgress(e,r))}catch(n){throw console.error("[ApiDataSource] 批量更新课时进度失败:",n),new nt(`批量更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async withRetry(e){let r;for(let n=1;n<=this.config.retryCount;n++)try{return await e()}catch(o){r=o instanceof Error?o:new Error(String(o)),n<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${n}次重试...`,r.message),await this.delay(this.config.retryDelay))}throw r}delay(e){return new Promise(r=>setTimeout(r,e))}getConfig(){return{...this.config}}}class Xg{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,r){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${r}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${r}`),new nt("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${r}`),{userId:r,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:we.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:we.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:fr[o.moduleCategory]||fr.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new nt("模拟数据源:获取用户个人信息失败","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 nt("模拟数据源:获取探索菜单数据失败","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 nt("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,r){if(await this.simulateDelay(),this.shouldSimulateError())throw new nt("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,r),{success:!0,results:r.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 we}getLessonsData(){const e={};return we.units.forEach(r=>{e[r.id]=r.lessons.map(n=>({id:n.id,title:n.title,duration:n.duration,knowledgeItems:n.knowledgeItems.map(o=>({...o,progress:0}))}))}),e}}class Jg{static instances=new Map;static createDataSource(e){const{type:r,config:n,customDataSourceClass:o}=e,s=this.getInstanceKey(r,n);if(this.instances.has(s))return this.instances.get(s);let i;switch(r){case"api":i=new Kg(n);break;case"mock":i=new Xg(n);break;case"custom":if(!o)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new o(n);break;default:throw new Error(`不支持的数据源类型: ${r}`)}return this.instances.set(s,i),console.log(`[DataSourceFactory] 创建数据源: type=${r}, 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 r=!1,n=!1,o=!1;try{typeof process<"u"&&process.env?(r=process.env.NODE_ENV==="development",n=process.env.NODE_ENV==="test",o=process.env.REACT_APP_USE_MOCK==="true"):(r=!0,o=!0)}catch(s){console.warn("无法检测环境变量,使用默认配置:",s),r=!0,o=!0}return r||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,r){return`${e}:${r.name}:${JSON.stringify(r)}`}}function Zg(){return Jg.createDefaultDataSource()}function Qg(t={}){const{dataSource:e=Zg(),fallbackStrategy:r="mock",errorHandling:n={},performance:o={},theme:s={},debug:i=!1,enableDevTools:a=!1}=t;return{dataSource:e,fallbackStrategy:r,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 em(t,e){return{...t,...e,errorHandling:{...t.errorHandling,...e.errorHandling},performance:{...t.performance,...e.performance},theme:{...t.theme,...e.theme}}}const Sa=b.createContext(null),_a=()=>{const t=b.useContext(Sa);if(!t)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return t},Ra=({children:t,config:e})=>{const[r,n]=b.useState(()=>Qg(e)),[o,s]=b.useState(null),[i,a]=b.useState([]),[c,l]=b.useState(null),[u,g]=b.useState({}),[m,f]=b.useState(!1),[p,h]=b.useState(null),[y,x]=b.useState(null),[v,w]=b.useState([]),S=b.useCallback(async(T,j)=>{f(!0),h(null);try{process.env.NODE_ENV!=="test"&&await new Promise(O=>setTimeout(O,100));const U=await r.dataSource.getUserGradeUnitsNav(T,j);l(U);const z={};we.units.forEach(O=>{z[O.id]=O.lessons.map(M=>({id:M.id,title:M.title,duration:M.duration,knowledgeItems:M.knowledgeItems.map(F=>({...F,progress:0}))}))}),console.log("Lessons data loaded:",z),g(z);try{const O=await r.dataSource.getUserProfile(j);s(O)}catch(O){console.warn("获取用户信息失败,使用默认数据:",O),s({id:j,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const O=await r.dataSource.getExploreMenu();a(O)}catch(O){console.warn("获取探索菜单失败,使用默认数据:",O),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(U){if(console.error("数据加载错误:",U),r.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const z={userId:j,courseId:T,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:we.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:we.units.map((M,F)=>({unitId:M.id,title:M.title,description:M.description,moduleCategory:M.moduleCategory,estimatedDuration:M.estimatedDuration,totalLessons:M.lessons.length,completedLessons:F<2?Math.floor(M.lessons.length*.5):0,progressPercentage:F<2?50:0,status:F<2?"in-progress":"not-started",lastAccessed:F<2?new Date().toISOString():void 0,isActive:F===0,route:`/math/grade-5/unit/${M.id}`,icon:fr[M.moduleCategory]||fr.Default}))};l(z);const O={};we.units.forEach(M=>{O[M.id]=M.lessons.map(F=>({id:F.id,title:F.title,duration:F.duration,knowledgeItems:F.knowledgeItems.map($=>({...$,progress:0}))}))}),g(O),s({id:j,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else h(U instanceof Error?U.message:"数据加载失败"),l(null)}finally{f(!1)}},[r]),C=b.useCallback(T=>{w(j=>j.includes(T)?j.filter(U=>U!==T):[...j,T])},[]),E=b.useCallback(T=>{x(T)},[]),_=b.useCallback(T=>{n(j=>em(j,T))},[]);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 T=c.units.find(U=>U.isActive);console.log("Found active unit:",T);const j=T?.unitId||c.units[0].unitId;console.log("Setting default active unit:",j),x(j),console.log("Default active unit set after state update:",j)}else console.log("No units data available for setting default active unit")},[c]);const A={userInfo:o,exploreMenu:i,unitsData:c,lessons:u,loading:m,error:p,activeUnitId:y,activeLessonIds:v,config:r,theme:r.theme,enableVirtualization:r.performance?.enableVirtualization,setLoading:f,setError:h,setActiveUnit:E,toggleLesson:C,loadPageData:S,updateConfig:_};return d.jsx(Sa.Provider,{value:A,children:t})},tm=({gradeId:t,userId:e,onLearnAction:r,className:n,userInfo:o,exploreMenu:s})=>{const{userInfo:i,exploreMenu:a,unitsData:c,lessons:l,loading:u,error:g,activeUnitId:m,activeLessonIds:f,setActiveUnit:p,toggleLesson:h,loadPageData:y}=_a(),x=o??i,v=s??a;b.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",t,"userId:",e),y(t,e)},[t,e,y]),b.useEffect(()=>{console.log("activeUnitId from context:",m),console.log("lessons from context:",l);const C=c?.units?.find(_=>_.unitId===m)||null,E=C&&m&&l[m]?{id:C.unitId,title:C.title,description:C.description,estimatedDuration:C.estimatedDuration,totalLessons:C.totalLessons,moduleCategory:C.moduleCategory,lessons:l[m]}:null;console.log("activeUnit computed:",E)},[m,l,c]);const w=c?.units?.find(C=>C.unitId===m)||null,S=w&&m&&l[m]?{id:w.unitId,title:w.title,description:w.description,estimatedDuration:w.estimatedDuration,totalLessons:w.totalLessons,moduleCategory:w.moduleCategory,lessons:l[m]}:null;return u?d.jsx("div",{className:`grade-unit-browser-page loading ${n||""}`,"data-testid":"grade-unit-browser-page",children:d.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):g?d.jsxs("div",{className:`grade-unit-browser-page error ${n||""}`,"data-testid":"grade-unit-browser-page",children:[d.jsx("div",{className:"error-message","data-testid":"error-message",children:g}),d.jsx(ft,{onClick:()=>y(t,e),intent:"retry",useNewClassName:!0,className:"retry-button",children:"重试"})]}):d.jsxs("div",{className:`grade-unit-browser-page ${n||""}`,"data-testid":"grade-unit-browser-page",children:[d.jsx("div",{className:"header-area",children:d.jsx(hi,{userData:x||void 0,exploreItems:v})}),d.jsx("div",{className:"sidebar-area",children:d.jsx(qs,{data:c,activeUnitId:m,onUnitSelect:p,loading:u})}),d.jsx("div",{className:"content-area",children:d.jsx(Hs,{unit:S,activeLessonIds:f,onToggleLesson:h,onLearnAction:r||(()=>{}),loading:u})})]})},rm=t=>d.jsx(Ra,{config:t.config,children:d.jsx(tm,{...t})});function nm(t){return t.steps!==void 0}function om(t){if(nm(t))return t;if(Array.isArray(t)){if(t.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=t[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=t.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:t,total_steps:t.length,strategy:"step_by_step",estimated_time:t.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}function Aa(t){return Array.isArray(t)}const sm=(t,e,r=.1)=>{if(!t.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const n=parseFloat(t);if(isNaN(n))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(n<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const s=Math.abs(n-e)<=r;return{isValid:!0,isCorrect:s,errorMessage:s?void 0:"答案不正确,请再试一次"}},im=()=>Yt.create((t,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:r=>{t({problemData:r,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:r=>{t({userAnswer:r,validationError:null})},updateChoiceAnswer:r=>{t({userAnswer:r,validationError:null})},submitAnswer:r=>{const n=e();if(!n.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}let o=n.userAnswer;if((Array.isArray(r)||r!==void 0)&&(o=r),Aa(o)){const u=o.map(f=>f.id),g=n.problemData.answer_info?.correctAnswers||[];process.env.NODE_ENV==="development"&&console.log("[答案验证]",{selectedIds:u,correctAnswers:g,answerInfo:n.problemData.answer_info});const m=u.length===g.length&&u.every(f=>g.includes(f));t({isCorrect:m,showAnswerForm:!1,validationError:null,currentScene:m?"success":"explanation"});return}const s=typeof o=="string"?o:"",i=n.problemData.answer_info?.value??n.problemData.answer.value,a=Number(i),c=n.problemData.answer_info?.tolerance??.1,l=sm(s,a,c);if(!l.isValid){t({userAnswer:o,validationError:l.errorMessage||"答案格式错误"});return}t({userAnswer:o,isCorrect:l.isCorrect,showAnswerForm:!1,validationError:null,currentScene:l.isCorrect?"success":"explanation"})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),wt=im(),Oo=()=>wt(t=>t.currentScene),Fo=()=>wt(t=>t.userAnswer),am=()=>wt(t=>t.isCorrect),Po=()=>wt(t=>t.showAnswerForm),Ea=()=>wt(t=>t.validationError),lm=()=>wt(t=>t.problemData),Do=()=>wt(It.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,updateChoiceAnswer:t.updateChoiceAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),cm=b.createContext(null),Sr=()=>{const t=b.useContext(cm);if(!t)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return t},dm=()=>{const t=Sr(),e=b.useCallback(r=>r.currentScene,[]);return t(e)},um=()=>{const t=Sr(),e=b.useCallback(r=>r.userAnswer,[]);return t(e)},fm=()=>{const t=Sr(),e=b.useCallback(r=>r.showAnswerForm,[]);return t(e)},gm=()=>{const t=Sr(),e=b.useCallback(r=>r.validationError,[]);return t(e)},mm=()=>Sr()(It.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,updateChoiceAnswer:e.updateChoiceAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),mn=()=>{try{return dm()}catch{return Oo()}},pn=()=>{try{return um()}catch{return Fo()}},hn=()=>{try{return fm()}catch{return Po()}},yn=()=>{try{return gm()}catch{return Ea()}},bn=()=>{try{return mm()}catch{return Do()}},Mt=({problemData:t,userAnswer:e,showAnswerForm:r,onAnswerSubmit:n,onAnswerChange:o,validationError:s,noBorder:i=!1})=>{const a=b.useCallback((m,f)=>{f.type==="optionChange"&&o(f.value)},[o]),c=b.useMemo(()=>Array.isArray(e)?(t.scenes?.question?.items??[]).reduce((f,p)=>(p.type==="optionGroup"&&p.metadata?.optionGroupId&&(f[p.metadata.optionGroupId]=e),f),{}):{},[e,t]),l=Array.isArray(e)||t.scenes?.question?.items?.some(m=>m.type==="optionGroup"),u=m=>{m.preventDefault(),n(e)},g=m=>{o(m)};return d.jsx("div",{className:"question-scene-container",children:d.jsxs("div",{className:"question-scene-card",children:[d.jsx("div",{className:"question-display-area",children:d.jsx(Oe,{data:{id:t.id,grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1},onContentInteraction:a,interactionValues:c})}),r&&d.jsxs("div",{className:"answer-form-container",children:[d.jsxs("form",{onSubmit:u,className:"answer-form",children:[!l&&d.jsxs(d.Fragment,{children:[d.jsx("label",{className:"answer-label",children:"答案"}),d.jsx("input",{type:"number",value:typeof e=="string"?e:"",onChange:m=>g(m.target.value),className:`answer-input ${s?"error":"normal"}`,placeholder:"?",required:!0}),d.jsx("span",{className:"answer-unit",children:t.basicInfo.answerUnit||t.basicInfo.areaUnit})]}),d.jsx(ft,{type:"submit",size:"lg",intent:"submit",useNewClassName:!0,className:"submit-button",children:"提交答案"})]}),s&&d.jsxs("div",{className:"validation-error",children:[d.jsx("span",{children:"⚠️"}),d.jsx("span",{children:s})]})]})]})})},Na=({problemData:t,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",t),console.log("🔍 RememberModule scenes.remember:",t?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",t?.scenes?.remember?.content);const n=(()=>{const s=t.scenes?.review?.items;if(s&&Array.isArray(s)&&s.length>0)return console.log("🔍 RememberModule 使用 review.items"),s;const i=t.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=t.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const c=t.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 s=d.jsx("div",{className:"remember-module-content",children:d.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?d.jsx(qt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):d.jsxs("div",{className:"remember-module-container",children:[d.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})}const o=d.jsx("div",{className:"remember-module-content",children:n.map((s,i)=>{const{type:a,content:c,style:l,parts:u}=s;switch(a){case"text":return d.jsx("p",{className:"remember-module-text-block",style:l,children:c},i);case"formula":return d.jsx("div",{className:"remember-module-formula-block",children:d.jsx(Oe,{data:{id:`formula-${i}`,grade:t.grade,unit:t.unit,content:[{type:"formula",content:c,parts:u||[c]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return d.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?d.jsx(qt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):d.jsxs("div",{className:"remember-module-container",children:[d.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})},Lo=({problemData:t,userAnswer:e,enableIXLStyle:r=!0})=>{const n=b.useMemo(()=>Aa(e)?e.length===0?"未选择":e.map(i=>i.contentType==="formula"?i.content:i.content||i.id).join("、"):e||"--",[e]),o=d.jsxs("div",{className:"review-module-content",children:[d.jsx("p",{className:"review-module-question",children:t.basicInfo.question}),d.jsx("div",{className:"review-module-graph",children:d.jsx(Oe,{data:{id:"review-problem",grade:t.grade,unit:t.unit,content:t.scenes?.question?.items||t.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:r?"ixl-adjusted":""})}),d.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",d.jsx("span",{className:"review-module-user-answer-value",children:n})]})]});return r?d.jsx(qt,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:o}):d.jsxs("div",{className:"review-module-container",children:[d.jsx("h4",{className:"review-module-title",children:"复习"}),o]})},pm=t=>[{color:"var(--mc-step-color-ident)",bg:"var(--mc-step-bg-ident)"},{color:"var(--mc-step-color-calc)",bg:"var(--mc-step-bg-calc)"},{color:"var(--mc-step-color-res)",bg:"var(--mc-step-bg-res)"}][t%3],hm=({step:t,problemData:e,stepNumber:r})=>{const{title:n,description:o,chartConfig:s}=t.content,i=!!s,a=pm(r-1),c=[{type:"text",content:o.replace(/<br>/g,`
45
+ `).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return d.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[d.jsxs("h3",{className:"explanation-step-title",children:[d.jsx("span",{className:"explanation-step-number",children:r}),d.jsx("span",{children:n})]}),d.jsxs("div",{className:"explanation-step-content",children:[d.jsx(Oe,{data:{id:`${t.id}-description`,grade:e.grade,unit:e.unit,content:c},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&s.type&&d.jsx("div",{className:"explanation-step-chart-container",children:s.type==="hundredGrid"?d.jsx(Eo,{rows:s.rows||2,cols:s.cols||6,cellSize:s.cellSize||36,mode:s.mode||"readonly",value:s.value,fillColor:s.fillColor,baseColor:s.baseColor,className:"mathwiz-hundredgrid-explanation"}):s.type==="geometryTransform"&&(s.config||s.metadata?.config)?d.jsx(To,{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)}):s.shapes&&s.shapes.length>0?d.jsx(vr,{shapes:s.shapes,width:s.width||400,height:s.height||300,boundingBox:s.boundingBox||[-10,10,10,-10],showGrid:s.showGrid||!1,showAxis:s.showAxis||!1,mode:"view",className:"mx-auto"}):null})]})]})},Go=({problemData:t,enableIXLStyle:e=!0})=>{const[r,n]=b.useState(!1),o=t?.scenes?.solve?.items||t?.scenes?.solve?.content,s=Array.isArray(o)&&o.length>0,i=b.useMemo(()=>o&&o.map(g=>g.type==="geometryTransform"&&g.metadata?.config&&!g.config?{...g,config:g.metadata.config}:g),[o]),a=b.useMemo(()=>om(t.explanation),[t.explanation]),c=a.steps.length>0,l=b.useMemo(()=>c?a.steps.map(g=>({...g,content:{title:g.title,description:g.description,chartConfig:g.chartConfig?{...g.chartConfig,boundingBox:g.chartConfig.type==="graph"&&Array.isArray(g.chartConfig.boundingBox)&&g.chartConfig.boundingBox.length===4?[g.chartConfig.boundingBox[0],g.chartConfig.boundingBox[1],g.chartConfig.boundingBox[2],g.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[c,a.steps]),u=d.jsxs("div",{className:"solve-module-content",children:[s?d.jsxs(d.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",o),o?.forEach?.((g,m)=>{if(g.type==="geometryTransform"){const f=i?.[m];console.log(`🔍 SolveModule: geometryTransform block [${m}] =`,{type:g.type,hasMetadata:!!g.metadata,metadata:g.metadata,hasMetadataConfig:!!g.metadata?.config,metadataConfig:g.metadata?.config,hasConfig:!!g.config,config:g.config,hasShapes:!!g.shapes,shapes:g.shapes,hasTransform:!!g.transform,transform:g.transform,fixedBlockHasConfig:!!f?.config,fixedBlockConfig:f?.config,fixedBlockHasMetadataConfig:!!f?.metadata?.config,fixedBlockMetadataConfig:f?.metadata?.config,isConfigFixed:!g.config&&!!f?.config})}}),d.jsx(Oe,{data:{id:"solve-steps",grade:t.grade,unit:t.unit,content:i},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):d.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),d.jsx("div",{className:"solve-module-button-container",children:d.jsx(ft,{intent:"solve",variant:"light",useNewClassName:!0,onClick:()=>n(g=>!g),className:"solve-module-button",children:r?"收起详细解题步骤":"查看详细解题步骤"})}),r&&d.jsxs("div",{className:"solve-module-detailed-container",children:[d.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),c?d.jsx("div",{className:"solve-module-detailed-list",children:l.map((g,m)=>d.jsx(hm,{step:g,problemData:t,stepNumber:m+1},g.id))}):d.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?d.jsx(qt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:u}):d.jsxs("div",{className:"solve-module-container",children:[d.jsx("h4",{className:"solve-module-title",children:"解题"}),u]})},ym=t=>{if(t.answer_info?.displayValue)return t.answer_info.displayValue;const e=t.answer_info?.value;if(e!=null)return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e);const r=t.answer?.value;return r!=null?String(r):"--"},Qt=({problemData:t,userAnswer:e,onNextQuestion:r})=>{console.log("🔍 ExplanationScene problemData:",t),console.log("🔍 ExplanationScene scenes.remember:",t?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",t?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",t?.scenes?.remember?.content);const n=b.useMemo(()=>ym(t),[t]);return d.jsxs("div",{children:[d.jsx("div",{className:"explanation-error-banner",children:d.jsxs("div",{className:"explanation-inner-container",children:[d.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),d.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[d.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),d.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[d.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),d.jsx("div",{className:"correct-answer-value-container",children:d.jsx("span",{className:"correct-answer-value",children:d.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:n})})})]})]}),d.jsx("div",{className:"explanation-button-container",children:d.jsx(ft,{onClick:r,size:"lg",intent:"next",useNewClassName:!0,className:"explanation-next-button",children:"明白了"})})]})}),d.jsxs("div",{className:"explanation-content-area",children:[d.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),d.jsx(Lo,{problemData:t,userAnswer:e}),d.jsx(Na,{problemData:t}),d.jsx(Go,{problemData:t})]}),d.jsx("div",{className:"explanation-bottom-area",children:d.jsx(ft,{onClick:r,size:"md",intent:"next",useNewClassName:!0,children:"明白了"})})]})},Ot=({problemData:t,onNextQuestion:e})=>d.jsxs("div",{className:"success-scene-container",children:[d.jsx("h3",{className:"success-message-title",children:"正确!"}),d.jsx("p",{className:"success-message-description",children:"你做得很好!"}),d.jsx("div",{className:"concept-review-container",children:d.jsx(Oe,{data:{id:"review-concepts",grade:t.grade,unit:t.unit,content:t.scenes?.review?.items||t.scenes?.review?.content||t.scenes?.remember?.items||t.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),d.jsx(ft,{onClick:e,size:"lg",intent:"next",useNewClassName:!0,className:"next-button",children:"下一题"})]}),ut={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};let zt=class extends Error{code;details;constructor(e,r,n){super(r),this.name="AdapterError",this.code=e,this.details=n}};const bm={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},xm={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},ce={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"},ee={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 Ce extends Error{code;details;constructor(e,r,n){super(r),this.name="AdapterError",this.code=e,this.details=n}}const qr={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"}},Ns={[ee.INVALID_INPUT]:"输入数据无效",[ee.MISSING_REQUIRED_FIELD]:"缺少必需字段",[ee.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[ee.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[ee.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[ee.STYLE_REF_NOT_FOUND]:"样式引用未找到",[ee.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[ee.BOARD_REF_NOT_FOUND]:"画板引用未找到",[ee.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[ee.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[ee.TRANSFORMATION_FAILED]:"数据转换失败",[ee.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},Rt={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Dn={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"]},Ta=["question","solve","review","remember"],pe={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_]*)$/},Ae={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},$a={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.5rem",heading_normal:"1.25rem",body:"1.2rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},ka={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_secondary",fontSize:"$fonts.heading_normal",fontWeight:"600",lineHeight:1.5,letterSpacing:"0.01em"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"},hundredGrid_primary:{id:"hundredGrid_primary",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.primary",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_highlight:{id:"hundredGrid_highlight",baseColor:"$colors.background_lighter",borderColor:"$colors.primary",selectedColor:"$colors.success",textColor:"$colors.text_primary",fontSize:"$fonts.body"},hundredGrid_solve:{id:"hundredGrid_solve",baseColor:"$colors.background_light",borderColor:"$colors.border_light",selectedColor:"$colors.highlight_yellow",textColor:"$colors.text_primary",fontSize:"$fonts.body"}}},ja={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:"左三角形模板"}}},Ia={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"}}},Ma={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:"缩放变换"}}},Gt={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:"垂直滑块动画"}}},Oa={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:"扩展画板配置(带网格和坐标轴)"}}},Nt={designTokens:$a.design_tokens,stylePresets:ka.style_presets,geometryPresets:ja.geometry_presets,layoutPresets:Ia.layout_presets,transformDefinitions:Ma.transform_definitions,animationDefinitions:Gt.slider_definitions,animationConfigs:Gt.slider_definitions,boardDefinitions:Oa.board_definitions};function Fa(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!Gt,sliderDefinitionsKeys:Gt.slider_definitions?Object.keys(Gt.slider_definitions):[]});const t=Gt.slider_definitions;return{designTokens:$a.design_tokens,stylePresets:ka.style_presets,geometryPresets:ja.geometry_presets,layoutPresets:Ia.layout_presets,transformDefinitions:Ma.transform_definitions,animationDefinitions:t,animationConfigs:t,boardDefinitions:Oa.board_definitions}}class Be{static canResolve(e){return pe.DESIGN_TOKEN.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,r.designTokens)}static resolvePath(e,r){const n=e.split(".");let o=r;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,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`设计令牌解析失败: ${o}`,s)}return n}static extractDesignTokenRefs(e){const r=[],n=o=>{typeof o=="string"?this.canResolve(o)&&r.push(o):Array.isArray(o)?o.forEach(n):typeof o=="object"&&o!==null&&Object.values(o).forEach(n)};return n(e),r}static replaceDesignTokenRefs(e,r,n){const o=s=>{if(typeof s=="string"){if(this.canResolve(s))try{return this.resolve(s,r)}catch(u){if(n)return n(s);throw u}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(s))!==null;){a.index>c&&l.push(s.substring(c,a.index));const u=a[0];try{const g=this.resolve(u,r);l.push(String(g))}catch{n?l.push(String(n(u))):l.push(u)}c=a.index+u.length}return c<s.length&&l.push(s.substring(c)),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,c]of Object.entries(s))i[a]=o(c);return i}}return s};return o(e)}}function wm(){return{type:ce.DESIGN_TOKEN,canResolve:Be.canResolve.bind(Be),resolve:Be.resolve.bind(Be)}}class Qe{static canResolve(e,r){if(typeof e!="string"||e.length===0)return!1;if(pe.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(r&&r.geometryPresets){let s;const i=e.match(pe.GEOMETRY_REF);return i?s=i[1]:s=e,s in r.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,r){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!r.geometryPresets,pointFound:!!r.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(r.geometryPresets&&r.geometryPresets[n]){const o=r.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,r){if(!this.canResolve(e,r))throw new Error(`无法解析的几何引用: ${e}`);let n;const o=e.match(pe.GEOMETRY_REF);o?n=o[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(r.geometryPresets||{}));const s=r.geometryPresets[n];if(!s)throw console.error(`❌ Geometry preset not found: ${n} in`,r.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,r):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,r):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,r){if(!this.canResolve(e,r))return!1;let n;const o=e.match(pe.GEOMETRY_REF);return o?n=o[1]:n=e,n in r.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,r){const n=this.resolve(e,r);if(n.styleRef&&r.stylePresets[n.styleRef]){const o=r.stylePresets[n.styleRef];return{...n,style:{...o}}}return n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`几何引用解析失败: ${o}`,s)}return n}static extractGeometryRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.geometryRef&&typeof o.geometryRef=="string"&&r.push(o.geometryRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.geometryRef&&typeof s.geometryRef=="string"&&r.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(r)]}}function vm(){return{type:ce.GEOMETRY_REF,canResolve:Qe.canResolve.bind(Qe),resolve:Qe.resolve.bind(Qe),validate:Qe.validate.bind(Qe)}}class Pe{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.TRANSFORM_REF.test(e)?!0:/_(rotation|translation|scale|transform|reflection|shear|mirror)$/i.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const o=e.match(pe.TRANSFORM_REF);if(o?n=o[1]:n=e,r.transformDefinitions&&r.transformDefinitions[n])return{...r.transformDefinitions[n]};const s=this.createDefaultTransform(n);if(s)return console.warn(`⚠️ 使用智能默认变换: ${n}`,s),s;throw new Error(`变换定义未找到: ${n}`)}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(pe.TRANSFORM_REF);return o?n=o[1]:n=e,r.transformDefinitions&&r.transformDefinitions[n]?!0:this.createDefaultTransform(n)!==null}static applyTransform(e,r){if(!r||!e)return e;const n={...e};switch(r.type){case"rotation":n.vertices=this.applyRotation(e.vertices,r.angle,r.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,r.dx,r.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,r.factor,r.origin);break;default:console.warn(`未知的变换类型: ${r.type}`)}return n}static applyRotation(e,r,n){if(!e||!Array.isArray(e))return e;const[o,s]=n,i=r*Math.PI/180,a=Math.cos(i),c=Math.sin(i);return e.map(([l,u])=>{const g=l-o,m=u-s;return[o+g*a-m*c,s+g*c+m*a]})}static applyTranslation(e,r,n){return!e||!Array.isArray(e)?e:e.map(([o,s])=>[o+r,s+n])}static applyScale(e,r,n){if(!e||!Array.isArray(e))return e;const[o,s]=n;return e.map(([i,a])=>{const c=i-o,l=a-s;return[o+c*r,s+l*r]})}static createDefaultTransform(e){const r=e.toLowerCase();if(r.includes("rotation")||r.includes("rotate")){let n=0,o=Math.PI,s="clockwise";return r.includes("left")?(s="clockwise",o=Math.PI):r.includes("right")?(s="counterclockwise",o=Math.PI):r.includes("half")||r.includes("180")?o=Math.PI:r.includes("full")||r.includes("360")?o=2*Math.PI:(r.includes("quarter")||r.includes("90"))&&(o=Math.PI/2),{type:"rotation",config:{center:[0,0],startAngle:n,endAngle:o,direction:s}}}else if(r.includes("translation")||r.includes("translate")||r.includes("move")){let n=[0,0],o=0;return r.includes("left")||r.includes("west")?(n=[-1,0],o=10):r.includes("right")||r.includes("east")?(n=[1,0],o=10):r.includes("up")||r.includes("north")?(n=[0,1],o=10):r.includes("down")||r.includes("south")?(n=[0,-1],o=10):r.includes("horizontal")?(n="horizontal",o=10):r.includes("vertical")&&(n="vertical",o=10),{type:"translation",config:{direction:n,distance:o}}}else if(r.includes("scale")||r.includes("zoom")){let n=1,o=1;return r.includes("enlarge")||r.includes("bigger")||r.includes("up")?o=2:(r.includes("shrink")||r.includes("smaller")||r.includes("down"))&&(o=.5),{type:"scale",config:{center:[0,0],startScale:n,endScale:o,uniform:!0}}}else if(r.includes("transform")||r.includes("main")||r.includes("default")||r.includes("primary"))return{type:"translation",config:{direction:"horizontal",distance:0}};return null}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`变换引用解析失败: ${o}`,s)}return n}static extractTransformRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.transformRef&&typeof o.transformRef=="string"&&r.push(o.transformRef),Array.isArray(o.transformations)&&o.transformations.forEach(s=>{s.transformRef&&typeof s.transformRef=="string"&&r.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(r)]}}function Cm(){return{type:ce.TRANSFORM_REF,canResolve:Pe.canResolve.bind(Pe),resolve:Pe.resolve.bind(Pe),validate:Pe.validate.bind(Pe)}}class Ie{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.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,r){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const o=e.match(pe.STYLE_REF);o?n=o[1]:n=e;const s=r.stylePresets[n];if(!s)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(s,r)}static resolveStylePreset(e,r){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(Be.canResolve(s))try{n[o]=Be.resolve(s,r)}catch(i){console.warn(`样式中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveStylePreset(s,r));return n}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(pe.STYLE_REF);return o?n=o[1]:n=e,n in r.stylePresets}static applyStyle(e,r){if(!e||!r)return e;const n={...e};return n.style=n.style?{...n.style,...r}:{...r},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(s=>{r[s]!==void 0&&(n[s]=r[s])}),n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`样式引用解析失败: ${o}`,s)}return n}static extractStyleRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.styleRef&&typeof o.styleRef=="string"&&r.push(o.styleRef),o.style&&typeof o.style=="object"&&o.style.styleRef&&typeof o.style.styleRef=="string"&&r.push(o.style.styleRef),Array.isArray(o.shapes)&&o.shapes.forEach(s=>{s.styleRef&&typeof s.styleRef=="string"&&r.push(s.styleRef),s.style&&s.style.styleRef&&typeof s.style.styleRef=="string"&&r.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(r)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Sm(){return{type:ce.STYLE_REF,canResolve:Ie.canResolve.bind(Ie),resolve:Ie.resolve.bind(Ie),validate:Ie.validate.bind(Ie)}}class et{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,r){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const o=e.match(pe.LAYOUT_REF);if(o?n=o[1]:n=e,r.layoutPresets&&r.layoutPresets[n]){const i=r.layoutPresets[n];return this.resolveLayoutPreset(i,r)}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,r){const n={...e};for(const[o,s]of Object.entries(e))if(typeof s=="string"){if(Be.canResolve(s))try{n[o]=Be.resolve(s,r)}catch(i){console.warn(`布局中的设计令牌解析失败: ${o}=${s}`,i),n[o]=s}}else s&&typeof s=="object"&&(n[o]=this.resolveLayoutPreset(s,r));return n}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(pe.LAYOUT_REF);return o?n=o[1]:n=e,r.layoutPresets&&r.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,r){if(!e||!r)return e;const n={...e};return n.layout?n.layout={...n.layout,...r}:n.layout={...r},n}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`布局引用解析失败: ${o}`,s)}return n}static extractLayoutRefs(e){const r=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&r.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const o of Object.values(n.layout))typeof o=="string"&&this.isLayoutRef(o)&&r.push(o);return[...new Set(r)]}static isLayoutRef(e){return pe.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function _m(){return{type:ce.LAYOUT_REF,canResolve:et.canResolve.bind(et),resolve:et.resolve.bind(et),validate:et.validate.bind(et)}}class At{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.ANIMATION_REF.test(e)}static resolve(e,r){if(!this.canResolve(e))throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(pe.ANIMATION_REF);if(!n)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const o=n[1],s=r.animationConfigs?.[o];if(!s)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${o}`);return this.resolveAnimationConfig(o,s,r)}static resolveAnimationConfig(e,r,n){if(!r.transforms||!Array.isArray(r.transforms))throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const o=r.transforms.map((a,c)=>{if(!a.id)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 id 字段`);if(!a.type)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] targetShapes 不能为空`);a.targetShapes.forEach((g,m)=>{if(typeof g!="string"||g.trim()==="")throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}].targetShapes[${m}] 必须是有效的字符串 ID`)});const l=ig(a.params),u=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:u}}),s={id:e,control:r.control,transforms:o,visualEffects:r.visualEffects||[],progressControl:r.progressControl},i=ag(s);if(!i.valid)throw new Ce(ee.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
18
46
  ${i.errors?.join(`
19
- `)}`);return s}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(me.ANIMATION_REF);return o?n=o[1]:n=e,n in(r.animationConfigs||{})}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`动画引用解析失败: ${o}`,s)}return n}static extractAnimationRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.animationRef&&typeof o.animationRef=="string"&&r.push(o.animationRef),o.chartConfig?.animationRef&&typeof o.chartConfig.animationRef=="string"&&r.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(r)]}}function Ag(){return{type:le.ANIMATION_REF,canResolve:Ct.canResolve.bind(Ct),resolve:Ct.resolve.bind(Ct),validate:Ct.validate.bind(Ct)}}class pt{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,r){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!r,contextKeys:Object.keys(r||{}),animationDefinitionsKeys:r.animationDefinitions?Object.keys(r.animationDefinitions):[],animationConfigsKeys:r.animationConfigs?Object.keys(r.animationConfigs):[]}),!this.canResolve(e))throw new we(Q.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(me.SLIDER_REF),o=n?n[1]:e;let s=r.animationDefinitions?.[o];return!s&&r.animationConfigs&&(s=r.animationConfigs[o]),!s&&Et?.animationDefinitions&&(s=Et.animationDefinitions[o]),!s&&Et?.animationConfigs&&(s=Et.animationConfigs[o]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:o,hasRawConfig:!!s,rawConfig:s,animationDefinitions:r.animationDefinitions,animationConfigs:r.animationConfigs,hasGlobalContext:!!Et}),s?this.validateAndTransformConfig(o,s):(console.warn(`⚠️ 滑块配置未找到: ${o},使用默认配置`),{...Eg,id:o})}static validateAndTransformConfig(e,r){if(!r.slider)throw new we(Q.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=r,o=["position","length","orientation","min","max","step"];for(const s of o)if(!(s in n))throw new we(Q.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${s} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new we(Q.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new we(Q.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new we(Q.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new we(Q.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:r.progressIndicator,duration:r.duration,easing:r.easing,description:r.description}}static validate(e,r){if(!this.canResolve(e))return!1;const n=e.match(me.SLIDER_REF),o=n?n[1]:e;return o in(r.animationDefinitions||{})||o in(r.animationConfigs||{}),!0}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`滑块引用解析失败: ${o}`,s)}return n}static extractSliderRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.sliderRef&&typeof o.sliderRef=="string"&&r.push(o.sliderRef),o.chartConfig?.sliderRef&&typeof o.chartConfig.sliderRef=="string"&&r.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(r)]}}const Eg={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 Tg(){return{type:le.SLIDER_REF,canResolve:pt.canResolve.bind(pt),resolve:pt.resolve.bind(pt),validate:pt.validate.bind(pt)}}class At{static canResolve(e){return typeof e!="string"||e.length===0?!1:me.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,r,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const o=e.match(me.GEOMETRY_TRANSFORM_REF),s=o?o[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${s}`,{hasGeometryTransformConfigs:!!r.geometryTransformConfigs,configKeys:r.geometryTransformConfigs?Object.keys(r.geometryTransformConfigs):[]});const i=r.geometryTransformConfigs?.[s];if(!i)throw new we(Q.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${s}`,{reference:e,configId:s,availableConfigs:r.geometryTransformConfigs?Object.keys(r.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,r){const n={...e};for(const[o,s]of Object.entries(r))s!==void 0&&(n[o]=s);return r.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},r.shapes.static&&(n.shapes.static=r.shapes.static),r.shapes.animated&&(n.shapes.animated=r.shapes.animated)),r.transform&&(n.transform={...n.transform,...r.transform}),n}static validate(e,r){if(!this.canResolve(e))return!1;const n=e.match(me.GEOMETRY_TRANSFORM_REF),o=n?n[1]:e;return!!r.geometryTransformConfigs?.[o]}static batchResolve(e,r,n){const o={};for(const s of e)if(this.canResolve(s)&&this.validate(s,r))try{const i=n?.[s];o[s]=this.resolve(s,r,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 r=[];for(const n of e){const o=this.extractFromContentBlock(n);o&&r.push(o)}return[...new Set(r)]}}function $g(){return{type:le.GEOMETRY_TRANSFORM_REF,canResolve:At.canResolve.bind(At),resolve:At.resolve.bind(At),validate:At.validate.bind(At)}}const Fn={geometryRef:le.GEOMETRY_REF,styleRef:le.STYLE_REF,layoutRef:le.LAYOUT_REF,boardRef:le.BOARD_REF,animationRef:le.ANIMATION_REF,transformRef:le.TRANSFORM_REF,appearanceRef:le.STYLE_REF,geometryTransformRef:le.GEOMETRY_TRANSFORM_REF,sliderRef:le.SLIDER_REF,$ref:le.GEOMETRY_REF};class Ng{static extractRefs(e){const r=[],n=new Set,o=s=>{if(!(!s||typeof s!="object"))for(const[i,a]of Object.entries(s)){if(i in Fn){if(typeof a=="string"){const c=Fn[i],l=`${i}:${a}`;n.has(l)||(n.add(l),r.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=l;n.has(d)||(n.add(d),r.push({ref:l,type:le.DESIGN_TOKEN,path:"$ref",value:l,fieldName:"",combined:d}))});continue}if(Array.isArray(a)){a.forEach(c=>o(c));continue}typeof a=="object"&&o(a)}};return o(e),r}static extractDesignTokens(e){const r=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let o;for(;(o=n.exec(e))!==null;)r.push(o[0]);return r}static calculateStats(e){const r=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 Fn?n[i]=(n[i]||0)+1:typeof a=="object"&&o(a)};return o(e),{totalRefs:r.length,uniqueRefs:new Set(r).size,fieldCounts:n}}}class Pt{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(vg()),this.register(_g()),this.register(Sg()),this.register(Rg()),this.register(Cg()),this.register(Ag()),this.register(Tg()),this.register($g())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(r=>r.type===e)}getResolverForRef(e){return this.resolvers.find(r=>r.canResolve(e))}resolve(e,r){if(typeof e!="string"){const o=this.getResolverByType(e.type);if(!o)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return o.resolve(e.value,r)}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,r)}catch(s){console.debug(`解析器 ${o.type} 解析 ${e} 失败:`,s);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,r){const n={};for(const o of e)try{const s=this.resolve(o,r),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 Ng.extractRefs(e)}catch(r){return console.warn("ReferenceExtractor 提取失败:",r),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const r=[],n=o=>{if(!(!o||typeof o!="object"))for(const[s,i]of Object.entries(o))if(s.endsWith("Ref")&&typeof i=="string")r.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&&r.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(r)]}validate(e,r){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,r);try{return n.resolve(e,r),!0}catch{return!1}}}function ba(){return new Pt}class Fr{static transform(e,r,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(r.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:Re.GRAPH};if(!o)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,r),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,r,{strictMode:s})))),i.styleRef){try{const a=ke.resolve(i.styleRef,r);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}`,c=Ct.resolve(a,r);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(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,r,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(r.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:!!r.geometryPresets,geometryPresetKeys:r.geometryPresets?Object.keys(r.geometryPresets):[]});try{const i=Ze.resolve(s.geometryRef,r);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,c=s.content,l={...s};Object.assign(s,i),s.id=e.id,a!==void 0&&(s.type=a),c!==void 0&&(s.content=c),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 d=s.type;let g=!1;const p=r.geometryPresets[s.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:s.geometryRef,originalGeometryExists:!!p,originalGeometryType:p?.type,originalGeometryKeys:p?Object.keys(p):[],hasVertices:p&&"vertices"in p,verticesIsArray:p&&Array.isArray(p.vertices),verticesLength:p?.vertices?.length,contextGeometryPresetsKeys:Object.keys(r.geometryPresets||{})}),p&&p.vertices&&Array.isArray(p.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:p.vertices,hasWithLabel:"withLabel"in p,withLabel:p.withLabel,hasLabel:"label"in p,label:p.label}),s.verticesConfig||(s.verticesConfig={}),p.vertices.forEach((f,m)=>{if(console.warn(`🔍 DEBUG: 检查顶点${m}:`,{vertex:f,isObject:f&&typeof f=="object",hasDollarRef:f&&typeof f=="object"&&"$ref"in f,refName:f?.$ref}),f&&typeof f=="object"&&"$ref"in f){const h=f.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${h},检查context.geometryPresets`),r.geometryPresets&&r.geometryPresets[h]){const y=r.geometryPresets[h];console.warn(`🔍 DEBUG: 找到点定义 ${h}:`,y),y.name?(s.verticesConfig[m]||(s.verticesConfig[m]={}),s.verticesConfig[m].name=y.name,console.warn(`✅ 从原始几何定义提取顶点${m}名字: ${y.name}`)):console.warn(`⚠️ 点定义 ${h} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${h}`)}else console.warn(`⚠️ 顶点${m}不是$ref对象`)}),p.withLabel!==void 0&&(s.verticesConfig.withLabel=p.withLabel),p.label&&typeof p.label=="object"){const f=p.label;f.offset&&Array.isArray(f.offset)&&f.offset.length>=2&&(s.verticesConfig.offset=f.offset),f.fontSize!==void 0&&(s.verticesConfig.fontSize=f.fontSize),f.color&&(s.verticesConfig.color=f.color),f.anchorX&&(s.verticesConfig.anchorX=f.anchorX),f.anchorY&&(s.verticesConfig.anchorY=f.anchorY)}console.warn("✅ 构建的verticesConfig:",s.verticesConfig)}if(d==="segment"||d==="line"?g="endpoints"in s&&Array.isArray(s.endpoints):d==="point"?g="position"in s&&s.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?g="vertices"in s&&Array.isArray(s.vertices):g="vertices"in s&&Array.isArray(s.vertices)||"endpoints"in s&&Array.isArray(s.endpoints)||"position"in s&&s.position!==void 0,g||(console.error(`❌ ERROR: After geometryRef merge, shape ${s.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(s))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const f=ke.resolve(i.styleRef,r);console.error(" 几何样式解析结果:",f),s.style=f}}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:",r.geometryPresets?Object.keys(r.geometryPresets):"undefined")}delete s.geometryRef}if(s.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${s.styleRef}, shape id: ${s.id}`);try{const i=ke.resolve(s.styleRef,r);console.error(" 形状样式解析成功:",i);const{id:a,...c}=i;s={...s,...c,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,r,{strictMode:o}))),s.label&&typeof s.label=="object"&&(s.label=this.transformLabel(s.label,r)),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,r),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],r),a=this.resolvePointReference(s.endpoints[1],r);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,r){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(r&&r.geometryPresets&&r.geometryPresets[n]){const o=r.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(r&&r.geometryPresets&&r.geometryPresets[n]){const o=r.geometryPresets[n];if(o.position)return o.position;if("x"in o&&"y"in o)return o}return e}return e}static convertShapeCoordinates(e,r){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,r);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,r);let c=null;if(s&&typeof s=="object"&&"$ref"in s){const l=s.$ref;r&&r.geometryPresets&&r.geometryPresets[l]&&(c=r.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&&(o[i]||(o[i]={}),o[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:(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,r);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,r);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,r);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,r);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,r):i):s&&typeof s=="object"&&(n[o]=this.convertShapeCoordinates(s,r));return n}static transformTransform(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Fe.resolve(s.transformRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformLabel(e,r){const n={...e};if(n.styleRef){try{const o=ke.resolve(n.styleRef,r);n.style=o}catch(o){console.warn(`标签样式解析失败: ${n.styleRef}`,o)}delete n.styleRef}return n}static resolveBoardConfig(e,r){if(r.boardDefinitions&&r.boardDefinitions[e])return r.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 r=[];return e?(e.type!==Re.GRAPH&&r.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&r.push("图形内容块 shapes 数组不能为空"):r.push("图形内容块缺少 shapes 数组"),r):(r.push("图形内容块不能为空"),r)}static batchTransform(e,r,n={}){return e.filter(o=>o.type===Re.GRAPH).map(o=>this.transform(o,r,n))}}function kg(){return{type:Re.GRAPH,transform:Fr.transform.bind(Fr),validate:Fr.validate.bind(Fr)}}class jr{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const r={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:r,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:r.static.length,animatedLength:r.animated.length}),r}static transform(e,r,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 d=At.resolve(e.geometryTransformRef,r,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const g={type:Re.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",g.metadata.config),g.metadata.config&&typeof g.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),g.metadata.config=this.transformConfig(g.metadata.config,r,{strictMode:s})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",g),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",g.metadata.config),g}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:Re.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(s)throw d;console.error("❌ 几何变换引用解析失败:",d),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",r.geometryTransformConfigs)}}const i=e.base||e.config?.base||r.basicInfo?.base||0,a=e.height||e.config?.height||r.basicInfo?.height||0,c=e.unit||e.config?.unit||r.basicInfo?.baseUnit||"cm",l={...e,type:Re.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,!o)return l;try{if(l.geometryRef){try{const d=Ze.resolve(l.geometryRef,r);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,d),d.styleRef){const g=ke.resolve(d.styleRef,r);l.metadata.config.style=g}}catch(d){if(s)throw d;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,d)}delete l.geometryRef}if(l.transformRef){try{const d=Fe.resolve(l.transformRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,d)}catch(d){if(s)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,r,{strictMode:s}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const d=ke.resolve(l.styleRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=d}catch(d){if(s)throw d;console.warn(`几何变换样式解析失败: ${l.styleRef}`,d)}delete l.styleRef}if(l.animationRef){try{const d=this.resolveAnimationConfig(l.animationRef,r,{strictMode:s});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(s)throw d;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,d)}delete l.animationRef}if(l.sliderRef){try{const d=pt.resolve(l.sliderRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(s)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,r,{strictMode:s});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(s)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(s)throw d;return console.warn("几何变换转换失败:",d),l}}static transformConfig(e,r,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,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,r,{strictMode:o});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})),s.shapes.animated&&(console.error(` 处理 animated shapes (${s.shapes.animated.length}):`),s.shapes.animated=s.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,r,{strictMode:o});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}))),s.transform){if(s.transform.transformRef)try{const a=Fe.resolve(s.transform.transformRef,r);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,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=Fe.resolve(l,r);console.error(`🔍 transform[${c}] 解析成功:`,d);const g=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${c}] 标准化后:`,g),g}catch(d){if(o)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}try{const l=Fe.resolve(a,r);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[${c}] 是对象格式,refName=${l}`);try{const d=Fe.resolve(l,r);console.error(`🔍 transform[${c}] 解析成功:`,d);const g={...d,...a,transformRef:void 0};console.error(`🔍 transform[${c}] 合并后:`,g);const p=this.normalizeTransformConfig(g,i);return console.error(`🔍 transform[${c}] 标准化后:`,p),p}catch(d){if(o)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(s.geometry&&typeof s.geometry=="object"&&(s.geometry=this.transformGeometry(s.geometry,r,{strictMode:o})),Array.isArray(s.transformations)&&(s.transformations=s.transformations.map(a=>{if(a.transformRef)try{const c=Fe.resolve(a.transformRef,r);return{...a,...c,transformRef:void 0}}catch(c){if(o)throw c;return console.warn(`Transformations解析失败: ${a.transformRef}`,c),a}return a})),s.style&&typeof s.style=="object"&&(s.style=this.transformStyle(s.style,r,{strictMode:o})),s.animationRef){try{const a=this.resolveAnimationConfig(s.animationRef,r,{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:!!r.animationDefinitions,animationDefinitionKeys:r.animationDefinitions?Object.keys(r.animationDefinitions):[]});try{const a={...Et,...r,animationDefinitions:r.animationDefinitions||Et.animationDefinitions},c=pt.resolve(s.sliderRef,a);s.animation={...c,...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,r,{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,r){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:r?Object.keys(r):[],geometryRefToShapeId:r});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,r)),delete n.config);break;default:if(n.config){const{type:o,...s}=n.config;Object.assign(n,s),delete n.config}}if(n.targetGroup&&r){const o=n.targetGroup;let s;if(r[o])s=r[o],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:o,mapped:s,type:"exact"});else{const i=Object.keys(r).find(a=>{if(a.startsWith(o+"_")||a===o||a.includes(o))return!0;const c=a.split("_"),l=o.split("_");return c.some(d=>l.includes(d))});i&&(s=r[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:r,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,r,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:!!r.geometryPresets,contextGeometryPresetKeys:r.geometryPresets?Object.keys(r.geometryPresets):[]});const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",s.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",r.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",r.geometryPresets?Object.keys(r.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=Ze.resolve(s.geometryRef,r);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,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),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=ke.resolve(s.styleRef,r);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&&(s.metadata.rotationGroup=s.metadata.id),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,c=.1;s.type="circle",s.vertices=[[i,a],[i+c,a]],delete s.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:s.type,vertices:s.vertices})}return s}static transformGeometry(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){try{const i=Ze.resolve(s.geometryRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`几何对象解析失败: ${s.geometryRef}`,i)}delete s.geometryRef}return s}static transformTransform(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Fe.resolve(s.transformRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换对象解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformStyle(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.styleRef){try{const i=ke.resolve(s.styleRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`样式对象解析失败: ${s.styleRef}`,i)}delete s.styleRef}return s}static resolveAnimationConfig(e,r,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(r.animationDefinitions&&r.animationDefinitions[s])return{...r.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,r,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:!!r.boardDefinitions,contextBoardDefinitionKeys:r.boardDefinitions?Object.keys(r.boardDefinitions):[],hasRefInContext:r.boardDefinitions&&!!r.boardDefinitions[s]}),r.boardDefinitions&&r.boardDefinitions[s]){const a={...r.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 r={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 r[e]||r.slider_horizontal}static getFallbackBoardConfig(e){const r={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 r[e]||r.default}static validate(e){const r=[];return e?(e.type!==Re.GEOMETRY_TRANSFORM&&r.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||r.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&r.push("几何变换内容块缺少 geometry 或 geometryRef"),r):(r.push("几何变换内容块不能为空"),r)}static batchTransform(e,r,n={}){return e.filter(o=>o.type===Re.GEOMETRY_TRANSFORM).map(o=>this.transform(o,r,n))}}function Mg(){return{type:Re.GEOMETRY_TRANSFORM,transform:jr.transform.bind(jr),validate:jr.validate.bind(jr)}}class yt{static transformText(e,r,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:Re.TEXT};if(!o)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,r,{strictMode:s})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,r,{strictMode:s})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=ke.resolve(i.styleRef,r);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,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n,i={...e,type:Re.FORMULA};if(!o)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,r,{strictMode:s})),i.styleRef){try{const a=ke.resolve(i.styleRef,r);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,r,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 c=i[0],l=i[1];console.error(` 发现设计令牌: ${c}, path=${l}`);try{const d=ze.resolve(c,r);console.error(` 解析结果: ${c} -> ${d}`),s=s.replace(c,String(d))}catch(d){if(o)throw d;console.warn(`文本中的设计令牌解析失败: ${c}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${s}"`),s}static resolveStyle(e,r,n={}){const{strictMode:o=!1}=n;try{return ze.replaceDesignTokenRefs(e,r,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 r=[];return e?(e.type!==Re.TEXT&&r.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&r.push("文本内容块缺少 content 字段"),r):(r.push("文本内容块不能为空"),r)}static validateFormula(e){const r=[];return e?(e.type!==Re.FORMULA&&r.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&r.push("公式内容块缺少 content 字段"),r):(r.push("公式内容块不能为空"),r)}static batchTransformText(e,r,n={}){return e.filter(o=>o.type===Re.TEXT).map(o=>this.transformText(o,r,n))}static batchTransformFormula(e,r,n={}){return e.filter(o=>o.type===Re.FORMULA).map(o=>this.transformFormula(o,r,n))}}function Og(){return{type:Re.TEXT,transform:yt.transformText.bind(yt),validate:yt.validateText.bind(yt)}}function Ig(){return{type:Re.FORMULA,transform:yt.transformFormula.bind(yt),validate:yt.validateFormula.bind(yt)}}class Fg{type="hundredGrid";transform(e,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error("🔄 HundredChartTransformer.transform START for content block:",{blockType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,enableReferenceResolution:o,strictMode:s});try{const i=e.geometryRef;if(!i)throw new Gt(dt.MISSING_REQUIRED_FIELD,"HundredGrid内容块缺少geometryRef字段");const a=this.extractShapeId(i),c=r.geometry_shapes?.[a]||r.geometryPresets?.[a];if(!c)throw new Gt(dt.GEOMETRY_REF_NOT_FOUND,`HundredGrid引用未找到: ${i} (解析后shapeId: ${a})`);if(c.type!=="hundredGrid")throw new Gt(dt.GEOMETRY_REF_NOT_FOUND,`引用${a}不是hundredGrid类型: ${c.type}`);const l=c.config||{},d=e.config||{},g=this.mergeConfigs(l,d),p=this.resolveStyle(c,r,g,o),f=this.mapToHundredChartProps(g,p),m={type:"hundredGrid",content:"",props:f,metadata:{shapeId:a,config:g,styleRef:c.styleRef}};return console.error("✅ HundredChartTransformer.transform SUCCESS:",{shapeId:a,propsKeys:Object.keys(f),hasHighlight:!!g.highlight?.numbers,highlightCount:g.highlight?.numbers?.length||0}),m}catch(i){if(console.error("❌ HundredChartTransformer.transform ERROR:",i),s)throw i;return e}}extractShapeId(e){return e.startsWith("geometryRef:")?e.replace("geometryRef:",""):e}mergeConfigs(e,r){const n={...e};return r.grid&&(n.grid={...e.grid,...r.grid}),r.highlight&&(n.highlight={...e.highlight,...r.highlight},r.highlight.numbers!==void 0&&(n.highlight.numbers=r.highlight.numbers)),r.interactive&&(n.interactive={...e.interactive,...r.interactive}),r.style&&(n.style={...e.style,...r.style}),n}resolveStyle(e,r,n,o){const s={};if(e.styleRef&&o)try{const i=e.styleRef.startsWith("styleRef:")?e.styleRef.replace("styleRef:",""):e.styleRef,a=r.stylePresets?.[i];a&&Object.entries(a).forEach(([c,l])=>{if(typeof l=="string"&&l.startsWith("$"))try{s[c]=ze.resolve(l,r)}catch(d){console.warn(`设计令牌解析失败: ${c}=${l}`,d),s[c]=l}else s[c]=l})}catch(i){console.warn(`样式引用解析失败: ${e.styleRef}`,i)}return n.style&&Object.entries(n.style).forEach(([i,a])=>{if(o&&typeof a=="string"&&a.startsWith("$"))try{s[i]=ze.resolve(a,r)}catch(c){console.warn(`设计令牌解析失败: ${i}=${a}`,c),s[i]=a}else s[i]=a}),s.baseColor||(s.baseColor="#f3f4f6"),s.selectedColor||(s.selectedColor="#3b82f6"),s.borderColor||(s.borderColor="#d1d5db"),s.textColor||(s.textColor="#333"),s.fontSize||(s.fontSize=14),s}mapToHundredChartProps(e,r){const n={};return n.rows=e.grid?.rows||10,n.cols=e.grid?.cols||10,n.cellSize=e.grid?.cellSize||36,n.mode=this.mapInteractiveMode(e.interactive?.mode),n.value=this.calculateValueFromHighlight(e.highlight?.numbers||[],n.rows,n.cols),n.fillColor=this.normalizeColor(r.selectedColor),n.baseColor=this.normalizeColor(r.baseColor),n.strokeColor=this.normalizeColor(r.borderColor),n.shadingDirection="ltr",n.hasShadow=!0,n.className="mathwiz-hundredgrid",n._config=e,n._style=r,n}mapInteractiveMode(e){return e==="readonly"?"readonly":"edit"}calculateValueFromHighlight(e,r=10,n=10){if(!e.length)return 0;const o=r*n;return e.length/o}normalizeColor(e){return typeof e!="string"?e:e.startsWith("#")?e.toLowerCase():e}validate(e){const r=[];return e.type||r.push("内容块缺少 type 字段"),e.type!=="hundredGrid"&&r.push(`内容块类型应为 hundredGrid,实际为 ${e.type}`),e.geometryRef||r.push("HundredGrid内容块缺少 geometryRef 字段"),r}}function jg(){return new Fg}class Pg{type="optionGroup";transform(e,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error("🔄 OptionGroupTransformer.transform START for content block:",{blockType:e.type,hasOptionGroupRef:!!e.optionGroupRef,optionGroupRef:e.optionGroupRef,enableReferenceResolution:o,strictMode:s});try{const{optionGroupRef:i}=e;if(!i)throw new Gt(dt.MISSING_REQUIRED_FIELD,"OptionGroup 内容块缺少 optionGroupRef 字段");const a=r.optionGroups?.[i];if(!a)throw new Gt(dt.GEOMETRY_REF_NOT_FOUND,`OptionGroup 定义未找到: ${i}`);if(a.type!=="optionGroup")throw new Gt(dt.GEOMETRY_REF_NOT_FOUND,`引用 ${i} 不是 optionGroup 类型: ${a.type}`);const c=a.options.map(d=>({id:d.id,content:d.content,contentType:d.contentType||"text",graphConfig:d.graphConfig})),l={type:"optionGroup",content:"",options:c,correctAnswers:a.correctAnswers,answerType:a.answerType,layout:a.layout||"vertical",variant:a.variant||"default",mode:e.mode||"question",showUserAnswer:e.showUserAnswer||!1,metadata:{optionGroupId:i,definition:a}};return console.error("✅ OptionGroupTransformer.transform SUCCESS:",{optionGroupRef:i,optionsCount:c.length,answerType:a.answerType,correctAnswers:a.correctAnswers}),l}catch(i){if(console.error("❌ OptionGroupTransformer.transform ERROR:",i),s)throw i;return e}}validate(e){const r=[];return e.type||r.push("内容块缺少 type 字段"),e.type!=="optionGroup"&&r.push(`内容块类型应为 optionGroup,实际为 ${e.type}`),e.optionGroupRef||r.push("OptionGroup 内容块缺少 optionGroupRef 字段"),r}}function Dg(){return new Pg}class Lg{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(kg()),this.register(Mg()),this.register(Og()),this.register(Ig()),this.register(jg()),this.register(Dg())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,r,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,r,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,r,n={}){return e.map(o=>this.transform(o,r,n))}transformScene(e,r,n={}){const o=e.items||e.content;if(!e||!Array.isArray(o))return{items:[],layout:e?.layout};const s=this.batchTransform(o,r,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,r,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=Qe.resolve(e.layout,r)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:s,layout:i}}resolveLayoutReferences(e,r,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return Qe.resolve(e,r)}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=Qe.resolve(s,r),{layoutRef:a,...c}=e;return{...i,...c}}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]=Qe.resolve(i,r)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),o[s]=i}else if(typeof i=="string"&&i.startsWith("$"))try{o[s]=ze.resolve(i,r)}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,r,n):o[s]=i;return o}return e}transformScenes(e,r,n={}){const o={};for(const[s,i]of Object.entries(e))o[s]=this.transformScene(i,r,n);return o}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const r=this.getTransformer(e.type);return!r||!r.validate?[]:r.validate(e)}batchValidate(e){return e.map(r=>({block:r,errors:this.validate(r)}))}}function xa(){return new Lg}class ro{static validate(e,r={}){const{strictMode:n=!1,skipOptionalFields:o=!1}=r,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,r,n,o){const{skipOptionalFields:s}=o;for(const i of In.RAW_DATA)e[i]===void 0&&r.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of In.BASIC_INFO)e.basic_info[i]===void 0&&r.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of In.ANSWER_INFO)e.answer_info[i]===void 0&&r.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,r,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&r.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&r.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&r.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&r.push(`${a} 应为对象类型`)})}static validateScenes(e,r,n){if(!e.scenes||typeof e.scenes!="object"){r.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||r.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){r.push(`场景 ${s} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||r.push(`场景 ${s} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&r.push(`场景 ${s} 的 layout 应为对象类型`),da.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,r,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"&&r.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&r.push(`basic_info.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&r.push("basic_info.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&r.push("basic_info.context 应为对象类型"),o.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(o.shape)&&n.push(`未知的形状类型: ${o.shape}`)}static validateAnswerInfo(e,r,n){if(!e.answer_info||typeof e.answer_info!="object")return;const o=e.answer_info;typeof o.value!="number"&&r.push("answer_info.value 应为数字类型"),typeof o.unit!="string"&&r.push("answer_info.unit 应为字符串类型"),typeof o.explanation_text!="string"&&r.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,r,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 r=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of r)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,r={}){const{strictMode:n=!1,removeInvalidFields:o=!1}=r,s=this.validate(e,{strictMode:n});let i=e;return o&&!s.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(c=>{c in i&&delete i[c]})),{data:i,errors:s.errors,warnings:s.warnings}}}class no{static validate(e,r={}){const{strictMode:n=!1,checkSceneContent:o=!0}=r,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,r,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&&r.push(`缺少必需字段: ${s}`)}static validateFieldTypes(e,r,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&r.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&r.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&r.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&r.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&r.push(`${i} 应为对象类型`)})}static validateScenes(e,r,n){if(!e.scenes||typeof e.scenes!="object"){r.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||r.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){r.push(`场景 ${s} 应为对象类型`);continue}const a=i,c=a.items||a.content;Array.isArray(c)?c.length===0&&n.push(`场景 ${s} 的内容数组为空`):r.push(`场景 ${s} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&r.push(`场景 ${s} 的 layout 应为对象类型`),da.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,r,n){if(!e.basicInfo||typeof e.basicInfo!="object"){r.push("basicInfo 应为对象类型");return}const o=e.basicInfo;(o.question===void 0||typeof o.question!="string")&&r.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="number"&&r.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&r.push(`basicInfo.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&r.push("basicInfo.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&r.push("basicInfo.context 应为对象类型")}static validateAnswer(e,r,n){if(!e.answer||typeof e.answer!="object"){r.push("answer 应为对象类型");return}const o=e.answer;typeof o.value!="number"&&r.push("answer.value 应为数字类型"),typeof o.unit!="string"&&r.push("answer.unit 应为字符串类型"),typeof o.explanation!="string"&&r.push("answer.explanation 应为字符串类型"),o.value!==void 0&&(o.value<0&&n.push("answer.value 为负数,可能不正确"),o.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,r,n){if(e.explanation===void 0){r.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){r.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((o,s)=>{(!o||typeof o!="object")&&r.push(`explanation[${s}] 应为对象类型`)})):e.explanation.steps===void 0?r.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||r.push("explanation.steps 应为数组类型")}static validateStrictMode(e,r,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 r=["id","title","basicInfo","scenes","answer"];for(const n of r)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 kt{static validateInput(e,r={}){const{isValid:n,errors:o,warnings:s}=ro.validate(e,r);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateOutput(e,r={}){const{isValid:n,errors:o,warnings:s}=no.validate(e,r);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateComplete(e,r,n={}){const{inputStrictMode:o=!1,outputStrictMode:s=!1}=n,i=this.validateInput(e,{strictMode:o}),a=this.validateOutput(r,{strictMode:s}),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 ro.quickValidate(e)}static quickValidateOutput(e){return no.quickValidate(e)}static validateAndReport(e,r,n={}){const o=r==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${r.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 oo{static extractAllReferences(e){const r=[],n=o=>{typeof o=="string"?r.push(o):Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return n(e),[...new Set(r)]}static categorizeReferences(e,r){const n={[le.DESIGN_TOKEN]:[],[le.STYLE_REF]:[],[le.GEOMETRY_REF]:[],[le.TRANSFORM_REF]:[],[le.LAYOUT_REF]:[]},o=new Pt;for(const s of e){const i=o.getResolverForRef(s);i&&n[i.type].push(s)}return n}static batchResolveReferences(e,r,n={}){const{strictMode:o=!1,onMissing:s}=n,i=new Pt,a={};for(const c of e){const l=i.getResolverForRef(c);if(l)try{a[c]=l.resolve(c,r)}catch(d){if(o)throw d;console.warn(`引用解析失败: ${c}`,d),s&&(a[c]=s(c))}}return a}static replaceReferences(e,r,n={}){const{strictMode:o=!1,onMissing:s,maxDepth:i=10}=n,a=new Pt,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,g=0,p)=>{if(g>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(p&&c.has(p))return console.warn(`🛡️ 跳过保留字段 "${p}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const m=a.getResolverForRef(d);if(m)try{return m.resolve(d,r)}catch(h){if(o)throw h;return console.warn(`引用解析失败: ${d}`,h),s?s(d):d}return d}else{if(Array.isArray(d))return d.map(f=>l(f,g+1,void 0));if(d&&typeof d=="object"){const f={};for(const[m,h]of Object.entries(d))f[m]=l(h,g+1,m);return f}}return d};return l(e)}static calculateReferenceStats(e,r){const n=new Pt,o={total:e.length,resolved:0,failed:0,byType:{}};Object.values(le).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 c=i.resolve(s,r);console.log(`🔍 引用解析成功: ${s} =>`,c),o.resolved++,o.byType[a].resolved++}catch(c){console.error(`🔍 引用解析失败: ${s}`,c),o.failed++,o.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${s}`)}return o}static checkReferenceExists(e,r){const o=new Pt().getResolverForRef(e);if(!o)return!1;if(o.validate)return o.validate(e,r);try{return o.resolve(e,r),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const r=e.match(/^(\w+):(\w+)$/);return r?[r[1],r[2]]:[e]}static createReference(e,r){switch(e){case le.DESIGN_TOKEN:return`$${r.join(".")}`;case le.STYLE_REF:return`styleRef:${r[0]}`;case le.GEOMETRY_REF:return`geometryRef:${r[0]}`;case le.TRANSFORM_REF:return`transformRef:${r[0]}`;case le.LAYOUT_REF:return`layoutRef:${r[0]}`;default:return r.join(":")}}static flattenNestedReferences(e){const r=[],n=(o,s=[])=>{if(typeof o=="string")r.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),r}}class wa{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 r=this.marks.get(e);if(!r){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),o=n-r.startTime;r.endTime=n,r.duration=o,this.updateStats(e,o)}updateStats(e,r){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=r;break;case"transformation":this.stats.transformationTime=r;break;case"validation":this.stats.validationTime=r;break;case"total":this.stats.totalTime=r;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>Rt.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${Rt.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>Rt.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${Rt.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>Rt.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${Rt.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>Rt.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 Gg{static deepMerge(e,r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return Array.isArray(e)?e.map((o,s)=>s<r.length?this.deepMerge(o,r[s]):o):[...r];const n={...e};for(const[o,s]of Object.entries(r))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,r){if(e===r)return!0;if(typeof e!=typeof r||typeof e!="object"||e===null||r===null||Array.isArray(e)!==Array.isArray(r))return!1;if(Array.isArray(e))return e.length!==r.length?!1:e.every((s,i)=>this.deepEqual(s,r[i]));const n=Object.keys(e),o=Object.keys(r);return n.length!==o.length?!1:n.every(s=>s in r?this.deepEqual(e[s],r[s]):!1)}static safeGet(e,r,n=void 0){const o=Array.isArray(r)?r:r.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 c=parseInt(a[1],10);s=s[c]}else s=s[i]}return s!==void 0?s:n}static safeSet(e,r,n){const o=Array.isArray(r)?r:r.split("."),s=Array.isArray(e)?[...e]:{...e};let i=s;for(let l=0;l<o.length-1;l++){const d=o[l],g=d.match(/^\[(\d+)\]$/);if(g&&Array.isArray(i)){const p=parseInt(g[1],10);i[p]===void 0&&(i[p]={}),i=i[p]}else{if(i[d]===void 0){const f=o[l+1].match(/^\[(\d+)\]$/);i[d]=f?[]:{}}i=i[d]}}const a=o[o.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 s}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,r){let n=0;return(...o)=>{const s=Date.now();s-n>=r&&(n=s,e(...o))}}static debounce(e,r){let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>e(...o),r)}}static formatBytes(e,r=2){if(e===0)return"0 Bytes";const n=1024,o=r<0?0:r,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 r=new Set,n=o=>r.has(o)?0:typeof o=="string"?o.length*2:typeof o=="number"?8:typeof o=="boolean"?4:o==null?0:Array.isArray(o)?(r.add(o),o.reduce((s,i)=>s+n(i),0)):typeof o=="object"?(r.add(o),Object.values(o).reduce((s,i)=>s+n(i),0)):0;return n(e)}}class Ug{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...wg,...e},this.referenceContext=ya(),this.resolverRegistry=ba(),this.transformerRegistry=xa(),this.performanceMonitor=new wa}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 r=this.validateInput(e);if(!r.isValid&&this.config.strictMode)throw new we(Q.INVALID_INPUT,ys[Q.INVALID_INPUT],{errors:r.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 we(Q.OUTPUT_VALIDATION_FAILED,ys[Q.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:r,outputValidation:i,inputWarnings:r.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(r){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw r;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",r),this.createFallbackResult(e,r);throw r}}validateInput(e){return kt.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(([r,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${r}:`,{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(` 📍 ${r}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[r]=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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[r]=o}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(r=>{r&&r.content&&Array.isArray(r.content)&&r.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(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${r}:`,{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[r]=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(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${r}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[r]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}extractOptionGroupsFromInput(e){if(!e){console.error("⚠️ extractOptionGroupsFromInput: inputData is null or undefined");return}this.referenceContext.optionGroups||(this.referenceContext.optionGroups={}),e.option_groups&&typeof e.option_groups=="object"?(console.error("📦 Extracting option_groups:",Object.keys(e.option_groups)),Object.entries(e.option_groups).forEach(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing option group ${r}:`,{id:n.id,type:n.type,answerType:n.answerType,optionsCount:n.options?.length||0}),this.referenceContext.optionGroups[r]=n)}),console.error("✅ optionGroups after extraction:",Object.keys(this.referenceContext.optionGroups))):console.error("⚠️ No option_groups found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;if(console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0}),e.type==="hundredGrid")return console.error(`✅ hundredGrid类型跳过坐标转换: ${e.id}`),e;const r={...e};r.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line"),Array.isArray(r.position)&&r.position.length>=2&&(r.position={x:r.position[0],y:r.position[1]}),Array.isArray(r.vertices)&&(r.vertices=r.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(r.endpoints)?(console.error(`🔄 Processing endpoints for shape ${r.id||"unknown"}:`,{endpointsLength:r.endpoints.length,firstEndpoint:r.endpoints[0],firstEndpointType:typeof r.endpoints[0],firstEndpointIsArray:Array.isArray(r.endpoints[0])}),r.endpoints=r.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)),r.type==="segment"&&Array.isArray(r.endpoints)&&r.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line",r.start=r.endpoints[0],r.end=r.endpoints[1],delete r.endpoints)):"endpoints"in r&&console.error(`⚠️ Shape ${r.id||"unknown"} has endpoints but not array:`,{endpoints:r.endpoints,endpointsType:typeof r.endpoints});for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=o:r[n]=this.convertGeometryShapeCoordinates(o));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),endpointsLength:r.endpoints?r.endpoints.length:0,keys:Object.keys(r)}),r}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const r={...e};if(r.config&&r.config.center){const n=r.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(r.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(r))Array.isArray(o)?r[n]=o.map(s=>typeof s=="object"?this.convertTransformDefinitionCoordinates(s):s):o&&typeof o=="object"&&(r[n]=this.convertTransformDefinitionCoordinates(o));return r}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(r=>{if(r&&r.type==="point"&&r.position&&Array.isArray(r.position)&&r.position.length>=2){const n=r.id||`point_${r.position[0]}_${r.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:r.position[0],y:r.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e),this.extractOptionGroupsFromInput(e);const r={id:e.math_prob_id||Gg.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&&(r[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,r.basicInfo=o,console.error("🔧 transformBaseData: transformed.basicInfo set =",r.basicInfo),r.explanation=this.transformExplanation(e.explanation),r}parseGrade(e){const r=e.match(/g(\d+)/);return r?parseInt(r[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 r={...e};return console.error("🔄 transformBasicInfo: transformed copy:",r),r.question===void 0&&r.content!==void 0&&(r.question=r.content),r.question===void 0&&(r.question=""),console.error("🔄 transformBasicInfo: returning:",r),r}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const r={};return["question","solve","review"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];r[s]={...i,items:a},i.content!==void 0&&delete r[s].content}else r[s]={items:[]}}),["remember","explanation","success"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];r[s]={...i,items:a},i.content!==void 0&&delete r[s].content}}),r}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 r=e.steps.map((n,o)=>(console.error(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:r}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const r=e.chartConfig,n=r.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(r)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={type:n,...r};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,...c}=s;i={...c,...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 r=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(r.length),this.resolverRegistry.batchResolve(r,this.referenceContext),oo.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const r={...e};return r.scenes&&typeof r.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),r.scenes=this.transformerRegistry.transformScenes(r.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),r}validateOutput(e){return kt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,r,n){const o=this.performanceMonitor.getStats(),s=this.performanceMonitor.checkPerformance(),i=[...r.inputValidation.warnings.map(d=>({code:Q.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...r.outputValidation.warnings.map(d=>({code:Q.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...s.warnings.map(d=>({code:Q.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=n||e,c=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=oo.calculateReferenceStats(c,this.referenceContext);return{data:e,warnings:i,performance:o,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,r){const n={...zr,id:e?.math_prob_id||zr.id,title:e?.title||zr.title},o={code:Q.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${r.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 _r{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...xg,...e},this.referenceContext=ya(),this.resolverRegistry=ba(),this.transformerRegistry=xa(),this.performanceMonitor=new wa,this.syncAdapter=new Ug(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 r=e,n=this.syncAdapter.adapt(r);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(r){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw r;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",r),this.createFallbackResult(e,r);throw r}}_validateInput(e){return kt.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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[r]=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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[r]=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 r=e.steps.map((n,o)=>(this.config.enableLogging&&console.log(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:r}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const r=e.chartConfig,n=r.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(r))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={...r,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,...c}=s;i={...c,...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 r={...e};r.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line"),Array.isArray(r.position)&&r.position.length>=2&&(r.position={x:r.position[0],y:r.position[1]}),Array.isArray(r.vertices)&&(r.vertices=r.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(r.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${r.id||"unknown"}:`,{endpointsLength:r.endpoints.length,firstEndpoint:r.endpoints[0],firstEndpointType:typeof r.endpoints[0],firstEndpointIsArray:Array.isArray(r.endpoints[0])}),r.endpoints=r.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)),r.type==="line"&&Array.isArray(r.endpoints)&&r.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line",r.start=r.endpoints[0],r.end=r.endpoints[1],delete r.endpoints)):"endpoints"in r&&this.config.enableLogging&&console.log(`⚠️ Shape ${r.id||"unknown"} has endpoints but not array:`,{endpoints:r.endpoints,endpointsType:typeof r.endpoints});for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=o:r[n]=this.convertGeometryShapeCoordinates(o));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),endpointsLength:r.endpoints?r.endpoints.length:0,keys:Object.keys(r)}),r}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const r={...e};if(r.config&&r.config.center){const n=r.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(r.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=this.convertTransformDefinitionCoordinates(o):r[n]=this.deepClone(o));return r}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const r={};for(const n in e)e.hasOwnProperty(n)&&(r[n]=this.deepClone(e[n]));return r}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const r={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=r.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),r}_resolveReferences(e){const r=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(r.length),this.resolverRegistry.batchResolve(r,this.referenceContext),oo.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const r={...e};return r.scenes&&typeof r.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),r.scenes=this.transformerRegistry.transformScenes(r.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),r}_validateOutput(e){return kt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,r,n){const o=this.performanceMonitor.getStats(),s=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(r.inputWarnings||[]).map(a=>({code:dt.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(r.outputWarnings||[]).map(a=>({code:dt.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?o:void 0,referenceStats:s}}createFallbackResult(e,r){return{data:{...zr,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:dt.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${r instanceof Error?r.message:r}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new _r(e)}}function It(t,e){return new _r(e).adapt(t)}async function Oo(t,e){return Promise.resolve(It(t,e))}function va(t,e){const r=typeof t=="function"?t():t;return It(r,e)}async function _a(t,e){const r=typeof t=="function"?await t():t instanceof Promise?await t:t;return It(r,e)}function Sa(t){return new _r(t)}function Ra(t){const e=new _r(t);return{adapt:r=>Promise.resolve(e.adapt(r))}}function Vg(t,e="input"){return e==="input"?kt.validateInput(t):kt.validateOutput(t)}function zg(t,e,r=100){const n=[];for(let c=0;c<r;c++){const l=performance.now();t.adapt(e);const d=performance.now();n.push(d-l)}const o=n.reduce((c,l)=>c+l,0)/r,s=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:o,minTime:s,maxTime:i,memoryUsage:a}}const Bg={adapt:(t,e)=>It(t,e),adaptAsync:(t,e)=>Oo(t,e),create:t=>Sa(t)},Hg="4.0.0",Ca="4.0.0";function qg(t="4.0.0"){return Ca>=t}function Aa(t){return t?.schema_version==="4.0.0"||t?.schema_version?.startsWith("4.")}function Wg(t){return Aa(t)&&(t.geometry_shapes||t.transform_definitions||t.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(t.basic_info.shape))}class jn extends Error{constructor(e,r,n,o){super(`Failed to generate config for ${r}: ${e}`),this.shapeType=r,this.options=n,this.innerError=o,this.name="ConfigGenerationError"}}function Yg(t){const e=[],r=[];if(t.shapes||e.push(W("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),t.transform||e.push(W("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),t.strategy||e.push(W("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:xs(e),timestamp:new Date().toISOString()};t.shapes&&e.push(...Kg(t.shapes));let n=!1;if(t.shapes?.animated){for(const o of t.shapes.animated)if(o.transform){n=!0;break}}return t.transform?e.push(...Xg(t.transform)):n||e.push(W("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...Jg(t)),e.push(...Zg(t)),e.push(...Qg(t)),e.length>0&&r.push(...xs(e)),{isValid:e.length===0,errors:e,fixes:r,timestamp:new Date().toISOString()}}function Ea(t){if(!t||typeof t!="object"||!t.type||typeof t.type!="string"||!["rotation","translation","scale","composite"].includes(t.type))return!1;switch(t.type){case"rotation":if(!t.config||typeof t.config!="object")return!1;const r=t.config.center;if(r!=="auto"&&(!Array.isArray(r)||r.length!==2)||typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number"||t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical")return!1;break;case"translation":if(!t.config||typeof t.config!="object")return!1;const n=t.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 t.config.distance!="number"||t.config.distance<=0)return!1;break;case"scale":if(!t.config||typeof t.config!="object")return!1;const o=t.config.center;if(o!=="centroid"&&(!Array.isArray(o)||o.length!==2)||typeof t.config.startScale!="number"||typeof t.config.endScale!="number"||typeof t.config.uniform!="boolean")return!1;break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))return!1;for(const s of t.transforms)if(!Ea(s))return!1;if(t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel")return!1;break}return!0}function Ta(t,e){const r=[];if(!t||typeof t!="object")return r.push(W("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,t,{type:"rotation"})),r;(!t.type||typeof t.type!="string")&&r.push(W("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,t.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(t.type&&!n.includes(t.type)&&r.push(W("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${t.type}`,`${e}.type`,t.type,"rotation")),t.type){case"rotation":if(!t.config||typeof t.config!="object")r.push(W("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,t.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const o=t.config.center;o!=="auto"&&(!Array.isArray(o)||o.length!==2)&&r.push(W("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,t.config.center,[0,0])),(typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number")&&r.push(W("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,t.config,{startAngle:0,endAngle:Math.PI})),t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical"&&r.push(W("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,t.config.direction,"clockwise"))}break;case"translation":if(!t.config||typeof t.config!="object")r.push(W("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,t.config,{direction:"horizontal",distance:1}));else{const o=t.config.direction;Array.isArray(o)?o.length!==2?r.push(W("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,o,[1,0])):(typeof o[0]!="number"||typeof o[1]!="number")&&r.push(W("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,o,[1,0])):typeof o=="string"?o!=="horizontal"&&o!=="vertical"&&r.push(W("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,o,"horizontal")):r.push(W("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,o,"horizontal")),(typeof t.config.distance!="number"||t.config.distance<=0)&&r.push(W("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,t.config.distance,1))}break;case"scale":if(!t.config||typeof t.config!="object")r.push(W("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,t.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const o=t.config.center;o!=="centroid"&&(!Array.isArray(o)||o.length!==2)&&r.push(W("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,t.config.center,"centroid")),(typeof t.config.startScale!="number"||typeof t.config.endScale!="number")&&r.push(W("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,t.config,{startScale:1,endScale:2})),typeof t.config.uniform!="boolean"&&r.push(W("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,t.config.uniform,!0))}break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))r.push(W("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,t.transforms,[]));else for(let o=0;o<t.transforms.length;o++){const s=Ta(t.transforms[o],`${e}.transforms[${o}]`);r.push(...s)}t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel"&&r.push(W("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,t.executionMode,"sequential"));break}return r}function W(t,e,r,n,o){let s=o;if(o===void 0)switch(t){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:t,message:e,path:r,value:n,suggestedValue:s}}function Kg(t){const e=[];if(!t||typeof t!="object")return e.push(W("MISSING_SHAPES","形状定义无效或缺失","$.shapes",t)),e;if(!Array.isArray(t.static))e.push(W("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",t.static));else for(let r=0;r<t.static.length;r++){const n=t.static[r],o=bs(n,`$.shapes.static[${r}]`);e.push(...o)}if(!Array.isArray(t.animated))e.push(W("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",t.animated));else for(let r=0;r<t.animated.length;r++){const n=t.animated[r],o=bs(n,`$.shapes.animated[${r}]`);e.push(...o)}return e}function bs(t,e){const r=[];if(!t||typeof t!="object")return r.push(W("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,t)),r;if((!t.type||typeof t.type!="string")&&r.push(W("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,t.type)),!Array.isArray(t.vertices))r.push(W("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,t.vertices));else if(t.vertices.length===0)r.push(W("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,t.vertices));else for(let n=0;n<t.vertices.length;n++){const o=t.vertices[n];!Array.isArray(o)||o.length!==2?r.push(W("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,o)):(typeof o[0]!="number"||typeof o[1]!="number")&&r.push(W("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,o))}if(t.transform!==void 0){const n=Ta(t.transform,`${e}.transform`);r.push(...n)}return r}function Xg(t){const e=[];if(!t)return e.push(W("MISSING_TRANSFORM","变换配置缺失","$.transform",t)),e;const r=Array.isArray(t),n=r?t:[t],o="$.transform";for(let s=0;s<n.length;s++){const i=n[s],a=r?`${o}[${s}]`:o;Ea(i)||e.push(W("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function Jg(t){const e=[];if(!t.strategy)return e;const{strategy:r}=t;let n=0;if(t.transform&&(Array.isArray(t.transform)?n+=t.transform.length:typeof t.transform=="object"&&(t.transform&&typeof t.transform=="object"&&"transforms"in t.transform?n+=t.transform.transforms.length:n+=1)),t.shapes?.animated)for(const s of t.shapes.animated)s.transform&&(n+=1);return r.includes("single")&&n!==1&&e.push(W("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",r,n===0?"single_rotation":"double_rotation")),r.includes("double")&&n!==2&&e.push(W("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",r,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(r)||e.push(W("STRATEGY_MISMATCH",`无效的策略名称: ${r}`,"$.strategy",r,"single_rotation")),e}function Zg(t){const e=[];if(t.unit&&typeof t.unit!="string"&&e.push(W("UNIT_MISMATCH","单位必须是字符串","$.unit",t.unit,"in")),t.baseUnit&&typeof t.baseUnit!="string"&&e.push(W("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",t.baseUnit,t.unit||"in")),t.heightUnit&&typeof t.heightUnit!="string"&&e.push(W("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",t.heightUnit,t.unit||"in")),t.unit&&t.baseUnit&&t.baseUnit!==t.unit&&e.push(W("UNIT_MISMATCH",`底边单位 (${t.baseUnit}) 与主单位 (${t.unit}) 不一致`,"$.baseUnit",t.baseUnit,t.unit)),t.unit&&t.heightUnit&&t.heightUnit!==t.unit&&e.push(W("UNIT_MISMATCH",`高度单位 (${t.heightUnit}) 与主单位 (${t.unit}) 不一致`,"$.heightUnit",t.heightUnit,t.unit)),t.unit&&t.boardConfig&&t.boardConfig.boundingBox){const[r,n,o,s]=t.boardConfig.boundingBox,i=o-r,a=n-s,c=t.unit==="cm"?50:20;(i>c*5||a>c*5)&&e.push(W("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${t.unit})不匹配`,"$.boardConfig.boundingBox",t.boardConfig.boundingBox,void 0))}return e}function Qg(t){const e=[];if(t.shapes&&t.boardConfig&&t.boardConfig.boundingBox){const r=t.boardConfig.boundingBox,[n,o,s,i]=r,a=[...t.shapes.static||[],...t.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 g=l.vertices[d];if(Array.isArray(g)&&g.length===2){const[p,f]=g;(p<n||p>s||f<i||f>o)&&e.push(W("GEOMETRY_INCONSISTENCY",`形状 ${c} 的顶点 ${d} (${p}, ${f}) 超出画板边界`,`$.shapes.${c<(t.shapes.static?.length||0)?"static":"animated"}[${c}].vertices[${d}]`,g,[Math.max(n,Math.min(p,s)),Math.max(i,Math.min(f,o))]))}}}}if(t.metadata&&t.metadata.base&&t.metadata.height){const r=.5*t.metadata.base*t.metadata.height;if(t.shapes?.static?.[0]?.vertices){const n=t.shapes.static[0].vertices;if(n.length===3){const[o,s]=n[0],[i,a]=n[1],[c,l]=n[2],d=.5*Math.abs((i-o)*(l-s)-(c-o)*(a-s));Math.abs(d-r)>.01&&e.push(W("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${r.toFixed(2)}) 不一致`,"$.metadata",{base:t.metadata.base,height:t.metadata.height,calculatedArea:d,expectedArea:r}))}}}return e}function xs(t){const e=[];for(const r of t)switch(r.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:r.path,value:r.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${r.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:r.path,value:r.suggestedValue||1,description:`将底边长度修复为: ${r.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:r.path,value:r.suggestedValue||1,description:`将高度修复为: ${r.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:r.path,value:r.suggestedValue||0,description:`将原点坐标修复为: ${r.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:r.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:r.suggestedValue!==void 0&&e.push({action:"replace",path:r.path,value:r.suggestedValue,description:`修复 ${r.code} 错误`,isSafe:!1})}return e}function ws(t){if(!em(t))throw new jn("Invalid parallelogram config options","parallelogram",t);const{base:e,height:r,unit:n="in",layoutDensity:o="compact",theme:s="light"}=t,i=t.originX??0,a=t.originY??0,c=t.skew??e/3;try{const l=tm(e,r,c,i,a,s),d=rm(e),g=nm(o),p=om(e,r,c,i,a);return{ui:{layoutDensity:o},base:e,height:r,unit:n,shapes:l,transform:d,animation:g,boardConfig:p,strategy:"cut_and_paste",theme:s,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:r,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){if(l instanceof jn)throw l;const d=l instanceof Error?l.message:String(l);throw new jn(d,"parallelogram",t,l instanceof Error?l:void 0)}}function em(t){if(!t||typeof t!="object")return!1;const e=["base","height"];for(const r of e)if(!(r in t))return!1;return!(typeof t.base!="number"||t.base<=0||typeof t.height!="number"||t.height<=0||t.skew!==void 0&&(typeof t.skew!="number"||t.skew<0)||t.originX!==void 0&&(typeof t.originX!="number"||!isFinite(t.originX))||t.originY!==void 0&&(typeof t.originY!="number"||!isFinite(t.originY)))}function tm(t,e,r,n,o,s){const a=s==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},c=[[n+r,o],[n+t,o],[n+t+r,o+e],[n+r,o+e]],l=[[n,o],[n+r,o],[n+r,o+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 rm(t){return{type:"translation",config:{direction:[1,0],distance:t}}}function nm(t){return{slider:{position:t==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function om(t,e,r,n,o){const s=Math.min(n,n+r,n+t,n+t+r),i=Math.max(n,n+r,n+t,n+t+r),a=Math.min(o,o+e),c=Math.max(o,o+e),l=3;return{boundingBox:[s-l,c+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function sm(t){return{id:t.id||t.math_prob_id,title:t.title||"",grade:t.grade||5,unit:t.unit||t.unit_name||"",lesson:t.lesson||t.lesson_name||"",skill:t.skill||t.skill_description||"",objective:t.objective||"",knowledgePoints:Array.isArray(t.knowledge_points)?t.knowledge_points:Array.isArray(t.knowledgePoints)?t.knowledgePoints:[],difficulty:t.difficulty||1,description:t.description||"",metadata:t.metadata||{topic:"",skill:"",tags:[]},math_prob_id:t.math_prob_id,grade_id:t.grade_id,unit_id:t.unit_id,lesson_id:t.lesson_id,module_id:t.module_id,skill_item_id:t.skill_item_id,skill_id:t.skill_id,created_at:t.created_at,updated_at:t.updated_at,layout:t.layout||{type:"card",padding:"20px",theme:"light"}}}function im(t){const e=t||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function am(t,e,r){return{value:t,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:r}}function lm(t){return t?{value:t.value,unit:t.unit,explanation:t.explanation_text||t.explanation||"正确答案"}:null}function cm(t){return t.answer?t.answer:t.answer_info?lm(t.answer_info):null}function dm(){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 um(){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 fm(t){return Array.isArray(t)||t&&t.steps?t:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function $a(t){const e=sm(t),r=im(t.basic_info||t.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:{...r,question:r.question||"计算下面平行四边形的面积:",answerUnit:r.answerUnit||"平方英寸",shape:r.shape||"parallelogram",base:r.base||9,height:r.height||6,baseUnit:r.baseUnit||"in",heightUnit:r.heightUnit||"in",variables:r.variables||{b:9,h:6,unit:"in"},context:r.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:pm(t.scenes||dm(),"parallelogram",r),explanation:fm(t.explanation||um()),answer:cm(t)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:t.answer_info||am(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:t.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function gm(t){return t?.config&&typeof t.config=="object"}function mm(t){if(t.shapes?.static&&t.shapes?.animated)return console.log("🔍 JSON config already in system format"),t;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!t.transform,type:Lt(t.transform),distance:ct(t.transform),direction:Br(t.transform)});try{const e={...t};if(t.shapes&&typeof t.shapes=="object"){const n=[],o=[];if(t.shapes.trapezoid){const s=t.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(t.shapes.triangle){const s=t.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(t.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&&t.base&&(e.base=t.base),!e.height&&t.height&&(e.height=t.height),!e.unit&&t.unit&&(e.unit=t.unit);const r=Lt(t.transform);return t.transform&&r==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:r,translation:t.transform.translation,distance:ct(t.transform),direction:Br(t.transform)}),t.transform.translation&&(e.transform={type:"translation",translation:t.transform.translation},console.log("✅ Set converted.transform with distance:",ct(t.transform)))):t.transform?console.log("⚠️ JSON has transform but not translation type:",Lt(t.transform)):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&t.boardConfig&&(e.boardConfig=t.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:Lt(e.transform),distance:ct(e.transform),direction:Br(e.transform)}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),t}}function ct(t){if(!t)return"N/A";const e=Array.isArray(t)?t[0]:t;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function Br(t){if(!t)return;const e=Array.isArray(t)?t[0]:t;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function Lt(t){return t&&(Array.isArray(t)?t[0]:t)?.type||"N/A"}function pm(t,e,r){if(t?.solve?.content){const n=t.solve.content.map(o=>{if(o.type==="geometryTransform"){if(gm(o))try{const i=mm(o.config),a=Yg(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",ct(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:Lt(i.transform),distance:ct(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=r?.base||9,a=r?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),s=ws({base:i,height:a,unit:r?.baseUnit||r?.unit||"in",originX:r?.originX,originY:r?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",ct(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=ws({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",ct(s.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:Lt(s.transform),direction:Br(s.transform),distance:ct(s.transform)}),{...o,metadata:{...o.metadata,config:s,source:"generated"}}}return o});return{...t,solve:{...t.solve,content:n}}}return t}const hm="4.0.0",ym="1.0.0",bm="mp-10506-0002-0002-G01-0001",xm="锐角三角形面积练习",wm="通过双旋转策略练习锐角三角形面积公式 A=½bh",vm="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",_m=1,Sm="g5",Rm="三角形面积计算",Cm=1050602,Am="锐角三角形的面积",Em=105060201,Tm=1002,$m="已知锐角三角形的底和高,求三角形面积",Nm="s-105-06-0002",km=1002,Mm=2,Om=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Im={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Fm={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}},jm={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"}},Pm={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},Dm={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"以下三角形面积是多少?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},Lm={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"}}]}}]},Gm={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²"]},Um="2026-01-20T20:34:00Z",Vm="2026-01-20T20:34:00Z",zm={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"}},Bm={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left_triangle"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right_triangle"}},Hm={schema_version:hm,config_version:ym,math_prob_id:bm,title:xm,description:wm,objective:vm,difficulty:_m,grade_id:Sm,unit_name:Rm,unit_id:Cm,lesson_name:Am,lesson_id:Em,module_id:Tm,skill_description:$m,skill_item_id:Nm,skill_id:km,score:Mm,knowledge_points:Om,metadata:Im,basic_info:Fm,geometry_shapes:jm,layout:Pm,scenes:Dm,explanation:Lm,answer_info:Gm,created_at:Um,updated_at:Vm,geometry_transform_configs:zm,transform_definitions:Bm},qm="mp-10506-0001-0001-G01-0001",Wm="平行四边形面积公式推导",Ym="通过割补变换演示理解平行四边形面积公式 A=bh",Km="理解平行四边形面积公式 A=bh",Xm=1,Jm="g5",Zm="多边形的面积",Qm=1050601,ep="平行四边形的面积",tp=105060101,rp=1002,np="已知平行四边形的底和高,求平行四边形面积",op="s-105-06-0001",sp=1001,ip=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],ap={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},lp={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}},cp={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},dp={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"}}}},up={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:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},fp={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 平方英寸"}]},gp="2024-01-15T10:30:00Z",mp="2024-01-15T10:30:00Z",pp={math_prob_id:qm,title:Wm,description:Ym,objective:Km,difficulty:Xm,grade_id:Jm,unit_name:Zm,unit_id:Qm,lesson_name:ep,lesson_id:tp,module_id:rp,skill_description:np,skill_item_id:op,skill_id:sp,knowledge_points:ip,metadata:ap,basic_info:lp,layout:cp,scenes:dp,explanation:up,answer_info:fp,created_at:gp,updated_at:mp},hp={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function yp(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
47
+ `)}`);return s}static validate(e,r){if(!this.canResolve(e))return!1;let n;const o=e.match(pe.ANIMATION_REF);return o?n=o[1]:n=e,n in(r.animationConfigs||{})}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`动画引用解析失败: ${o}`,s)}return n}static extractAnimationRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.animationRef&&typeof o.animationRef=="string"&&r.push(o.animationRef),o.chartConfig?.animationRef&&typeof o.chartConfig.animationRef=="string"&&r.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(r)]}}function Rm(){return{type:ce.ANIMATION_REF,canResolve:At.canResolve.bind(At),resolve:At.resolve.bind(At),validate:At.validate.bind(At)}}class ht{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,r){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!r,contextKeys:Object.keys(r||{}),animationDefinitionsKeys:r.animationDefinitions?Object.keys(r.animationDefinitions):[],animationConfigsKeys:r.animationConfigs?Object.keys(r.animationConfigs):[]}),!this.canResolve(e))throw new Ce(ee.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(pe.SLIDER_REF),o=n?n[1]:e;let s=r.animationDefinitions?.[o];return!s&&r.animationConfigs&&(s=r.animationConfigs[o]),!s&&Nt?.animationDefinitions&&(s=Nt.animationDefinitions[o]),!s&&Nt?.animationConfigs&&(s=Nt.animationConfigs[o]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:o,hasRawConfig:!!s,rawConfig:s,animationDefinitions:r.animationDefinitions,animationConfigs:r.animationConfigs,hasGlobalContext:!!Nt}),s?this.validateAndTransformConfig(o,s):(console.warn(`⚠️ 滑块配置未找到: ${o},使用默认配置`),{...Am,id:o})}static validateAndTransformConfig(e,r){if(!r.slider)throw new Ce(ee.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=r,o=["position","length","orientation","min","max","step"];for(const s of o)if(!(s in n))throw new Ce(ee.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${s} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new Ce(ee.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new Ce(ee.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new Ce(ee.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new Ce(ee.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:r.progressIndicator,duration:r.duration,easing:r.easing,description:r.description}}static validate(e,r){if(!this.canResolve(e))return!1;const n=e.match(pe.SLIDER_REF),o=n?n[1]:e;return o in(r.animationDefinitions||{})||o in(r.animationConfigs||{}),!0}static batchResolve(e,r){const n={};for(const o of e)if(this.canResolve(o))try{n[o]=this.resolve(o,r)}catch(s){console.warn(`滑块引用解析失败: ${o}`,s)}return n}static extractSliderRefs(e){const r=[],n=o=>{if(!(!o||typeof o!="object")){o.sliderRef&&typeof o.sliderRef=="string"&&r.push(o.sliderRef),o.chartConfig?.sliderRef&&typeof o.chartConfig.sliderRef=="string"&&r.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(r)]}}const Am={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 Em(){return{type:ce.SLIDER_REF,canResolve:ht.canResolve.bind(ht),resolve:ht.resolve.bind(ht),validate:ht.validate.bind(ht)}}class Et{static canResolve(e){return typeof e!="string"||e.length===0?!1:pe.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,r,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const o=e.match(pe.GEOMETRY_TRANSFORM_REF),s=o?o[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${s}`,{hasGeometryTransformConfigs:!!r.geometryTransformConfigs,configKeys:r.geometryTransformConfigs?Object.keys(r.geometryTransformConfigs):[]});const i=r.geometryTransformConfigs?.[s];if(!i)throw new Ce(ee.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${s}`,{reference:e,configId:s,availableConfigs:r.geometryTransformConfigs?Object.keys(r.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,r){const n={...e};for(const[o,s]of Object.entries(r))s!==void 0&&(n[o]=s);return r.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},r.shapes.static&&(n.shapes.static=r.shapes.static),r.shapes.animated&&(n.shapes.animated=r.shapes.animated)),r.transform&&(n.transform={...n.transform,...r.transform}),n}static validate(e,r){if(!this.canResolve(e))return!1;const n=e.match(pe.GEOMETRY_TRANSFORM_REF),o=n?n[1]:e;return!!r.geometryTransformConfigs?.[o]}static batchResolve(e,r,n){const o={};for(const s of e)if(this.canResolve(s)&&this.validate(s,r))try{const i=n?.[s];o[s]=this.resolve(s,r,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 r=[];for(const n of e){const o=this.extractFromContentBlock(n);o&&r.push(o)}return[...new Set(r)]}}function Nm(){return{type:ce.GEOMETRY_TRANSFORM_REF,canResolve:Et.canResolve.bind(Et),resolve:Et.resolve.bind(Et),validate:Et.validate.bind(Et)}}const Ln={geometryRef:ce.GEOMETRY_REF,styleRef:ce.STYLE_REF,layoutRef:ce.LAYOUT_REF,boardRef:ce.BOARD_REF,animationRef:ce.ANIMATION_REF,transformRef:ce.TRANSFORM_REF,appearanceRef:ce.STYLE_REF,geometryTransformRef:ce.GEOMETRY_TRANSFORM_REF,sliderRef:ce.SLIDER_REF,$ref:ce.GEOMETRY_REF};class Tm{static extractRefs(e){const r=[],n=new Set,o=s=>{if(!(!s||typeof s!="object"))for(const[i,a]of Object.entries(s)){if(i in Ln){if(typeof a=="string"){const c=Ln[i],l=`${i}:${a}`;n.has(l)||(n.add(l),r.push({ref:a,type:c,path:i,value:a,fieldName:i,combined:l}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(l=>{const u=l;n.has(u)||(n.add(u),r.push({ref:l,type:ce.DESIGN_TOKEN,path:"$ref",value:l,fieldName:"",combined:u}))});continue}if(Array.isArray(a)){a.forEach(c=>o(c));continue}typeof a=="object"&&o(a)}};return o(e),r}static extractDesignTokens(e){const r=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let o;for(;(o=n.exec(e))!==null;)r.push(o[0]);return r}static calculateStats(e){const r=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 Ln?n[i]=(n[i]||0)+1:typeof a=="object"&&o(a)};return o(e),{totalRefs:r.length,uniqueRefs:new Set(r).size,fieldCounts:n}}}class Lt{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(wm()),this.register(vm()),this.register(Cm()),this.register(Sm()),this.register(_m()),this.register(Rm()),this.register(Em()),this.register(Nm())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(r=>r.type===e)}getResolverForRef(e){return this.resolvers.find(r=>r.canResolve(e))}resolve(e,r){if(typeof e!="string"){const o=this.getResolverByType(e.type);if(!o)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return o.resolve(e.value,r)}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,r)}catch(s){console.debug(`解析器 ${o.type} 解析 ${e} 失败:`,s);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,r){const n={};for(const o of e)try{const s=this.resolve(o,r),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 Tm.extractRefs(e)}catch(r){return console.warn("ReferenceExtractor 提取失败:",r),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const r=[],n=o=>{if(!(!o||typeof o!="object"))for(const[s,i]of Object.entries(o))if(s.endsWith("Ref")&&typeof i=="string")r.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&&r.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(r)]}validate(e,r){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,r);try{return n.resolve(e,r),!0}catch{return!1}}}function Pa(){return new Lt}class Dr{static transform(e,r,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(r.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:Ae.GRAPH};if(!o)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,r),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,r,{strictMode:s})))),i.styleRef){try{const a=Ie.resolve(i.styleRef,r);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}`,c=At.resolve(a,r);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(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,r,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(r.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:!!r.geometryPresets,geometryPresetKeys:r.geometryPresets?Object.keys(r.geometryPresets):[]});try{const i=Qe.resolve(s.geometryRef,r);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,c=s.content,l={...s};Object.assign(s,i),s.id=e.id,a!==void 0&&(s.type=a),c!==void 0&&(s.content=c),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 u=s.type;let g=!1;const m=r.geometryPresets[s.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:s.geometryRef,originalGeometryExists:!!m,originalGeometryType:m?.type,originalGeometryKeys:m?Object.keys(m):[],hasVertices:m&&"vertices"in m,verticesIsArray:m&&Array.isArray(m.vertices),verticesLength:m?.vertices?.length,contextGeometryPresetsKeys:Object.keys(r.geometryPresets||{})}),m&&m.vertices&&Array.isArray(m.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:m.vertices,hasWithLabel:"withLabel"in m,withLabel:m.withLabel,hasLabel:"label"in m,label:m.label}),s.verticesConfig||(s.verticesConfig={}),m.vertices.forEach((f,p)=>{if(console.warn(`🔍 DEBUG: 检查顶点${p}:`,{vertex:f,isObject:f&&typeof f=="object",hasDollarRef:f&&typeof f=="object"&&"$ref"in f,refName:f?.$ref}),f&&typeof f=="object"&&"$ref"in f){const h=f.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${h},检查context.geometryPresets`),r.geometryPresets&&r.geometryPresets[h]){const y=r.geometryPresets[h];console.warn(`🔍 DEBUG: 找到点定义 ${h}:`,y),y.name?(s.verticesConfig[p]||(s.verticesConfig[p]={}),s.verticesConfig[p].name=y.name,console.warn(`✅ 从原始几何定义提取顶点${p}名字: ${y.name}`)):console.warn(`⚠️ 点定义 ${h} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${h}`)}else console.warn(`⚠️ 顶点${p}不是$ref对象`)}),m.withLabel!==void 0&&(s.verticesConfig.withLabel=m.withLabel),m.label&&typeof m.label=="object"){const f=m.label;f.offset&&Array.isArray(f.offset)&&f.offset.length>=2&&(s.verticesConfig.offset=f.offset),f.fontSize!==void 0&&(s.verticesConfig.fontSize=f.fontSize),f.color&&(s.verticesConfig.color=f.color),f.anchorX&&(s.verticesConfig.anchorX=f.anchorX),f.anchorY&&(s.verticesConfig.anchorY=f.anchorY)}console.warn("✅ 构建的verticesConfig:",s.verticesConfig)}if(u==="segment"||u==="line"?g="endpoints"in s&&Array.isArray(s.endpoints):u==="point"?g="position"in s&&s.position!==void 0:u==="polygon"||u==="triangle"||u==="rectangle"||u==="parallelogram"?g="vertices"in s&&Array.isArray(s.vertices):g="vertices"in s&&Array.isArray(s.vertices)||"endpoints"in s&&Array.isArray(s.endpoints)||"position"in s&&s.position!==void 0,g||(console.error(`❌ ERROR: After geometryRef merge, shape ${s.id} (type: ${u}) 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 f=Ie.resolve(i.styleRef,r);console.error(" 几何样式解析结果:",f),s.style=f}}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:",r.geometryPresets?Object.keys(r.geometryPresets):"undefined")}delete s.geometryRef}if(s.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${s.styleRef}, shape id: ${s.id}`);try{const i=Ie.resolve(s.styleRef,r);console.error(" 形状样式解析成功:",i);const{id:a,...c}=i;s={...s,...c,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,r,{strictMode:o}))),s.label&&typeof s.label=="object"&&(s.label=this.transformLabel(s.label,r)),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,r),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],r),a=this.resolvePointReference(s.endpoints[1],r);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,r){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(r&&r.geometryPresets&&r.geometryPresets[n]){const o=r.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(r&&r.geometryPresets&&r.geometryPresets[n]){const o=r.geometryPresets[n];if(o.position)return o.position;if("x"in o&&"y"in o)return o}return e}return e}static convertShapeCoordinates(e,r){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,r);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,r);let c=null;if(s&&typeof s=="object"&&"$ref"in s){const l=s.$ref;r&&r.geometryPresets&&r.geometryPresets[l]&&(c=r.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&&(o[i]||(o[i]={}),o[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:(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,r);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,r);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,r);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,r);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,r):i):s&&typeof s=="object"&&(n[o]=this.convertShapeCoordinates(s,r));return n}static transformTransform(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Pe.resolve(s.transformRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformLabel(e,r){const n={...e};if(n.styleRef){try{const o=Ie.resolve(n.styleRef,r);n.style=o}catch(o){console.warn(`标签样式解析失败: ${n.styleRef}`,o)}delete n.styleRef}return n}static resolveBoardConfig(e,r){if(r.boardDefinitions&&r.boardDefinitions[e])return r.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 r=[];return e?(e.type!==Ae.GRAPH&&r.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&r.push("图形内容块 shapes 数组不能为空"):r.push("图形内容块缺少 shapes 数组"),r):(r.push("图形内容块不能为空"),r)}static batchTransform(e,r,n={}){return e.filter(o=>o.type===Ae.GRAPH).map(o=>this.transform(o,r,n))}}function $m(){return{type:Ae.GRAPH,transform:Dr.transform.bind(Dr),validate:Dr.validate.bind(Dr)}}class Lr{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const r={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:r,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:r.static.length,animatedLength:r.animated.length}),r}static transform(e,r,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 u=Et.resolve(e.geometryTransformRef,r,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",u),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(u||{}));const g={type:Ae.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:u}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",g.metadata.config),g.metadata.config&&typeof g.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),g.metadata.config=this.transformConfig(g.metadata.config,r,{strictMode:s})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",g),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",g.metadata.config),g}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:Ae.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(u){if(s)throw u;console.error("❌ 几何变换引用解析失败:",u),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",r.geometryTransformConfigs)}}const i=e.base||e.config?.base||r.basicInfo?.base||0,a=e.height||e.config?.height||r.basicInfo?.height||0,c=e.unit||e.config?.unit||r.basicInfo?.baseUnit||"cm",l={...e,type:Ae.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,!o)return l;try{if(l.geometryRef){try{const u=Qe.resolve(l.geometryRef,r);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,u),u.styleRef){const g=Ie.resolve(u.styleRef,r);l.metadata.config.style=g}}catch(u){if(s)throw u;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,u)}delete l.geometryRef}if(l.transformRef){try{const u=Pe.resolve(l.transformRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,u)}catch(u){if(s)throw u;console.warn(`几何变换变换解析失败: ${l.transformRef}`,u)}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,r,{strictMode:s}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const u=Ie.resolve(l.styleRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=u}catch(u){if(s)throw u;console.warn(`几何变换样式解析失败: ${l.styleRef}`,u)}delete l.styleRef}if(l.animationRef){try{const u=this.resolveAnimationConfig(l.animationRef,r,{strictMode:s});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...u,...l.metadata.config.animation||{}}}catch(u){if(s)throw u;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,u)}delete l.animationRef}if(l.sliderRef){try{const u=ht.resolve(l.sliderRef,r);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...u,...l.metadata.config.animation||{}}}catch(u){if(s)throw u;console.warn(`顶层滑块引用解析失败: ${l.sliderRef}`,u)}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 u=this.resolveBoardConfig(l.boardRef,r,{strictMode:s});console.error("🔍 解析后的 boardConfig:",u),l.metadata.config||(l.metadata.config={}),l.metadata.config.boardConfig={...u,...l.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",l.metadata.config.boardConfig)}catch(u){if(s)throw u;console.warn(`顶层画板引用解析失败: ${l.boardRef}`,u)}delete l.boardRef}if(l.metadata?.config?.boardConfig&&typeof l.metadata.config.boardConfig=="object"){const u=l.metadata.config.boardConfig;(!u.boundingBox||!Array.isArray(u.boundingBox)||u.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),u.boundingBox=[0,7,10,0],u.originX=u.originX??2,u.originY=u.originY??2,u.keepAspectRatio=u.keepAspectRatio??!0,u.showGrid=u.showGrid??!1,u.showAxis=u.showAxis??!1,u.description=u.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(u){if(s)throw u;return console.warn("几何变换转换失败:",u),l}}static transformConfig(e,r,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,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,r,{strictMode:o});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})),s.shapes.animated&&(console.error(` 处理 animated shapes (${s.shapes.animated.length}):`),s.shapes.animated=s.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,r,{strictMode:o});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}))),s.transform){if(s.transform.transformRef)try{const a=Pe.resolve(s.transform.transformRef,r);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,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 u=Pe.resolve(l,r);console.error(`🔍 transform[${c}] 解析成功:`,u);const g=this.normalizeTransformConfig(u,i);return console.error(`🔍 transform[${c}] 标准化后:`,g),g}catch(u){if(o)throw u;return console.warn(`Transform ref解析失败: ${l}`,u),a}}try{const l=Pe.resolve(a,r);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[${c}] 是对象格式,refName=${l}`);try{const u=Pe.resolve(l,r);console.error(`🔍 transform[${c}] 解析成功:`,u);const g={...u,...a,transformRef:void 0};console.error(`🔍 transform[${c}] 合并后:`,g);const m=this.normalizeTransformConfig(g,i);return console.error(`🔍 transform[${c}] 标准化后:`,m),m}catch(u){if(o)throw u;return console.warn(`Transform ref解析失败: ${l}`,u),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${c}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${c}] 未处理,返回原始值:`,a),a}))}if(s.geometry&&typeof s.geometry=="object"&&(s.geometry=this.transformGeometry(s.geometry,r,{strictMode:o})),Array.isArray(s.transformations)&&(s.transformations=s.transformations.map(a=>{if(a.transformRef)try{const c=Pe.resolve(a.transformRef,r);return{...a,...c,transformRef:void 0}}catch(c){if(o)throw c;return console.warn(`Transformations解析失败: ${a.transformRef}`,c),a}return a})),s.style&&typeof s.style=="object"&&(s.style=this.transformStyle(s.style,r,{strictMode:o})),s.animationRef){try{const a=this.resolveAnimationConfig(s.animationRef,r,{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:!!r.animationDefinitions,animationDefinitionKeys:r.animationDefinitions?Object.keys(r.animationDefinitions):[]});try{const a={...Nt,...r,animationDefinitions:r.animationDefinitions||Nt.animationDefinitions},c=ht.resolve(s.sliderRef,a);s.animation={...c,...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,r,{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,r){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:r?Object.keys(r):[],geometryRefToShapeId:r});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,r)),delete n.config);break;default:if(n.config){const{type:o,...s}=n.config;Object.assign(n,s),delete n.config}}if(n.targetGroup&&r){const o=n.targetGroup;let s;if(r[o])s=r[o],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:o,mapped:s,type:"exact"});else{const i=Object.keys(r).find(a=>{if(a.startsWith(o+"_")||a===o||a.includes(o))return!0;const c=a.split("_"),l=o.split("_");return c.some(u=>l.includes(u))});i&&(s=r[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:r,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,r,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:!!r.geometryPresets,contextGeometryPresetKeys:r.geometryPresets?Object.keys(r.geometryPresets):[]});const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",s.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",r.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",r.geometryPresets?Object.keys(r.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=Qe.resolve(s.geometryRef,r);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,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),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=Ie.resolve(s.styleRef,r);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&&(s.metadata.rotationGroup=s.metadata.id),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,c=.1;s.type="circle",s.vertices=[[i,a],[i+c,a]],delete s.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:s.type,vertices:s.vertices})}return s}static transformGeometry(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.geometryRef){try{const i=Qe.resolve(s.geometryRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`几何对象解析失败: ${s.geometryRef}`,i)}delete s.geometryRef}return s}static transformTransform(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.transformRef){try{const i=Pe.resolve(s.transformRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`变换对象解析失败: ${s.transformRef}`,i)}delete s.transformRef}return s}static transformStyle(e,r,n={}){const{strictMode:o=!1}=n,s={...e};if(s.styleRef){try{const i=Ie.resolve(s.styleRef,r);Object.assign(s,i)}catch(i){if(o)throw i;console.warn(`样式对象解析失败: ${s.styleRef}`,i)}delete s.styleRef}return s}static resolveAnimationConfig(e,r,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(r.animationDefinitions&&r.animationDefinitions[s])return{...r.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,r,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:!!r.boardDefinitions,contextBoardDefinitionKeys:r.boardDefinitions?Object.keys(r.boardDefinitions):[],hasRefInContext:r.boardDefinitions&&!!r.boardDefinitions[s]}),r.boardDefinitions&&r.boardDefinitions[s]){const a={...r.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 r={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 r[e]||r.slider_horizontal}static getFallbackBoardConfig(e){const r={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 r[e]||r.default}static validate(e){const r=[];return e?(e.type!==Ae.GEOMETRY_TRANSFORM&&r.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||r.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&r.push("几何变换内容块缺少 geometry 或 geometryRef"),r):(r.push("几何变换内容块不能为空"),r)}static batchTransform(e,r,n={}){return e.filter(o=>o.type===Ae.GEOMETRY_TRANSFORM).map(o=>this.transform(o,r,n))}}function km(){return{type:Ae.GEOMETRY_TRANSFORM,transform:Lr.transform.bind(Lr),validate:Lr.validate.bind(Lr)}}class bt{static transformText(e,r,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:Ae.TEXT};if(!o)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,r,{strictMode:s})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,r,{strictMode:s})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=Ie.resolve(i.styleRef,r);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,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n,i={...e,type:Ae.FORMULA};if(!o)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,r,{strictMode:s})),i.styleRef){try{const a=Ie.resolve(i.styleRef,r);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,r,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 c=i[0],l=i[1];console.error(` 发现设计令牌: ${c}, path=${l}`);try{const u=Be.resolve(c,r);console.error(` 解析结果: ${c} -> ${u}`),s=s.replace(c,String(u))}catch(u){if(o)throw u;console.warn(`文本中的设计令牌解析失败: ${c}`,u)}}return console.error(` resolveTextContent END: original="${e}", resolved="${s}"`),s}static resolveStyle(e,r,n={}){const{strictMode:o=!1}=n;try{return Be.replaceDesignTokenRefs(e,r,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 r=[];return e?(e.type!==Ae.TEXT&&r.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&r.push("文本内容块缺少 content 字段"),r):(r.push("文本内容块不能为空"),r)}static validateFormula(e){const r=[];return e?(e.type!==Ae.FORMULA&&r.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&r.push("公式内容块缺少 content 字段"),r):(r.push("公式内容块不能为空"),r)}static batchTransformText(e,r,n={}){return e.filter(o=>o.type===Ae.TEXT).map(o=>this.transformText(o,r,n))}static batchTransformFormula(e,r,n={}){return e.filter(o=>o.type===Ae.FORMULA).map(o=>this.transformFormula(o,r,n))}}function jm(){return{type:Ae.TEXT,transform:bt.transformText.bind(bt),validate:bt.validateText.bind(bt)}}function Im(){return{type:Ae.FORMULA,transform:bt.transformFormula.bind(bt),validate:bt.validateFormula.bind(bt)}}class Mm{type="hundredGrid";transform(e,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error("🔄 HundredChartTransformer.transform START for content block:",{blockType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,enableReferenceResolution:o,strictMode:s});try{const i=e.geometryRef;if(!i)throw new zt(ut.MISSING_REQUIRED_FIELD,"HundredGrid内容块缺少geometryRef字段");const a=this.extractShapeId(i),c=r.geometry_shapes?.[a]||r.geometryPresets?.[a];if(!c)throw new zt(ut.GEOMETRY_REF_NOT_FOUND,`HundredGrid引用未找到: ${i} (解析后shapeId: ${a})`);if(c.type!=="hundredGrid")throw new zt(ut.GEOMETRY_REF_NOT_FOUND,`引用${a}不是hundredGrid类型: ${c.type}`);const l=c.config||{},u=e.config||{},g=this.mergeConfigs(l,u),m=this.resolveStyle(c,r,g,o),f=this.mapToHundredChartProps(g,m),p={type:"hundredGrid",content:"",props:f,metadata:{shapeId:a,config:g,styleRef:c.styleRef}};return console.error("✅ HundredChartTransformer.transform SUCCESS:",{shapeId:a,propsKeys:Object.keys(f),hasHighlight:!!g.highlight?.numbers,highlightCount:g.highlight?.numbers?.length||0}),p}catch(i){if(console.error("❌ HundredChartTransformer.transform ERROR:",i),s)throw i;return e}}extractShapeId(e){return e.startsWith("geometryRef:")?e.replace("geometryRef:",""):e}mergeConfigs(e,r){const n={...e};return r.grid&&(n.grid={...e.grid,...r.grid}),r.highlight&&(n.highlight={...e.highlight,...r.highlight},r.highlight.numbers!==void 0&&(n.highlight.numbers=r.highlight.numbers)),r.interactive&&(n.interactive={...e.interactive,...r.interactive}),r.style&&(n.style={...e.style,...r.style}),n}resolveStyle(e,r,n,o){const s={};if(e.styleRef&&o)try{const i=e.styleRef.startsWith("styleRef:")?e.styleRef.replace("styleRef:",""):e.styleRef,a=r.stylePresets?.[i];a&&Object.entries(a).forEach(([c,l])=>{if(typeof l=="string"&&l.startsWith("$"))try{s[c]=Be.resolve(l,r)}catch(u){console.warn(`设计令牌解析失败: ${c}=${l}`,u),s[c]=l}else s[c]=l})}catch(i){console.warn(`样式引用解析失败: ${e.styleRef}`,i)}return n.style&&Object.entries(n.style).forEach(([i,a])=>{if(o&&typeof a=="string"&&a.startsWith("$"))try{s[i]=Be.resolve(a,r)}catch(c){console.warn(`设计令牌解析失败: ${i}=${a}`,c),s[i]=a}else s[i]=a}),s.baseColor||(s.baseColor="#f3f4f6"),s.selectedColor||(s.selectedColor="#3b82f6"),s.borderColor||(s.borderColor="#d1d5db"),s.textColor||(s.textColor="#333"),s.fontSize||(s.fontSize=14),s}mapToHundredChartProps(e,r){const n={};return n.rows=e.grid?.rows||10,n.cols=e.grid?.cols||10,n.cellSize=e.grid?.cellSize||36,n.mode=this.mapInteractiveMode(e.interactive?.mode),n.value=this.calculateValueFromHighlight(e.highlight?.numbers||[],n.rows,n.cols),n.fillColor=this.normalizeColor(r.selectedColor),n.baseColor=this.normalizeColor(r.baseColor),n.strokeColor=this.normalizeColor(r.borderColor),n.shadingDirection="ltr",n.hasShadow=!0,n.className="mathwiz-hundredgrid",n._config=e,n._style=r,n}mapInteractiveMode(e){return e==="readonly"?"readonly":"edit"}calculateValueFromHighlight(e,r=10,n=10){if(!e.length)return 0;const o=r*n;return e.length/o}normalizeColor(e){return typeof e!="string"?e:e.startsWith("#")?e.toLowerCase():e}validate(e){const r=[];return e.type||r.push("内容块缺少 type 字段"),e.type!=="hundredGrid"&&r.push(`内容块类型应为 hundredGrid,实际为 ${e.type}`),e.geometryRef||r.push("HundredGrid内容块缺少 geometryRef 字段"),r}}function Om(){return new Mm}class Fm{type="optionGroup";transform(e,r,n={}){const{enableReferenceResolution:o=!0,strictMode:s=!1}=n;console.error("🔄 OptionGroupTransformer.transform START for content block:",{blockType:e.type,hasOptionGroupRef:!!e.optionGroupRef,optionGroupRef:e.optionGroupRef,enableReferenceResolution:o,strictMode:s});try{const{optionGroupRef:i}=e;if(!i)throw new zt(ut.MISSING_REQUIRED_FIELD,"OptionGroup 内容块缺少 optionGroupRef 字段");const a=r.optionGroups?.[i];if(!a)throw new zt(ut.GEOMETRY_REF_NOT_FOUND,`OptionGroup 定义未找到: ${i}`);if(a.type!=="optionGroup")throw new zt(ut.GEOMETRY_REF_NOT_FOUND,`引用 ${i} 不是 optionGroup 类型: ${a.type}`);const c=a.options.map(u=>({id:u.id,content:u.content,contentType:u.contentType||"text",graphConfig:u.graphConfig})),l={type:"optionGroup",content:"",options:c,correctAnswers:a.correctAnswers,answerType:a.answerType,layout:a.layout||"vertical",variant:a.variant||"default",mode:e.mode||"question",showUserAnswer:e.showUserAnswer||!1,metadata:{optionGroupId:i,definition:a}};return console.error("✅ OptionGroupTransformer.transform SUCCESS:",{optionGroupRef:i,optionsCount:c.length,answerType:a.answerType,correctAnswers:a.correctAnswers}),l}catch(i){if(console.error("❌ OptionGroupTransformer.transform ERROR:",i),s)throw i;return e}}validate(e){const r=[];return e.type||r.push("内容块缺少 type 字段"),e.type!=="optionGroup"&&r.push(`内容块类型应为 optionGroup,实际为 ${e.type}`),e.optionGroupRef||r.push("OptionGroup 内容块缺少 optionGroupRef 字段"),r}}function Pm(){return new Fm}class Dm{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register($m()),this.register(km()),this.register(jm()),this.register(Im()),this.register(Om()),this.register(Pm())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,r,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,r,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,r,n={}){return e.map(o=>this.transform(o,r,n))}transformScene(e,r,n={}){const o=e.items||e.content;if(!e||!Array.isArray(o))return{items:[],layout:e?.layout};const s=this.batchTransform(o,r,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,r,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=et.resolve(e.layout,r)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:s,layout:i}}resolveLayoutReferences(e,r,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return et.resolve(e,r)}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=et.resolve(s,r),{layoutRef:a,...c}=e;return{...i,...c}}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]=et.resolve(i,r)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),o[s]=i}else if(typeof i=="string"&&i.startsWith("$"))try{o[s]=Be.resolve(i,r)}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,r,n):o[s]=i;return o}return e}transformScenes(e,r,n={}){const o={};for(const[s,i]of Object.entries(e))o[s]=this.transformScene(i,r,n);return o}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const r=this.getTransformer(e.type);return!r||!r.validate?[]:r.validate(e)}batchValidate(e){return e.map(r=>({block:r,errors:this.validate(r)}))}}function Da(){return new Dm}class so{static validate(e,r={}){const{strictMode:n=!1,skipOptionalFields:o=!1}=r,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,r,n,o){const{skipOptionalFields:s}=o;for(const i of Dn.RAW_DATA)e[i]===void 0&&r.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Dn.BASIC_INFO)e.basic_info[i]===void 0&&r.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Dn.ANSWER_INFO)e.answer_info[i]===void 0&&r.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,r,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&r.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&r.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&r.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&r.push(`${a} 应为对象类型`)})}static validateScenes(e,r,n){if(!e.scenes||typeof e.scenes!="object"){r.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||r.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){r.push(`场景 ${s} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||r.push(`场景 ${s} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&r.push(`场景 ${s} 的 layout 应为对象类型`),Ta.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,r,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"&&r.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&r.push(`basic_info.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&r.push("basic_info.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&r.push("basic_info.context 应为对象类型"),o.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(o.shape)&&n.push(`未知的形状类型: ${o.shape}`)}static validateAnswerInfo(e,r,n){if(!e.answer_info||typeof e.answer_info!="object")return;const o=e.answer_info;typeof o.value!="number"&&r.push("answer_info.value 应为数字类型"),typeof o.unit!="string"&&r.push("answer_info.unit 应为字符串类型"),typeof o.explanation_text!="string"&&r.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,r,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 r=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of r)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,r={}){const{strictMode:n=!1,removeInvalidFields:o=!1}=r,s=this.validate(e,{strictMode:n});let i=e;return o&&!s.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(c=>{c in i&&delete i[c]})),{data:i,errors:s.errors,warnings:s.warnings}}}class io{static validate(e,r={}){const{strictMode:n=!1,checkSceneContent:o=!0}=r,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,r,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&&r.push(`缺少必需字段: ${s}`)}static validateFieldTypes(e,r,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&r.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&r.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&r.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&r.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&r.push(`${i} 应为对象类型`)})}static validateScenes(e,r,n){if(!e.scenes||typeof e.scenes!="object"){r.push("scenes 应为对象类型");return}const o=["question","solve","review"];for(const s of o)e.scenes[s]||r.push(`缺少必需场景: ${s}`);for(const[s,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){r.push(`场景 ${s} 应为对象类型`);continue}const a=i,c=a.items||a.content;Array.isArray(c)?c.length===0&&n.push(`场景 ${s} 的内容数组为空`):r.push(`场景 ${s} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&r.push(`场景 ${s} 的 layout 应为对象类型`),Ta.includes(s)||n.push(`未知的场景名称: ${s}`)}}static validateBasicInfo(e,r,n){if(!e.basicInfo||typeof e.basicInfo!="object"){r.push("basicInfo 应为对象类型");return}const o=e.basicInfo;(o.question===void 0||typeof o.question!="string")&&r.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="number"&&r.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{o[a]!==void 0&&typeof o[a]!="string"&&r.push(`basicInfo.${a} 应为字符串类型`)}),o.variables!==void 0&&typeof o.variables!="object"&&r.push("basicInfo.variables 应为对象类型"),o.context!==void 0&&typeof o.context!="object"&&r.push("basicInfo.context 应为对象类型")}static validateAnswer(e,r,n){if(!e.answer||typeof e.answer!="object"){r.push("answer 应为对象类型");return}const o=e.answer;typeof o.value!="number"&&r.push("answer.value 应为数字类型"),typeof o.unit!="string"&&r.push("answer.unit 应为字符串类型"),typeof o.explanation!="string"&&r.push("answer.explanation 应为字符串类型"),o.value!==void 0&&(o.value<0&&n.push("answer.value 为负数,可能不正确"),o.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,r,n){if(e.explanation===void 0){r.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){r.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((o,s)=>{(!o||typeof o!="object")&&r.push(`explanation[${s}] 应为对象类型`)})):e.explanation.steps===void 0?r.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||r.push("explanation.steps 应为数组类型")}static validateStrictMode(e,r,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 r=["id","title","basicInfo","scenes","answer"];for(const n of r)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 jt{static validateInput(e,r={}){const{isValid:n,errors:o,warnings:s}=so.validate(e,r);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateOutput(e,r={}){const{isValid:n,errors:o,warnings:s}=io.validate(e,r);return{isValid:n,errors:o,warnings:s,timestamp:Date.now()}}static validateComplete(e,r,n={}){const{inputStrictMode:o=!1,outputStrictMode:s=!1}=n,i=this.validateInput(e,{strictMode:o}),a=this.validateOutput(r,{strictMode:s}),c=[...i.errors,...a.errors],l=[...i.warnings,...a.warnings],u={isValid:i.isValid&&a.isValid,errors:c,warnings:l};return{input:i,output:a,overall:u}}static quickValidateInput(e){return so.quickValidate(e)}static quickValidateOutput(e){return io.quickValidate(e)}static validateAndReport(e,r,n={}){const o=r==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${r.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 ao{static extractAllReferences(e){const r=[],n=o=>{typeof o=="string"?r.push(o):Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)};return n(e),[...new Set(r)]}static categorizeReferences(e,r){const n={[ce.DESIGN_TOKEN]:[],[ce.STYLE_REF]:[],[ce.GEOMETRY_REF]:[],[ce.TRANSFORM_REF]:[],[ce.LAYOUT_REF]:[]},o=new Lt;for(const s of e){const i=o.getResolverForRef(s);i&&n[i.type].push(s)}return n}static batchResolveReferences(e,r,n={}){const{strictMode:o=!1,onMissing:s}=n,i=new Lt,a={};for(const c of e){const l=i.getResolverForRef(c);if(l)try{a[c]=l.resolve(c,r)}catch(u){if(o)throw u;console.warn(`引用解析失败: ${c}`,u),s&&(a[c]=s(c))}}return a}static replaceReferences(e,r,n={}){const{strictMode:o=!1,onMissing:s,maxDepth:i=10}=n,a=new Lt,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=(u,g=0,m)=>{if(g>i)return console.warn(`引用替换达到最大深度: ${i}`),u;if(typeof u=="string"){if(m&&c.has(m))return console.warn(`🛡️ 跳过保留字段 "${m}" 的通用解析: "${u}"`),u;if(!(u.startsWith("$")||u.includes("Ref:")))return u;const p=a.getResolverForRef(u);if(p)try{return p.resolve(u,r)}catch(h){if(o)throw h;return console.warn(`引用解析失败: ${u}`,h),s?s(u):u}return u}else{if(Array.isArray(u))return u.map(f=>l(f,g+1,void 0));if(u&&typeof u=="object"){const f={};for(const[p,h]of Object.entries(u))f[p]=l(h,g+1,p);return f}}return u};return l(e)}static calculateReferenceStats(e,r){const n=new Lt,o={total:e.length,resolved:0,failed:0,byType:{}};Object.values(ce).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 c=i.resolve(s,r);console.log(`🔍 引用解析成功: ${s} =>`,c),o.resolved++,o.byType[a].resolved++}catch(c){console.error(`🔍 引用解析失败: ${s}`,c),o.failed++,o.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${s}`)}return o}static checkReferenceExists(e,r){const o=new Lt().getResolverForRef(e);if(!o)return!1;if(o.validate)return o.validate(e,r);try{return o.resolve(e,r),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const r=e.match(/^(\w+):(\w+)$/);return r?[r[1],r[2]]:[e]}static createReference(e,r){switch(e){case ce.DESIGN_TOKEN:return`$${r.join(".")}`;case ce.STYLE_REF:return`styleRef:${r[0]}`;case ce.GEOMETRY_REF:return`geometryRef:${r[0]}`;case ce.TRANSFORM_REF:return`transformRef:${r[0]}`;case ce.LAYOUT_REF:return`layoutRef:${r[0]}`;default:return r.join(":")}}static flattenNestedReferences(e){const r=[],n=(o,s=[])=>{if(typeof o=="string")r.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),r}}class La{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 r=this.marks.get(e);if(!r){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),o=n-r.startTime;r.endTime=n,r.duration=o,this.updateStats(e,o)}updateStats(e,r){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=r;break;case"transformation":this.stats.transformationTime=r;break;case"validation":this.stats.validationTime=r;break;case"total":this.stats.totalTime=r;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>Rt.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${Rt.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>Rt.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${Rt.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>Rt.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${Rt.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>Rt.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 Lm{static deepMerge(e,r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return Array.isArray(e)?e.map((o,s)=>s<r.length?this.deepMerge(o,r[s]):o):[...r];const n={...e};for(const[o,s]of Object.entries(r))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,r){if(e===r)return!0;if(typeof e!=typeof r||typeof e!="object"||e===null||r===null||Array.isArray(e)!==Array.isArray(r))return!1;if(Array.isArray(e))return e.length!==r.length?!1:e.every((s,i)=>this.deepEqual(s,r[i]));const n=Object.keys(e),o=Object.keys(r);return n.length!==o.length?!1:n.every(s=>s in r?this.deepEqual(e[s],r[s]):!1)}static safeGet(e,r,n=void 0){const o=Array.isArray(r)?r:r.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 c=parseInt(a[1],10);s=s[c]}else s=s[i]}return s!==void 0?s:n}static safeSet(e,r,n){const o=Array.isArray(r)?r:r.split("."),s=Array.isArray(e)?[...e]:{...e};let i=s;for(let l=0;l<o.length-1;l++){const u=o[l],g=u.match(/^\[(\d+)\]$/);if(g&&Array.isArray(i)){const m=parseInt(g[1],10);i[m]===void 0&&(i[m]={}),i=i[m]}else{if(i[u]===void 0){const f=o[l+1].match(/^\[(\d+)\]$/);i[u]=f?[]:{}}i=i[u]}}const a=o[o.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 s}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,r){let n=0;return(...o)=>{const s=Date.now();s-n>=r&&(n=s,e(...o))}}static debounce(e,r){let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>e(...o),r)}}static formatBytes(e,r=2){if(e===0)return"0 Bytes";const n=1024,o=r<0?0:r,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 r=new Set,n=o=>r.has(o)?0:typeof o=="string"?o.length*2:typeof o=="number"?8:typeof o=="boolean"?4:o==null?0:Array.isArray(o)?(r.add(o),o.reduce((s,i)=>s+n(i),0)):typeof o=="object"?(r.add(o),Object.values(o).reduce((s,i)=>s+n(i),0)):0;return n(e)}}class Gm{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...xm,...e},this.referenceContext=Fa(),this.resolverRegistry=Pa(),this.transformerRegistry=Da(),this.performanceMonitor=new La}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 r=this.validateInput(e);if(!r.isValid&&this.config.strictMode)throw new Ce(ee.INVALID_INPUT,Ns[ee.INVALID_INPUT],{errors:r.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 Ce(ee.OUTPUT_VALIDATION_FAILED,Ns[ee.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:r,outputValidation:i,inputWarnings:r.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(r){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw r;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",r),this.createFallbackResult(e,r);throw r}}validateInput(e){return jt.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(([r,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${r}:`,{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(` 📍 ${r}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[r]=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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[r]=o}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(r=>{r&&r.content&&Array.isArray(r.content)&&r.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(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${r}:`,{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[r]=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(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${r}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[r]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}extractOptionGroupsFromInput(e){if(!e){console.error("⚠️ extractOptionGroupsFromInput: inputData is null or undefined");return}this.referenceContext.optionGroups||(this.referenceContext.optionGroups={}),e.option_groups&&typeof e.option_groups=="object"?(console.error("📦 Extracting option_groups:",Object.keys(e.option_groups)),Object.entries(e.option_groups).forEach(([r,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing option group ${r}:`,{id:n.id,type:n.type,answerType:n.answerType,optionsCount:n.options?.length||0}),this.referenceContext.optionGroups[r]=n)}),console.error("✅ optionGroups after extraction:",Object.keys(this.referenceContext.optionGroups))):console.error("⚠️ No option_groups found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;if(console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0}),e.type==="hundredGrid")return console.error(`✅ hundredGrid类型跳过坐标转换: ${e.id}`),e;const r={...e};r.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line"),Array.isArray(r.position)&&r.position.length>=2&&(r.position={x:r.position[0],y:r.position[1]}),Array.isArray(r.vertices)&&(r.vertices=r.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(r.endpoints)?(console.error(`🔄 Processing endpoints for shape ${r.id||"unknown"}:`,{endpointsLength:r.endpoints.length,firstEndpoint:r.endpoints[0],firstEndpointType:typeof r.endpoints[0],firstEndpointIsArray:Array.isArray(r.endpoints[0])}),r.endpoints=r.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)),r.type==="segment"&&Array.isArray(r.endpoints)&&r.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line",r.start=r.endpoints[0],r.end=r.endpoints[1],delete r.endpoints)):"endpoints"in r&&console.error(`⚠️ Shape ${r.id||"unknown"} has endpoints but not array:`,{endpoints:r.endpoints,endpointsType:typeof r.endpoints});for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=o:r[n]=this.convertGeometryShapeCoordinates(o));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),endpointsLength:r.endpoints?r.endpoints.length:0,keys:Object.keys(r)}),r}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const r={...e};if(r.config&&r.config.center){const n=r.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(r.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(r))Array.isArray(o)?r[n]=o.map(s=>typeof s=="object"?this.convertTransformDefinitionCoordinates(s):s):o&&typeof o=="object"&&(r[n]=this.convertTransformDefinitionCoordinates(o));return r}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(r=>{if(r&&r.type==="point"&&r.position&&Array.isArray(r.position)&&r.position.length>=2){const n=r.id||`point_${r.position[0]}_${r.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:r.position[0],y:r.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e),this.extractOptionGroupsFromInput(e);const r={id:e.math_prob_id||Lm.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&&(r[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,r.basicInfo=o,console.error("🔧 transformBaseData: transformed.basicInfo set =",r.basicInfo),r.explanation=this.transformExplanation(e.explanation),r}parseGrade(e){const r=e.match(/g(\d+)/);return r?parseInt(r[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 r={...e};return console.error("🔄 transformBasicInfo: transformed copy:",r),r.question===void 0&&r.content!==void 0&&(r.question=r.content),r.question===void 0&&(r.question=""),console.error("🔄 transformBasicInfo: returning:",r),r}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const r={};return["question","solve","review"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];r[s]={...i,items:a},i.content!==void 0&&delete r[s].content}else r[s]={items:[]}}),["remember","explanation","success"].forEach(s=>{if(e[s]){const i=e[s],a=i.items||i.content||[];r[s]={...i,items:a},i.content!==void 0&&delete r[s].content}}),r}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 r=e.steps.map((n,o)=>(console.error(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:r}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const r=e.chartConfig,n=r.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(r)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={type:n,...r};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,...c}=s;i={...c,...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 r=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(r.length),this.resolverRegistry.batchResolve(r,this.referenceContext),ao.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const r={...e};return r.scenes&&typeof r.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),r.scenes=this.transformerRegistry.transformScenes(r.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),r}validateOutput(e){return jt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,r,n){const o=this.performanceMonitor.getStats(),s=this.performanceMonitor.checkPerformance(),i=[...r.inputValidation.warnings.map(u=>({code:ee.INVALID_INPUT,message:`输入验证警告: ${u}`,suggestion:"检查输入数据格式"})),...r.outputValidation.warnings.map(u=>({code:ee.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${u}`,suggestion:"检查数据转换逻辑"})),...s.warnings.map(u=>({code:ee.TRANSFORMATION_FAILED,message:`性能警告: ${u}`,suggestion:"优化数据转换性能"}))],a=n||e,c=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=ao.calculateReferenceStats(c,this.referenceContext);return{data:e,warnings:i,performance:o,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,r){const n={...qr,id:e?.math_prob_id||qr.id,title:e?.title||qr.title},o={code:ee.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${r.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 _r{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...bm,...e},this.referenceContext=Fa(),this.resolverRegistry=Pa(),this.transformerRegistry=Da(),this.performanceMonitor=new La,this.syncAdapter=new Gm(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 r=e,n=this.syncAdapter.adapt(r);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(r){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw r;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",r),this.createFallbackResult(e,r);throw r}}_validateInput(e){return jt.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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[r]=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(([r,n])=>{if(n&&typeof n=="object"){const o=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[r]=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 r=e.steps.map((n,o)=>(this.config.enableLogging&&console.log(` Step ${o}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:r}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const r=e.chartConfig,n=r.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(r))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const o={...r,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,...c}=s;i={...c,...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 r={...e};r.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line"),Array.isArray(r.position)&&r.position.length>=2&&(r.position={x:r.position[0],y:r.position[1]}),Array.isArray(r.vertices)&&(r.vertices=r.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(r.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${r.id||"unknown"}:`,{endpointsLength:r.endpoints.length,firstEndpoint:r.endpoints[0],firstEndpointType:typeof r.endpoints[0],firstEndpointIsArray:Array.isArray(r.endpoints[0])}),r.endpoints=r.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)),r.type==="line"&&Array.isArray(r.endpoints)&&r.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${r.id||"unknown"}`),r.type="line",r.start=r.endpoints[0],r.end=r.endpoints[1],delete r.endpoints)):"endpoints"in r&&this.config.enableLogging&&console.log(`⚠️ Shape ${r.id||"unknown"} has endpoints but not array:`,{endpoints:r.endpoints,endpointsType:typeof r.endpoints});for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=o:r[n]=this.convertGeometryShapeCoordinates(o));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:r.type,hasEndpoints:"endpoints"in r,endpoints:r.endpoints,endpointsIsArray:Array.isArray(r.endpoints),endpointsLength:r.endpoints?r.endpoints.length:0,keys:Object.keys(r)}),r}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const r={...e};if(r.config&&r.config.center){const n=r.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(r.config.center=[n.x,n.y])}for(const[n,o]of Object.entries(r))Array.isArray(o)?r[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?r[n]=this.convertTransformDefinitionCoordinates(o):r[n]=this.deepClone(o));return r}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const r={};for(const n in e)e.hasOwnProperty(n)&&(r[n]=this.deepClone(e[n]));return r}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const r={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=r.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),r}_resolveReferences(e){const r=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(r.length),this.resolverRegistry.batchResolve(r,this.referenceContext),ao.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const r={...e};return r.scenes&&typeof r.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),r.scenes=this.transformerRegistry.transformScenes(r.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),r}_validateOutput(e){return jt.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,r,n){const o=this.performanceMonitor.getStats(),s=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(r.inputWarnings||[]).map(a=>({code:ut.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(r.outputWarnings||[]).map(a=>({code:ut.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?o:void 0,referenceStats:s}}createFallbackResult(e,r){return{data:{...qr,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:ut.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${r instanceof Error?r.message:r}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new _r(e)}}function Ft(t,e){return new _r(e).adapt(t)}async function Vo(t,e){return Promise.resolve(Ft(t,e))}function Ga(t,e){const r=typeof t=="function"?t():t;return Ft(r,e)}async function Va(t,e){const r=typeof t=="function"?await t():t instanceof Promise?await t:t;return Ft(r,e)}function za(t){return new _r(t)}function Ua(t){const e=new _r(t);return{adapt:r=>Promise.resolve(e.adapt(r))}}function Vm(t,e="input"){return e==="input"?jt.validateInput(t):jt.validateOutput(t)}function zm(t,e,r=100){const n=[];for(let c=0;c<r;c++){const l=performance.now();t.adapt(e);const u=performance.now();n.push(u-l)}const o=n.reduce((c,l)=>c+l,0)/r,s=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:o,minTime:s,maxTime:i,memoryUsage:a}}const Um={adapt:(t,e)=>Ft(t,e),adaptAsync:(t,e)=>Vo(t,e),create:t=>za(t)},Bm="4.0.0",Ba="4.0.0";function Hm(t="4.0.0"){return Ba>=t}function Ha(t){return t?.schema_version==="4.0.0"||t?.schema_version?.startsWith("4.")}function qm(t){return Ha(t)&&(t.geometry_shapes||t.transform_definitions||t.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(t.basic_info.shape))}class Gn extends Error{constructor(e,r,n,o){super(`Failed to generate config for ${r}: ${e}`),this.shapeType=r,this.options=n,this.innerError=o,this.name="ConfigGenerationError"}}function Wm(t){const e=[],r=[];if(t.shapes||e.push(K("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),t.transform||e.push(K("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),t.strategy||e.push(K("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:$s(e),timestamp:new Date().toISOString()};t.shapes&&e.push(...Ym(t.shapes));let n=!1;if(t.shapes?.animated){for(const o of t.shapes.animated)if(o.transform){n=!0;break}}return t.transform?e.push(...Km(t.transform)):n||e.push(K("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...Xm(t)),e.push(...Jm(t)),e.push(...Zm(t)),e.length>0&&r.push(...$s(e)),{isValid:e.length===0,errors:e,fixes:r,timestamp:new Date().toISOString()}}function qa(t){if(!t||typeof t!="object"||!t.type||typeof t.type!="string"||!["rotation","translation","scale","composite"].includes(t.type))return!1;switch(t.type){case"rotation":if(!t.config||typeof t.config!="object")return!1;const r=t.config.center;if(r!=="auto"&&(!Array.isArray(r)||r.length!==2)||typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number"||t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical")return!1;break;case"translation":if(!t.config||typeof t.config!="object")return!1;const n=t.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 t.config.distance!="number"||t.config.distance<=0)return!1;break;case"scale":if(!t.config||typeof t.config!="object")return!1;const o=t.config.center;if(o!=="centroid"&&(!Array.isArray(o)||o.length!==2)||typeof t.config.startScale!="number"||typeof t.config.endScale!="number"||typeof t.config.uniform!="boolean")return!1;break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))return!1;for(const s of t.transforms)if(!qa(s))return!1;if(t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel")return!1;break}return!0}function Wa(t,e){const r=[];if(!t||typeof t!="object")return r.push(K("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,t,{type:"rotation"})),r;(!t.type||typeof t.type!="string")&&r.push(K("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,t.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(t.type&&!n.includes(t.type)&&r.push(K("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${t.type}`,`${e}.type`,t.type,"rotation")),t.type){case"rotation":if(!t.config||typeof t.config!="object")r.push(K("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,t.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const o=t.config.center;o!=="auto"&&(!Array.isArray(o)||o.length!==2)&&r.push(K("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,t.config.center,[0,0])),(typeof t.config.startAngle!="number"||typeof t.config.endAngle!="number")&&r.push(K("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,t.config,{startAngle:0,endAngle:Math.PI})),t.config.direction!=="clockwise"&&t.config.direction!=="counterclockwise"&&t.config.direction!=="horizontal"&&t.config.direction!=="vertical"&&r.push(K("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,t.config.direction,"clockwise"))}break;case"translation":if(!t.config||typeof t.config!="object")r.push(K("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,t.config,{direction:"horizontal",distance:1}));else{const o=t.config.direction;Array.isArray(o)?o.length!==2?r.push(K("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,o,[1,0])):(typeof o[0]!="number"||typeof o[1]!="number")&&r.push(K("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,o,[1,0])):typeof o=="string"?o!=="horizontal"&&o!=="vertical"&&r.push(K("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,o,"horizontal")):r.push(K("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,o,"horizontal")),(typeof t.config.distance!="number"||t.config.distance<=0)&&r.push(K("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,t.config.distance,1))}break;case"scale":if(!t.config||typeof t.config!="object")r.push(K("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,t.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const o=t.config.center;o!=="centroid"&&(!Array.isArray(o)||o.length!==2)&&r.push(K("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,t.config.center,"centroid")),(typeof t.config.startScale!="number"||typeof t.config.endScale!="number")&&r.push(K("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,t.config,{startScale:1,endScale:2})),typeof t.config.uniform!="boolean"&&r.push(K("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,t.config.uniform,!0))}break;case"composite":if(!t.transforms||!Array.isArray(t.transforms))r.push(K("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,t.transforms,[]));else for(let o=0;o<t.transforms.length;o++){const s=Wa(t.transforms[o],`${e}.transforms[${o}]`);r.push(...s)}t.executionMode!==void 0&&t.executionMode!=="sequential"&&t.executionMode!=="parallel"&&r.push(K("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,t.executionMode,"sequential"));break}return r}function K(t,e,r,n,o){let s=o;if(o===void 0)switch(t){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:t,message:e,path:r,value:n,suggestedValue:s}}function Ym(t){const e=[];if(!t||typeof t!="object")return e.push(K("MISSING_SHAPES","形状定义无效或缺失","$.shapes",t)),e;if(!Array.isArray(t.static))e.push(K("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",t.static));else for(let r=0;r<t.static.length;r++){const n=t.static[r],o=Ts(n,`$.shapes.static[${r}]`);e.push(...o)}if(!Array.isArray(t.animated))e.push(K("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",t.animated));else for(let r=0;r<t.animated.length;r++){const n=t.animated[r],o=Ts(n,`$.shapes.animated[${r}]`);e.push(...o)}return e}function Ts(t,e){const r=[];if(!t||typeof t!="object")return r.push(K("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,t)),r;if((!t.type||typeof t.type!="string")&&r.push(K("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,t.type)),!Array.isArray(t.vertices))r.push(K("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,t.vertices));else if(t.vertices.length===0)r.push(K("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,t.vertices));else for(let n=0;n<t.vertices.length;n++){const o=t.vertices[n];!Array.isArray(o)||o.length!==2?r.push(K("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,o)):(typeof o[0]!="number"||typeof o[1]!="number")&&r.push(K("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,o))}if(t.transform!==void 0){const n=Wa(t.transform,`${e}.transform`);r.push(...n)}return r}function Km(t){const e=[];if(!t)return e.push(K("MISSING_TRANSFORM","变换配置缺失","$.transform",t)),e;const r=Array.isArray(t),n=r?t:[t],o="$.transform";for(let s=0;s<n.length;s++){const i=n[s],a=r?`${o}[${s}]`:o;qa(i)||e.push(K("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function Xm(t){const e=[];if(!t.strategy)return e;const{strategy:r}=t;let n=0;if(t.transform&&(Array.isArray(t.transform)?n+=t.transform.length:typeof t.transform=="object"&&(t.transform&&typeof t.transform=="object"&&"transforms"in t.transform?n+=t.transform.transforms.length:n+=1)),t.shapes?.animated)for(const s of t.shapes.animated)s.transform&&(n+=1);return r.includes("single")&&n!==1&&e.push(K("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",r,n===0?"single_rotation":"double_rotation")),r.includes("double")&&n!==2&&e.push(K("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",r,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(r)||e.push(K("STRATEGY_MISMATCH",`无效的策略名称: ${r}`,"$.strategy",r,"single_rotation")),e}function Jm(t){const e=[];if(t.unit&&typeof t.unit!="string"&&e.push(K("UNIT_MISMATCH","单位必须是字符串","$.unit",t.unit,"in")),t.baseUnit&&typeof t.baseUnit!="string"&&e.push(K("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",t.baseUnit,t.unit||"in")),t.heightUnit&&typeof t.heightUnit!="string"&&e.push(K("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",t.heightUnit,t.unit||"in")),t.unit&&t.baseUnit&&t.baseUnit!==t.unit&&e.push(K("UNIT_MISMATCH",`底边单位 (${t.baseUnit}) 与主单位 (${t.unit}) 不一致`,"$.baseUnit",t.baseUnit,t.unit)),t.unit&&t.heightUnit&&t.heightUnit!==t.unit&&e.push(K("UNIT_MISMATCH",`高度单位 (${t.heightUnit}) 与主单位 (${t.unit}) 不一致`,"$.heightUnit",t.heightUnit,t.unit)),t.unit&&t.boardConfig&&t.boardConfig.boundingBox){const[r,n,o,s]=t.boardConfig.boundingBox,i=o-r,a=n-s,c=t.unit==="cm"?50:20;(i>c*5||a>c*5)&&e.push(K("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${t.unit})不匹配`,"$.boardConfig.boundingBox",t.boardConfig.boundingBox,void 0))}return e}function Zm(t){const e=[];if(t.shapes&&t.boardConfig&&t.boardConfig.boundingBox){const r=t.boardConfig.boundingBox,[n,o,s,i]=r,a=[...t.shapes.static||[],...t.shapes.animated||[]];for(let c=0;c<a.length;c++){const l=a[c];if(l&&l.vertices)for(let u=0;u<l.vertices.length;u++){const g=l.vertices[u];if(Array.isArray(g)&&g.length===2){const[m,f]=g;(m<n||m>s||f<i||f>o)&&e.push(K("GEOMETRY_INCONSISTENCY",`形状 ${c} 的顶点 ${u} (${m}, ${f}) 超出画板边界`,`$.shapes.${c<(t.shapes.static?.length||0)?"static":"animated"}[${c}].vertices[${u}]`,g,[Math.max(n,Math.min(m,s)),Math.max(i,Math.min(f,o))]))}}}}if(t.metadata&&t.metadata.base&&t.metadata.height){const r=.5*t.metadata.base*t.metadata.height;if(t.shapes?.static?.[0]?.vertices){const n=t.shapes.static[0].vertices;if(n.length===3){const[o,s]=n[0],[i,a]=n[1],[c,l]=n[2],u=.5*Math.abs((i-o)*(l-s)-(c-o)*(a-s));Math.abs(u-r)>.01&&e.push(K("GEOMETRY_INCONSISTENCY",`计算面积 (${u.toFixed(2)}) 与预期面积 (${r.toFixed(2)}) 不一致`,"$.metadata",{base:t.metadata.base,height:t.metadata.height,calculatedArea:u,expectedArea:r}))}}}return e}function $s(t){const e=[];for(const r of t)switch(r.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:r.path,value:r.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${r.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:r.path,value:r.suggestedValue||1,description:`将底边长度修复为: ${r.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:r.path,value:r.suggestedValue||1,description:`将高度修复为: ${r.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:r.path,value:r.suggestedValue||0,description:`将原点坐标修复为: ${r.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:r.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:r.suggestedValue!==void 0&&e.push({action:"replace",path:r.path,value:r.suggestedValue,description:`修复 ${r.code} 错误`,isSafe:!1})}return e}function ks(t){if(!Qm(t))throw new Gn("Invalid parallelogram config options","parallelogram",t);const{base:e,height:r,unit:n="in",layoutDensity:o="compact",theme:s="light"}=t,i=t.originX??0,a=t.originY??0,c=t.skew??e/3;try{const l=ep(e,r,c,i,a,s),u=tp(e),g=rp(o),m=np(e,r,c,i,a);return{ui:{layoutDensity:o},base:e,height:r,unit:n,shapes:l,transform:u,animation:g,boardConfig:m,strategy:"cut_and_paste",theme:s,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{triangleType:"right_triangle",base:e,height:r,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){if(l instanceof Gn)throw l;const u=l instanceof Error?l.message:String(l);throw new Gn(u,"parallelogram",t,l instanceof Error?l:void 0)}}function Qm(t){if(!t||typeof t!="object")return!1;const e=["base","height"];for(const r of e)if(!(r in t))return!1;return!(typeof t.base!="number"||t.base<=0||typeof t.height!="number"||t.height<=0||t.skew!==void 0&&(typeof t.skew!="number"||t.skew<0)||t.originX!==void 0&&(typeof t.originX!="number"||!isFinite(t.originX))||t.originY!==void 0&&(typeof t.originY!="number"||!isFinite(t.originY)))}function ep(t,e,r,n,o,s){const a=s==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},c=[[n+r,o],[n+t,o],[n+t+r,o+e],[n+r,o+e]],l=[[n,o],[n+r,o],[n+r,o+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 tp(t){return{type:"translation",config:{direction:[1,0],distance:t}}}function rp(t){return{slider:{position:t==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function np(t,e,r,n,o){const s=Math.min(n,n+r,n+t,n+t+r),i=Math.max(n,n+r,n+t,n+t+r),a=Math.min(o,o+e),c=Math.max(o,o+e),l=3;return{boundingBox:[s-l,c+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function op(t){return{id:t.id||t.math_prob_id,title:t.title||"",grade:t.grade||5,unit:t.unit||t.unit_name||"",lesson:t.lesson||t.lesson_name||"",skill:t.skill||t.skill_description||"",objective:t.objective||"",knowledgePoints:Array.isArray(t.knowledge_points)?t.knowledge_points:Array.isArray(t.knowledgePoints)?t.knowledgePoints:[],difficulty:t.difficulty||1,description:t.description||"",metadata:t.metadata||{topic:"",skill:"",tags:[]},math_prob_id:t.math_prob_id,grade_id:t.grade_id,unit_id:t.unit_id,lesson_id:t.lesson_id,module_id:t.module_id,skill_item_id:t.skill_item_id,skill_id:t.skill_id,created_at:t.created_at,updated_at:t.updated_at,layout:t.layout||{type:"card",padding:"20px",theme:"light"}}}function sp(t){const e=t||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function ip(t,e,r){return{value:t,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:r}}function ap(t){return t?{value:t.value,unit:t.unit,explanation:t.explanation_text||t.explanation||"正确答案"}:null}function lp(t){return t.answer?t.answer:t.answer_info?ap(t.answer_info):null}function cp(){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 dp(){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 up(t){return Array.isArray(t)||t&&t.steps?t:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Ya(t){const e=op(t),r=sp(t.basic_info||t.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:{...r,question:r.question||"计算下面平行四边形的面积:",answerUnit:r.answerUnit||"平方英寸",shape:r.shape||"parallelogram",base:r.base||9,height:r.height||6,baseUnit:r.baseUnit||"in",heightUnit:r.heightUnit||"in",variables:r.variables||{b:9,h:6,unit:"in"},context:r.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:mp(t.scenes||cp(),"parallelogram",r),explanation:up(t.explanation||dp()),answer:lp(t)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:t.answer_info||ip(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),layout:t.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function fp(t){return t?.config&&typeof t.config=="object"}function gp(t){if(t.shapes?.static&&t.shapes?.animated)return console.log("🔍 JSON config already in system format"),t;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!t.transform,type:Vt(t.transform),distance:dt(t.transform),direction:Wr(t.transform)});try{const e={...t};if(t.shapes&&typeof t.shapes=="object"){const n=[],o=[];if(t.shapes.trapezoid){const s=t.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(t.shapes.triangle){const s=t.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(t.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&&t.base&&(e.base=t.base),!e.height&&t.height&&(e.height=t.height),!e.unit&&t.unit&&(e.unit=t.unit);const r=Vt(t.transform);return t.transform&&r==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:r,translation:t.transform.translation,distance:dt(t.transform),direction:Wr(t.transform)}),t.transform.translation&&(e.transform={type:"translation",translation:t.transform.translation},console.log("✅ Set converted.transform with distance:",dt(t.transform)))):t.transform?console.log("⚠️ JSON has transform but not translation type:",Vt(t.transform)):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&t.boardConfig&&(e.boardConfig=t.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:Vt(e.transform),distance:dt(e.transform),direction:Wr(e.transform)}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),t}}function dt(t){if(!t)return"N/A";const e=Array.isArray(t)?t[0]:t;return e?.translation?.distance!==void 0?String(e.translation.distance):e?.config?.distance!==void 0?String(e.config.distance):"N/A"}function Wr(t){if(!t)return;const e=Array.isArray(t)?t[0]:t;if(e?.translation?.direction!==void 0)return e.translation.direction;if(e?.config?.direction!==void 0)return e.config.direction}function Vt(t){return t&&(Array.isArray(t)?t[0]:t)?.type||"N/A"}function mp(t,e,r){if(t?.solve?.content){const n=t.solve.content.map(o=>{if(o.type==="geometryTransform"){if(fp(o))try{const i=gp(o.config),a=Wm(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",dt(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:Vt(i.transform),distance:dt(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=r?.base||9,a=r?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),s=ks({base:i,height:a,unit:r?.baseUnit||r?.unit||"in",originX:r?.originX,originY:r?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",dt(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=ks({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",dt(s.transform))}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:Vt(s.transform),direction:Wr(s.transform),distance:dt(s.transform)}),{...o,metadata:{...o.metadata,config:s,source:"generated"}}}return o});return{...t,solve:{...t.solve,content:n}}}return t}const pp="4.0.0",hp="1.0.0",yp="mp-10506-0002-0002-G01-0001",bp="锐角三角形面积练习",xp="通过双旋转策略练习锐角三角形面积公式 A=½bh",wp="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",vp=1,Cp="g5",Sp="三角形面积计算",_p=1050602,Rp="锐角三角形的面积",Ap=105060201,Ep=1002,Np="已知锐角三角形的底和高,求三角形面积",Tp="s-105-06-0002",$p=1002,kp=2,jp=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Ip={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Mp={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}},Op={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"}},Fp={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},Pp={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"以下三角形面积是多少?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},Dp={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"}}]}}]},Lp={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²"]},Gp="2026-01-20T20:34:00Z",Vp="2026-01-20T20:34:00Z",zp={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"}},Up={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left_triangle"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right_triangle"}},Bp={schema_version:pp,config_version:hp,math_prob_id:yp,title:bp,description:xp,objective:wp,difficulty:vp,grade_id:Cp,unit_name:Sp,unit_id:_p,lesson_name:Rp,lesson_id:Ap,module_id:Ep,skill_description:Np,skill_item_id:Tp,skill_id:$p,score:kp,knowledge_points:jp,metadata:Ip,basic_info:Mp,geometry_shapes:Op,layout:Fp,scenes:Pp,explanation:Dp,answer_info:Lp,created_at:Gp,updated_at:Vp,geometry_transform_configs:zp,transform_definitions:Up},Hp="mp-10506-0001-0001-G01-0001",qp="平行四边形面积公式推导",Wp="通过割补变换演示理解平行四边形面积公式 A=bh",Yp="理解平行四边形面积公式 A=bh",Kp=1,Xp="g5",Jp="多边形的面积",Zp=1050601,Qp="平行四边形的面积",eh=105060101,th=1002,rh="已知平行四边形的底和高,求平行四边形面积",nh="s-105-06-0001",oh=1001,sh=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],ih={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},ah={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}},lh={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},ch={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"}}}},dh={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:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},uh={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 平方英寸"}]},fh="2024-01-15T10:30:00Z",gh="2024-01-15T10:30:00Z",mh={math_prob_id:Hp,title:qp,description:Wp,objective:Yp,difficulty:Kp,grade_id:Xp,unit_name:Jp,unit_id:Zp,lesson_name:Qp,lesson_id:eh,module_id:th,skill_description:rh,skill_item_id:nh,skill_id:oh,knowledge_points:sh,metadata:ih,basic_info:ah,layout:lh,scenes:ch,explanation:dh,answer_info:uh,created_at:fh,updated_at:gh},ph={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function hh(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
20
48
  函数 loadAcuteTriangleV2Data() 已弃用。
21
49
  组件库不再包含数据加载逻辑。
22
50
 
@@ -29,7 +57,7 @@ ${i.errors?.join(`
29
57
  ${new Error().stack?.split(`
30
58
  `).slice(2,6).join(`
31
59
  `)||"无法获取调用栈"}
32
- `);const t=It(Hm,hp);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",t.data.id),t.data}async function bp(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
60
+ `);const t=Ft(Bp,ph);return console.log("V4三角形数据适配成功 (GeometryAdapterV4):",t.data.id),t.data}async function yh(){return console.warn(`⚠️ DEPRECATION WARNING ⚠️
33
61
  函数 loadTriangleProblemData() 已弃用。
34
62
  组件库不再包含数据加载逻辑。
35
63
 
@@ -42,7 +70,7 @@ ${new Error().stack?.split(`
42
70
  ${new Error().stack?.split(`
43
71
  `).slice(2,6).join(`
44
72
  `)||"无法获取调用栈"}
45
- `),yp()}async function xp(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
73
+ `),hh()}async function bh(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
46
74
  函数 loadParallelogramProblemData() 已弃用。
47
75
  组件库不再包含数据加载逻辑。
48
76
 
@@ -55,56 +83,56 @@ ${new Error().stack?.split(`
55
83
  ${new Error().stack?.split(`
56
84
  `).slice(2,6).join(`
57
85
  `)||"无法获取调用栈"}
58
- `);try{const t=$a(pp);return console.log("平行四边形数据加载成功 (传统适配器):",t.id),t}catch(t){return console.error("传统适配器失败:",t),wp()}}function wp(){return $a({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const vp=({className:t="",problemData:e})=>{const r=dn(),n=un(),o=fn(),s=gn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=mn(),[d,g]=x.useState(!0),[p,f]=x.useState(null),[m,h]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){g(!1),f(null),h(null);return}(async()=>{try{g(!0),f(null);const w=await xp();h(w)}catch(w){const C=w instanceof Error?w.message:"数据加载失败";f(C),console.error("页面数据加载失败:",w)}finally{g(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&l(b)},[b,l]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):p?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:p}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&u.jsx(Mt,{problemData:b,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&u.jsx(Xt,{problemData:b,userAnswer:n,onNextQuestion:c}),r==="success"&&u.jsx(Ot,{problemData:b,onNextQuestion:c})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},_p=({className:t="",problemData:e})=>{const r=dn(),n=un(),o=fn(),s=gn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=mn(),[d,g]=x.useState(!0),[p,f]=x.useState(null),[m,h]=x.useState(null),y=x.useMemo(()=>e,[e]);x.useEffect(()=>{if(y){g(!1),f(null),h(null);return}(async()=>{try{g(!0),f(null);const w=await bp();h(w)}catch(w){const C=w instanceof Error?w.message:"数据加载失败";f(C),console.error("页面数据加载失败:",w)}finally{g(!1)}})()},[y]);const b=x.useMemo(()=>y||m,[y,m]);return x.useEffect(()=>{b&&l(b)},[b,l]),d?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),u.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):p?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),u.jsx("div",{className:"text-lg text-red-600 mb-4",children:p}),u.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):b?u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[b.grade,"年级 • ",b.unit]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&u.jsx(Mt,{problemData:b,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&u.jsx(Xt,{problemData:b,userAnswer:n,onNextQuestion:c}),r==="success"&&u.jsx(Ot,{problemData:b,onNextQuestion:c})]})]}):u.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[u.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),u.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Na=x.createContext(void 0),Sp=()=>{const t=x.useContext(Na);if(!t)throw new Error("useMathCardContext must be used within a MathCard component");return t},ka=(t,e,r)=>t.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,r.join(", ")),Rp=t=>t.type==="formula"?x.createElement(Kt,{key:t.content,parts:[t.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):t.type==="image"?x.createElement("img",{src:t.content,alt:"content",className:"image",key:t.content}):x.createElement("span",{key:t.content},t.content),Io=t=>t.map((e,r)=>x.createElement("div",{className:"content-block",key:r},Rp(e))),Cp=t=>{const e=[];let r=0;const n=/\$\$?[^$]+\$\$?/g;let o;for(;(o=n.exec(t))!==null;){const s=o.index,i=o.index+o[0].length;if(s>r){const l=t.substring(r,s);l.trim()&&e.push({type:"text",content:l})}const c=o[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:c}),r=i}if(r<t.length){const s=t.substring(r);s.trim()&&e.push({type:"text",content:s})}return e},Ap=(t,e,r)=>{const n=ka(t,e,r),o=Cp(n);return Io(o)},Ep=t=>{const{type:e,content:r,style:n={}}=t,o={marginBottom:"8px",lineHeight:"1.6",...n};switch(e){case"instruction":return x.createElement("div",{key:t.id,style:{...o,fontWeight:"bold",color:"#4a6cf7"}},r);case"formula":const s=r.includes("\\\\")||r.includes("\\downarrow")||r.includes("\\quad");return x.createElement(Kt,{key:t.id,parts:[r],children:null,displayMode:s,fontSize:"1.1em",color:"#333333"});case"conclusion":return x.createElement("div",{key:t.id,style:{...o,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},r);case"image":return x.createElement("div",{key:t.id,style:o},x.createElement("img",{src:r,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return x.createElement("div",{key:t.id,style:o},x.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},r));default:return x.createElement("div",{key:t.id,style:o},r)}},Tp=(t,e,r)=>{const{type:n,content:o,style:s={}}=t,i={marginBottom:"8px",lineHeight:"1.6",...s};switch(n){case"instruction":return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},o);case"formula":const a=o.includes("\\\\")||o.includes("\\downarrow")||o.includes("\\quad");return x.createElement(Kt,{key:t.id,parts:[o],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const c=ka(o,r,e);return x.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},c);default:return x.createElement("div",{key:t.id,style:i},o)}},$p=t=>t.map(Ep),Np=(t,e,r)=>t.map(n=>Tp(n,e,r)),Ma=({scene:t,position:e="header",size:r="medium",color:n,bgColor:o,hidden:s=!1})=>{if(s)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=o||l[t],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"}}[r]),c};return u.jsx("div",{style:a(),children:i[t]})},Oa=({question:t})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return u.jsx("div",{style:e,children:Io(t)})},Ia=({problemType:t,options:e,value:r=[],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"},c=g=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:g?"#f97316":"transparent",color:g?"#ffffff":"inherit",borderColor:g?"#f97316":"#e0e0e0"}),l=g=>{if(n)if(t==="multiple-choice"){const p=r.includes(g)?r.filter(f=>f!==g):[...r,g];n(p)}else n([g])},d=g=>{n&&n([g.target.value])};return t==="multiple-choice"&&e?u.jsx("div",{style:s,children:u.jsx("div",{style:a,children:e.map(g=>u.jsx("div",{style:c(r.includes(g.id)),onClick:()=>l(g.id),children:Io(g.content)},g.id))})}):u.jsx("div",{style:s,children:u.jsx("input",{type:"text",style:i,placeholder:o,value:r[0]||"",onChange:d})})},Hr=({onClick:t,children:e,disabled:r=!1,loading:n=!1})=>{const o={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.6:1};return u.jsx("button",{style:o,onClick:t,disabled:r||n,children:n?"提交中...":e})},Fa=({steps:t,title:e="解题步骤"})=>{const r={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 u.jsxs("div",{style:r,children:[u.jsx("div",{style:n,children:e}),u.jsx("div",{style:o,children:$p(t).map((i,a)=>u.jsx("div",{style:s,children:i},t[a].id))})]})},ja=({reviewContent:t,userAnswer:e,correctAnswer:r})=>{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"},c={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return u.jsxs("div",{style:n,children:[u.jsx("div",{style:o,children:"复习内容"}),u.jsxs("div",{style:s,children:[t.reviewTemplate&&u.jsx("div",{style:i,children:Ap(t.reviewTemplate,r,e)}),t.reviewExplanation&&u.jsx("div",{style:a,children:Np(t.reviewExplanation,e,r).map((l,d)=>u.jsx("div",{style:c,children:l},t.reviewExplanation[d].id))})]})]})},Pa=({type:t="skeleton"})=>{const e={padding:"20px"},r={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 t==="spinner"?u.jsx("div",{style:n,children:u.jsx("div",{style:o})}):u.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[u.jsx("div",{style:{...r,width:"80%"}}),u.jsx("div",{style:{...r,width:"60%"}}),u.jsx("div",{style:{...r,width:"70%"}})]})},Qr=({error:t,onRetry:e})=>{const r={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 t=="string"?t:t.message;return u.jsxs("div",{style:r,children:[u.jsx("div",{style:n,children:s}),e&&u.jsx("button",{style:o,onClick:()=>e(t),children:"重试"})]})},kp=({orientation:t="horizontal",size:e="medium"})=>{const r={background:"#e0e0e0"},n={small:"12px",medium:"16px",large:"20px"};return t==="horizontal"?(r.height="1px",r.width="100%",r.margin=`${n[e]} 0`):(r.width="1px",r.height="100%",r.margin=`0 ${n[e]}`),u.jsx("div",{style:r})},Mp=({onSubmit:t,onNext:e,onRetry:r,onAnswerChange:n,value:o})=>{const{problemData:s,scene:i,submissionResult:a,config:c}=Sp();if(!s)return u.jsx(Qr,{error:"No problem data provided"});const l=()=>{t&&t()},d=()=>{e&&e(s.problemId)},g=()=>{r&&r(s.problemId)},p=h=>{n&&n(h,s.problemType)},f={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"},m={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return u.jsxs("div",{style:f,"data-testid":"math-card","data-theme":c?.theme,children:[c?.showBanner!==!1&&u.jsx(Ma,{scene:i,position:c?.bannerPosition,size:c?.bannerSize,color:c?.bannerCustomStyle?.color,bgColor:c?.bannerCustomStyle?.bgColor}),u.jsx(Oa,{question:s.question,problemType:s.problemType}),i==="question"&&u.jsxs(u.Fragment,{children:[u.jsx(Ia,{problemType:s.problemType,options:s.answer.options,value:o,onChange:p,placeholder:c?.inputPlaceholder}),u.jsx("div",{style:m,children:u.jsx(Hr,{onClick:l,disabled:!t,children:c?.submitButtonText||"提交答案"})})]}),i==="solve"&&s.explanation&&u.jsx(Fa,{steps:s.explanation,title:"官方解析"}),i==="review"&&a&&s.reviewContent&&u.jsx(ja,{reviewContent:s.reviewContent,userAnswer:a.userAnswer,correctAnswer:s.answer.correctAnswer}),(i==="solve"||i==="review")&&u.jsxs("div",{style:m,children:[e&&u.jsx(Hr,{onClick:d,children:c?.nextButtonText||"下一题"}),r&&u.jsx(Hr,{onClick:g,children:c?.retryButtonText||"重新作答"})]})]})},ot=({problemData:t,scene:e,submissionResult:r,loading:n,error:o,config:s,children:i,onSubmit:a,onNext:c,onRetry:l,onErrorRetry:d,onAnswerChange:g,onHintToggle:p,value:f})=>{if(n)return u.jsx(Pa,{type:"skeleton"});if(o)return u.jsx(Qr,{error:o,onRetry:d});if(!t)return u.jsx(Qr,{error:"No problem data provided"});const m={problemData:t,scene:e,submissionResult:r,config:s,value:f};return u.jsx(Na.Provider,{value:m,children:i||u.jsx(Mp,{onSubmit:a,onNext:c,onRetry:l,onAnswerChange:g,onHintToggle:p,value:f})})};ot.Banner=Ma;ot.Question=Oa;ot.AnswerInput=Ia;ot.SubmitButton=Hr;ot.Explanation=Fa;ot.ReviewContent=ja;ot.LoadingState=Pa;ot.ErrorState=Qr;ot.Divider=kp;function Op(t){if(t.sheet)return t.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===t)return document.styleSheets[e]}function Ip(t){var e=document.createElement("style");return e.setAttribute("data-emotion",t.key),t.nonce!==void 0&&e.setAttribute("nonce",t.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var Fp=(function(){function t(r){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=r.speedy===void 0?!0:r.speedy,this.tags=[],this.ctr=0,this.nonce=r.nonce,this.key=r.key,this.container=r.container,this.prepend=r.prepend,this.insertionPoint=r.insertionPoint,this.before=null}var e=t.prototype;return e.hydrate=function(n){n.forEach(this._insertTag)},e.insert=function(n){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(Ip(this));var o=this.tags[this.tags.length-1];if(this.isSpeedy){var s=Op(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},t})(),Ne="-ms-",en="-moz-",ne="-webkit-",Da="comm",Fo="rule",jo="decl",jp="@import",La="@keyframes",Pp="@layer",Dp=Math.abs,pn=String.fromCharCode,Lp=Object.assign;function Gp(t,e){return Ae(t,0)^45?(((e<<2^Ae(t,0))<<2^Ae(t,1))<<2^Ae(t,2))<<2^Ae(t,3):0}function Ga(t){return t.trim()}function Up(t,e){return(t=e.exec(t))?t[0]:t}function oe(t,e,r){return t.replace(e,r)}function so(t,e){return t.indexOf(e)}function Ae(t,e){return t.charCodeAt(e)|0}function dr(t,e,r){return t.slice(e,r)}function et(t){return t.length}function Po(t){return t.length}function Pr(t,e){return e.push(t),t}function Vp(t,e){return t.map(e).join("")}var hn=1,Ht=1,Ua=0,De=0,ve=0,Jt="";function yn(t,e,r,n,o,s,i){return{value:t,root:e,parent:r,type:n,props:o,children:s,line:hn,column:Ht,length:i,return:""}}function nr(t,e){return Lp(yn("",null,null,"",null,null,0),t,{length:-t.length},e)}function zp(){return ve}function Bp(){return ve=De>0?Ae(Jt,--De):0,Ht--,ve===10&&(Ht=1,hn--),ve}function Be(){return ve=De<Ua?Ae(Jt,De++):0,Ht++,ve===10&&(Ht=1,hn++),ve}function nt(){return Ae(Jt,De)}function qr(){return De}function Sr(t,e){return dr(Jt,t,e)}function ur(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function Va(t){return hn=Ht=1,Ua=et(Jt=t),De=0,[]}function za(t){return Jt="",t}function Wr(t){return Ga(Sr(De-1,io(t===91?t+2:t===40?t+1:t)))}function Hp(t){for(;(ve=nt())&&ve<33;)Be();return ur(t)>2||ur(ve)>3?"":" "}function qp(t,e){for(;--e&&Be()&&!(ve<48||ve>102||ve>57&&ve<65||ve>70&&ve<97););return Sr(t,qr()+(e<6&&nt()==32&&Be()==32))}function io(t){for(;Be();)switch(ve){case t:return De;case 34:case 39:t!==34&&t!==39&&io(ve);break;case 40:t===41&&io(t);break;case 92:Be();break}return De}function Wp(t,e){for(;Be()&&t+ve!==57;)if(t+ve===84&&nt()===47)break;return"/*"+Sr(e,De-1)+"*"+pn(t===47?t:Be())}function Yp(t){for(;!ur(nt());)Be();return Sr(t,De)}function Kp(t){return za(Yr("",null,null,null,[""],t=Va(t),0,[0],t))}function Yr(t,e,r,n,o,s,i,a,c){for(var l=0,d=0,g=i,p=0,f=0,m=0,h=1,y=1,b=1,_=0,w="",C=o,v=s,k=n,S=w;y;)switch(m=_,_=Be()){case 40:if(m!=108&&Ae(S,g-1)==58){so(S+=oe(Wr(_),"&","&\f"),"&\f")!=-1&&(b=-1);break}case 34:case 39:case 91:S+=Wr(_);break;case 9:case 10:case 13:case 32:S+=Hp(m);break;case 92:S+=qp(qr()-1,7);continue;case 47:switch(nt()){case 42:case 47:Pr(Xp(Wp(Be(),qr()),e,r),c);break;default:S+="/"}break;case 123*h:a[l++]=et(S)*b;case 125*h:case 59:case 0:switch(_){case 0:case 125:y=0;case 59+d:b==-1&&(S=oe(S,/\f/g,"")),f>0&&et(S)-g&&Pr(f>32?_s(S+";",n,r,g-1):_s(oe(S," ","")+";",n,r,g-2),c);break;case 59:S+=";";default:if(Pr(k=vs(S,e,r,l,d,o,a,w,C=[],v=[],g),s),_===123)if(d===0)Yr(S,e,k,k,C,s,g,a,v);else switch(p===99&&Ae(S,3)===110?100:p){case 100:case 108:case 109:case 115:Yr(t,k,k,n&&Pr(vs(t,k,k,0,0,o,a,w,o,C=[],g),v),o,v,g,a,n?C:v);break;default:Yr(S,k,k,k,[""],v,0,a,v)}}l=d=f=0,h=b=1,w=S="",g=i;break;case 58:g=1+et(S),f=m;default:if(h<1){if(_==123)--h;else if(_==125&&h++==0&&Bp()==125)continue}switch(S+=pn(_),_*h){case 38:b=d>0?1:(S+="\f",-1);break;case 44:a[l++]=(et(S)-1)*b,b=1;break;case 64:nt()===45&&(S+=Wr(Be())),p=nt(),d=g=et(w=S+=Yp(qr())),_++;break;case 45:m===45&&et(S)==2&&(h=0)}}return s}function vs(t,e,r,n,o,s,i,a,c,l,d){for(var g=o-1,p=o===0?s:[""],f=Po(p),m=0,h=0,y=0;m<n;++m)for(var b=0,_=dr(t,g+1,g=Dp(h=i[m])),w=t;b<f;++b)(w=Ga(h>0?p[b]+" "+_:oe(_,/&\f/g,p[b])))&&(c[y++]=w);return yn(t,e,r,o===0?Fo:a,c,l,d)}function Xp(t,e,r){return yn(t,e,r,Da,pn(zp()),dr(t,2,-2),0)}function _s(t,e,r,n){return yn(t,e,r,jo,dr(t,0,n),dr(t,n+1,-1),n)}function Ut(t,e){for(var r="",n=Po(t),o=0;o<n;o++)r+=e(t[o],o,t,e)||"";return r}function Jp(t,e,r,n){switch(t.type){case Pp:if(t.children.length)break;case jp:case jo:return t.return=t.return||t.value;case Da:return"";case La:return t.return=t.value+"{"+Ut(t.children,n)+"}";case Fo:t.value=t.props.join(",")}return et(r=Ut(t.children,n))?t.return=t.value+"{"+r+"}":""}function Zp(t){var e=Po(t);return function(r,n,o,s){for(var i="",a=0;a<e;a++)i+=t[a](r,n,o,s)||"";return i}}function Qp(t){return function(e){e.root||(e=e.return)&&t(e)}}function eh(t){var e=Object.create(null);return function(r){return e[r]===void 0&&(e[r]=t(r)),e[r]}}var th=function(e,r,n){for(var o=0,s=0;o=s,s=nt(),o===38&&s===12&&(r[n]=1),!ur(s);)Be();return Sr(e,De)},rh=function(e,r){var n=-1,o=44;do switch(ur(o)){case 0:o===38&&nt()===12&&(r[n]=1),e[n]+=th(De-1,r,n);break;case 2:e[n]+=Wr(o);break;case 4:if(o===44){e[++n]=nt()===58?"&\f":"",r[n]=e[n].length;break}default:e[n]+=pn(o)}while(o=Be());return e},nh=function(e,r){return za(rh(Va(e),r))},Ss=new WeakMap,oh=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var r=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&&r.charCodeAt(0)!==58&&!Ss.get(n))&&!o){Ss.set(e,!0);for(var s=[],i=nh(r,s),a=n.props,c=0,l=0;c<i.length;c++)for(var d=0;d<a.length;d++,l++)e.props[l]=s[c]?i[c].replace(/&\f/g,a[d]):a[d]+" "+i[c]}}},sh=function(e){if(e.type==="decl"){var r=e.value;r.charCodeAt(0)===108&&r.charCodeAt(2)===98&&(e.return="",e.value="")}};function Ba(t,e){switch(Gp(t,e)){case 5103:return ne+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return ne+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return ne+t+en+t+Ne+t+t;case 6828:case 4268:return ne+t+Ne+t+t;case 6165:return ne+t+Ne+"flex-"+t+t;case 5187:return ne+t+oe(t,/(\w+).+(:[^]+)/,ne+"box-$1$2"+Ne+"flex-$1$2")+t;case 5443:return ne+t+Ne+"flex-item-"+oe(t,/flex-|-self/,"")+t;case 4675:return ne+t+Ne+"flex-line-pack"+oe(t,/align-content|flex-|-self/,"")+t;case 5548:return ne+t+Ne+oe(t,"shrink","negative")+t;case 5292:return ne+t+Ne+oe(t,"basis","preferred-size")+t;case 6060:return ne+"box-"+oe(t,"-grow","")+ne+t+Ne+oe(t,"grow","positive")+t;case 4554:return ne+oe(t,/([^-])(transform)/g,"$1"+ne+"$2")+t;case 6187:return oe(oe(oe(t,/(zoom-|grab)/,ne+"$1"),/(image-set)/,ne+"$1"),t,"")+t;case 5495:case 3959:return oe(t,/(image-set\([^]*)/,ne+"$1$`$1");case 4968:return oe(oe(t,/(.+:)(flex-)?(.*)/,ne+"box-pack:$3"+Ne+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+ne+t+t;case 4095:case 3583:case 4068:case 2532:return oe(t,/(.+)-inline(.+)/,ne+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(et(t)-1-e>6)switch(Ae(t,e+1)){case 109:if(Ae(t,e+4)!==45)break;case 102:return oe(t,/(.+:)(.+)-([^]+)/,"$1"+ne+"$2-$3$1"+en+(Ae(t,e+3)==108?"$3":"$2-$3"))+t;case 115:return~so(t,"stretch")?Ba(oe(t,"stretch","fill-available"),e)+t:t}break;case 4949:if(Ae(t,e+1)!==115)break;case 6444:switch(Ae(t,et(t)-3-(~so(t,"!important")&&10))){case 107:return oe(t,":",":"+ne)+t;case 101:return oe(t,/(.+:)([^;!]+)(;|!.+)?/,"$1"+ne+(Ae(t,14)===45?"inline-":"")+"box$3$1"+ne+"$2$3$1"+Ne+"$2box$3")+t}break;case 5936:switch(Ae(t,e+11)){case 114:return ne+t+Ne+oe(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return ne+t+Ne+oe(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return ne+t+Ne+oe(t,/[svh]\w+-[tblr]{2}/,"lr")+t}return ne+t+Ne+t+t}return t}var ih=function(e,r,n,o){if(e.length>-1&&!e.return)switch(e.type){case jo:e.return=Ba(e.value,e.length);break;case La:return Ut([nr(e,{value:oe(e.value,"@","@"+ne)})],o);case Fo:if(e.length)return Vp(e.props,function(s){switch(Up(s,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Ut([nr(e,{props:[oe(s,/:(read-\w+)/,":"+en+"$1")]})],o);case"::placeholder":return Ut([nr(e,{props:[oe(s,/:(plac\w+)/,":"+ne+"input-$1")]}),nr(e,{props:[oe(s,/:(plac\w+)/,":"+en+"$1")]}),nr(e,{props:[oe(s,/:(plac\w+)/,Ne+"input-$1")]})],o)}return""})}},ah=[ih],lh=function(e){var r=e.key;if(r==="css"){var n=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(n,function(h){var y=h.getAttribute("data-emotion");y.indexOf(" ")!==-1&&(document.head.appendChild(h),h.setAttribute("data-s",""))})}var o=e.stylisPlugins||ah,s={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+r+' "]'),function(h){for(var y=h.getAttribute("data-emotion").split(" "),b=1;b<y.length;b++)s[y[b]]=!0;a.push(h)});var c,l=[oh,sh];{var d,g=[Jp,Qp(function(h){d.insert(h)})],p=Zp(l.concat(o,g)),f=function(y){return Ut(Kp(y),p)};c=function(y,b,_,w){d=_,f(y?y+"{"+b.styles+"}":b.styles),w&&(m.inserted[b.name]=!0)}}var m={key:r,sheet:new Fp({key:r,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:s,registered:{},insert:c};return m.sheet.hydrate(a),m},Dr={exports:{}},ie={};var Rs;function ch(){if(Rs)return ie;Rs=1;var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,r=t?Symbol.for("react.portal"):60106,n=t?Symbol.for("react.fragment"):60107,o=t?Symbol.for("react.strict_mode"):60108,s=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,c=t?Symbol.for("react.async_mode"):60111,l=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,g=t?Symbol.for("react.suspense"):60113,p=t?Symbol.for("react.suspense_list"):60120,f=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,h=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,_=t?Symbol.for("react.scope"):60119;function w(v){if(typeof v=="object"&&v!==null){var k=v.$$typeof;switch(k){case e:switch(v=v.type,v){case c:case l:case n:case s:case o:case g:return v;default:switch(v=v&&v.$$typeof,v){case a:case d:case m:case f:case i:return v;default:return k}}case r:return k}}}function C(v){return w(v)===l}return ie.AsyncMode=c,ie.ConcurrentMode=l,ie.ContextConsumer=a,ie.ContextProvider=i,ie.Element=e,ie.ForwardRef=d,ie.Fragment=n,ie.Lazy=m,ie.Memo=f,ie.Portal=r,ie.Profiler=s,ie.StrictMode=o,ie.Suspense=g,ie.isAsyncMode=function(v){return C(v)||w(v)===c},ie.isConcurrentMode=C,ie.isContextConsumer=function(v){return w(v)===a},ie.isContextProvider=function(v){return w(v)===i},ie.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===e},ie.isForwardRef=function(v){return w(v)===d},ie.isFragment=function(v){return w(v)===n},ie.isLazy=function(v){return w(v)===m},ie.isMemo=function(v){return w(v)===f},ie.isPortal=function(v){return w(v)===r},ie.isProfiler=function(v){return w(v)===s},ie.isStrictMode=function(v){return w(v)===o},ie.isSuspense=function(v){return w(v)===g},ie.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===l||v===s||v===o||v===g||v===p||typeof v=="object"&&v!==null&&(v.$$typeof===m||v.$$typeof===f||v.$$typeof===i||v.$$typeof===a||v.$$typeof===d||v.$$typeof===y||v.$$typeof===b||v.$$typeof===_||v.$$typeof===h)},ie.typeOf=w,ie}var ae={};var Cs;function dh(){return Cs||(Cs=1,process.env.NODE_ENV!=="production"&&(function(){var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,r=t?Symbol.for("react.portal"):60106,n=t?Symbol.for("react.fragment"):60107,o=t?Symbol.for("react.strict_mode"):60108,s=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,c=t?Symbol.for("react.async_mode"):60111,l=t?Symbol.for("react.concurrent_mode"):60111,d=t?Symbol.for("react.forward_ref"):60112,g=t?Symbol.for("react.suspense"):60113,p=t?Symbol.for("react.suspense_list"):60120,f=t?Symbol.for("react.memo"):60115,m=t?Symbol.for("react.lazy"):60116,h=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,b=t?Symbol.for("react.responder"):60118,_=t?Symbol.for("react.scope"):60119;function w(A){return typeof A=="string"||typeof A=="function"||A===n||A===l||A===s||A===o||A===g||A===p||typeof A=="object"&&A!==null&&(A.$$typeof===m||A.$$typeof===f||A.$$typeof===i||A.$$typeof===a||A.$$typeof===d||A.$$typeof===y||A.$$typeof===b||A.$$typeof===_||A.$$typeof===h)}function C(A){if(typeof A=="object"&&A!==null){var se=A.$$typeof;switch(se){case e:var ue=A.type;switch(ue){case c:case l:case n:case s:case o:case g:return ue;default:var V=ue&&ue.$$typeof;switch(V){case a:case d:case m:case f:case i:return V;default:return se}}case r:return se}}}var v=c,k=l,S=a,E=i,N=e,I=d,Y=n,K=m,L=f,O=r,U=s,T=o,q=g,$=!1;function ee(A){return $||($=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),de(A)||C(A)===c}function de(A){return C(A)===l}function re(A){return C(A)===a}function te(A){return C(A)===i}function G(A){return typeof A=="object"&&A!==null&&A.$$typeof===e}function Z(A){return C(A)===d}function ge(A){return C(A)===n}function Ce(A){return C(A)===m}function ce(A){return C(A)===f}function ft(A){return C(A)===r}function st(A){return C(A)===s}function F(A){return C(A)===o}function M(A){return C(A)===g}ae.AsyncMode=v,ae.ConcurrentMode=k,ae.ContextConsumer=S,ae.ContextProvider=E,ae.Element=N,ae.ForwardRef=I,ae.Fragment=Y,ae.Lazy=K,ae.Memo=L,ae.Portal=O,ae.Profiler=U,ae.StrictMode=T,ae.Suspense=q,ae.isAsyncMode=ee,ae.isConcurrentMode=de,ae.isContextConsumer=re,ae.isContextProvider=te,ae.isElement=G,ae.isForwardRef=Z,ae.isFragment=ge,ae.isLazy=Ce,ae.isMemo=ce,ae.isPortal=ft,ae.isProfiler=st,ae.isStrictMode=F,ae.isSuspense=M,ae.isValidElementType=w,ae.typeOf=C})()),ae}var As;function uh(){return As||(As=1,process.env.NODE_ENV==="production"?Dr.exports=ch():Dr.exports=dh()),Dr.exports}var Pn,Es;function fh(){if(Es)return Pn;Es=1;var t=uh(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},r={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[t.ForwardRef]=n,s[t.Memo]=o;function i(m){return t.isMemo(m)?o:s[m.$$typeof]||e}var a=Object.defineProperty,c=Object.getOwnPropertyNames,l=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,g=Object.getPrototypeOf,p=Object.prototype;function f(m,h,y){if(typeof h!="string"){if(p){var b=g(h);b&&b!==p&&f(m,b,y)}var _=c(h);l&&(_=_.concat(l(h)));for(var w=i(m),C=i(h),v=0;v<_.length;++v){var k=_[v];if(!r[k]&&!(y&&y[k])&&!(C&&C[k])&&!(w&&w[k])){var S=d(h,k);try{a(m,k,S)}catch{}}}}return m}return Pn=f,Pn}fh();var gh=!0;function mh(t,e,r){var n="";return r.split(" ").forEach(function(o){t[o]!==void 0?e.push(t[o]+";"):o&&(n+=o+" ")}),n}var Ha=function(e,r,n){var o=e.key+"-"+r.name;(n===!1||gh===!1)&&e.registered[o]===void 0&&(e.registered[o]=r.styles)},ph=function(e,r,n){Ha(e,r,n);var o=e.key+"-"+r.name;if(e.inserted[r.name]===void 0){var s=r;do e.insert(r===s?"."+o:"",s,e.sheet,!0),s=s.next;while(s!==void 0)}};function hh(t){for(var e=0,r,n=0,o=t.length;o>=4;++n,o-=4)r=t.charCodeAt(n)&255|(t.charCodeAt(++n)&255)<<8|(t.charCodeAt(++n)&255)<<16|(t.charCodeAt(++n)&255)<<24,r=(r&65535)*1540483477+((r>>>16)*59797<<16),r^=r>>>24,e=(r&65535)*1540483477+((r>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(o){case 3:e^=(t.charCodeAt(n+2)&255)<<16;case 2:e^=(t.charCodeAt(n+1)&255)<<8;case 1:e^=t.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 yh={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},bh=/[A-Z]|^ms/g,xh=/_EMO_([^_]+?)_([^]*?)_EMO_/g,qa=function(e){return e.charCodeAt(1)===45},Ts=function(e){return e!=null&&typeof e!="boolean"},Dn=eh(function(t){return qa(t)?t:t.replace(bh,"-$&").toLowerCase()}),$s=function(e,r){switch(e){case"animation":case"animationName":if(typeof r=="string")return r.replace(xh,function(n,o,s){return tt={name:o,styles:s,next:tt},o})}return yh[e]!==1&&!qa(e)&&typeof r=="number"&&r!==0?r+"px":r};function fr(t,e,r){if(r==null)return"";var n=r;if(n.__emotion_styles!==void 0)return n;switch(typeof r){case"boolean":return"";case"object":{var o=r;if(o.anim===1)return tt={name:o.name,styles:o.styles,next:tt},o.name;var s=r;if(s.styles!==void 0){var i=s.next;if(i!==void 0)for(;i!==void 0;)tt={name:i.name,styles:i.styles,next:tt},i=i.next;var a=s.styles+";";return a}return wh(t,e,r)}case"function":{if(t!==void 0){var c=tt,l=r(t);return tt=c,fr(t,e,l)}break}}var d=r;return d}function wh(t,e,r){var n="";if(Array.isArray(r))for(var o=0;o<r.length;o++)n+=fr(t,e,r[o])+";";else for(var s in r){var i=r[s];if(typeof i!="object"){var a=i;Ts(a)&&(n+=Dn(s)+":"+$s(s,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var c=0;c<i.length;c++)Ts(i[c])&&(n+=Dn(s)+":"+$s(s,i[c])+";");else{var l=fr(t,e,i);switch(s){case"animation":case"animationName":{n+=Dn(s)+":"+l+";";break}default:n+=s+"{"+l+"}"}}}return n}var Ns=/label:\s*([^\s;{]+)\s*(;|$)/g,tt;function Wa(t,e,r){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null&&t[0].styles!==void 0)return t[0];var n=!0,o="";tt=void 0;var s=t[0];if(s==null||s.raw===void 0)n=!1,o+=fr(r,e,s);else{var i=s;o+=i[0]}for(var a=1;a<t.length;a++)if(o+=fr(r,e,t[a]),n){var c=s;o+=c[a]}Ns.lastIndex=0;for(var l="",d;(d=Ns.exec(o))!==null;)l+="-"+d[1];var g=hh(o)+l;return{name:g,styles:o,next:tt}}var vh=function(e){return e()},_h=Ve.useInsertionEffect?Ve.useInsertionEffect:!1,Sh=_h||vh,Ya=Ve.createContext(typeof HTMLElement<"u"?lh({key:"css"}):null);Ya.Provider;var Rh=function(e){return x.forwardRef(function(r,n){var o=x.useContext(Ya);return e(r,o,n)})},Ch=Ve.createContext({}),Do={}.hasOwnProperty,ao="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",Ah=function(e,r){var n={};for(var o in r)Do.call(r,o)&&(n[o]=r[o]);return n[ao]=e,n},Eh=function(e){var r=e.cache,n=e.serialized,o=e.isStringTag;return Ha(r,n,o),Sh(function(){return ph(r,n,o)}),null},Th=Rh(function(t,e,r){var n=t.css;typeof n=="string"&&e.registered[n]!==void 0&&(n=e.registered[n]);var o=t[ao],s=[n],i="";typeof t.className=="string"?i=mh(e.registered,s,t.className):t.className!=null&&(i=t.className+" ");var a=Wa(s,void 0,Ve.useContext(Ch));i+=e.key+"-"+a.name;var c={};for(var l in t)Do.call(t,l)&&l!=="css"&&l!==ao&&(c[l]=t[l]);return c.className=i,r&&(c.ref=r),Ve.createElement(Ve.Fragment,null,Ve.createElement(Eh,{cache:e,serialized:a,isStringTag:typeof o=="string"}),Ve.createElement(o,c))}),$h=Th,ks=function(e,r){var n=arguments;if(r==null||!Do.call(r,"css"))return Ve.createElement.apply(void 0,n);var o=n.length,s=new Array(o);s[0]=$h,s[1]=Ah(e,r);for(var i=2;i<o;i++)s[i]=n[i];return Ve.createElement.apply(null,s)};(function(t){var e;e||(e=t.JSX||(t.JSX={}))})(ks||(ks={}));function pe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return Wa(e)}const j={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)"}};pe`
59
- background: ${j.colors.background.card};
60
- border-radius: ${j.borderRadius.card};
61
- box-shadow: ${j.shadows.card};
62
- font-family: ${j.typography.fontFamily};
63
- font-size: ${j.typography.fontSizeBase};
86
+ `);try{const t=Ya(mh);return console.log("平行四边形数据加载成功 (传统适配器):",t.id),t}catch(t){return console.error("传统适配器失败:",t),xh()}}function xh(){return Ya({id:"parallelogram-area-fallback",title:"平行四边形面积公式推导(默认)",grade:5,unit:"多边形的面积",basic_info:{question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",base:9,height:6}})}const wh=({className:t="",problemData:e})=>{const r=mn(),n=pn(),o=hn(),s=yn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=bn(),[u,g]=b.useState(!0),[m,f]=b.useState(null),[p,h]=b.useState(null),y=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(y){g(!1),f(null),h(null);return}(async()=>{try{g(!0),f(null);const w=await bh();h(w)}catch(w){const S=w instanceof Error?w.message:"数据加载失败";f(S),console.error("页面数据加载失败:",w)}finally{g(!1)}})()},[y]);const x=b.useMemo(()=>y||p,[y,p]);return b.useEffect(()=>{x&&l(x)},[x,l]),u?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),d.jsx("div",{className:"text-lg text-slate-700",children:"正在加载平行四边形面积数据..."})]}):m?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),d.jsx("div",{className:"text-lg text-red-600 mb-4",children:m}),d.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),d.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&d.jsx(Mt,{problemData:x,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&d.jsx(Qt,{problemData:x,userAnswer:n,onNextQuestion:c}),r==="success"&&d.jsx(Ot,{problemData:x,onNextQuestion:c})]})]}):d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),d.jsx("div",{className:"text-lg text-slate-700",children:"未能加载平行四边形面积数据。"})]})},vh=({className:t="",problemData:e})=>{const r=mn(),n=pn(),o=hn(),s=yn(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=bn(),[u,g]=b.useState(!0),[m,f]=b.useState(null),[p,h]=b.useState(null),y=b.useMemo(()=>e,[e]);b.useEffect(()=>{if(y){g(!1),f(null),h(null);return}(async()=>{try{g(!0),f(null);const w=await yh();h(w)}catch(w){const S=w instanceof Error?w.message:"数据加载失败";f(S),console.error("页面数据加载失败:",w)}finally{g(!1)}})()},[y]);const x=b.useMemo(()=>y||p,[y,p]);return b.useEffect(()=>{x&&l(x)},[x,l]),u?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"加载中..."}),d.jsx("div",{className:"text-lg text-slate-700",children:"正在加载三角形面积数据..."})]}):m?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据加载失败"}),d.jsx("div",{className:"text-lg text-red-600 mb-4",children:m}),d.jsx("div",{className:"text-slate-700",children:"请检查网络连接或稍后重试。"})]}):x?d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsxs("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:[x.grade,"年级 • ",x.unit]}),d.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&d.jsx(Mt,{problemData:x,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&d.jsx(Qt,{problemData:x,userAnswer:n,onNextQuestion:c}),r==="success"&&d.jsx(Ot,{problemData:x,onNextQuestion:c})]})]}):d.jsxs("div",{className:"min-h-screen bg-cyan-50 flex flex-col items-center justify-center p-4 font-sans",children:[d.jsx("div",{className:"text-slate-500 text-sm font-medium mb-4 tracking-wide uppercase",children:"数据不可用"}),d.jsx("div",{className:"text-lg text-slate-700",children:"未能加载三角形面积数据。"})]})},Ka=b.createContext(void 0),Ch=()=>{const t=b.useContext(Ka);if(!t)throw new Error("useMathCardContext must be used within a MathCard component");return t},Xa=(t,e,r)=>t.replace(/{correctAnswer}/g,e.join(", ")).replace(/{userAnswer}/g,r.join(", ")),Sh=t=>t.type==="formula"?b.createElement(Zt,{key:t.content,parts:[t.content],children:null,displayMode:!1,fontSize:"1em",color:"#333333"}):t.type==="image"?b.createElement("img",{src:t.content,alt:"content",className:"image",key:t.content}):b.createElement("span",{key:t.content},t.content),zo=t=>t.map((e,r)=>b.createElement("div",{className:"content-block",key:r},Sh(e))),_h=t=>{const e=[];let r=0;const n=/\$\$?[^$]+\$\$?/g;let o;for(;(o=n.exec(t))!==null;){const s=o.index,i=o.index+o[0].length;if(s>r){const l=t.substring(r,s);l.trim()&&e.push({type:"text",content:l})}const c=o[0].replace(/^\$\$?/,"").replace(/\$\$?$/,"");e.push({type:"formula",content:c}),r=i}if(r<t.length){const s=t.substring(r);s.trim()&&e.push({type:"text",content:s})}return e},Rh=(t,e,r)=>{const n=Xa(t,e,r),o=_h(n);return zo(o)},Ah=t=>{const{type:e,content:r,style:n={}}=t,o={marginBottom:"8px",lineHeight:"1.6",...n};switch(e){case"instruction":return b.createElement("div",{key:t.id,style:{...o,fontWeight:"bold",color:"#4a6cf7"}},r);case"formula":const s=r.includes("\\\\")||r.includes("\\downarrow")||r.includes("\\quad");return b.createElement(Zt,{key:t.id,parts:[r],children:null,displayMode:s,fontSize:"1.1em",color:"#333333"});case"conclusion":return b.createElement("div",{key:t.id,style:{...o,fontWeight:"bold",color:"#22c55e",borderLeft:"3px solid #22c55e",paddingLeft:"12px"}},r);case"image":return b.createElement("div",{key:t.id,style:o},b.createElement("img",{src:r,alt:"解题步骤",style:{maxWidth:"100%",height:"auto",borderRadius:"4px"}}));case"table":return b.createElement("div",{key:t.id,style:o},b.createElement("div",{style:{border:"1px solid #e0e0e0",borderRadius:"4px",padding:"8px",backgroundColor:"#f8f9fa"}},r));default:return b.createElement("div",{key:t.id,style:o},r)}},Eh=(t,e,r)=>{const{type:n,content:o,style:s={}}=t,i={marginBottom:"8px",lineHeight:"1.6",...s};switch(n){case"instruction":return b.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80"}},o);case"formula":const a=o.includes("\\\\")||o.includes("\\downarrow")||o.includes("\\quad");return b.createElement(Zt,{key:t.id,parts:[o],children:null,displayMode:a,fontSize:"1.1em",color:"#333333"});case"conclusion":const c=Xa(o,r,e);return b.createElement("div",{key:t.id,style:{...i,fontWeight:"bold",color:"#4ade80",borderLeft:"3px solid #4ade80",paddingLeft:"12px"}},c);default:return b.createElement("div",{key:t.id,style:i},o)}},Nh=t=>t.map(Ah),Th=(t,e,r)=>t.map(n=>Eh(n,e,r)),Ja=({scene:t,position:e="header",size:r="medium",color:n,bgColor:o,hidden:s=!1})=>{if(s)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=o||l[t],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"}}[r]),c};return d.jsx("div",{style:a(),children:i[t]})},Za=({question:t})=>{const e={padding:"20px",lineHeight:"1.6",fontSize:"16px"};return d.jsx("div",{style:e,children:zo(t)})},Qa=({problemType:t,options:e,value:r=[],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"},c=g=>({padding:"12px 16px",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s ease",background:g?"#f97316":"transparent",color:g?"#ffffff":"inherit",borderColor:g?"#f97316":"#e0e0e0"}),l=g=>{if(n)if(t==="multiple-choice"){const m=r.includes(g)?r.filter(f=>f!==g):[...r,g];n(m)}else n([g])},u=g=>{n&&n([g.target.value])};return t==="multiple-choice"&&e?d.jsx("div",{style:s,children:d.jsx("div",{style:a,children:e.map(g=>d.jsx("div",{style:c(r.includes(g.id)),onClick:()=>l(g.id),children:zo(g.content)},g.id))})}):d.jsx("div",{style:s,children:d.jsx("input",{type:"text",style:i,placeholder:o,value:r[0]||"",onChange:u})})},Yr=({onClick:t,children:e,disabled:r=!1,loading:n=!1})=>{const o={padding:"12px 24px",background:"#f97316",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.6:1};return d.jsx("button",{style:o,onClick:t,disabled:r||n,children:n?"提交中...":e})},el=({steps:t,title:e="解题步骤"})=>{const r={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 d.jsxs("div",{style:r,children:[d.jsx("div",{style:n,children:e}),d.jsx("div",{style:o,children:Nh(t).map((i,a)=>d.jsx("div",{style:s,children:i},t[a].id))})]})},tl=({reviewContent:t,userAnswer:e,correctAnswer:r})=>{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"},c={padding:"12px",borderLeft:"3px solid #4ade80",background:"#f8f9fa",borderRadius:"0 4px 4px 0",lineHeight:"1.6"};return d.jsxs("div",{style:n,children:[d.jsx("div",{style:o,children:"复习内容"}),d.jsxs("div",{style:s,children:[t.reviewTemplate&&d.jsx("div",{style:i,children:Rh(t.reviewTemplate,r,e)}),t.reviewExplanation&&d.jsx("div",{style:a,children:Th(t.reviewExplanation,e,r).map((l,u)=>d.jsx("div",{style:c,children:l},t.reviewExplanation[u].id))})]})]})},rl=({type:t="skeleton"})=>{const e={padding:"20px"},r={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 t==="spinner"?d.jsx("div",{style:n,children:d.jsx("div",{style:o})}):d.jsxs("div",{style:e,"data-testid":"loading-skeleton",children:[d.jsx("div",{style:{...r,width:"80%"}}),d.jsx("div",{style:{...r,width:"60%"}}),d.jsx("div",{style:{...r,width:"70%"}})]})},rn=({error:t,onRetry:e})=>{const r={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 t=="string"?t:t.message;return d.jsxs("div",{style:r,children:[d.jsx("div",{style:n,children:s}),e&&d.jsx("button",{style:o,onClick:()=>e(t),children:"重试"})]})},$h=({orientation:t="horizontal",size:e="medium"})=>{const r={background:"#e0e0e0"},n={small:"12px",medium:"16px",large:"20px"};return t==="horizontal"?(r.height="1px",r.width="100%",r.margin=`${n[e]} 0`):(r.width="1px",r.height="100%",r.margin=`0 ${n[e]}`),d.jsx("div",{style:r})},kh=({onSubmit:t,onNext:e,onRetry:r,onAnswerChange:n,value:o})=>{const{problemData:s,scene:i,submissionResult:a,config:c}=Ch();if(!s)return d.jsx(rn,{error:"No problem data provided"});const l=()=>{t&&t()},u=()=>{e&&e(s.problemId)},g=()=>{r&&r(s.problemId)},m=h=>{n&&n(h,s.problemType)},f={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"},p={padding:"20px",borderTop:"1px solid #e0e0e0",display:"flex",gap:"12px"};return d.jsxs("div",{style:f,"data-testid":"math-card","data-theme":c?.theme,children:[c?.showBanner!==!1&&d.jsx(Ja,{scene:i,position:c?.bannerPosition,size:c?.bannerSize,color:c?.bannerCustomStyle?.color,bgColor:c?.bannerCustomStyle?.bgColor}),d.jsx(Za,{question:s.question,problemType:s.problemType}),i==="question"&&d.jsxs(d.Fragment,{children:[d.jsx(Qa,{problemType:s.problemType,options:s.answer.options,value:o,onChange:m,placeholder:c?.inputPlaceholder}),d.jsx("div",{style:p,children:d.jsx(Yr,{onClick:l,disabled:!t,children:c?.submitButtonText||"提交答案"})})]}),i==="solve"&&s.explanation&&d.jsx(el,{steps:s.explanation,title:"官方解析"}),i==="review"&&a&&s.reviewContent&&d.jsx(tl,{reviewContent:s.reviewContent,userAnswer:a.userAnswer,correctAnswer:s.answer.correctAnswer}),(i==="solve"||i==="review")&&d.jsxs("div",{style:p,children:[e&&d.jsx(Yr,{onClick:u,children:c?.nextButtonText||"下一题"}),r&&d.jsx(Yr,{onClick:g,children:c?.retryButtonText||"重新作答"})]})]})},st=({problemData:t,scene:e,submissionResult:r,loading:n,error:o,config:s,children:i,onSubmit:a,onNext:c,onRetry:l,onErrorRetry:u,onAnswerChange:g,onHintToggle:m,value:f})=>{if(n)return d.jsx(rl,{type:"skeleton"});if(o)return d.jsx(rn,{error:o,onRetry:u});if(!t)return d.jsx(rn,{error:"No problem data provided"});const p={problemData:t,scene:e,submissionResult:r,config:s,value:f};return d.jsx(Ka.Provider,{value:p,children:i||d.jsx(kh,{onSubmit:a,onNext:c,onRetry:l,onAnswerChange:g,onHintToggle:m,value:f})})};st.Banner=Ja;st.Question=Za;st.AnswerInput=Qa;st.SubmitButton=Yr;st.Explanation=el;st.ReviewContent=tl;st.LoadingState=rl;st.ErrorState=rn;st.Divider=$h;function jh(t){if(t.sheet)return t.sheet;for(var e=0;e<document.styleSheets.length;e++)if(document.styleSheets[e].ownerNode===t)return document.styleSheets[e]}function Ih(t){var e=document.createElement("style");return e.setAttribute("data-emotion",t.key),t.nonce!==void 0&&e.setAttribute("nonce",t.nonce),e.appendChild(document.createTextNode("")),e.setAttribute("data-s",""),e}var Mh=(function(){function t(r){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=r.speedy===void 0?!0:r.speedy,this.tags=[],this.ctr=0,this.nonce=r.nonce,this.key=r.key,this.container=r.container,this.prepend=r.prepend,this.insertionPoint=r.insertionPoint,this.before=null}var e=t.prototype;return e.hydrate=function(n){n.forEach(this._insertTag)},e.insert=function(n){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(Ih(this));var o=this.tags[this.tags.length-1];if(this.isSpeedy){var s=jh(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},t})(),je="-ms-",nn="-moz-",oe="-webkit-",nl="comm",Uo="rule",Bo="decl",Oh="@import",ol="@keyframes",Fh="@layer",Ph=Math.abs,xn=String.fromCharCode,Dh=Object.assign;function Lh(t,e){return Ne(t,0)^45?(((e<<2^Ne(t,0))<<2^Ne(t,1))<<2^Ne(t,2))<<2^Ne(t,3):0}function sl(t){return t.trim()}function Gh(t,e){return(t=e.exec(t))?t[0]:t}function se(t,e,r){return t.replace(e,r)}function lo(t,e){return t.indexOf(e)}function Ne(t,e){return t.charCodeAt(e)|0}function gr(t,e,r){return t.slice(e,r)}function tt(t){return t.length}function Ho(t){return t.length}function Gr(t,e){return e.push(t),t}function Vh(t,e){return t.map(e).join("")}var wn=1,Wt=1,il=0,Ge=0,Se=0,er="";function vn(t,e,r,n,o,s,i){return{value:t,root:e,parent:r,type:n,props:o,children:s,line:wn,column:Wt,length:i,return:""}}function ir(t,e){return Dh(vn("",null,null,"",null,null,0),t,{length:-t.length},e)}function zh(){return Se}function Uh(){return Se=Ge>0?Ne(er,--Ge):0,Wt--,Se===10&&(Wt=1,wn--),Se}function He(){return Se=Ge<il?Ne(er,Ge++):0,Wt++,Se===10&&(Wt=1,wn++),Se}function ot(){return Ne(er,Ge)}function Kr(){return Ge}function Rr(t,e){return gr(er,t,e)}function mr(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function al(t){return wn=Wt=1,il=tt(er=t),Ge=0,[]}function ll(t){return er="",t}function Xr(t){return sl(Rr(Ge-1,co(t===91?t+2:t===40?t+1:t)))}function Bh(t){for(;(Se=ot())&&Se<33;)He();return mr(t)>2||mr(Se)>3?"":" "}function Hh(t,e){for(;--e&&He()&&!(Se<48||Se>102||Se>57&&Se<65||Se>70&&Se<97););return Rr(t,Kr()+(e<6&&ot()==32&&He()==32))}function co(t){for(;He();)switch(Se){case t:return Ge;case 34:case 39:t!==34&&t!==39&&co(Se);break;case 40:t===41&&co(t);break;case 92:He();break}return Ge}function qh(t,e){for(;He()&&t+Se!==57;)if(t+Se===84&&ot()===47)break;return"/*"+Rr(e,Ge-1)+"*"+xn(t===47?t:He())}function Wh(t){for(;!mr(ot());)He();return Rr(t,Ge)}function Yh(t){return ll(Jr("",null,null,null,[""],t=al(t),0,[0],t))}function Jr(t,e,r,n,o,s,i,a,c){for(var l=0,u=0,g=i,m=0,f=0,p=0,h=1,y=1,x=1,v=0,w="",S=o,C=s,E=n,_=w;y;)switch(p=v,v=He()){case 40:if(p!=108&&Ne(_,g-1)==58){lo(_+=se(Xr(v),"&","&\f"),"&\f")!=-1&&(x=-1);break}case 34:case 39:case 91:_+=Xr(v);break;case 9:case 10:case 13:case 32:_+=Bh(p);break;case 92:_+=Hh(Kr()-1,7);continue;case 47:switch(ot()){case 42:case 47:Gr(Kh(qh(He(),Kr()),e,r),c);break;default:_+="/"}break;case 123*h:a[l++]=tt(_)*x;case 125*h:case 59:case 0:switch(v){case 0:case 125:y=0;case 59+u:x==-1&&(_=se(_,/\f/g,"")),f>0&&tt(_)-g&&Gr(f>32?Is(_+";",n,r,g-1):Is(se(_," ","")+";",n,r,g-2),c);break;case 59:_+=";";default:if(Gr(E=js(_,e,r,l,u,o,a,w,S=[],C=[],g),s),v===123)if(u===0)Jr(_,e,E,E,S,s,g,a,C);else switch(m===99&&Ne(_,3)===110?100:m){case 100:case 108:case 109:case 115:Jr(t,E,E,n&&Gr(js(t,E,E,0,0,o,a,w,o,S=[],g),C),o,C,g,a,n?S:C);break;default:Jr(_,E,E,E,[""],C,0,a,C)}}l=u=f=0,h=x=1,w=_="",g=i;break;case 58:g=1+tt(_),f=p;default:if(h<1){if(v==123)--h;else if(v==125&&h++==0&&Uh()==125)continue}switch(_+=xn(v),v*h){case 38:x=u>0?1:(_+="\f",-1);break;case 44:a[l++]=(tt(_)-1)*x,x=1;break;case 64:ot()===45&&(_+=Xr(He())),m=ot(),u=g=tt(w=_+=Wh(Kr())),v++;break;case 45:p===45&&tt(_)==2&&(h=0)}}return s}function js(t,e,r,n,o,s,i,a,c,l,u){for(var g=o-1,m=o===0?s:[""],f=Ho(m),p=0,h=0,y=0;p<n;++p)for(var x=0,v=gr(t,g+1,g=Ph(h=i[p])),w=t;x<f;++x)(w=sl(h>0?m[x]+" "+v:se(v,/&\f/g,m[x])))&&(c[y++]=w);return vn(t,e,r,o===0?Uo:a,c,l,u)}function Kh(t,e,r){return vn(t,e,r,nl,xn(zh()),gr(t,2,-2),0)}function Is(t,e,r,n){return vn(t,e,r,Bo,gr(t,0,n),gr(t,n+1,-1),n)}function Ut(t,e){for(var r="",n=Ho(t),o=0;o<n;o++)r+=e(t[o],o,t,e)||"";return r}function Xh(t,e,r,n){switch(t.type){case Fh:if(t.children.length)break;case Oh:case Bo:return t.return=t.return||t.value;case nl:return"";case ol:return t.return=t.value+"{"+Ut(t.children,n)+"}";case Uo:t.value=t.props.join(",")}return tt(r=Ut(t.children,n))?t.return=t.value+"{"+r+"}":""}function Jh(t){var e=Ho(t);return function(r,n,o,s){for(var i="",a=0;a<e;a++)i+=t[a](r,n,o,s)||"";return i}}function Zh(t){return function(e){e.root||(e=e.return)&&t(e)}}function Qh(t){var e=Object.create(null);return function(r){return e[r]===void 0&&(e[r]=t(r)),e[r]}}var ey=function(e,r,n){for(var o=0,s=0;o=s,s=ot(),o===38&&s===12&&(r[n]=1),!mr(s);)He();return Rr(e,Ge)},ty=function(e,r){var n=-1,o=44;do switch(mr(o)){case 0:o===38&&ot()===12&&(r[n]=1),e[n]+=ey(Ge-1,r,n);break;case 2:e[n]+=Xr(o);break;case 4:if(o===44){e[++n]=ot()===58?"&\f":"",r[n]=e[n].length;break}default:e[n]+=xn(o)}while(o=He());return e},ry=function(e,r){return ll(ty(al(e),r))},Ms=new WeakMap,ny=function(e){if(!(e.type!=="rule"||!e.parent||e.length<1)){for(var r=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&&r.charCodeAt(0)!==58&&!Ms.get(n))&&!o){Ms.set(e,!0);for(var s=[],i=ry(r,s),a=n.props,c=0,l=0;c<i.length;c++)for(var u=0;u<a.length;u++,l++)e.props[l]=s[c]?i[c].replace(/&\f/g,a[u]):a[u]+" "+i[c]}}},oy=function(e){if(e.type==="decl"){var r=e.value;r.charCodeAt(0)===108&&r.charCodeAt(2)===98&&(e.return="",e.value="")}};function cl(t,e){switch(Lh(t,e)){case 5103:return oe+"print-"+t+t;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return oe+t+t;case 5349:case 4246:case 4810:case 6968:case 2756:return oe+t+nn+t+je+t+t;case 6828:case 4268:return oe+t+je+t+t;case 6165:return oe+t+je+"flex-"+t+t;case 5187:return oe+t+se(t,/(\w+).+(:[^]+)/,oe+"box-$1$2"+je+"flex-$1$2")+t;case 5443:return oe+t+je+"flex-item-"+se(t,/flex-|-self/,"")+t;case 4675:return oe+t+je+"flex-line-pack"+se(t,/align-content|flex-|-self/,"")+t;case 5548:return oe+t+je+se(t,"shrink","negative")+t;case 5292:return oe+t+je+se(t,"basis","preferred-size")+t;case 6060:return oe+"box-"+se(t,"-grow","")+oe+t+je+se(t,"grow","positive")+t;case 4554:return oe+se(t,/([^-])(transform)/g,"$1"+oe+"$2")+t;case 6187:return se(se(se(t,/(zoom-|grab)/,oe+"$1"),/(image-set)/,oe+"$1"),t,"")+t;case 5495:case 3959:return se(t,/(image-set\([^]*)/,oe+"$1$`$1");case 4968:return se(se(t,/(.+:)(flex-)?(.*)/,oe+"box-pack:$3"+je+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+oe+t+t;case 4095:case 3583:case 4068:case 2532:return se(t,/(.+)-inline(.+)/,oe+"$1$2")+t;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(tt(t)-1-e>6)switch(Ne(t,e+1)){case 109:if(Ne(t,e+4)!==45)break;case 102:return se(t,/(.+:)(.+)-([^]+)/,"$1"+oe+"$2-$3$1"+nn+(Ne(t,e+3)==108?"$3":"$2-$3"))+t;case 115:return~lo(t,"stretch")?cl(se(t,"stretch","fill-available"),e)+t:t}break;case 4949:if(Ne(t,e+1)!==115)break;case 6444:switch(Ne(t,tt(t)-3-(~lo(t,"!important")&&10))){case 107:return se(t,":",":"+oe)+t;case 101:return se(t,/(.+:)([^;!]+)(;|!.+)?/,"$1"+oe+(Ne(t,14)===45?"inline-":"")+"box$3$1"+oe+"$2$3$1"+je+"$2box$3")+t}break;case 5936:switch(Ne(t,e+11)){case 114:return oe+t+je+se(t,/[svh]\w+-[tblr]{2}/,"tb")+t;case 108:return oe+t+je+se(t,/[svh]\w+-[tblr]{2}/,"tb-rl")+t;case 45:return oe+t+je+se(t,/[svh]\w+-[tblr]{2}/,"lr")+t}return oe+t+je+t+t}return t}var sy=function(e,r,n,o){if(e.length>-1&&!e.return)switch(e.type){case Bo:e.return=cl(e.value,e.length);break;case ol:return Ut([ir(e,{value:se(e.value,"@","@"+oe)})],o);case Uo:if(e.length)return Vh(e.props,function(s){switch(Gh(s,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Ut([ir(e,{props:[se(s,/:(read-\w+)/,":"+nn+"$1")]})],o);case"::placeholder":return Ut([ir(e,{props:[se(s,/:(plac\w+)/,":"+oe+"input-$1")]}),ir(e,{props:[se(s,/:(plac\w+)/,":"+nn+"$1")]}),ir(e,{props:[se(s,/:(plac\w+)/,je+"input-$1")]})],o)}return""})}},iy=[sy],ay=function(e){var r=e.key;if(r==="css"){var n=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(n,function(h){var y=h.getAttribute("data-emotion");y.indexOf(" ")!==-1&&(document.head.appendChild(h),h.setAttribute("data-s",""))})}var o=e.stylisPlugins||iy,s={},i,a=[];i=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+r+' "]'),function(h){for(var y=h.getAttribute("data-emotion").split(" "),x=1;x<y.length;x++)s[y[x]]=!0;a.push(h)});var c,l=[ny,oy];{var u,g=[Xh,Zh(function(h){u.insert(h)})],m=Jh(l.concat(o,g)),f=function(y){return Ut(Yh(y),m)};c=function(y,x,v,w){u=v,f(y?y+"{"+x.styles+"}":x.styles),w&&(p.inserted[x.name]=!0)}}var p={key:r,sheet:new Mh({key:r,container:i,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:s,registered:{},insert:c};return p.sheet.hydrate(a),p},Vr={exports:{}},ae={};var Os;function ly(){if(Os)return ae;Os=1;var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,r=t?Symbol.for("react.portal"):60106,n=t?Symbol.for("react.fragment"):60107,o=t?Symbol.for("react.strict_mode"):60108,s=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,c=t?Symbol.for("react.async_mode"):60111,l=t?Symbol.for("react.concurrent_mode"):60111,u=t?Symbol.for("react.forward_ref"):60112,g=t?Symbol.for("react.suspense"):60113,m=t?Symbol.for("react.suspense_list"):60120,f=t?Symbol.for("react.memo"):60115,p=t?Symbol.for("react.lazy"):60116,h=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,x=t?Symbol.for("react.responder"):60118,v=t?Symbol.for("react.scope"):60119;function w(C){if(typeof C=="object"&&C!==null){var E=C.$$typeof;switch(E){case e:switch(C=C.type,C){case c:case l:case n:case s:case o:case g:return C;default:switch(C=C&&C.$$typeof,C){case a:case u:case p:case f:case i:return C;default:return E}}case r:return E}}}function S(C){return w(C)===l}return ae.AsyncMode=c,ae.ConcurrentMode=l,ae.ContextConsumer=a,ae.ContextProvider=i,ae.Element=e,ae.ForwardRef=u,ae.Fragment=n,ae.Lazy=p,ae.Memo=f,ae.Portal=r,ae.Profiler=s,ae.StrictMode=o,ae.Suspense=g,ae.isAsyncMode=function(C){return S(C)||w(C)===c},ae.isConcurrentMode=S,ae.isContextConsumer=function(C){return w(C)===a},ae.isContextProvider=function(C){return w(C)===i},ae.isElement=function(C){return typeof C=="object"&&C!==null&&C.$$typeof===e},ae.isForwardRef=function(C){return w(C)===u},ae.isFragment=function(C){return w(C)===n},ae.isLazy=function(C){return w(C)===p},ae.isMemo=function(C){return w(C)===f},ae.isPortal=function(C){return w(C)===r},ae.isProfiler=function(C){return w(C)===s},ae.isStrictMode=function(C){return w(C)===o},ae.isSuspense=function(C){return w(C)===g},ae.isValidElementType=function(C){return typeof C=="string"||typeof C=="function"||C===n||C===l||C===s||C===o||C===g||C===m||typeof C=="object"&&C!==null&&(C.$$typeof===p||C.$$typeof===f||C.$$typeof===i||C.$$typeof===a||C.$$typeof===u||C.$$typeof===y||C.$$typeof===x||C.$$typeof===v||C.$$typeof===h)},ae.typeOf=w,ae}var le={};var Fs;function cy(){return Fs||(Fs=1,process.env.NODE_ENV!=="production"&&(function(){var t=typeof Symbol=="function"&&Symbol.for,e=t?Symbol.for("react.element"):60103,r=t?Symbol.for("react.portal"):60106,n=t?Symbol.for("react.fragment"):60107,o=t?Symbol.for("react.strict_mode"):60108,s=t?Symbol.for("react.profiler"):60114,i=t?Symbol.for("react.provider"):60109,a=t?Symbol.for("react.context"):60110,c=t?Symbol.for("react.async_mode"):60111,l=t?Symbol.for("react.concurrent_mode"):60111,u=t?Symbol.for("react.forward_ref"):60112,g=t?Symbol.for("react.suspense"):60113,m=t?Symbol.for("react.suspense_list"):60120,f=t?Symbol.for("react.memo"):60115,p=t?Symbol.for("react.lazy"):60116,h=t?Symbol.for("react.block"):60121,y=t?Symbol.for("react.fundamental"):60117,x=t?Symbol.for("react.responder"):60118,v=t?Symbol.for("react.scope"):60119;function w(N){return typeof N=="string"||typeof N=="function"||N===n||N===l||N===s||N===o||N===g||N===m||typeof N=="object"&&N!==null&&(N.$$typeof===p||N.$$typeof===f||N.$$typeof===i||N.$$typeof===a||N.$$typeof===u||N.$$typeof===y||N.$$typeof===x||N.$$typeof===v||N.$$typeof===h)}function S(N){if(typeof N=="object"&&N!==null){var ie=N.$$typeof;switch(ie){case e:var fe=N.type;switch(fe){case c:case l:case n:case s:case o:case g:return fe;default:var H=fe&&fe.$$typeof;switch(H){case a:case u:case p:case f:case i:return H;default:return ie}}case r:return ie}}}var C=c,E=l,_=a,A=i,T=e,j=u,U=n,z=p,O=f,M=r,F=s,$=o,B=g,k=!1;function te(N){return k||(k=!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.")),ue(N)||S(N)===c}function ue(N){return S(N)===l}function ne(N){return S(N)===a}function re(N){return S(N)===i}function V(N){return typeof N=="object"&&N!==null&&N.$$typeof===e}function Q(N){return S(N)===u}function me(N){return S(N)===n}function Ee(N){return S(N)===p}function de(N){return S(N)===f}function gt(N){return S(N)===r}function it(N){return S(N)===s}function P(N){return S(N)===o}function I(N){return S(N)===g}le.AsyncMode=C,le.ConcurrentMode=E,le.ContextConsumer=_,le.ContextProvider=A,le.Element=T,le.ForwardRef=j,le.Fragment=U,le.Lazy=z,le.Memo=O,le.Portal=M,le.Profiler=F,le.StrictMode=$,le.Suspense=B,le.isAsyncMode=te,le.isConcurrentMode=ue,le.isContextConsumer=ne,le.isContextProvider=re,le.isElement=V,le.isForwardRef=Q,le.isFragment=me,le.isLazy=Ee,le.isMemo=de,le.isPortal=gt,le.isProfiler=it,le.isStrictMode=P,le.isSuspense=I,le.isValidElementType=w,le.typeOf=S})()),le}var Ps;function dy(){return Ps||(Ps=1,process.env.NODE_ENV==="production"?Vr.exports=ly():Vr.exports=cy()),Vr.exports}var Vn,Ds;function uy(){if(Ds)return Vn;Ds=1;var t=dy(),e={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},r={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[t.ForwardRef]=n,s[t.Memo]=o;function i(p){return t.isMemo(p)?o:s[p.$$typeof]||e}var a=Object.defineProperty,c=Object.getOwnPropertyNames,l=Object.getOwnPropertySymbols,u=Object.getOwnPropertyDescriptor,g=Object.getPrototypeOf,m=Object.prototype;function f(p,h,y){if(typeof h!="string"){if(m){var x=g(h);x&&x!==m&&f(p,x,y)}var v=c(h);l&&(v=v.concat(l(h)));for(var w=i(p),S=i(h),C=0;C<v.length;++C){var E=v[C];if(!r[E]&&!(y&&y[E])&&!(S&&S[E])&&!(w&&w[E])){var _=u(h,E);try{a(p,E,_)}catch{}}}}return p}return Vn=f,Vn}uy();var fy=!0;function gy(t,e,r){var n="";return r.split(" ").forEach(function(o){t[o]!==void 0?e.push(t[o]+";"):o&&(n+=o+" ")}),n}var dl=function(e,r,n){var o=e.key+"-"+r.name;(n===!1||fy===!1)&&e.registered[o]===void 0&&(e.registered[o]=r.styles)},my=function(e,r,n){dl(e,r,n);var o=e.key+"-"+r.name;if(e.inserted[r.name]===void 0){var s=r;do e.insert(r===s?"."+o:"",s,e.sheet,!0),s=s.next;while(s!==void 0)}};function py(t){for(var e=0,r,n=0,o=t.length;o>=4;++n,o-=4)r=t.charCodeAt(n)&255|(t.charCodeAt(++n)&255)<<8|(t.charCodeAt(++n)&255)<<16|(t.charCodeAt(++n)&255)<<24,r=(r&65535)*1540483477+((r>>>16)*59797<<16),r^=r>>>24,e=(r&65535)*1540483477+((r>>>16)*59797<<16)^(e&65535)*1540483477+((e>>>16)*59797<<16);switch(o){case 3:e^=(t.charCodeAt(n+2)&255)<<16;case 2:e^=(t.charCodeAt(n+1)&255)<<8;case 1:e^=t.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 hy={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},yy=/[A-Z]|^ms/g,by=/_EMO_([^_]+?)_([^]*?)_EMO_/g,ul=function(e){return e.charCodeAt(1)===45},Ls=function(e){return e!=null&&typeof e!="boolean"},zn=Qh(function(t){return ul(t)?t:t.replace(yy,"-$&").toLowerCase()}),Gs=function(e,r){switch(e){case"animation":case"animationName":if(typeof r=="string")return r.replace(by,function(n,o,s){return rt={name:o,styles:s,next:rt},o})}return hy[e]!==1&&!ul(e)&&typeof r=="number"&&r!==0?r+"px":r};function pr(t,e,r){if(r==null)return"";var n=r;if(n.__emotion_styles!==void 0)return n;switch(typeof r){case"boolean":return"";case"object":{var o=r;if(o.anim===1)return rt={name:o.name,styles:o.styles,next:rt},o.name;var s=r;if(s.styles!==void 0){var i=s.next;if(i!==void 0)for(;i!==void 0;)rt={name:i.name,styles:i.styles,next:rt},i=i.next;var a=s.styles+";";return a}return xy(t,e,r)}case"function":{if(t!==void 0){var c=rt,l=r(t);return rt=c,pr(t,e,l)}break}}var u=r;return u}function xy(t,e,r){var n="";if(Array.isArray(r))for(var o=0;o<r.length;o++)n+=pr(t,e,r[o])+";";else for(var s in r){var i=r[s];if(typeof i!="object"){var a=i;Ls(a)&&(n+=zn(s)+":"+Gs(s,a)+";")}else if(Array.isArray(i)&&typeof i[0]=="string"&&e==null)for(var c=0;c<i.length;c++)Ls(i[c])&&(n+=zn(s)+":"+Gs(s,i[c])+";");else{var l=pr(t,e,i);switch(s){case"animation":case"animationName":{n+=zn(s)+":"+l+";";break}default:n+=s+"{"+l+"}"}}}return n}var Vs=/label:\s*([^\s;{]+)\s*(;|$)/g,rt;function fl(t,e,r){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null&&t[0].styles!==void 0)return t[0];var n=!0,o="";rt=void 0;var s=t[0];if(s==null||s.raw===void 0)n=!1,o+=pr(r,e,s);else{var i=s;o+=i[0]}for(var a=1;a<t.length;a++)if(o+=pr(r,e,t[a]),n){var c=s;o+=c[a]}Vs.lastIndex=0;for(var l="",u;(u=Vs.exec(o))!==null;)l+="-"+u[1];var g=py(o)+l;return{name:g,styles:o,next:rt}}var wy=function(e){return e()},vy=Ue.useInsertionEffect?Ue.useInsertionEffect:!1,Cy=vy||wy,gl=Ue.createContext(typeof HTMLElement<"u"?ay({key:"css"}):null);gl.Provider;var Sy=function(e){return b.forwardRef(function(r,n){var o=b.useContext(gl);return e(r,o,n)})},_y=Ue.createContext({}),qo={}.hasOwnProperty,uo="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",Ry=function(e,r){var n={};for(var o in r)qo.call(r,o)&&(n[o]=r[o]);return n[uo]=e,n},Ay=function(e){var r=e.cache,n=e.serialized,o=e.isStringTag;return dl(r,n,o),Cy(function(){return my(r,n,o)}),null},Ey=Sy(function(t,e,r){var n=t.css;typeof n=="string"&&e.registered[n]!==void 0&&(n=e.registered[n]);var o=t[uo],s=[n],i="";typeof t.className=="string"?i=gy(e.registered,s,t.className):t.className!=null&&(i=t.className+" ");var a=fl(s,void 0,Ue.useContext(_y));i+=e.key+"-"+a.name;var c={};for(var l in t)qo.call(t,l)&&l!=="css"&&l!==uo&&(c[l]=t[l]);return c.className=i,r&&(c.ref=r),Ue.createElement(Ue.Fragment,null,Ue.createElement(Ay,{cache:e,serialized:a,isStringTag:typeof o=="string"}),Ue.createElement(o,c))}),Ny=Ey,zs=function(e,r){var n=arguments;if(r==null||!qo.call(r,"css"))return Ue.createElement.apply(void 0,n);var o=n.length,s=new Array(o);s[0]=Ny,s[1]=Ry(e,r);for(var i=2;i<o;i++)s[i]=n[i];return Ue.createElement.apply(null,s)};(function(t){var e;e||(e=t.JSX||(t.JSX={}))})(zs||(zs={}));function he(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return fl(e)}const D={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)"}};he`
87
+ background: ${D.colors.background.card};
88
+ border-radius: ${D.borderRadius.card};
89
+ box-shadow: ${D.shadows.card};
90
+ font-family: ${D.typography.fontFamily};
91
+ font-size: ${D.typography.fontSizeBase};
64
92
  overflow: hidden;
65
93
 
66
94
  &[data-theme="dark"] {
67
95
  background: #1a1a1a;
68
96
  color: #ffffff;
69
97
  }
70
- `;pe`
98
+ `;he`
71
99
  display: flex;
72
100
  align-items: center;
73
101
  justify-content: center;
74
- padding: ${j.spacing.sm} ${j.spacing.md};
102
+ padding: ${D.spacing.sm} ${D.spacing.md};
75
103
  font-weight: 600;
76
104
  text-transform: uppercase;
77
105
  letter-spacing: 0.5px;
78
- `,pe`
79
- font-size: ${j.typography.fontSizeSmall};
80
- padding: 8px ${j.spacing.sm};
81
- `,pe`
82
- font-size: ${j.typography.fontSizeBase};
83
- padding: ${j.spacing.sm} ${j.spacing.md};
84
- `,pe`
85
- font-size: ${j.typography.fontSizeLarge};
86
- padding: ${j.spacing.md} ${j.spacing.lg};
87
- `,pe`
88
- border-bottom: 1px solid ${j.colors.border.default};
89
- `,pe`
90
- border-right: 1px solid ${j.colors.border.default};
106
+ `,he`
107
+ font-size: ${D.typography.fontSizeSmall};
108
+ padding: 8px ${D.spacing.sm};
109
+ `,he`
110
+ font-size: ${D.typography.fontSizeBase};
111
+ padding: ${D.spacing.sm} ${D.spacing.md};
112
+ `,he`
113
+ font-size: ${D.typography.fontSizeLarge};
114
+ padding: ${D.spacing.md} ${D.spacing.lg};
115
+ `,he`
116
+ border-bottom: 1px solid ${D.colors.border.default};
117
+ `,he`
118
+ border-right: 1px solid ${D.colors.border.default};
91
119
  writing-mode: vertical-rl;
92
120
  text-orientation: mixed;
93
- `,pe`
94
- background: ${j.colors.scene.question};
95
- color: ${j.colors.text.light};
96
- `,pe`
97
- background: ${j.colors.scene.solve};
98
- color: ${j.colors.text.light};
99
- `,pe`
100
- background: ${j.colors.scene.review};
101
- color: ${j.colors.text.light};
102
- `;pe`
103
- padding: ${j.spacing.lg};
121
+ `,he`
122
+ background: ${D.colors.scene.question};
123
+ color: ${D.colors.text.light};
124
+ `,he`
125
+ background: ${D.colors.scene.solve};
126
+ color: ${D.colors.text.light};
127
+ `,he`
128
+ background: ${D.colors.scene.review};
129
+ color: ${D.colors.text.light};
130
+ `;he`
131
+ padding: ${D.spacing.lg};
104
132
  line-height: 1.6;
105
133
 
106
134
  .content-block {
107
- margin-bottom: ${j.spacing.sm};
135
+ margin-bottom: ${D.spacing.sm};
108
136
 
109
137
  &:last-child {
110
138
  margin-bottom: 0;
@@ -120,53 +148,53 @@ ${new Error().stack?.split(`
120
148
  .image {
121
149
  max-width: 100%;
122
150
  height: auto;
123
- border-radius: ${j.borderRadius.input};
151
+ border-radius: ${D.borderRadius.input};
124
152
  }
125
- `;pe`
126
- padding: ${j.spacing.lg};
127
- border-top: 1px solid ${j.colors.border.default};
128
- `,pe`
153
+ `;he`
154
+ padding: ${D.spacing.lg};
155
+ border-top: 1px solid ${D.colors.border.default};
156
+ `,he`
129
157
  width: 100%;
130
- padding: ${j.spacing.sm} ${j.spacing.md};
131
- border: 1px solid ${j.colors.border.default};
132
- border-radius: ${j.borderRadius.input};
133
- font-size: ${j.typography.fontSizeBase};
158
+ padding: ${D.spacing.sm} ${D.spacing.md};
159
+ border: 1px solid ${D.colors.border.default};
160
+ border-radius: ${D.borderRadius.input};
161
+ font-size: ${D.typography.fontSizeBase};
134
162
 
135
163
  &:focus {
136
164
  outline: none;
137
- border-color: ${j.colors.scene.question};
165
+ border-color: ${D.colors.scene.question};
138
166
  }
139
- `,pe`
167
+ `,he`
140
168
  display: grid;
141
- gap: ${j.spacing.sm};
142
- `,pe`
143
- padding: ${j.spacing.sm} ${j.spacing.md};
144
- border: 1px solid ${j.colors.border.default};
145
- border-radius: ${j.borderRadius.input};
169
+ gap: ${D.spacing.sm};
170
+ `,he`
171
+ padding: ${D.spacing.sm} ${D.spacing.md};
172
+ border: 1px solid ${D.colors.border.default};
173
+ border-radius: ${D.borderRadius.input};
146
174
  cursor: pointer;
147
175
  transition: all 0.2s ease;
148
176
 
149
177
  &:hover {
150
- border-color: ${j.colors.scene.question};
178
+ border-color: ${D.colors.scene.question};
151
179
  }
152
180
 
153
181
  &[data-selected="true"] {
154
- background: ${j.colors.scene.question};
155
- color: ${j.colors.text.light};
156
- border-color: ${j.colors.scene.question};
182
+ background: ${D.colors.scene.question};
183
+ color: ${D.colors.text.light};
184
+ border-color: ${D.colors.scene.question};
157
185
  }
158
- `;pe`
159
- padding: ${j.spacing.lg};
160
- border-radius: ${j.borderRadius.card};
161
- margin: ${j.spacing.md} 0;
162
- `,pe`
163
- background: ${j.colors.background.feedbackCorrect};
186
+ `;he`
187
+ padding: ${D.spacing.lg};
188
+ border-radius: ${D.borderRadius.card};
189
+ margin: ${D.spacing.md} 0;
190
+ `,he`
191
+ background: ${D.colors.background.feedbackCorrect};
164
192
  border: 1px solid #22c55e;
165
- `,pe`
166
- background: ${j.colors.background.feedbackIncorrect};
193
+ `,he`
194
+ background: ${D.colors.background.feedbackIncorrect};
167
195
  border: 1px solid #ef4444;
168
- `;pe`
169
- padding: ${j.spacing.lg};
196
+ `;he`
197
+ padding: ${D.spacing.lg};
170
198
 
171
199
  .skeleton-line {
172
200
  height: 16px;
@@ -174,7 +202,7 @@ ${new Error().stack?.split(`
174
202
  background-size: 200% 100%;
175
203
  animation: loading 1.5s infinite;
176
204
  border-radius: 4px;
177
- margin-bottom: ${j.spacing.sm};
205
+ margin-bottom: ${D.spacing.sm};
178
206
 
179
207
  &:last-child {
180
208
  margin-bottom: 0;
@@ -185,17 +213,17 @@ ${new Error().stack?.split(`
185
213
  0% { background-position: 200% 0; }
186
214
  100% { background-position: -200% 0; }
187
215
  }
188
- `,pe`
216
+ `,he`
189
217
  display: flex;
190
218
  justify-content: center;
191
219
  align-items: center;
192
- padding: ${j.spacing.xl};
220
+ padding: ${D.spacing.xl};
193
221
 
194
222
  .spinner {
195
223
  width: 40px;
196
224
  height: 40px;
197
225
  border: 4px solid #f0f0f0;
198
- border-top: 4px solid ${j.colors.scene.question};
226
+ border-top: 4px solid ${D.colors.scene.question};
199
227
  border-radius: 50%;
200
228
  animation: spin 1s linear infinite;
201
229
  }
@@ -204,55 +232,55 @@ ${new Error().stack?.split(`
204
232
  0% { transform: rotate(0deg); }
205
233
  100% { transform: rotate(360deg); }
206
234
  }
207
- `;pe`
208
- padding: ${j.spacing.xl};
235
+ `;he`
236
+ padding: ${D.spacing.xl};
209
237
  text-align: center;
210
238
  color: #ef4444;
211
239
 
212
240
  .error-message {
213
- margin-bottom: ${j.spacing.md};
214
- font-size: ${j.typography.fontSizeLarge};
241
+ margin-bottom: ${D.spacing.md};
242
+ font-size: ${D.typography.fontSizeLarge};
215
243
  }
216
244
 
217
245
  .retry-button {
218
- padding: ${j.spacing.sm} ${j.spacing.md};
246
+ padding: ${D.spacing.sm} ${D.spacing.md};
219
247
  background: #ef4444;
220
248
  color: white;
221
249
  border: none;
222
- border-radius: ${j.borderRadius.button};
250
+ border-radius: ${D.borderRadius.button};
223
251
  cursor: pointer;
224
- font-size: ${j.typography.fontSizeBase};
252
+ font-size: ${D.typography.fontSizeBase};
225
253
 
226
254
  &:hover {
227
255
  background: #dc2626;
228
256
  }
229
257
  }
230
- `;pe`
258
+ `;he`
231
259
  height: 1px;
232
- background: ${j.colors.border.default};
233
- margin: ${j.spacing.md} 0;
260
+ background: ${D.colors.border.default};
261
+ margin: ${D.spacing.md} 0;
234
262
 
235
263
  &[data-size="small"] {
236
- margin: ${j.spacing.sm} 0;
264
+ margin: ${D.spacing.sm} 0;
237
265
  }
238
266
 
239
267
  &[data-size="large"] {
240
- margin: ${j.spacing.lg} 0;
268
+ margin: ${D.spacing.lg} 0;
241
269
  }
242
- `,pe`
270
+ `,he`
243
271
  width: 1px;
244
- background: ${j.colors.border.default};
245
- margin: 0 ${j.spacing.md};
272
+ background: ${D.colors.border.default};
273
+ margin: 0 ${D.spacing.md};
246
274
 
247
275
  &[data-size="small"] {
248
- margin: 0 ${j.spacing.sm};
276
+ margin: 0 ${D.spacing.sm};
249
277
  }
250
278
 
251
279
  &[data-size="large"] {
252
- margin: 0 ${j.spacing.lg};
280
+ margin: 0 ${D.spacing.lg};
253
281
  }
254
- `;const Nh="/api/v1/content",kh="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",Mh=10,mt="question",ye=gr.create()(ll.devtools((t,e)=>({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:"question",userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1,loadQuestions:async(r,n)=>{t({loading:!0,sessionId:r});try{const{gradeLevel:o,unitId:s,lessonId:i,count:a=Mh}=n,c=`${Nh}/grades/${o}/units/${s}/lessons/${i}/sessions/${r}/questions`,l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kh}`},body:JSON.stringify({count:a})});if(!l.ok)throw new Error(`Failed to load questions: ${l.status} ${l.statusText}`);const g=(await l.json()).questions||[],p={};g.forEach(f=>{f.geometryShapes&&Array.isArray(f.geometryShapes)&&(p[f.problemId]=f.geometryShapes)}),t({problems:g,totalProblems:g.length,currentProblemIndex:0,currentScene:mt,geometryShapes:p,loading:!1,error:null,startTime:Date.now()})}catch(o){const s=o instanceof Error?o.message:"Unknown error occurred";throw t({error:s,loading:!1}),o}},goToNextProblem:()=>{const{currentProblemIndex:r,problems:n,currentScene:o}=e();if(o!==mt){console.warn("Cannot navigate during review/solve scene");return}r<n.length-1?t({currentProblemIndex:r+1,currentScene:mt}):t({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:r,currentScene:n}=e();n===mt&&r>0&&t({currentProblemIndex:r-1,currentScene:mt})},goToProblem:r=>{const{problems:n,currentScene:o}=e();o===mt&&(r<0||r>=n.length||t({currentProblemIndex:r,currentScene:mt}))},switchScene:r=>{t({currentScene:r})},submitAnswer:async(r,n)=>{const{problems:o,currentProblemIndex:s}=e(),i=o[s];t({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."};t(d=>({userAnswers:{...d.userAnswers,[r]:n},submissionResults:{...d.submissionResults,[r]:l},loading:!1,currentScene:c?"review":"solve"}))}catch(a){t({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(r,n)=>{t(o=>({userAnswers:{...o.userAnswers,[r]:n}}))},updateShape:(r,n,o)=>{t(s=>{const a=(s.geometryShapes[r]||[]).map(c=>c.id===n&&c.type==="point"?{...c,position:o}:c);return{geometryShapes:{...s.geometryShapes,[r]:a}}})},selectShape:(r,n)=>{t({selectedShapeId:n})},setGeometryMode:(r,n)=>{t({geometryMode:n})},startTimer:()=>{t({startTime:Date.now()})},stopTimer:()=>{const{startTime:r}=e();if(r){const n=Math.floor((Date.now()-r)/1e3);t(o=>({timeSpent:o.timeSpent+n,startTime:null}))}},reset:()=>{t({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:mt,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:r,currentProblemIndex:n}=e();return r[n]||null},getProgress:()=>{const{currentProblemIndex:r,totalProblems:n}=e();return{current:r+1,total:n,percentage:n>0?(r+1)/n*100:0}},getSessionResults:()=>{const{sessionId:r,problems:n,submissionResults:o,timeSpent:s}=e(),i=n.map(c=>({problemId:c.problemId,userAnswer:o[c.problemId]?.userAnswer||[],isCorrect:o[c.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(c=>c.isCorrect).length;return{sessionId:r||"",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"})),Ka=(t,e,r,n,o,s,i)=>{const a=x.useMemo(()=>r==="question",[r]),c=x.useMemo(()=>t<e.length-1,[t,e.length]),l=x.useMemo(()=>t>0,[t]),d=x.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:c,canGoPrevious:l,shouldRenderMathGraph:d}},Xa=(t,e,r,n,o)=>{const s=ye(d=>d.selectShape),i=ye(d=>d.setGeometryMode),a=x.useMemo(()=>!e||!n?[]:n[e]||[],[n,e]);x.useEffect(()=>{if(!e||!r)return;let d="view";switch(t){case"question":d="edit";break;case"solve":case"review":d="view";break;default:d="view"}o!==d&&i(e,d)},[t,e,o,i,r]);const c=x.useCallback(d=>{e&&ye.setState(g=>({geometryShapes:{...g.geometryShapes,[e]:d}}))},[e]),l=x.useCallback(d=>{if(e){const g=d.length>0?d[0]:null;s(e,g)}},[e,s]);return{currentGeometryShapes:a,geometryMode:o,handleShapeChange:c,handleSelectionChange:l}},Ja=(t,e,r)=>{const n=ye(f=>f.updateUserAnswer),o=ye(f=>f.submitAnswer),s=ye(f=>f.goToNextProblem),i=ye(f=>f.goToPreviousProblem),a=ye(f=>f.goToProblem),c=x.useCallback(f=>{t&&n(t,f)},[t,n]),l=x.useCallback(()=>{t&&r[t]&&o(t,r[t])},[t,r,o]),d=x.useCallback(f=>{s(),f?.(t,e+1)},[s,t,e]),g=x.useCallback(f=>{i(),f?.(t,e-1)},[i,t,e]),p=x.useCallback((f,m)=>{a(f-1),m?.(t,f-1)},[a,t]);return{handleAnswerChange:c,handleSubmit:l,handleNext:d,handlePrevious:g,handlePagination:p}},Za=({config:t={},onSessionComplete:e,onSessionExit:r,onProblemChange:n,className:o="",style:s})=>{const i=ye(T=>T.problems),a=ye(T=>T.currentProblemIndex),c=ye(T=>T.currentScene),l=ye(T=>T.loading),d=ye(T=>T.error),g=ye(T=>T.sessionComplete),p=ye(T=>T.submissionResults),f=ye(T=>T.userAnswers),m=ye(T=>T.geometryShapes),h=ye(T=>T.geometryMode),y=ye(T=>T.getSessionResults),b=x.useMemo(()=>i[a]??null,[i,a]),_=x.useMemo(()=>b?.problemId??"",[b]),{canNavigate:w,canGoNext:C,canGoPrevious:v,shouldRenderMathGraph:k}=Ka(a,i,c,b,_,m,t),{currentGeometryShapes:S,handleShapeChange:E,handleSelectionChange:N}=Xa(c,_,k,m,h),{handleAnswerChange:I,handleSubmit:Y,handleNext:K,handlePrevious:L,handlePagination:O}=Ja(_,a,f);x.useEffect(()=>{if(g&&typeof y=="function"){const T=y();e?.(T)}},[g,y,e]);const U=T=>typeof T=="string"?T:T instanceof Error?T.message:String(T);return l&&i.length===0?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:u.jsxs("div",{className:"text-center",children:[u.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),u.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):d&&d!==null?u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:u.jsxs("div",{className:"text-center text-red-600",children:[u.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),u.jsx("p",{children:U(d)})]})}):b?u.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:[u.jsx("div",{className:"mb-6",children:u.jsx(Ue.Pagination,{total:i.length,page:a+1,onChange:T=>O(T,n),isDisabled:!w,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),u.jsx(ot,{problemData:b,scene:c,submissionResult:p[_],loading:l,error:d?U(d):void 0,value:f[_],onAnswerChange:I,onSubmit:Y,onNext:()=>K(n),config:{theme:t.theme??"light",submitButtonText:"提交答案",nextButtonText:c==="solve"?"Got it!":"下一题",showHints:t.enableHints}}),k&&u.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:u.jsx(xr,{shapes:S,mode:h,onShapeChange:E,onSelectionChange:N,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),t.showProgress&&u.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[u.jsx("button",{onClick:()=>L(n),disabled:!v,className:"px-4 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"上一题"}),u.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),u.jsx("button",{onClick:()=>K(n),disabled:!C||!w,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:"下一题"})]}),r&&u.jsx("div",{className:"mt-4 flex justify-center",children:u.jsx("button",{onClick:r,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):u.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:u.jsx("p",{className:"text-gray-600",children:"No problems available"})})},Oh=({sessionId:t,gradeId:e,unitId:r,lessonId:n,userId:o,config:s={},className:i="",onSessionComplete:a,onSessionExit:c})=>{const[l,d]=x.useState({loading:!1,error:null,initialized:!1}),[g,p]=x.useState(0),[f,m]=x.useState(""),h=x.useRef(null),y=x.useRef(null),b=x.useRef(null),_=ye(E=>E.loadQuestions),w=ye(E=>E.reset);x.useEffect(()=>{const E=async()=>{try{d(N=>({...N,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:t,gradeId:e,unitId:r,lessonId:n,userId:o}),await _(t,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:r,lessonId:n,count:s.questionCount||10}),d(N=>({...N,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch(N){const I=N instanceof Error?N.message:"Failed to initialize session";d(Y=>({...Y,loading:!1,error:I,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",N)}};t&&e&&r&&n&&!l.initialized&&E()},[t,e,r,n,_,s.questionCount,l.initialized,g]),x.useEffect(()=>{l.loading&&!l.initialized?m("正在加载数学练习内容,请稍候..."):l.error?m(`加载失败:${l.error},请点击重试按钮重新加载`):l.initialized&&m("数学练习内容已加载完成,可以开始练习")},[l.loading,l.error,l.initialized]),x.useEffect(()=>{l.initialized&&h.current&&h.current.focus()},[l.initialized]),x.useEffect(()=>{l.error&&b.current&&b.current.focus()},[l.error]),x.useEffect(()=>{l.loading&&y.current&&y.current.focus()},[l.loading]),x.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),w()},[w]);const C=x.useCallback(E=>{console.log("🎉 MathSessionPage: 会话完成",E),a?.(E)},[a]),v=x.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),c?.()},[c]),k=x.useCallback((E,N)=>{console.log(`📝 MathSessionPage: 切换到题目 ${N+1}`,E)},[]),S=x.useCallback(E=>{E.key==="Escape"&&(E.preventDefault(),v()),E.key==="Enter"&&l.error&&E.target===b.current&&(E.preventDefault(),d({loading:!1,error:null,initialized:!1}),p(N=>N+1))},[v,l.error]);return l.loading&&!l.initialized?u.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:S,tabIndex:-1,ref:y,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:f}),u.jsx("div",{className:"page-loading-container",children:u.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[u.jsx("div",{className:"spinner","aria-hidden":"true"}),u.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):l.error?u.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:S,tabIndex:-1,ref:b,children:[u.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:f}),u.jsxs("div",{className:"error-container",children:[u.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),u.jsx("h3",{className:"error-title",children:"加载失败"}),u.jsx("p",{className:"error-message",children:l.error}),u.jsx(ut,{onClick:()=>{d({loading:!1,error:null,initialized:!1}),p(E=>E+1)},intent:"retry",useNewClassName:!0,className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):u.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:S,children:[u.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:f}),s.layout?.showHeader&&u.jsx("header",{className:"page-header",role:"banner",children:u.jsxs("div",{className:"header-content",children:[u.jsx("h1",{className:"page-title",children:"数学练习"}),u.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[u.jsxs("span",{className:"session-id",children:["会话: ",t]}),u.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),u.jsx("main",{className:"page-main",ref:h,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:u.jsx(Za,{config:{showProgress:s.showProgress??!0,enableHints:s.enableHints??!1,autoAdvance:s.autoAdvance??!1,theme:s.theme??"light"},onSessionComplete:C,onSessionExit:v,onProblemChange:k})}),s.layout?.showFooter&&u.jsx("footer",{className:"page-footer",role:"contentinfo",children:u.jsx("div",{className:"footer-content",children:u.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},Ih=x.memo(Oh),Fh=({problemData:t,userAnswer:e,onNextQuestion:r})=>u.jsxs("div",{children:[u.jsxs("div",{className:"decimal-error-banner",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),u.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",u.jsx("strong",{children:t.answer.value})]})]}),u.jsx("button",{onClick:r,className:"decimal-understand-button",children:"明白了"})]}),u.jsxs("div",{className:"decimal-content-area",children:[u.jsx(ko,{problemData:t,userAnswer:e}),u.jsx(Mo,{problemData:t})]}),u.jsx("div",{className:"decimal-bottom-area",children:u.jsx("button",{onClick:r,className:"decimal-bottom-button",children:"明白了"})})]}),jh="rectangle-area-003",Ph="矩形面积计算问题",Dh=5,Lh="几何与测量",Gh="计算矩形的面积,理解面积公式 A = l × w 的应用",Uh={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},Vh=[{type:"text",content:"What is the area of this rectangle?"}],zh={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"}}]}},Bh=[{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}}}],Hh={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},qh={type:"card",padding:"20px"},Wh={id:jh,title:Ph,grade:Dh,unit:Lh,description:Gh,basicInfo:Uh,content:Vh,scenes:zh,explanation:Bh,answer:Hh,layout:qh},Yh=({className:t=""})=>{const e=Eo(),r=To(),n=$o(),{updateUserAnswer:o,submitAnswer:s,nextQuestion:i}=No(),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(p=>{if(d.scenes?.[p]){const f=d.scenes[p];!f.items&&f.content&&(f.items=f.content),Array.isArray(f.items)||(f.items=[])}}),d},c=x.useMemo(()=>a(Wh),[]);return u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[c.grade,"年级 - ",c.unit]})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&u.jsx(Mt,{problemData:c,userAnswer:r,showAnswerForm:n,onAnswerSubmit:s,onAnswerChange:o}),e==="explanation"&&u.jsx(Xt,{problemData:c,userAnswer:r,onNextQuestion:i}),e==="success"&&u.jsx(Ot,{problemData:c,onNextQuestion:i})]})]})},Zt=gr.create(t=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{t({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{const r=typeof e=="string"?e:JSON.stringify(e);t({userAnswer:r,validationError:null})},submitAnswer:e=>{const r=Zt.getState();if(!r.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}const n=r.problemData.answer.value.toString(),o=typeof e=="string"?e:JSON.stringify(e),s=o.trim(),i=n.trim();let a=!1;(s===i||s===".12"&&i==="0.12"||s==="0,12"&&i==="0.12")&&(a=!0),t({userAnswer:o,isCorrect:a,showAnswerForm:!1,validationError:null,currentScene:a?"success":"explanation"})},updateChoiceAnswer:e=>{t({userAnswer:e,validationError:null})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),Qa=()=>Zt(t=>t.currentScene),el=()=>Zt(t=>t.userAnswer),tl=()=>Zt(t=>t.showAnswerForm),Kh=()=>Zt(t=>t.validationError),rl=()=>Zt(lo.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),Xh={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?
282
+ `;const Ty="/api/v1/content",$y="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",ky=10,pt="question",be=Yt.create()(Bl.devtools((t,e)=>({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:"question",userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1,loadQuestions:async(r,n)=>{t({loading:!0,sessionId:r});try{const{gradeLevel:o,unitId:s,lessonId:i,count:a=ky}=n,c=`${Ty}/grades/${o}/units/${s}/lessons/${i}/sessions/${r}/questions`,l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$y}`},body:JSON.stringify({count:a})});if(!l.ok)throw new Error(`Failed to load questions: ${l.status} ${l.statusText}`);const g=(await l.json()).questions||[],m={};g.forEach(f=>{f.geometryShapes&&Array.isArray(f.geometryShapes)&&(m[f.problemId]=f.geometryShapes)}),t({problems:g,totalProblems:g.length,currentProblemIndex:0,currentScene:pt,geometryShapes:m,loading:!1,error:null,startTime:Date.now()})}catch(o){const s=o instanceof Error?o.message:"Unknown error occurred";throw t({error:s,loading:!1}),o}},goToNextProblem:()=>{const{currentProblemIndex:r,problems:n,currentScene:o}=e();if(o!==pt){console.warn("Cannot navigate during review/solve scene");return}r<n.length-1?t({currentProblemIndex:r+1,currentScene:pt}):t({sessionComplete:!0})},goToPreviousProblem:()=>{const{currentProblemIndex:r,currentScene:n}=e();n===pt&&r>0&&t({currentProblemIndex:r-1,currentScene:pt})},goToProblem:r=>{const{problems:n,currentScene:o}=e();o===pt&&(r<0||r>=n.length||t({currentProblemIndex:r,currentScene:pt}))},switchScene:r=>{t({currentScene:r})},submitAnswer:async(r,n)=>{const{problems:o,currentProblemIndex:s}=e(),i=o[s];t({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."};t(u=>({userAnswers:{...u.userAnswers,[r]:n},submissionResults:{...u.submissionResults,[r]:l},loading:!1,currentScene:c?"review":"solve"}))}catch(a){t({error:a instanceof Error?a.message:"Submission error",loading:!1})}},updateUserAnswer:(r,n)=>{t(o=>({userAnswers:{...o.userAnswers,[r]:n}}))},updateShape:(r,n,o)=>{t(s=>{const a=(s.geometryShapes[r]||[]).map(c=>c.id===n&&c.type==="point"?{...c,position:o}:c);return{geometryShapes:{...s.geometryShapes,[r]:a}}})},selectShape:(r,n)=>{t({selectedShapeId:n})},setGeometryMode:(r,n)=>{t({geometryMode:n})},startTimer:()=>{t({startTime:Date.now()})},stopTimer:()=>{const{startTime:r}=e();if(r){const n=Math.floor((Date.now()-r)/1e3);t(o=>({timeSpent:o.timeSpent+n,startTime:null}))}},reset:()=>{t({sessionId:null,problems:[],totalProblems:0,currentProblemIndex:0,currentScene:pt,userAnswers:{},submissionResults:{},geometryShapes:{},selectedShapeId:null,geometryMode:"view",loading:!1,error:null,timeSpent:0,startTime:null,sessionComplete:!1})},getCurrentProblem:()=>{const{problems:r,currentProblemIndex:n}=e();return r[n]||null},getProgress:()=>{const{currentProblemIndex:r,totalProblems:n}=e();return{current:r+1,total:n,percentage:n>0?(r+1)/n*100:0}},getSessionResults:()=>{const{sessionId:r,problems:n,submissionResults:o,timeSpent:s}=e(),i=n.map(c=>({problemId:c.problemId,userAnswer:o[c.problemId]?.userAnswer||[],isCorrect:o[c.problemId]?.isCorrect||!1,timeSpent:0})),a=i.filter(c=>c.isCorrect).length;return{sessionId:r||"",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"})),ml=(t,e,r,n,o,s,i)=>{const a=b.useMemo(()=>r==="question",[r]),c=b.useMemo(()=>t<e.length-1,[t,e.length]),l=b.useMemo(()=>t>0,[t]),u=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:c,canGoPrevious:l,shouldRenderMathGraph:u}},pl=(t,e,r,n,o)=>{const s=be(u=>u.selectShape),i=be(u=>u.setGeometryMode),a=b.useMemo(()=>!e||!n?[]:n[e]||[],[n,e]);b.useEffect(()=>{if(!e||!r)return;let u="view";switch(t){case"question":u="edit";break;case"solve":case"review":u="view";break;default:u="view"}o!==u&&i(e,u)},[t,e,o,i,r]);const c=b.useCallback(u=>{e&&be.setState(g=>({geometryShapes:{...g.geometryShapes,[e]:u}}))},[e]),l=b.useCallback(u=>{if(e){const g=u.length>0?u[0]:null;s(e,g)}},[e,s]);return{currentGeometryShapes:a,geometryMode:o,handleShapeChange:c,handleSelectionChange:l}},hl=(t,e,r)=>{const n=be(f=>f.updateUserAnswer),o=be(f=>f.submitAnswer),s=be(f=>f.goToNextProblem),i=be(f=>f.goToPreviousProblem),a=be(f=>f.goToProblem),c=b.useCallback(f=>{t&&n(t,f)},[t,n]),l=b.useCallback(()=>{t&&r[t]&&o(t,r[t])},[t,r,o]),u=b.useCallback(f=>{s(),f?.(t,e+1)},[s,t,e]),g=b.useCallback(f=>{i(),f?.(t,e-1)},[i,t,e]),m=b.useCallback((f,p)=>{a(f-1),p?.(t,f-1)},[a,t]);return{handleAnswerChange:c,handleSubmit:l,handleNext:u,handlePrevious:g,handlePagination:m}},yl=({config:t={},onSessionComplete:e,onSessionExit:r,onProblemChange:n,className:o="",style:s})=>{const i=be($=>$.problems),a=be($=>$.currentProblemIndex),c=be($=>$.currentScene),l=be($=>$.loading),u=be($=>$.error),g=be($=>$.sessionComplete),m=be($=>$.submissionResults),f=be($=>$.userAnswers),p=be($=>$.geometryShapes),h=be($=>$.geometryMode),y=be($=>$.getSessionResults),x=b.useMemo(()=>i[a]??null,[i,a]),v=b.useMemo(()=>x?.problemId??"",[x]),{canNavigate:w,canGoNext:S,canGoPrevious:C,shouldRenderMathGraph:E}=ml(a,i,c,x,v,p,t),{currentGeometryShapes:_,handleShapeChange:A,handleSelectionChange:T}=pl(c,v,E,p,h),{handleAnswerChange:j,handleSubmit:U,handleNext:z,handlePrevious:O,handlePagination:M}=hl(v,a,f);b.useEffect(()=>{if(g&&typeof y=="function"){const $=y();e?.($)}},[g,y,e]);const F=$=>typeof $=="string"?$:$ instanceof Error?$.message:String($);return l&&i.length===0?d.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-loading",children:d.jsxs("div",{className:"text-center",children:[d.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),d.jsx("p",{className:"text-gray-600",children:"Loading questions..."})]})}):u&&u!==null?d.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-error",children:d.jsxs("div",{className:"text-center text-red-600",children:[d.jsx("p",{className:"text-lg font-semibold mb-2",children:"Error"}),d.jsx("p",{children:F(u)})]})}):x?d.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:[d.jsx("div",{className:"mb-6",children:d.jsx(X.Pagination,{total:i.length,page:a+1,onChange:$=>M($,n),isDisabled:!w,showControls:!1,color:"primary",size:"lg",className:"justify-center"})}),d.jsx(st,{problemData:x,scene:c,submissionResult:m[v],loading:l,error:u?F(u):void 0,value:f[v],onAnswerChange:j,onSubmit:U,onNext:()=>z(n),config:{theme:t.theme??"light",submitButtonText:"提交答案",nextButtonText:c==="solve"?"Got it!":"下一题",showHints:t.enableHints}}),E&&d.jsx("div",{className:"mt-4 w-full max-w-4xl mx-auto","data-testid":"mathgraph-container",children:d.jsx(vr,{shapes:_,mode:h,onShapeChange:A,onSelectionChange:T,showGrid:!0,showAxis:!0,width:800,height:500,boundingBoxOptions:{padding:.5,margin:2,minSize:8}})}),t.showProgress&&d.jsxs("div",{className:"mt-6 flex justify-between items-center",children:[d.jsx("button",{onClick:()=>O(n),disabled:!C,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:"上一题"}),d.jsxs("div",{className:"text-sm text-gray-600",children:[a+1," / ",i.length]}),d.jsx("button",{onClick:()=>z(n),disabled:!S||!w,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:"下一题"})]}),r&&d.jsx("div",{className:"mt-4 flex justify-center",children:d.jsx("button",{onClick:r,className:"px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors",children:"退出练习"})})]}):d.jsx("div",{className:"flex items-center justify-center p-12","data-testid":"math-session-empty",children:d.jsx("p",{className:"text-gray-600",children:"No problems available"})})},jy=({sessionId:t,gradeId:e,unitId:r,lessonId:n,userId:o,config:s={},className:i="",onSessionComplete:a,onSessionExit:c})=>{const[l,u]=b.useState({loading:!1,error:null,initialized:!1}),[g,m]=b.useState(0),[f,p]=b.useState(""),h=b.useRef(null),y=b.useRef(null),x=b.useRef(null),v=be(A=>A.loadQuestions),w=be(A=>A.reset);b.useEffect(()=>{const A=async()=>{try{u(T=>({...T,loading:!0,error:null})),console.log("🎯 MathSessionPage: 开始初始化会话",{sessionId:t,gradeId:e,unitId:r,lessonId:n,userId:o}),await v(t,{gradeLevel:parseInt(e.replace("g",""))||5,unitId:r,lessonId:n,count:s.questionCount||10}),u(T=>({...T,loading:!1,initialized:!0})),console.log("✅ MathSessionPage: 会话初始化完成")}catch(T){const j=T instanceof Error?T.message:"Failed to initialize session";u(U=>({...U,loading:!1,error:j,initialized:!1})),console.error("❌ MathSessionPage: 会话初始化失败",T)}};t&&e&&r&&n&&!l.initialized&&A()},[t,e,r,n,v,s.questionCount,l.initialized,g]),b.useEffect(()=>{l.loading&&!l.initialized?p("正在加载数学练习内容,请稍候..."):l.error?p(`加载失败:${l.error},请点击重试按钮重新加载`):l.initialized&&p("数学练习内容已加载完成,可以开始练习")},[l.loading,l.error,l.initialized]),b.useEffect(()=>{l.initialized&&h.current&&h.current.focus()},[l.initialized]),b.useEffect(()=>{l.error&&x.current&&x.current.focus()},[l.error]),b.useEffect(()=>{l.loading&&y.current&&y.current.focus()},[l.loading]),b.useEffect(()=>()=>{console.log("🧹 MathSessionPage: 清理会话状态"),w()},[w]);const S=b.useCallback(A=>{console.log("🎉 MathSessionPage: 会话完成",A),a?.(A)},[a]),C=b.useCallback(()=>{console.log("🚪 MathSessionPage: 退出会话"),c?.()},[c]),E=b.useCallback((A,T)=>{console.log(`📝 MathSessionPage: 切换到题目 ${T+1}`,A)},[]),_=b.useCallback(A=>{A.key==="Escape"&&(A.preventDefault(),C()),A.key==="Enter"&&l.error&&A.target===x.current&&(A.preventDefault(),u({loading:!1,error:null,initialized:!1}),m(T=>T+1))},[C,l.error]);return l.loading&&!l.initialized?d.jsxs("div",{className:`math-session-page loading ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:_,tabIndex:-1,ref:y,children:[d.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:f}),d.jsx("div",{className:"page-loading-container",children:d.jsxs("div",{className:"loading-spinner","data-testid":"page-loading-spinner",role:"status","aria-label":"正在加载练习内容",children:[d.jsx("div",{className:"spinner","aria-hidden":"true"}),d.jsx("p",{className:"loading-text",children:"正在加载练习内容..."})]})})]}):l.error?d.jsxs("div",{className:`math-session-page error ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面 - 错误状态",onKeyDown:_,tabIndex:-1,ref:x,children:[d.jsx("div",{"aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:f}),d.jsxs("div",{className:"error-container",children:[d.jsx("div",{className:"error-icon",role:"img","aria-label":"警告图标",children:"⚠️"}),d.jsx("h3",{className:"error-title",children:"加载失败"}),d.jsx("p",{className:"error-message",children:l.error}),d.jsx(ft,{onClick:()=>{u({loading:!1,error:null,initialized:!1}),m(A=>A+1)},intent:"retry",useNewClassName:!0,className:"retry-button","data-testid":"retry-button","aria-label":"重新加载练习内容",children:"重试"})]})]}):d.jsxs("div",{className:`math-session-page ${i}`,"data-testid":"math-session-page",role:"main","aria-label":"数学练习页面",onKeyDown:_,children:[d.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:f}),s.layout?.showHeader&&d.jsx("header",{className:"page-header",role:"banner",children:d.jsxs("div",{className:"header-content",children:[d.jsx("h1",{className:"page-title",children:"数学练习"}),d.jsxs("div",{className:"session-info","aria-label":"会话信息",children:[d.jsxs("span",{className:"session-id",children:["会话: ",t]}),d.jsxs("span",{className:"grade-info",children:["年级: ",e]})]})]})}),d.jsx("main",{className:"page-main",ref:h,tabIndex:-1,"aria-label":"数学练习主要内容区域",children:d.jsx(yl,{config:{showProgress:s.showProgress??!0,enableHints:s.enableHints??!1,autoAdvance:s.autoAdvance??!1,theme:s.theme??"light"},onSessionComplete:S,onSessionExit:C,onProblemChange:E})}),s.layout?.showFooter&&d.jsx("footer",{className:"page-footer",role:"contentinfo",children:d.jsx("div",{className:"footer-content",children:d.jsx("p",{className:"footer-text",children:"© 2024 MathWiz - 小学数学益智教育平台"})})})]})},Iy=b.memo(jy),My=({problemData:t,userAnswer:e,onNextQuestion:r})=>d.jsxs("div",{children:[d.jsxs("div",{className:"decimal-error-banner",children:[d.jsxs("div",{children:[d.jsx("h3",{className:"decimal-error-title",children:"抱歉,答案不正确..."}),d.jsxs("p",{className:"decimal-error-description",children:["正确答案是: ",d.jsx("strong",{children:t.answer.value})]})]}),d.jsx("button",{onClick:r,className:"decimal-understand-button",children:"明白了"})]}),d.jsxs("div",{className:"decimal-content-area",children:[d.jsx(Lo,{problemData:t,userAnswer:e}),d.jsx(Go,{problemData:t})]}),d.jsx("div",{className:"decimal-bottom-area",children:d.jsx("button",{onClick:r,className:"decimal-bottom-button",children:"明白了"})})]}),Oy="rectangle-area-003",Fy="矩形面积计算问题",Py=5,Dy="几何与测量",Ly="计算矩形的面积,理解面积公式 A = l × w 的应用",Gy={shape:"rectangle",length:7,width:5,lengthUnit:"码",widthUnit:"码",areaUnit:"平方码",question:"这个矩形的面积是多少?"},Vy=[{type:"text",content:"What is the area of this rectangle?"}],zy={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"}}]}},Uy=[{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}}}],By={value:35,unit:"平方码",explanation:"矩形的面积是 35 平方码。计算方法:长度 7 码 × 宽度 5 码 = 35 平方码。"},Hy={type:"card",padding:"20px"},qy={id:Oy,title:Fy,grade:Py,unit:Dy,description:Ly,basicInfo:Gy,content:Vy,scenes:zy,explanation:Uy,answer:By,layout:Hy},Wy=({className:t=""})=>{const e=Oo(),r=Fo(),n=Po(),{updateUserAnswer:o,submitAnswer:s,nextQuestion:i}=Do(),a=l=>{if(!l)return l;const u=JSON.parse(JSON.stringify(l));return u.lesson||(u.lesson="面积计算"),u.skill||(u.skill="面积公式应用"),u.objective||(u.objective="掌握面积计算方法"),(!u.knowledgePoints||!Array.isArray(u.knowledgePoints))&&(u.knowledgePoints=["面积公式","几何变换"]),u.difficulty||(u.difficulty=2),u.metadata||(u.metadata={topic:"几何",skill:"面积计算",tags:["面积","公式"]}),["question","solve","review","remember"].forEach(m=>{if(u.scenes?.[m]){const f=u.scenes[m];!f.items&&f.content&&(f.items=f.content),Array.isArray(f.items)||(f.items=[])}}),u},c=b.useMemo(()=>a(qy),[]);return d.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[d.jsxs("header",{className:"mb-8",children:[d.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"数学练习"}),d.jsxs("p",{className:"text-slate-600 mt-2",children:[c.grade,"年级 - ",c.unit]})]}),d.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[e==="question"&&d.jsx(Mt,{problemData:c,userAnswer:r,showAnswerForm:n,onAnswerSubmit:s,onAnswerChange:o}),e==="explanation"&&d.jsx(Qt,{problemData:c,userAnswer:r,onNextQuestion:i}),e==="success"&&d.jsx(Ot,{problemData:c,onNextQuestion:i})]})]})},tr=Yt.create(t=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:e=>{t({problemData:e,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:e=>{const r=typeof e=="string"?e:JSON.stringify(e);t({userAnswer:r,validationError:null})},submitAnswer:e=>{const r=tr.getState();if(!r.problemData){t({validationError:"问题数据未加载,请刷新页面重试"});return}const n=r.problemData.answer.value.toString(),o=typeof e=="string"?e:JSON.stringify(e),s=o.trim(),i=n.trim();let a=!1;(s===i||s===".12"&&i==="0.12"||s==="0,12"&&i==="0.12")&&(a=!0),t({userAnswer:o,isCorrect:a,showAnswerForm:!1,validationError:null,currentScene:a?"success":"explanation"})},updateChoiceAnswer:e=>{t({userAnswer:e,validationError:null})},nextQuestion:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{t({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),bl=()=>tr(t=>t.currentScene),xl=()=>tr(t=>t.userAnswer),wl=()=>tr(t=>t.showAnswerForm),Yy=()=>tr(t=>t.validationError),vl=()=>tr(It.useShallow(t=>({updateUserAnswer:t.updateUserAnswer,submitAnswer:t.submitAnswer,nextQuestion:t.nextQuestion,resetSession:t.resetSession,setProblemData:t.setProblemData}))),Ky={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?
255
283
  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?
256
- 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。"}},Jh=({className:t="",problemData:e})=>{const r=Qa(),n=el(),o=tl(),s=Kh(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=rl(),d=x.useMemo(()=>e||Xh,[e]);return x.useEffect(()=>{l(d)},[d,l]),u.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[u.jsxs("header",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[d.grade,"年级 - ",d.unit]}),u.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),u.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&u.jsx(Mt,{problemData:d,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&u.jsx(Fh,{problemData:d,userAnswer:n,onNextQuestion:c}),r==="success"&&u.jsx(Ot,{problemData:d,onNextQuestion:c})]}),u.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[r==="question"&&"请识别百格图代表的小数",r==="explanation"&&"查看详细解释",r==="success"&&"恭喜!答案正确"]})]})},We=(t,e,r)=>({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r}),Zh=()=>{const t={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},r={x:.9,y:.75,name:"C"},n={...We(t,e,1/3),name:"D"},o={...We(t,r,1/3),name:"E"},s={...We(t,e,2/3),name:"M"},i={...We(t,r,2/3),name:"N"},a={...We(e,r,1/3),name:"P"},c={...We(e,r,2/3),name:"Q"},l={...We(n,o,1/3),name:"U"},d={...We(n,o,2/3),name:"S"},g={...We(s,i,1/3),name:"K"},p={...We(s,i,2/3),name:"L"};return{A:t,B:e,C:r,D:n,E:o,M:s,N:i,P:a,Q:c,U:l,S:d,K:g,L:p}},Qh=(t,e,r)=>{const n={};for(const[o,s]of Object.entries(t))n[o]={...s,x:s.x*e,y:s.y*r};return n},ey=(t,e)=>{const[r,n,o]=e,{x:s,y:i}=t,a=(n.y-o.y)*(r.x-o.x)+(o.x-n.x)*(r.y-o.y);if(Math.abs(a)<1e-4)return!1;const c=((n.y-o.y)*(s-o.x)+(o.x-n.x)*(i-o.y))/a,l=((o.y-r.y)*(s-o.x)+(r.x-o.x)*(i-o.y))/a,d=1-c-l;return c>=-.001&&l>=-.001&&d>=-.001},ty=(t,e)=>{if(!t||!e||t.length!==3||e.length!==3)return!1;const r=t.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return r.every((o,s)=>o===n[s])},ry=(t,e)=>{if(!t||!e||t.length!==e.length)return!1;const r=t.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return r.join("")===n.join("")},ny=()=>[{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"}],oy=()=>[{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"}],sy={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},nl=(t=wr.id)=>{const e=be.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),c=o.lessons.map((l,d)=>{const g=Math.min(100,Math.max(0,i-d*10+Math.random()*30));return{lessonId:l.id,status:g>=100?"completed":g>0?"in-progress":"not-started",progressPercentage:Math.round(g),lastAccessed:g>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:g>0?Math.floor(Math.random()*120+10):void 0,score:g>=100?Math.floor(Math.random()*21+80):void 0,attempts:g>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:o.id,userId:t,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:c}}),r=e.reduce((o,s)=>o+s.progressPercentage,0)/e.length,n=e.filter(o=>o.status==="completed").length;return{courseId:be.id,userId:t,totalUnits:e.length,completedUnits:n,progressPercentage:Math.round(r),status:r>=100?"completed":r>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},ol=nl(),Lo=(t,e)=>t===wr.id&&e===be.id?ol:null,sl=(t,e,r)=>{const n=Lo(t,e);return n&&n.units.find(o=>o.unitId===r)||null},iy=(t,e,r,n)=>{const o=sl(t,e,r);return o&&o.lessons.find(s=>s.lessonId===n)||null},ay=(t,e,r,n,o)=>(console.log("Updating lesson progress:",{userId:t,courseId:e,unitId:r,lessonId:n,progress:o}),!0),Go=(t,e)=>{const r=Lo(t,e);if(!r)return null;const n=be.units.map((o,s)=>{const i=r.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-${be.level}/unit/${o.id}`}});return{userId:t,courseId:be.id,courseTitle:be.title,courseLevel:be.level,totalUnits:n.length,completedUnits:n.filter(o=>o.status==="completed").length,overallProgress:r.progressPercentage,status:r.status,lastAccessed:r.lastAccessed,units:n}},ly=(t,e,r)=>{const n=Go(t,e);return n&&n.units.find(o=>o.unitId===r)||null},cy=(t,e,r,n)=>(console.log("Updating unit active status:",{userId:t,courseId:e,unitId:r,isActive:n}),!0),dy=Go(wr.id,be.id),uy={userId:wr.id,courseId:be.id,courseTitle:be.title,courseLevel:be.level,totalUnits:be.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:"📊"}]},fy=({className:t="",problemData:e,children:r})=>{const n=dn(),o=un(),s=fn(),i=gn(),{updateUserAnswer:a,submitAnswer:c,nextQuestion:l,setProblemData:d}=mn();x.useEffect(()=>{e&&d(e)},[e,d]);const p=(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"text-cyan-600",label:"三角形面积"};case"parallelogram":return{titleColor:"text-blue-600",label:"平行四边形面积"};case"trapezoid":return{titleColor:"text-green-600",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"text-purple-600",label:"年龄问题"}:{titleColor:"text-slate-600",label:"数学问题"}}})();return u.jsxs("div",{className:`bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center p-4 font-sans ${t}`,children:[u.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[u.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${p.titleColor}`,children:e?.title||"数学问题练习"}),u.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),u.jsx("div",{className:"mt-4 md:mt-0",children:u.jsx("span",{className:"inline-block px-3 py-1 text-sm font-medium rounded-full bg-white border border-slate-200 text-slate-700",children:p.label})})]}),e?.description&&u.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),u.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm",children:e?u.jsxs(u.Fragment,{children:[n==="question"&&u.jsx(Mt,{problemData:e,userAnswer:o,showAnswerForm:s,onAnswerSubmit:c,onAnswerChange:a,validationError:i}),n==="explanation"&&u.jsx(Xt,{problemData:e,userAnswer:o,onNextQuestion:l}),n==="success"&&u.jsx(Ot,{problemData:e,onNextQuestion:l})]}):u.jsxs("div",{className:"p-8 text-center",children:[u.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),u.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),u.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),u.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:u.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[u.jsx("div",{className:"mb-4 md:mb-0",children:u.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),u.jsx("div",{children:u.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),r&&u.jsx("div",{className:"w-full max-w-4xl mt-8",children:r})]})},gy=()=>u.jsxs("div",{className:"ixl-dashboard-panels",children:[u.jsxs("div",{className:"ixl-dashboard-card ixl-questions-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Questions",u.jsx("br",{}),"answered"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-time-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["Time",u.jsx("br",{}),"elapsed"]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsxs("div",{className:"ixl-time-display",children:[u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"hr"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"00"}),u.jsx("div",{className:"ixl-time-label",children:"min"})]}),u.jsx("div",{className:"ixl-time-separator",children:":"}),u.jsxs("div",{className:"ixl-time-unit",children:[u.jsx("div",{className:"ixl-time-value",children:"06"}),u.jsx("div",{className:"ixl-time-label",children:"sec"})]})]})})]}),u.jsxs("div",{className:"ixl-dashboard-card ixl-score-card",children:[u.jsxs("div",{className:"ixl-dashboard-card-header",children:["SmartScore",u.jsx("span",{className:"ixl-score-subtitle",children:"out of 100"}),u.jsx("span",{className:"ixl-help-icon",title:"What is this?",children:"?"})]}),u.jsx("div",{className:"ixl-dashboard-card-body",children:u.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),u.jsx("p",{className:"ixl-dashboard-note",children:"*在实际业务项目中集成StatBlock组件显示实时数据"})]}),my=()=>u.jsxs("div",{className:"ixl-scaffolding-links",children:[u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),u.jsx("span",{children:"Learn with an example"})]}),u.jsx("span",{className:"ixl-scaffolding-separator",children:"or"}),u.jsxs("button",{className:"ixl-scaffolding-link",children:[u.jsx("svg",{className:"ixl-scaffolding-icon",fill:"currentColor",viewBox:"0 0 20 20",children:u.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"})}),u.jsx("span",{children:"Watch a video"})]})]}),py=()=>{const t=[{icon:"💎",title:"Understanding area of a triangle",isPurple:!1},{icon:"💎",title:"Multiply two decimals: products up to hundredths",isPurple:!1},{icon:"💎",title:"Division with decimal divisors",isPurple:!1},{icon:"📚",title:"Lesson: Area of triangles",isPurple:!0}];return u.jsx("div",{className:"ixl-work-it-out-grid",children:t.map((e,r)=>u.jsxs("a",{href:"#",className:`ixl-work-it-out-card ${e.isPurple?"ixl-work-it-out-card-purple":""}`,children:[u.jsx("span",{className:`ixl-work-it-out-icon ${e.isPurple?"ixl-work-it-out-icon-purple":""}`,children:e.icon}),u.jsx("span",{className:"ixl-work-it-out-text",children:e.title})]},r))})},hy=({className:t="",problemData:e,children:r})=>{const n=dn(),o=un(),s=fn(),i=gn(),{updateUserAnswer:a,submitAnswer:c,nextQuestion:l,setProblemData:d}=mn();return x.useEffect(()=>{e&&d(e)},[e,d]),(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"ixl-title-color-triangle",label:"三角形面积"};case"parallelogram":return{titleColor:"ixl-title-color-parallelogram",label:"平行四边形面积"};case"trapezoid":return{titleColor:"ixl-title-color-trapezoid",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"ixl-title-color-age",label:"年龄问题"}:{titleColor:"ixl-title-color-default",label:"数学问题"}}})(),u.jsxs("div",{className:`ixl-immersive-container ${t}`,children:[u.jsx("div",{className:"ixl-top-nav",children:u.jsxs("div",{className:"ixl-breadcrumb",children:[u.jsx("span",{className:"ixl-breadcrumb-item",children:"Sixth grade"}),u.jsx("span",{className:"ixl-breadcrumb-separator",children:"›"}),u.jsx("span",{className:"ixl-breadcrumb-item",children:"GG.6 Area of triangles"}),u.jsx("span",{className:"ixl-breadcrumb-tag",children:"C8S"})]})}),u.jsxs("main",{className:"ixl-main-layout",children:[u.jsxs("div",{className:"ixl-content-area",children:[u.jsxs("div",{className:"ixl-main-card",children:[u.jsx(my,{}),u.jsxs("div",{className:"ixl-status-banner",children:[u.jsx("strong",{children:"Parent results not recorded."})," Continue practicing or ",u.jsx("a",{href:"#",className:"ixl-status-link",children:"switch user"}),"."]}),u.jsx("div",{className:"ixl-question-display",children:e?u.jsxs(u.Fragment,{children:[n==="question"&&u.jsx(Mt,{problemData:e,userAnswer:o,showAnswerForm:s,onAnswerSubmit:c,onAnswerChange:a,validationError:i}),n==="explanation"&&u.jsx(Xt,{problemData:e,userAnswer:o,onNextQuestion:l}),n==="success"&&u.jsx(Ot,{problemData:e,onNextQuestion:l})]}):u.jsxs("div",{className:"ixl-no-data-message",children:[u.jsx("div",{className:"ixl-no-data-icon",children:"⚠️"}),u.jsx("h3",{className:"ixl-no-data-title",children:"缺少问题数据"}),u.jsx("p",{className:"ixl-no-data-desc",children:"请提供有效的problemData prop"})]})})]}),u.jsxs("div",{className:"ixl-review-area",children:[u.jsxs("div",{className:"ixl-review-header",children:[u.jsx("h3",{className:"ixl-review-title",children:"Work it out"}),u.jsx("p",{className:"ixl-review-subtitle",children:"Not feeling ready yet? These can help:"})]}),u.jsx(py,{})]})]}),u.jsx("aside",{className:"ixl-dashboard-area",children:u.jsx(gy,{})})]}),r&&u.jsx("div",{className:"ixl-children-area",children:r})]})},yy=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
257
- 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AbilityAssessmentDashboard=Vf;exports.AbilityProgressBar=ta;exports.AreaGeometrySessionPage=fy;exports.AreaGeometrySessionPageIXL=hy;exports.Button=ut;exports.ContentAccordion=Is;exports.DEFAULT_IXL_CONFIG=Mf;exports.DecimalNumberRecognitionSessionPage=Jh;exports.EquationRender=Kt;exports.ExplanationScene=Xt;exports.GEOMETRY_CONFIG=sy;exports.GeometryProblemAdapterV4=Bg;exports.GeometryTransform=ji;exports.GradeNavigation=Ff;exports.GradeUnitBrowserPage=ng;exports.GradeUnitBrowserProvider=ia;exports.GraphContainer=Ki;exports.HundredChart=Ro;exports.IXLStyleCard=Bt;exports.IXL_COLORS=Of;exports.IXL_LABELS=If;exports.InputValidator=ro;exports.MOCK_USER_COURSE_PROGRESS=ol;exports.MOCK_USER_GRADE_UNITS_NAV=dy;exports.MOCK_USER_GRADE_UNITS_PROGRESS=uy;exports.MathCard=yy;exports.MathCardV2=Oe;exports.MathGraph=xr;exports.MathPracticeSessionPage=Yh;exports.MathSessionContainer=Za;exports.MathSessionPage=Ih;exports.MathWizHeader=si;exports.OptionCard=yo;exports.OptionGroup=bo;exports.OutputValidator=no;exports.ParallelogramAreaCalculationSessionPage=vp;exports.PersonalizedAdvicePanel=ra;exports.QuestionScene=Mt;exports.RadarChart=ea;exports.RecommendationCard=na;exports.RememberModule=ca;exports.ReviewModule=ko;exports.SCHEMA_VERSION=Ca;exports.Sidebar=Fs;exports.SolveModule=Mo;exports.StatBlock=ii;exports.Submenu=co;exports.SuccessScene=Ot;exports.Table=Ri;exports.TriangleAreaCalculationSessionPage=_p;exports.UserProfile=oi;exports.VERSION=Hg;exports.ValidationManager=kt;exports.adaptGeometryData=Oo;exports.adaptGeometryDataAsync=Oo;exports.adaptGeometryDataSync=It;exports.adaptGeometryDataV4=It;exports.benchmarkAdapter=zg;exports.calculateBoundingBox=Co;exports.calculateDragRange=Ui;exports.calculateFilledCells=Li;exports.calculateGamePoints=Zh;exports.calculateValueFromDrag=Vi;exports.categoryIcons=cr;exports.checkCompatibility=qg;exports.comparePointArrays=ry;exports.courseData=be;exports.createAsyncAdapter=Ra;exports.createGeometryDataAdapter=Ra;exports.createSyncAdapter=Sa;exports.exploreItems=Wf;exports.formatPercentage=hf;exports.generateCellData=Gi;exports.generateMockUserCourseProgress=nl;exports.getBasicGemDefinitions=oy;exports.getBasicLineDefinitions=ny;exports.getUnitNavItem=ly;exports.getUserCourseProgress=Lo;exports.getUserGradeUnitsNav=Go;exports.getUserLessonProgress=iy;exports.getUserUnitProgress=sl;exports.isGeometryProblem=Wg;exports.isPointInTriangle=ey;exports.isV4Format=Aa;exports.loadGeometryProblemData=_a;exports.loadGeometryProblemDataAsync=_a;exports.loadGeometryProblemDataSync=va;exports.loadGeometryProblemDataV4=va;exports.pointOnLine=We;exports.statusColors=Bf;exports.statusMapping=zf;exports.toPixelCoordinates=Qh;exports.trianglesMatch=ty;exports.updateUnitActiveStatus=cy;exports.updateUserLessonProgress=ay;exports.useAnswerCorrectness=lg;exports.useAnswerFormVisibility=$o;exports.useCurrentScene=Eo;exports.useDataAdapter=zi;exports.useDecimalAnswerFormVisibility=tl;exports.useDecimalCurrentScene=Qa;exports.useDecimalSessionActions=rl;exports.useDecimalUserAnswer=el;exports.useGeometryManagement=Xa;exports.useGradeUnitBrowser=sa;exports.useHundredChartDrag=Di;exports.useHundredChartStore=So;exports.useHundredChartValue=Pi;exports.useIXLStyle=Zi;exports.useMathPracticeSessionStore=xt;exports.useProblemData=cg;exports.useResponsive=Qi;exports.useSessionActions=No;exports.useSessionCalculations=Ka;exports.useSessionEventHandlers=Ja;exports.useSessionStore=ye;exports.useTableCore=Hu;exports.useTableState=Si;exports.useUserAnswer=To;exports.useValidationError=la;exports.userData=Yf;exports.validateGeometryData=Vg;exports.validateValue=Vr;
284
+ The large square represents 1 whole.`},{type:"hundredGrid",content:"",props:{value:.12,mode:"readonly",rows:10,cols:10,cellSize:12,fillColor:"#a5b4fc",baseColor:"#e2e8f0",strokeColor:"#d1d5db",shadingDirection:"ltr",hasShadow:!0}}]}},explanation:[],answer:{value:.12,unit:"",explanation:"模型中100个方格有12个被涂色,代表12/100,即0.12。"}},Xy=({className:t="",problemData:e})=>{const r=bl(),n=xl(),o=wl(),s=Yy(),{updateUserAnswer:i,submitAnswer:a,nextQuestion:c,setProblemData:l}=vl(),u=b.useMemo(()=>e||Ky,[e]);return b.useEffect(()=>{l(u)},[u,l]),d.jsxs("div",{className:`max-w-4xl mx-auto p-4 md:p-8 bg-slate-50 min-h-screen ${t}`,children:[d.jsxs("header",{className:"mb-8",children:[d.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"小数认识练习"}),d.jsxs("p",{className:"text-slate-600 mt-2",children:[u.grade,"年级 - ",u.unit]}),d.jsx("p",{className:"text-slate-500 text-sm mt-1",children:"通过百格图模型理解百分位和小数的关系"})]}),d.jsxs("main",{className:"bg-white border border-slate-200 rounded-lg shadow-sm",children:[r==="question"&&d.jsx(Mt,{problemData:u,userAnswer:n,showAnswerForm:o,onAnswerSubmit:a,onAnswerChange:i,validationError:s}),r==="explanation"&&d.jsx(My,{problemData:u,userAnswer:n,onNextQuestion:c}),r==="success"&&d.jsx(Ot,{problemData:u,onNextQuestion:c})]}),d.jsxs("div",{className:"mt-4 text-center text-sm text-slate-500",children:[r==="question"&&"请识别百格图代表的小数",r==="explanation"&&"查看详细解释",r==="success"&&"恭喜!答案正确"]})]})},Ye=(t,e,r)=>({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r}),Jy=()=>{const t={x:.5,y:.1,name:"A"},e={x:.1,y:.75,name:"B"},r={x:.9,y:.75,name:"C"},n={...Ye(t,e,1/3),name:"D"},o={...Ye(t,r,1/3),name:"E"},s={...Ye(t,e,2/3),name:"M"},i={...Ye(t,r,2/3),name:"N"},a={...Ye(e,r,1/3),name:"P"},c={...Ye(e,r,2/3),name:"Q"},l={...Ye(n,o,1/3),name:"U"},u={...Ye(n,o,2/3),name:"S"},g={...Ye(s,i,1/3),name:"K"},m={...Ye(s,i,2/3),name:"L"};return{A:t,B:e,C:r,D:n,E:o,M:s,N:i,P:a,Q:c,U:l,S:u,K:g,L:m}},Zy=(t,e,r)=>{const n={};for(const[o,s]of Object.entries(t))n[o]={...s,x:s.x*e,y:s.y*r};return n},Qy=(t,e)=>{const[r,n,o]=e,{x:s,y:i}=t,a=(n.y-o.y)*(r.x-o.x)+(o.x-n.x)*(r.y-o.y);if(Math.abs(a)<1e-4)return!1;const c=((n.y-o.y)*(s-o.x)+(o.x-n.x)*(i-o.y))/a,l=((o.y-r.y)*(s-o.x)+(r.x-o.x)*(i-o.y))/a,u=1-c-l;return c>=-.001&&l>=-.001&&u>=-.001},eb=(t,e)=>{if(!t||!e||t.length!==3||e.length!==3)return!1;const r=t.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return r.every((o,s)=>o===n[s])},tb=(t,e)=>{if(!t||!e||t.length!==e.length)return!1;const r=t.map(o=>o.name).sort(),n=e.map(o=>o.name).sort();return r.join("")===n.join("")},rb=()=>[{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"}],nb=()=>[{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"}],ob={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},Cl=(t=Cr.id)=>{const e=we.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),c=o.lessons.map((l,u)=>{const g=Math.min(100,Math.max(0,i-u*10+Math.random()*30));return{lessonId:l.id,status:g>=100?"completed":g>0?"in-progress":"not-started",progressPercentage:Math.round(g),lastAccessed:g>0?new Date(Date.now()-Math.random()*7*24*60*60*1e3).toISOString():void 0,timeSpent:g>0?Math.floor(Math.random()*120+10):void 0,score:g>=100?Math.floor(Math.random()*21+80):void 0,attempts:g>0?Math.floor(Math.random()*3+1):void 0}});return{unitId:o.id,userId:t,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:c}}),r=e.reduce((o,s)=>o+s.progressPercentage,0)/e.length,n=e.filter(o=>o.status==="completed").length;return{courseId:we.id,userId:t,totalUnits:e.length,completedUnits:n,progressPercentage:Math.round(r),status:r>=100?"completed":r>0?"in-progress":"not-started",lastAccessed:new Date(Date.now()-Math.random()*3*24*60*60*1e3).toISOString(),units:e}},Sl=Cl(),Wo=(t,e)=>t===Cr.id&&e===we.id?Sl:null,_l=(t,e,r)=>{const n=Wo(t,e);return n&&n.units.find(o=>o.unitId===r)||null},sb=(t,e,r,n)=>{const o=_l(t,e,r);return o&&o.lessons.find(s=>s.lessonId===n)||null},ib=(t,e,r,n,o)=>(console.log("Updating lesson progress:",{userId:t,courseId:e,unitId:r,lessonId:n,progress:o}),!0),Yo=(t,e)=>{const r=Wo(t,e);if(!r)return null;const n=we.units.map((o,s)=>{const i=r.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-${we.level}/unit/${o.id}`}});return{userId:t,courseId:we.id,courseTitle:we.title,courseLevel:we.level,totalUnits:n.length,completedUnits:n.filter(o=>o.status==="completed").length,overallProgress:r.progressPercentage,status:r.status,lastAccessed:r.lastAccessed,units:n}},ab=(t,e,r)=>{const n=Yo(t,e);return n&&n.units.find(o=>o.unitId===r)||null},lb=(t,e,r,n)=>(console.log("Updating unit active status:",{userId:t,courseId:e,unitId:r,isActive:n}),!0),cb=Yo(Cr.id,we.id),db={userId:Cr.id,courseId:we.id,courseTitle:we.title,courseLevel:we.level,totalUnits:we.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:"📊"}]},fo={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},ub={HINT:"hint",EXPLANATION:"explanation",SOLUTION:"solution",FOLLOW_UP:"follow_up",GENERAL:"general"},fb={PENDING:"pending",UPLOADING:"uploading",SUCCESS:"success",ERROR:"error"},Ko="你好!我是你的数学学习助手。你可以问我任何数学问题,或者上传题目图片让我帮你解答。",Rl="输入消息...",Al=4,El=[{id:"1",label:"怎么解",message:"这道题怎么解?",icon:"HelpCircle"},{id:"2",label:"检查答案",message:"请检查我的答案",icon:"CheckCircle"},{id:"3",label:"类似题目",message:"给我一道类似的题目",icon:"Copy"},{id:"4",label:"知识点",message:"这道题涉及哪些知识点?",icon:"BookOpen"}],gb={inputValue:"",isInputFocused:!1,pendingImages:[],isContextBarCollapsed:!1,isHistoryOpen:!1,abortController:null},Nl=()=>Yt.create((t,e)=>({...gb,setInputValue:r=>{t({inputValue:r})},setInputFocused:r=>{t({isInputFocused:r})},clearInput:()=>{t({inputValue:"",pendingImages:[]})},addPendingImage:r=>{const{pendingImages:n}=e();if(n.length>=4){console.warn("[AICopilot] 最多只能添加4张图片");return}t({pendingImages:[...n,r]})},removePendingImage:r=>{const{pendingImages:n}=e();t({pendingImages:n.filter(o=>o.id!==r)})},clearPendingImages:()=>{t({pendingImages:[]})},updateImageStatus:(r,n)=>{const{pendingImages:o}=e();t({pendingImages:o.map(s=>s.id===r?{...s,status:n}:s)})},toggleContextBar:()=>{const{isContextBarCollapsed:r}=e();t({isContextBarCollapsed:!r})},collapseContextBar:()=>{t({isContextBarCollapsed:!0})},expandContextBar:()=>{t({isContextBarCollapsed:!1})},setHistoryOpen:r=>{t({isHistoryOpen:r})},toggleHistory:()=>{const{isHistoryOpen:r}=e();t({isHistoryOpen:!r})},setAbortController:r=>{t({abortController:r})}})),Ar=Nl(),Tl=()=>Ar(It.useShallow(t=>({inputValue:t.inputValue,isInputFocused:t.isInputFocused,setInputValue:t.setInputValue,setInputFocused:t.setInputFocused,clearInput:t.clearInput}))),$l=()=>Ar(It.useShallow(t=>({pendingImages:t.pendingImages,addPendingImage:t.addPendingImage,removePendingImage:t.removePendingImage,clearPendingImages:t.clearPendingImages,updateImageStatus:t.updateImageStatus}))),kl=()=>Ar(It.useShallow(t=>({isContextBarCollapsed:t.isContextBarCollapsed,isHistoryOpen:t.isHistoryOpen,toggleContextBar:t.toggleContextBar,collapseContextBar:t.collapseContextBar,expandContextBar:t.expandContextBar,setHistoryOpen:t.setHistoryOpen,toggleHistory:t.toggleHistory}))),mb=()=>Ar(It.useShallow(t=>({abortController:t.abortController,setAbortController:t.setAbortController}))),pb=t=>{try{return new Date(t).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}catch{return"未知时间"}},jl=b.memo(({message:t,showProblemTag:e=!1,className:r=""})=>{const n=t.role===fo.USER,o=t.role===fo.ASSISTANT,s=n?"mathwiz-chat-message--user flex-row-reverse":"mathwiz-chat-message--assistant flex-row",i=n?"mathwiz-chat-bubble--user bg-primary-100 text-primary-900":"mathwiz-chat-bubble--assistant bg-default-100 text-default-900",a=n?"用户消息":o?"AI助手消息":"系统消息",c=n?"你":"AI助手",l=n?"primary":"success";return d.jsxs("article",{className:`mathwiz-chat-message flex gap-3 p-4 ${s} ${r}`,"aria-label":a,"data-message-id":t.messageId,"data-role":t.role,children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx(X.Avatar,{size:"sm",color:l,className:"mathwiz-chat-avatar","aria-label":c,children:n?"U":"AI"})}),d.jsxs("div",{className:`flex-1 ${n?"text-right":"text-left"}`,children:[d.jsxs("div",{className:`flex items-center gap-2 mb-1 ${n?"justify-end":"justify-start"}`,children:[d.jsx("span",{className:"text-sm font-medium text-default-700",children:c}),d.jsx("span",{className:"text-xs text-default-400",children:pb(t.timestamp)})]}),e&&t.referencedProblemTitle&&d.jsx("div",{className:`mb-2 ${n?"text-right":"text-left"}`,children:d.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs rounded-full bg-default-200 text-default-600",children:["关联题目: ",t.referencedProblemTitle]})}),d.jsx("div",{className:`inline-block max-w-[80%] px-4 py-2 rounded-2xl text-left ${i}`,children:d.jsx("p",{className:"whitespace-pre-wrap break-words",children:t.content})}),t.images&&t.images.length>0&&d.jsx("div",{className:`flex gap-2 mt-2 flex-wrap ${n?"justify-end":"justify-start"}`,children:t.images.map((u,g)=>d.jsx("div",{className:"mathwiz-chat-image-preview relative w-20 h-20 rounded-lg overflow-hidden border border-default-200",children:d.jsx("img",{src:u.url,alt:`上传图片 ${g+1}`,className:"w-full h-full object-cover",loading:"lazy"})},u.id))})]})]})});jl.displayName="ChatMessage";const hb=()=>d.jsxs("div",{className:"mathwiz-typing-indicator flex items-center gap-1 px-2 py-3","data-testid":"typing-indicator",children:[d.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"0ms"}}),d.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"150ms"}}),d.jsx("span",{className:"w-2 h-2 rounded-full bg-default-400 animate-bounce",style:{animationDelay:"300ms"}})]}),Il=b.memo(({content:t,className:e=""})=>{const r=t&&t.trim().length>0;return d.jsxs("article",{className:`mathwiz-stream-message flex gap-3 p-4 ${e}`,"aria-label":"AI正在输入","aria-live":"polite","aria-busy":"true",children:[d.jsx("div",{className:"flex-shrink-0",children:d.jsx(X.Avatar,{size:"sm",color:"success",className:"mathwiz-chat-avatar","aria-label":"AI助手",children:"AI"})}),d.jsxs("div",{className:"flex-1",children:[d.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[d.jsx("span",{className:"text-sm font-medium text-default-700",children:"AI助手"}),d.jsx("span",{className:"text-xs text-default-400",children:"正在输入..."})]}),d.jsx("div",{className:"inline-block max-w-[80%] px-4 py-2 rounded-2xl bg-default-100 text-default-900",children:r?d.jsx("p",{className:"whitespace-pre-wrap break-words",children:t}):d.jsx(hb,{})}),!r&&d.jsxs("div",{className:"mt-2 space-y-2 max-w-[60%]",children:[d.jsx(X.Skeleton,{className:"h-3 w-full rounded-lg"}),d.jsx(X.Skeleton,{className:"h-3 w-3/4 rounded-lg"})]})]})]})});Il.displayName="StreamMessage";const Ml=b.memo(({welcomeMessage:t=Ko})=>d.jsxs("div",{className:"mathwiz-empty-state flex flex-col items-center justify-center h-full p-8 text-center",children:[d.jsx("div",{className:"w-16 h-16 mb-4 rounded-full bg-primary-100 flex items-center justify-center","data-testid":"empty-state-icon",children:d.jsx(xe.Bot,{size:32,className:"text-primary-600"})}),d.jsx("h3",{className:"text-lg font-semibold text-default-900 mb-2",children:"AI 数学助手"}),d.jsx("p",{className:"text-sm text-default-600 max-w-md",children:t}),d.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-default-400",children:[d.jsx(xe.MessageSquare,{size:14}),d.jsx("span",{children:"开始你的数学学习之旅"})]})]}));Ml.displayName="EmptyState";const Ol=b.memo(({messages:t,isStreaming:e=!1,streamingContent:r="",welcomeMessage:n,className:o=""})=>{const s=t.length>0,i=b.useRef(null);return b.useEffect(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[t,r]),d.jsx(X.ScrollShadow,{hideScrollBar:!0,className:`mathwiz-chat-container flex-1 overflow-y-auto ${o}`,role:"log","aria-label":"消息列表","aria-live":"polite",children:s?d.jsxs("div",{className:"pb-4",children:[t.map((a,c)=>{const l=a.role==="user"&&!!a.referencedProblemTitle&&t.findIndex(u=>u.referencedProblemId===a.referencedProblemId)===c;return d.jsx(jl,{message:a,showProblemTag:l},a.messageId)}),e&&d.jsx(Il,{content:r}),d.jsx("div",{ref:i})]}):d.jsx(Ml,{welcomeMessage:n})})});Ol.displayName="ChatContainer";const Fl=b.memo(({value:t,onChange:e,onSend:r,onAbort:n,isStreaming:o=!1,pendingImages:s,onImageAdd:i,onImageRemove:a,onImageUpload:c,placeholder:l="输入消息...",maxImages:u=4,disabled:g=!1,className:m=""})=>{const f=b.useRef(null),p=t.trim().length>0||s.length>0,h=s.length>=u,y=b.useCallback(async w=>{const S=w.target.files?.[0];if(S){if(c)try{const C=await c(S);i(C)}catch(C){console.error("图片上传失败:",C)}else{const C=URL.createObjectURL(S);i({id:`local_${Date.now()}`,url:C,file:S,status:"pending"})}f.current&&(f.current.value="")}},[i,c]),x=b.useCallback(w=>{w.key==="Enter"&&!w.shiftKey&&(w.preventDefault(),p&&!g&&!o&&r())},[p,g,o,r]),v=b.useCallback(()=>{o&&n?n():p&&!g&&r()},[o,p,g,n,r]);return d.jsxs("div",{className:`mathwiz-chat-input bg-background border-t border-default-200 ${m}`,children:[s.length>0&&d.jsx("div",{className:"flex gap-2 p-3 overflow-x-auto",children:s.map((w,S)=>d.jsxs("div",{className:"mathwiz-pending-image relative flex-shrink-0 w-16 h-16 rounded-lg overflow-hidden border border-default-200",children:[d.jsx("img",{src:w.url,alt:`待发送图片 ${S+1}`,className:"w-full h-full object-cover"}),d.jsx("button",{onClick:()=>a(w.id),className:"absolute top-0.5 right-0.5 p-0.5 bg-default-900/50 hover:bg-default-900/70 rounded-full text-white transition-colors","aria-label":"移除图片",children:d.jsx(xe.X,{size:12})})]},w.id))}),d.jsxs("div",{className:"flex items-end gap-2 p-3",children:[d.jsx(X.Tooltip,{content:h?`最多${u}张图片`:"上传图片",children:d.jsx(X.Button,{isIconOnly:!0,variant:"light",size:"sm",isDisabled:h||g||o,onPress:()=>f.current?.click(),"aria-label":"上传图片",children:d.jsx(xe.ImagePlus,{size:20})})}),d.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:y,"aria-hidden":"true"}),d.jsx(X.Textarea,{value:t,onChange:w=>e(w.target.value),onKeyDown:x,placeholder:l,minRows:1,maxRows:4,isDisabled:g,className:"flex-1",classNames:{input:"min-h-[40px] py-2"}}),o?d.jsx(X.Button,{isIconOnly:!0,color:"danger",variant:"solid",size:"sm",onPress:v,"aria-label":"停止生成",children:d.jsx(xe.Square,{size:18,fill:"currentColor"})}):d.jsx(X.Button,{isIconOnly:!0,color:"primary",variant:"solid",size:"sm",isDisabled:!p||g,onPress:v,"aria-label":"发送消息",children:d.jsx(xe.Send,{size:18})})]})]})});Fl.displayName="ChatInput";const yb=t=>{const e={size:16,className:"mr-1"};switch(t.icon){case"HelpCircle":return d.jsx(xe.HelpCircle,{...e});case"CheckCircle":return d.jsx(xe.CheckCircle,{...e});case"Copy":return d.jsx(xe.Copy,{...e});case"BookOpen":return d.jsx(xe.BookOpen,{...e});default:return d.jsx(xe.Sparkles,{...e})}},Pl=b.memo(({actions:t,onActionClick:e,className:r=""})=>!t||t.length===0?null:d.jsx(X.ScrollShadow,{orientation:"horizontal",hideScrollBar:!0,className:`mathwiz-quick-actions w-full ${r}`,role:"region","aria-label":"快捷操作",children:d.jsx("div",{className:"flex gap-2 px-4 py-2",children:t.map(n=>d.jsx(X.Button,{variant:"flat",size:"sm",className:"mathwiz-quick-action-btn flex-shrink-0",startContent:yb(n),onPress:()=>e(n),"aria-label":n.label,children:n.label},n.id))})}));Pl.displayName="QuickActions";const Dl=b.memo(({difficulty:t})=>{const e=Array.from({length:5},(r,n)=>n<t);return d.jsx("div",{className:"flex gap-0.5","aria-label":`难度等级: ${t}/5`,children:e.map((r,n)=>d.jsx(xe.Star,{size:14,"data-testid":"difficulty-star",className:r?"text-warning fill-warning":"text-default-300"},n))})});Dl.displayName="DifficultyStars";const Ll=b.memo(({problemContext:t,isCollapsed:e,onToggle:r,onChangeProblem:n,className:o=""})=>{const{title:s,difficulty:i,knowledgePoints:a}=t;return d.jsx(X.Card,{className:`mathwiz-context-bar mx-4 mb-4 ${o}`,role:"region","aria-label":"当前题目上下文",children:d.jsxs(X.CardBody,{className:"p-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(xe.BookOpen,{size:18,className:"text-primary"}),d.jsx("h3",{className:"font-medium text-default-900",children:s})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[n&&d.jsx(X.Tooltip,{content:"更换题目",children:d.jsx(X.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:n,"aria-label":"更换题目",children:d.jsx(xe.RefreshCw,{size:16})})}),d.jsx(X.Tooltip,{content:e?"展开":"折叠",children:d.jsx(X.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:r,"aria-label":e?"展开":"折叠",children:e?d.jsx(xe.ChevronDown,{size:16}):d.jsx(xe.ChevronUp,{size:16})})})]})]}),!e&&d.jsxs("div",{className:"mt-3 pt-3 border-t border-default-200",children:[d.jsx("div",{className:"flex items-center gap-4",children:d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-xs text-default-500",children:"难度:"}),d.jsx(Dl,{difficulty:i})]})}),a.length>0&&d.jsxs("div",{className:"mt-2 flex items-center gap-2 flex-wrap",children:[d.jsx("span",{className:"text-xs text-default-500",children:"知识点:"}),a.map(c=>d.jsx(X.Chip,{size:"sm",variant:"flat",color:"primary",children:c.name},c.id))]})]})]})})});Ll.displayName="CollapsibleContextBar";const Gl=b.memo(({onLoadHistory:t,onNewSession:e})=>d.jsxs(X.Navbar,{className:"mathwiz-copilot-header border-b border-default-200",shouldHideOnScroll:!1,children:[d.jsx(X.NavbarContent,{justify:"start",children:d.jsx(X.NavbarItem,{children:d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(xe.MessageSquare,{className:"text-primary",size:24}),d.jsx("span",{className:"font-bold text-lg",children:"AI 数学助手"})]})})}),d.jsxs(X.NavbarContent,{justify:"end",children:[e&&d.jsx(X.NavbarItem,{children:d.jsx(X.Tooltip,{content:"新建会话",children:d.jsx(X.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:e,"aria-label":"新建会话",children:d.jsx(xe.Plus,{size:20})})})}),t&&d.jsx(X.NavbarItem,{children:d.jsx(X.Tooltip,{content:"历史记录",children:d.jsx(X.Button,{isIconOnly:!0,variant:"light",size:"sm",onPress:t,"aria-label":"历史记录",children:d.jsx(xe.History,{size:20})})})})]})]}));Gl.displayName="Header";const Vl=b.memo(({messages:t,problemContext:e,isStreaming:r=!1,streamingContent:n="",onSendMessage:o,onAbortStreaming:s,onLoadHistory:i,onNewSession:a,onChangeProblem:c,onImageUpload:l,quickActions:u=El,welcomeMessage:g=Ko,placeholder:m=Rl,maxImages:f=Al,className:p=""})=>{const{inputValue:h,setInputValue:y,clearInput:x}=Tl(),{pendingImages:v,addPendingImage:w,removePendingImage:S}=$l(),{isContextBarCollapsed:C,toggleContextBar:E}=kl(),_=b.useCallback(()=>{!h.trim()&&v.length===0||(o(h,{problemId:e?.problemId,images:v.length>0?v:void 0}),x())},[h,v,e?.problemId,o,x]),A=b.useCallback(T=>{o(T.message,{problemId:e?.problemId})},[o,e?.problemId]);return d.jsxs("div",{className:`mathwiz-copilot flex flex-col h-full bg-background ${p}`,role:"main","aria-label":"AI数学助手",children:[d.jsx(Gl,{onLoadHistory:i,onNewSession:a}),e&&d.jsx(Ll,{problemContext:e,isCollapsed:C,onToggle:E,onChangeProblem:c}),d.jsx(Ol,{messages:t,isStreaming:r,streamingContent:n,welcomeMessage:g}),d.jsx(Pl,{actions:u,onActionClick:A}),d.jsx(Fl,{value:h,onChange:y,onSend:_,onAbort:s,isStreaming:r,pendingImages:v,onImageAdd:w,onImageRemove:S,onImageUpload:l,placeholder:m,maxImages:f})]})});Vl.displayName="AICopilot";const bb={CORRECT:"correct",INCORRECT:"incorrect",IDLE:"idle"},xb={LABEL:"label",INPUT:"input",RESULT:"result",PLACEHOLDER:"placeholder"},wb=({className:t="",problemData:e,children:r})=>{const n=mn(),o=pn(),s=hn(),i=yn(),{updateUserAnswer:a,submitAnswer:c,nextQuestion:l,setProblemData:u}=bn();b.useEffect(()=>{e&&u(e)},[e,u]);const m=(()=>{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 d.jsxs("div",{className:`bg-gradient-to-br from-slate-50 to-cyan-50 flex flex-col items-center p-4 font-sans ${t}`,children:[d.jsxs("header",{className:"w-full max-w-4xl mb-8",children:[d.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between",children:[d.jsxs("div",{children:[d.jsx("h1",{className:`text-2xl md:text-3xl font-bold ${m.titleColor}`,children:e?.title||"数学问题练习"}),d.jsxs("p",{className:"text-slate-600 mt-2",children:[e?.grade||5,"年级 · ",e?.unit||"数学",e?.lesson&&` · ${e.lesson}`]})]}),d.jsx("div",{className:"mt-4 md:mt-0",children:d.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:m.label})})]}),e?.description&&d.jsx("p",{className:"mt-4 text-slate-700 bg-white/50 p-3 rounded-lg border border-slate-200",children:e.description})]}),d.jsx("main",{className:"w-full max-w-4xl bg-white border border-slate-200 rounded-xl shadow-sm",children:e?d.jsxs(d.Fragment,{children:[n==="question"&&d.jsx(Mt,{problemData:e,userAnswer:o,showAnswerForm:s,onAnswerSubmit:c,onAnswerChange:a,validationError:i}),n==="explanation"&&d.jsx(Qt,{problemData:e,userAnswer:o,onNextQuestion:l}),n==="success"&&d.jsx(Ot,{problemData:e,onNextQuestion:l})]}):d.jsxs("div",{className:"p-8 text-center",children:[d.jsx("div",{className:"text-red-500 text-4xl mb-4",children:"⚠️"}),d.jsx("h3",{className:"text-xl font-semibold text-slate-800 mb-2",children:"缺少问题数据"}),d.jsx("p",{className:"text-slate-600",children:"请提供有效的problemData prop"})]})}),d.jsx("footer",{className:"w-full max-w-4xl mt-8 text-center text-slate-500 text-sm",children:d.jsxs("div",{className:"flex flex-col md:flex-row md:justify-between items-center",children:[d.jsx("div",{className:"mb-4 md:mb-0",children:d.jsx("p",{children:"使用MathCardV2组件系统 · 三场景交互设计"})}),d.jsx("div",{children:d.jsxs("p",{children:["数据源: ",e?.id||"未知"]})})]})}),r&&d.jsx("div",{className:"w-full max-w-4xl mt-8",children:r})]})},vb=()=>d.jsxs("div",{className:"ixl-dashboard-panels",children:[d.jsxs("div",{className:"ixl-dashboard-card ixl-questions-card",children:[d.jsxs("div",{className:"ixl-dashboard-card-header",children:["Questions",d.jsx("br",{}),"answered"]}),d.jsx("div",{className:"ixl-dashboard-card-body",children:d.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),d.jsxs("div",{className:"ixl-dashboard-card ixl-time-card",children:[d.jsxs("div",{className:"ixl-dashboard-card-header",children:["Time",d.jsx("br",{}),"elapsed"]}),d.jsx("div",{className:"ixl-dashboard-card-body",children:d.jsxs("div",{className:"ixl-time-display",children:[d.jsxs("div",{className:"ixl-time-unit",children:[d.jsx("div",{className:"ixl-time-value",children:"00"}),d.jsx("div",{className:"ixl-time-label",children:"hr"})]}),d.jsx("div",{className:"ixl-time-separator",children:":"}),d.jsxs("div",{className:"ixl-time-unit",children:[d.jsx("div",{className:"ixl-time-value",children:"00"}),d.jsx("div",{className:"ixl-time-label",children:"min"})]}),d.jsx("div",{className:"ixl-time-separator",children:":"}),d.jsxs("div",{className:"ixl-time-unit",children:[d.jsx("div",{className:"ixl-time-value",children:"06"}),d.jsx("div",{className:"ixl-time-label",children:"sec"})]})]})})]}),d.jsxs("div",{className:"ixl-dashboard-card ixl-score-card",children:[d.jsxs("div",{className:"ixl-dashboard-card-header",children:["SmartScore",d.jsx("span",{className:"ixl-score-subtitle",children:"out of 100"}),d.jsx("span",{className:"ixl-help-icon",title:"What is this?",children:"?"})]}),d.jsx("div",{className:"ixl-dashboard-card-body",children:d.jsx("div",{className:"ixl-dashboard-value",children:"0"})})]}),d.jsx("p",{className:"ixl-dashboard-note",children:"*在实际业务项目中集成StatBlock组件显示实时数据"})]}),Cb=()=>d.jsxs("div",{className:"ixl-scaffolding-links",children:[d.jsxs("button",{className:"ixl-scaffolding-link",children:[d.jsx("svg",{className:"ixl-scaffolding-icon",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:d.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),d.jsx("span",{children:"Learn with an example"})]}),d.jsx("span",{className:"ixl-scaffolding-separator",children:"or"}),d.jsxs("button",{className:"ixl-scaffolding-link",children:[d.jsx("svg",{className:"ixl-scaffolding-icon",fill:"currentColor",viewBox:"0 0 20 20",children:d.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"})}),d.jsx("span",{children:"Watch a video"})]})]}),Sb=()=>{const t=[{icon:"💎",title:"Understanding area of a triangle",isPurple:!1},{icon:"💎",title:"Multiply two decimals: products up to hundredths",isPurple:!1},{icon:"💎",title:"Division with decimal divisors",isPurple:!1},{icon:"📚",title:"Lesson: Area of triangles",isPurple:!0}];return d.jsx("div",{className:"ixl-work-it-out-grid",children:t.map((e,r)=>d.jsxs("a",{href:"#",className:`ixl-work-it-out-card ${e.isPurple?"ixl-work-it-out-card-purple":""}`,children:[d.jsx("span",{className:`ixl-work-it-out-icon ${e.isPurple?"ixl-work-it-out-icon-purple":""}`,children:e.icon}),d.jsx("span",{className:"ixl-work-it-out-text",children:e.title})]},r))})},_b=({className:t="",problemData:e,children:r})=>{const n=mn(),o=pn(),s=hn(),i=yn(),{updateUserAnswer:a,submitAnswer:c,nextQuestion:l,setProblemData:u}=bn();return b.useEffect(()=>{e&&u(e)},[e,u]),(()=>{switch(e?.basicInfo?.shape){case"triangle":return{titleColor:"ixl-title-color-triangle",label:"三角形面积"};case"parallelogram":return{titleColor:"ixl-title-color-parallelogram",label:"平行四边形面积"};case"trapezoid":return{titleColor:"ixl-title-color-trapezoid",label:"梯形面积"};default:return e?.title?.includes("年龄")||e?.basicInfo?.question?.includes("年龄")?{titleColor:"ixl-title-color-age",label:"年龄问题"}:{titleColor:"ixl-title-color-default",label:"数学问题"}}})(),d.jsxs("div",{className:`ixl-immersive-container ${t}`,children:[d.jsx("div",{className:"ixl-top-nav",children:d.jsxs("div",{className:"ixl-breadcrumb",children:[d.jsx("span",{className:"ixl-breadcrumb-item",children:"Sixth grade"}),d.jsx("span",{className:"ixl-breadcrumb-separator",children:"›"}),d.jsx("span",{className:"ixl-breadcrumb-item",children:"GG.6 Area of triangles"}),d.jsx("span",{className:"ixl-breadcrumb-tag",children:"C8S"})]})}),d.jsxs("main",{className:"ixl-main-layout",children:[d.jsxs("div",{className:"ixl-content-area",children:[d.jsxs("div",{className:"ixl-main-card",children:[d.jsx(Cb,{}),d.jsxs("div",{className:"ixl-status-banner",children:[d.jsx("strong",{children:"Parent results not recorded."})," Continue practicing or ",d.jsx("a",{href:"#",className:"ixl-status-link",children:"switch user"}),"."]}),d.jsx("div",{className:"ixl-question-display",children:e?d.jsxs(d.Fragment,{children:[n==="question"&&d.jsx(Mt,{problemData:e,userAnswer:o,showAnswerForm:s,onAnswerSubmit:c,onAnswerChange:a,validationError:i}),n==="explanation"&&d.jsx(Qt,{problemData:e,userAnswer:o,onNextQuestion:l}),n==="success"&&d.jsx(Ot,{problemData:e,onNextQuestion:l})]}):d.jsxs("div",{className:"ixl-no-data-message",children:[d.jsx("div",{className:"ixl-no-data-icon",children:"⚠️"}),d.jsx("h3",{className:"ixl-no-data-title",children:"缺少问题数据"}),d.jsx("p",{className:"ixl-no-data-desc",children:"请提供有效的problemData prop"})]})})]}),d.jsxs("div",{className:"ixl-review-area",children:[d.jsxs("div",{className:"ixl-review-header",children:[d.jsx("h3",{className:"ixl-review-title",children:"Work it out"}),d.jsx("p",{className:"ixl-review-subtitle",children:"Not feeling ready yet? These can help:"})]}),d.jsx(Sb,{})]})]}),d.jsx("aside",{className:"ixl-dashboard-area",children:d.jsx(vb,{})})]}),r&&d.jsx("div",{className:"ixl-children-area",children:r})]})},Rb=new Proxy({},{get(){throw new Error(`⚠️ MathCard 已废弃!请使用 MathCardV2 代替。
285
+ 更改: import { MathCard } from '@mathwiz/ui-components' → import { MathCardV2 as MathCard } from '@mathwiz/ui-components'`)}});exports.AICopilot=Vl;exports.AbilityAssessmentDashboard=Vg;exports.AbilityProgressBar=wa;exports.AnswerStatusConst=mg;exports.AreaGeometrySessionPage=wb;exports.AreaGeometrySessionPageIXL=_b;exports.Button=ft;exports.ContentAccordion=Hs;exports.DEFAULT_IXL_CONFIG=kg;exports.DEFAULT_MAX_IMAGES=Al;exports.DEFAULT_PLACEHOLDER=Rl;exports.DEFAULT_QUICK_ACTIONS=El;exports.DEFAULT_WELCOME_MESSAGE=Ko;exports.DecimalNumberRecognitionSessionPage=Xy;exports.EquationRender=Zt;exports.ExplanationScene=Qt;exports.FactorTable=$o;exports.GEOMETRY_CONFIG=ob;exports.GeometryProblemAdapterV4=Um;exports.GeometryTransform=qi;exports.GradeNavigation=Mg;exports.GradeUnitBrowserPage=rm;exports.GradeUnitBrowserProvider=Ra;exports.GraphContainer=sa;exports.HundredChart=Eo;exports.IXLStyleCard=qt;exports.IXL_COLORS=jg;exports.IXL_LABELS=Ig;exports.ImageStatusConst=fb;exports.InputValidator=so;exports.IntentTypeConst=ub;exports.LongDivision=Mo;exports.MOCK_USER_COURSE_PROGRESS=Sl;exports.MOCK_USER_GRADE_UNITS_NAV=cb;exports.MOCK_USER_GRADE_UNITS_PROGRESS=db;exports.MathCard=Rb;exports.MathCardV2=Oe;exports.MathCell=Io;exports.MathCellStatusConst=bb;exports.MathCellTypeConst=xb;exports.MathContainerModeConst=gg;exports.MathContainerTypeConst=fg;exports.MathGraph=vr;exports.MathPracticeSessionPage=Wy;exports.MathSessionContainer=yl;exports.MathSessionPage=Iy;exports.MathWizHeader=hi;exports.MessageRoleConst=fo;exports.OptionCard=wo;exports.OptionGroup=vo;exports.OutputValidator=io;exports.ParallelogramAreaCalculationSessionPage=wh;exports.PersonalizedAdvicePanel=va;exports.QuestionScene=Mt;exports.RadarChart=xa;exports.RecommendationCard=Ca;exports.RememberModule=Na;exports.ReviewModule=Lo;exports.SCHEMA_VERSION=Ba;exports.ShortDivision=ko;exports.Sidebar=qs;exports.SolveModule=Go;exports.StatBlock=yi;exports.Submenu=go;exports.SuccessScene=Ot;exports.Table=Mi;exports.TriangleAreaCalculationSessionPage=vh;exports.UserProfile=pi;exports.VERSION=Bm;exports.ValidationManager=jt;exports.VerticalMultiplication=jo;exports.adaptGeometryData=Vo;exports.adaptGeometryDataAsync=Vo;exports.adaptGeometryDataSync=Ft;exports.adaptGeometryDataV4=Ft;exports.benchmarkAdapter=zm;exports.calculateBoundingBox=No;exports.calculateDragRange=Ji;exports.calculateFilledCells=Ki;exports.calculateGamePoints=Jy;exports.calculateValueFromDrag=Zi;exports.categoryIcons=fr;exports.checkCompatibility=Hm;exports.comparePointArrays=tb;exports.courseData=we;exports.createAICopilotStore=Nl;exports.createAsyncAdapter=Ua;exports.createGeometryDataAdapter=Ua;exports.createSyncAdapter=za;exports.exploreItems=qg;exports.formatPercentage=Zf;exports.generateCellData=Xi;exports.generateMockUserCourseProgress=Cl;exports.getBasicGemDefinitions=nb;exports.getBasicLineDefinitions=rb;exports.getUnitNavItem=ab;exports.getUserCourseProgress=Wo;exports.getUserGradeUnitsNav=Yo;exports.getUserLessonProgress=sb;exports.getUserUnitProgress=_l;exports.isGeometryProblem=qm;exports.isPointInTriangle=Qy;exports.isV4Format=Ha;exports.loadGeometryProblemData=Va;exports.loadGeometryProblemDataAsync=Va;exports.loadGeometryProblemDataSync=Ga;exports.loadGeometryProblemDataV4=Ga;exports.pointOnLine=Ye;exports.statusColors=Ug;exports.statusMapping=zg;exports.toPixelCoordinates=Zy;exports.trianglesMatch=eb;exports.updateUnitActiveStatus=lb;exports.updateUserLessonProgress=ib;exports.useAICopilotStore=Ar;exports.useAbortController=mb;exports.useAnswerCorrectness=am;exports.useAnswerFormVisibility=Po;exports.useCurrentScene=Oo;exports.useDataAdapter=Qi;exports.useDecimalAnswerFormVisibility=wl;exports.useDecimalCurrentScene=bl;exports.useDecimalSessionActions=vl;exports.useDecimalUserAnswer=xl;exports.useFactorTable=aa;exports.useGeometryManagement=pl;exports.useGradeUnitBrowser=_a;exports.useHundredChartDrag=Yi;exports.useHundredChartStore=Ao;exports.useHundredChartValue=Wi;exports.useIXLStyle=ya;exports.useImageState=$l;exports.useInputState=Tl;exports.useLongDivision=da;exports.useMathPracticeSessionStore=wt;exports.usePanelState=kl;exports.useProblemData=lm;exports.useResponsive=ba;exports.useSessionActions=Do;exports.useSessionCalculations=ml;exports.useSessionEventHandlers=hl;exports.useSessionStore=be;exports.useShortDivision=la;exports.useTableCore=Nf;exports.useTableState=Ii;exports.useUserAnswer=Fo;exports.useValidationError=Ea;exports.useVerticalMultiplication=ca;exports.userData=Wg;exports.validateGeometryData=Vm;exports.validateValue=Hr;
258
286
  //# sourceMappingURL=index.cjs.map