semiotic 3.8.6 → 3.8.7

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 (213) hide show
  1. package/CLAUDE.md +33 -7
  2. package/README.md +82 -55
  3. package/ai/behaviorContracts.cjs +86 -1
  4. package/ai/componentMetadata.cjs +4 -9
  5. package/ai/dist/mcp-server.js +97 -10
  6. package/ai/examples.md +154 -7
  7. package/ai/schema.json +1611 -145
  8. package/ai/surface-manifest.json +12 -10
  9. package/ai/system-prompt.md +9 -3
  10. package/dist/{chunk-chartContainerDataAudit-FEOD5GTQ.module.min.js → chunk-chartContainerDataAudit-JDSVSKGM.module.min.js} +1 -1
  11. package/dist/chunk-chunk-2YAZHXL4.module.min.js +2 -0
  12. package/dist/{chunk-chunk-G7WFWHAD.module.min.js → chunk-chunk-4ITOQRXM.module.min.js} +1 -1
  13. package/dist/chunk-chunk-5SD6BHVW.module.min.js +2 -0
  14. package/dist/chunk-chunk-6V5VQVCT.module.min.js +2 -0
  15. package/dist/chunk-chunk-7TTBHSAG.module.min.js +2 -0
  16. package/dist/chunk-chunk-7ZDJSYKI.module.min.js +2 -0
  17. package/dist/chunk-chunk-BGHPD3RA.module.min.js +1 -0
  18. package/dist/chunk-chunk-BMRZ2SPU.module.min.js +2 -0
  19. package/dist/chunk-chunk-BNGBEY7N.module.min.js +2 -0
  20. package/dist/chunk-chunk-C7APLVQD.module.min.js +2 -0
  21. package/dist/chunk-chunk-DGWFBOGB.module.min.js +1 -0
  22. package/dist/{chunk-chunk-Q2BS46W2.module.min.js → chunk-chunk-DIVE2DRA.module.min.js} +1 -1
  23. package/dist/chunk-chunk-FBUNUIPV.module.min.js +2 -0
  24. package/dist/chunk-chunk-FQPKOAIH.module.min.js +2 -0
  25. package/dist/chunk-chunk-FRO4TRXK.module.min.js +2 -0
  26. package/dist/chunk-chunk-G7QVPZUD.module.min.js +2 -0
  27. package/dist/chunk-chunk-GBPYV4FP.module.min.js +2 -0
  28. package/dist/chunk-chunk-GU2EJIDJ.module.min.js +2 -0
  29. package/dist/chunk-chunk-J5QD4RAM.module.min.js +2 -0
  30. package/dist/{chunk-chunk-RA7JCG7D.module.min.js → chunk-chunk-JWXLNZSM.module.min.js} +1 -1
  31. package/dist/chunk-chunk-KXAFCCDB.module.min.js +2 -0
  32. package/dist/chunk-chunk-LG7YKJAK.module.min.js +2 -0
  33. package/dist/{chunk-chunk-XP3OHHFX.module.min.js → chunk-chunk-LVHDZAT3.module.min.js} +1 -1
  34. package/dist/chunk-chunk-LWITSR2O.module.min.js +2 -0
  35. package/dist/{chunk-chunk-SMVD3EQJ.module.min.js → chunk-chunk-MX35T6RX.module.min.js} +1 -1
  36. package/dist/chunk-chunk-NH4MEAKP.module.min.js +2 -0
  37. package/dist/chunk-chunk-NJETWX42.module.min.js +2 -0
  38. package/dist/chunk-chunk-NW25WGLS.module.min.js +2 -0
  39. package/dist/{chunk-chunk-GFTVACTO.module.min.js → chunk-chunk-OI7R7EJB.module.min.js} +1 -1
  40. package/dist/{chunk-chunk-OM6NWS4H.module.min.js → chunk-chunk-ONMLEXHR.module.min.js} +1 -1
  41. package/dist/chunk-chunk-OY66GCE6.module.min.js +1 -0
  42. package/dist/chunk-chunk-PZFT457G.module.min.js +1 -0
  43. package/dist/chunk-chunk-Q3WW6JGR.module.min.js +1 -0
  44. package/dist/chunk-chunk-Q6XKQTOQ.module.min.js +1 -0
  45. package/dist/chunk-chunk-RJRM2E6P.module.min.js +1 -0
  46. package/dist/chunk-chunk-RPL7WYXI.module.min.js +1 -0
  47. package/dist/chunk-chunk-SV4XAZ3Q.module.min.js +1 -0
  48. package/dist/chunk-chunk-TSCFL235.module.min.js +1 -0
  49. package/dist/chunk-chunk-UOQRPGPK.module.min.js +2 -0
  50. package/dist/chunk-chunk-V3OAKG32.module.min.js +1 -0
  51. package/dist/chunk-chunk-WLOIUMWG.module.min.js +2 -0
  52. package/dist/chunk-chunk-XEGXX4F7.module.min.js +1 -0
  53. package/dist/chunk-chunk-XFRBLXYM.module.min.js +1 -0
  54. package/dist/chunk-chunk-Z2AJERX5.module.min.js +2 -0
  55. package/dist/chunk-chunk-ZXYDYAB7.module.min.js +2 -0
  56. package/dist/components/ai/SemioticVACPBridge.d.ts +22 -0
  57. package/dist/components/ai/chartCapabilities.d.ts +4 -3
  58. package/dist/components/ai/conversationArc.d.ts +2 -176
  59. package/dist/components/ai/conversationArcTypes.d.ts +202 -0
  60. package/dist/components/ai/readerGrounding.d.ts +12 -0
  61. package/dist/components/ai/vacpAdapter.d.ts +13 -0
  62. package/dist/components/ai/vacpAdapterActions.d.ts +2 -0
  63. package/dist/components/ai/vacpAdapterModel.d.ts +7 -0
  64. package/dist/components/ai/vacpAdapterRuntime.d.ts +26 -0
  65. package/dist/components/ai/vacpAdapterState.d.ts +3 -0
  66. package/dist/components/ai/vacpAdapterTypes.d.ts +169 -0
  67. package/dist/components/ai/vacpTypes.d.ts +160 -0
  68. package/dist/components/charts/index.d.ts +4 -4
  69. package/dist/components/charts/physics/ChainReactionChart.capability.d.ts +9 -0
  70. package/dist/components/charts/physics/ChainReactionChart.d.ts +29 -0
  71. package/dist/components/charts/physics/CollisionSwarmChart.d.ts +1 -1
  72. package/dist/components/charts/physics/EventDropChart.d.ts +7 -2
  73. package/dist/components/charts/physics/GaltonBoardChart.d.ts +1 -1
  74. package/dist/components/charts/physics/{PhysicsPileChart.capability.d.ts → PacketFlowChart.capability.d.ts} +1 -1
  75. package/dist/components/charts/physics/{PhysicalFlowChart.d.ts → PacketFlowChart.d.ts} +22 -6
  76. package/dist/components/charts/physics/PhysicsCustomChart.d.ts +1 -1
  77. package/dist/components/charts/physics/ProcessFlowChart.d.ts +7 -4
  78. package/dist/components/charts/physics/{PhysicalFlowChart.capability.d.ts → UnitPileChart.capability.d.ts} +1 -1
  79. package/dist/components/charts/physics/{PhysicsPileChart.d.ts → UnitPileChart.d.ts} +19 -6
  80. package/dist/components/charts/physics/crucibleChartProps.d.ts +1 -1
  81. package/dist/components/charts/physics/crucibleChartUtils.d.ts +9 -0
  82. package/dist/components/charts/physics/gauntletChartProps.d.ts +6 -1
  83. package/dist/components/charts/physics/gauntletTerminal.d.ts +61 -0
  84. package/dist/components/charts/physics/packetFlowSemantics.d.ts +6 -0
  85. package/dist/components/charts/physics/physicsHocUtils.d.ts +45 -2
  86. package/dist/components/charts/shared/auditAccessibilityStyles.d.ts +9 -0
  87. package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
  88. package/dist/components/charts/shared/useChartLegend.d.ts +8 -1
  89. package/dist/components/charts/shared/useChartSetup.d.ts +7 -0
  90. package/dist/components/data/portability/capabilityBinding.d.ts +41 -0
  91. package/dist/components/data/portability/index.d.ts +2 -0
  92. package/dist/components/legendLayout.d.ts +56 -0
  93. package/dist/components/recipes/geographicDotGrid.d.ts +82 -0
  94. package/dist/components/recipes/geographicGrid.d.ts +100 -0
  95. package/dist/components/recipes/physics.d.ts +2 -0
  96. package/dist/components/recipes/physicsStageGeography.d.ts +137 -0
  97. package/dist/components/semiotic-ai.d.ts +4 -3
  98. package/dist/components/semiotic-experimental-vacp.d.ts +11 -0
  99. package/dist/components/semiotic-experimental.d.ts +6 -3
  100. package/dist/components/semiotic-geo.d.ts +4 -0
  101. package/dist/components/semiotic-physics.d.ts +9 -6
  102. package/dist/components/semiotic-recipes-core.d.ts +6 -1
  103. package/dist/components/server/renderEvidence.d.ts +1 -1
  104. package/dist/components/server/renderToStaticSVG.d.ts +2 -1
  105. package/dist/components/server/serverChartConfigHeatmap.d.ts +6 -0
  106. package/dist/components/server/serverChartConfigNetworkStyles.d.ts +12 -0
  107. package/dist/components/server/serverChartConfigShared.d.ts +16 -0
  108. package/dist/components/server/serverChartConfigs.d.ts +2 -2
  109. package/dist/components/server/serverChartConfigsPhysics.d.ts +2 -2
  110. package/dist/components/server/serverChartConfigsXY.d.ts +0 -1
  111. package/dist/components/server/staticLegend.d.ts +6 -0
  112. package/dist/components/server/staticSVGChrome.d.ts +10 -2
  113. package/dist/components/server/staticValue.d.ts +8 -0
  114. package/dist/components/stream/geoPipelineConfig.d.ts +10 -0
  115. package/dist/components/stream/legendRenderer.d.ts +8 -0
  116. package/dist/components/stream/physics/PhysicsEvidence.d.ts +37 -0
  117. package/dist/components/stream/physics/PhysicsPipelineStore.d.ts +9 -0
  118. package/dist/components/stream/physics/PhysicsSettledScene.d.ts +5 -0
  119. package/dist/components/stream/physics/physicsFramePipelineConfig.d.ts +19 -0
  120. package/dist/components/stream/physics/physicsPipelineSettle.d.ts +52 -0
  121. package/dist/components/stream/physics/physicsRegionRuntime.d.ts +23 -0
  122. package/dist/components/stream/types.d.ts +2 -0
  123. package/dist/components/types/legendTypes.d.ts +17 -1
  124. package/dist/controls.min.js +1 -1
  125. package/dist/controls.module.min.js +1 -1
  126. package/dist/geo.min.js +1 -1
  127. package/dist/geo.module.min.js +1 -1
  128. package/dist/network.min.js +1 -1
  129. package/dist/network.module.min.js +1 -1
  130. package/dist/ordinal.min.js +1 -1
  131. package/dist/ordinal.module.min.js +1 -1
  132. package/dist/physics.min.js +1 -1
  133. package/dist/physics.module.min.js +1 -1
  134. package/dist/physicsWorker.js +1 -1
  135. package/dist/realtime.min.js +1 -1
  136. package/dist/realtime.module.min.js +1 -1
  137. package/dist/semiotic-ai-core.min.js +1 -1
  138. package/dist/semiotic-ai-core.module.min.js +1 -1
  139. package/dist/semiotic-ai.d.ts +4 -3
  140. package/dist/semiotic-ai.min.js +1 -1
  141. package/dist/semiotic-ai.module.min.js +1 -1
  142. package/dist/semiotic-data.module.min.js +1 -1
  143. package/dist/semiotic-experimental-vacp.d.ts +11 -0
  144. package/dist/semiotic-experimental-vacp.min.js +1 -0
  145. package/dist/semiotic-experimental-vacp.module.min.js +1 -0
  146. package/dist/semiotic-experimental.d.ts +6 -3
  147. package/dist/semiotic-experimental.min.js +2 -1
  148. package/dist/semiotic-experimental.module.min.js +2 -1
  149. package/dist/semiotic-geo.d.ts +4 -0
  150. package/dist/semiotic-physics.d.ts +9 -6
  151. package/dist/semiotic-realtime-core.min.js +1 -1
  152. package/dist/semiotic-realtime-core.module.min.js +1 -1
  153. package/dist/semiotic-recipes-core.d.ts +6 -1
  154. package/dist/semiotic-recipes-core.min.js +1 -1
  155. package/dist/semiotic-recipes-core.module.min.js +1 -1
  156. package/dist/semiotic-recipes.min.js +1 -1
  157. package/dist/semiotic-recipes.module.min.js +1 -1
  158. package/dist/semiotic-server-edge.min.js +1 -1
  159. package/dist/semiotic-server-edge.module.min.js +1 -1
  160. package/dist/semiotic-server-node.min.js +1 -1
  161. package/dist/semiotic-server-node.module.min.js +1 -1
  162. package/dist/semiotic-utils-core.min.js +1 -1
  163. package/dist/semiotic-utils-core.module.min.js +1 -1
  164. package/dist/semiotic-utils.min.js +1 -1
  165. package/dist/semiotic-utils.module.min.js +1 -1
  166. package/dist/semiotic.min.js +1 -1
  167. package/dist/semiotic.module.min.js +1 -1
  168. package/dist/server.min.js +1 -1
  169. package/dist/server.module.min.js +1 -1
  170. package/dist/xy.min.js +1 -1
  171. package/dist/xy.module.min.js +1 -1
  172. package/package.json +18 -2
  173. package/spec/README.md +94 -2
  174. package/spec/bindings/README.md +14 -3
  175. package/spec/v0.1/examples/annotation-provenance-reviewed-revision.json +27 -0
  176. package/spec/v0.1/examples/annotation-provenance-watcher-threshold.json +21 -0
  177. package/spec/v0.1/examples/audience-profile-executive-review.json +24 -0
  178. package/spec/v0.1/examples/audience-profile-incident-operators.json +42 -0
  179. package/spec/v0.1/examples/chart-capability-bar-comparison.json +48 -0
  180. package/spec/v0.1/examples/chart-capability-service-flow.json +54 -0
  181. package/dist/chunk-chunk-2CHN2TA3.module.min.js +0 -1
  182. package/dist/chunk-chunk-3SHB24AG.module.min.js +0 -1
  183. package/dist/chunk-chunk-4MMOOYTX.module.min.js +0 -2
  184. package/dist/chunk-chunk-5RKXZQ2P.module.min.js +0 -1
  185. package/dist/chunk-chunk-75OTQSXS.module.min.js +0 -1
  186. package/dist/chunk-chunk-7ALTGHK6.module.min.js +0 -1
  187. package/dist/chunk-chunk-A5GRQUOF.module.min.js +0 -1
  188. package/dist/chunk-chunk-AAF5LZAU.module.min.js +0 -2
  189. package/dist/chunk-chunk-ARZGA4LJ.module.min.js +0 -2
  190. package/dist/chunk-chunk-C4YA6TDR.module.min.js +0 -1
  191. package/dist/chunk-chunk-CAFLML4L.module.min.js +0 -2
  192. package/dist/chunk-chunk-CO5KQMGH.module.min.js +0 -1
  193. package/dist/chunk-chunk-FHBN7OEB.module.min.js +0 -2
  194. package/dist/chunk-chunk-GMQ5AYTD.module.min.js +0 -1
  195. package/dist/chunk-chunk-IP2UE74X.module.min.js +0 -1
  196. package/dist/chunk-chunk-ITDWLZXV.module.min.js +0 -2
  197. package/dist/chunk-chunk-JCG72SGW.module.min.js +0 -2
  198. package/dist/chunk-chunk-LPSPATPC.module.min.js +0 -1
  199. package/dist/chunk-chunk-PX5YQGDP.module.min.js +0 -2
  200. package/dist/chunk-chunk-QSQVBIJA.module.min.js +0 -1
  201. package/dist/chunk-chunk-RCF52Z42.module.min.js +0 -2
  202. package/dist/chunk-chunk-RNUHEXZA.module.min.js +0 -2
  203. package/dist/chunk-chunk-ROZWKEUG.module.min.js +0 -1
  204. package/dist/chunk-chunk-T2FKJD4O.module.min.js +0 -2
  205. package/dist/chunk-chunk-UDREYOLV.module.min.js +0 -1
  206. package/dist/chunk-chunk-VOWE3SAP.module.min.js +0 -2
  207. package/dist/chunk-chunk-VQPNBUSW.module.min.js +0 -2
  208. package/dist/chunk-chunk-WAWCIHFJ.module.min.js +0 -1
  209. package/dist/chunk-chunk-WYARAXHR.module.min.js +0 -2
  210. package/dist/chunk-chunk-XV3KGYTR.module.min.js +0 -2
  211. package/dist/chunk-chunk-YC2IVEPX.module.min.js +0 -1
  212. package/dist/chunk-chunk-ZOAQDIJO.module.min.js +0 -1
  213. package/dist/chunk-chunk-ZXIXAPRE.module.min.js +0 -2
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- var e,t=Object.create,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,a=(e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))s.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(a=i(t,c))||a.enumerable});return e},c=(e,i,o)=>(o=null!=e?t(r(e)):{},a(!i&&e&&e.__esModule?o:n(o,"default",{value:e,enumerable:!0}),e)),l={};((e,t)=>{for(var i in t)n(e,i,{get:t[i],enumerable:!0})})(l,{BuiltInPhysicsEngineAdapter:()=>Pi,ChainReactionChart:()=>Gh,CollisionSwarmChart:()=>Ic,CrucibleChart:()=>xh,DEFAULT_CRUCIBLE_HEIGHT:()=>eu,DEFAULT_CRUCIBLE_OUTLETS:()=>nu,DEFAULT_CRUCIBLE_SIZE:()=>tu,DEFAULT_CRUCIBLE_WIDTH:()=>Jd,EventDropChart:()=>cc,GaltonBoardChart:()=>rc,GauntletChart:()=>Rl,GuantletChart:()=>$l,PhysicalFlowChart:()=>Ll,PhysicsCustomChart:()=>vc,PhysicsPileChart:()=>uc,PhysicsPipelineStore:()=>Co,PhysicsSVGOverlay:()=>Un,PhysicsSedimentAccumulator:()=>Li,ProcessFlowChart:()=>Jl,StreamPhysicsFrame:()=>ds,absorbRegion:()=>ca,aggregateRegionCounts:()=>_s,applyCrucibleEvent:()=>Vd,arrivalReplay:()=>Cd,bodiesToAnnotationAnchors:()=>Gn,bodyGroupSpec:()=>da,buildCollisionSwarmPhysics:()=>Os,buildCrucibleEvidence:()=>Zd,buildCrucibleInitialSpawns:()=>Iu,buildCrucibleLayout:()=>pu,buildCruciblePhysicsConfig:()=>bu,buildCrucibleProductEvents:()=>lh,buildCrucibleProjection:()=>Ud,buildCrucibleStateSpawns:()=>Cu,buildCrucibleTerminalSpawns:()=>Ru,buildEventDropPhysics:()=>Bs,buildGaltonBoardPhysics:()=>$s,buildPhysicalFlowPhysics:()=>Hs,buildPhysicsAnnotationContext:()=>Xn,buildPhysicsPile:()=>Es,buildProcessFlowPhysics:()=>pa,calculateBlockerAmplification:()=>Dh,capacitatedRegion:()=>sa,chargeGateRegion:()=>ia,cloneCrucibleState:()=>Td,collidersFromScales:()=>Id,comparePhysicsTrace:()=>md,compileCruciblePlan:()=>Eu,compileDependencyMachine:()=>Ah,compileMotionEncoding:()=>Cc,compilePhysicsEncoding:()=>Bc,composePhysicsControllers:()=>Jo,composeStyleRules:()=>gs,createCapacityQueueController:()=>_o,createDefaultPhysicsEngineAdapter:()=>Di,createDependencyGateController:()=>Qo,createInitialCrucibleState:()=>uu,createLogicalJoin:()=>Rh,createPhysicsEncodingLayout:()=>Tc,createPortalController:()=>er,createProcessJourneyLedger:()=>yd,createServiceLevelController:()=>Ko,createServiceResourcePoolController:()=>Vo,crucibleBondId:()=>wu,crucibleBoundaryColliders:()=>fu,crucibleComponentBodyId:()=>xu,crucibleProductBodyId:()=>vu,crucibleProjectionRows:()=>Kd,crucibleSemanticKey:()=>Pu,default:()=>Xh,deriveMotionVector:()=>Dc,evaluateCrucibleConservation:()=>Qd,evaluatePhysicsBodyBudget:()=>_i,forceFieldRegion:()=>la,galtonPegs:()=>Sd,groupCompletionRows:()=>Xs,hatchFillId:()=>re,hatchPatternDef:()=>ae,isHatchFill:()=>ie,makeRuleValueResolver:()=>hs,matchesThreshold:()=>ms,membraneRegion:()=>na,normalizePhysicsAnnotations:()=>Vn,opacityFromAge:()=>$c,physicsProcessBoundaryColliders:()=>Nc,physicsProcessGroupSemanticItems:()=>qc,physicsProcessRegionSemanticItem:()=>Oc,physicsProcessStageSemanticItems:()=>Wc,physicsReferenceEnvelope:()=>ld,planGauntletPropertyWork:()=>ll,portalRegion:()=>aa,pressureFieldRegion:()=>ra,processChrome:()=>Ql,processJourneyRows:()=>bd,processLaneWalls:()=>ua,processStageLayout:()=>Js,processStageRegions:()=>ta,processVolumePolygons:()=>Ks,regionCountsToProjectionRows:()=>Gs,replaceGauntletNegative:()=>dl,replayCruciblePlan:()=>Tu,replayStateTransitions:()=>Ph,resolveCrucibleSelector:()=>qd,resolveCrucibleSnapshotAt:()=>Bu,resolveCrucibleTime:()=>Du,resolveMotionAccessor:()=>Ac,resolveMotionAge:()=>Rc,resolveMotionVector:()=>Pc,resolveStyleRules:()=>ys,resolveSvgFill:()=>ce,routeDependencyTracks:()=>Ch,routeSurfaceRegion:()=>oa,ruleMatches:()=>fs,sedimentBake:()=>Ad,sedimentHeightfield:()=>Yi,spawnFromTokens:()=>jd,stageTargetInVolume:()=>Us,updateProcessJourney:()=>gd}),module.exports=(e=l,a(n({},"__esModule",{value:!0}),e));var d=require("react"),u=c(require("react")),h=require("react"),p=c(require("react")),m=require("react"),f=require("react"),y=require("react/jsx-runtime");function g(e){let t=null;const n=()=>(t||(t=(0,f.createContext)(null)),t),i=b(e);return[function({children:t,initialState:i}){const o=(0,f.useRef)(i),r=(0,f.useMemo)(()=>b(e,o.current),[]),s=n();return(0,y.jsx)(s.Provider,{value:r,children:t})},(e,t)=>{const o=n(),r=(0,f.useContext)(o)??i,s=(0,f.useRef)(e);s.current=e;const a=(0,f.useRef)({hasValue:!1,value:void 0}),c=(0,f.useCallback)(()=>{const e=s.current(r.getState()),n=a.current;return n.hasValue&&t&&t(n.value,e)?n.value:(a.current={hasValue:!0,value:e},e)},[r,t]),l=(0,f.useCallback)(()=>s.current(r.getState()),[r]);return(0,f.useSyncExternalStore)(r.subscribe,c,l)}]}function b(e,t){const n=new Set;let i={...e(function(e){const t=e(i);if(function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}(t)){i={...i,...t};for(const e of n)e()}}),...t??{}};return{getState:()=>i,subscribe:function(e){return n.add(e),()=>{n.delete(e)}}}}function x(e){if(!e.accessibility)return e;let t=e;if(e.accessibility.colorBlindSafe&&(t={...t,colors:{...t.colors,categorical:v}}),e.accessibility.highContrast){const e="dark"===t.mode;t={...t,colors:{...t.colors,text:e?"#ffffff":"#000000",textSecondary:e?"#cccccc":"#333333",grid:e?"#666666":"#999999",border:e?"#888888":"#000000"}}}return t}var v=["#0072B2","#E69F00","#009E73","#CC79A7","#56B4E9","#D55E00","#F0E442","#000000"],w={mode:"light",colors:{primary:"#00a2ce",secondary:"#6c757d",categorical:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],sequential:"blues",diverging:"RdBu",background:"transparent",surface:"#ffffff",text:"#333",textSecondary:"#666",grid:"#e0e0e0",border:"#ccc",selection:"#00a2ce",selectionOpacity:.15,success:"#2ca02c",danger:"#d62728",warning:"#f0ad4e",error:"#b4181b",info:"#00a2ce"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},k={mode:"dark",colors:{primary:"#4fc3f7",secondary:"#90a4ae",categorical:["#4fc3f7","#ffb74d","#81c784","#ef5350","#ba68c8","#a1887f","#f06292","#90a4ae","#dce775","#4dd0e1"],sequential:"blues",diverging:"RdBu",background:"#1a1a2e",surface:"#252540",text:"#e0e0e0",textSecondary:"#aaa",grid:"#333",border:"#555",selection:"#4fc3f7",selectionOpacity:.15,success:"#81c784",danger:"#ef5350",warning:"#ffb74d",error:"#d84848",info:"#4fc3f7"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},M={mode:"light",colors:{primary:"#0000cc",secondary:"#333333",categorical:v,sequential:"blues",diverging:"RdBu",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#333333",grid:"#999999",border:"#000000",focus:"#0000cc",selection:"#0000cc",selectionOpacity:.1,success:"#006400",danger:"#cc0000",warning:"#b15a00",error:"#8b0000",info:"#0000cc"},typography:{fontFamily:"system-ui, sans-serif",titleSize:18,labelSize:14,tickSize:12},tooltip:{background:"#000000",text:"#ffffff",borderRadius:"4px",fontSize:"14px",shadow:"0 2px 8px rgba(0, 0, 0, 0.3)"},borderRadius:"4px"};function I(e,t){if("light"===t)return w;if("dark"===t)return k;if("high-contrast"===t)return M;if("string"==typeof t)return void 0!==console&&console.warn(`[ThemeStore] Unknown theme preset "${t}". Keeping current theme.`),e;if(t.mode&&"auto"!==t.mode){const e="dark"===t.mode?k:w;return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}var[S,j]=g(e=>({theme:w,setTheme(t){e(e=>({theme:I(e.theme,t)}))}})),A=require("react");function C(){const[e,t]=(0,A.useState)(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return(0,A.useEffect)(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)");return t(e.matches),function(e,t){if("function"==typeof e.addEventListener)return e.addEventListener("change",t),()=>e.removeEventListener("change",t);const n=e;return n.addListener(t),()=>n.removeListener(t)}(e,e=>t(e.matches))},[]),e}var R=require("react");function $(e,t,n){const i=(0,R.useRef)(null),[o,r]=(0,R.useState)(null);return(0,R.useEffect)(()=>{if(!t&&!n)return;const e=i.current;if(!e)return;const o=new ResizeObserver(e=>{for(const t of e){const{width:e,height:n}=t.contentRect;r(t=>t&&t.w===e&&t.h===n?t:{w:e,h:n})}});return o.observe(e),()=>o.disconnect()},[t,n]),[i,[t&&o?o.w:e[0],n&&o?o.h:e[1]]]}var P=new WeakMap,D=0,B=!1,T=null,E=null;function N(e,t){if(!t)return t;const n=function(e){const t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;const n=t.slice(4,-1),i=n.indexOf(",");if(-1===i){const e=n.trim();return e.startsWith("--")?{name:e}:null}const o=n.slice(0,i).trim(),r=n.slice(i+1).trim();return o.startsWith("--")?{name:o,fallback:r||void 0}:null}(t);if(!n)return t;const i=()=>n.fallback?N(e,n.fallback):t,o=e.canvas;if(!o)return i();!function(){if(B)return;if("undefined"==typeof window||"undefined"==typeof document)return;B=!0;const e=()=>{D++};if("undefined"!=typeof MutationObserver&&document.documentElement&&new MutationObserver(e).observe(document.documentElement,{attributes:!0,attributeFilter:["class","style","data-theme","data-semiotic-theme"],subtree:!0}),"function"==typeof window.matchMedia)try{T=window.matchMedia("(prefers-color-scheme: dark)"),E=e,"function"==typeof T.addEventListener?T.addEventListener("change",E):"function"==typeof T.addListener&&T.addListener(E)}catch{}}();let r=P.get(o);r&&r.version===D||(r={version:D,map:new Map},P.set(o,r));const s=r.map.get(t);if(void 0!==s)return s;const a=getComputedStyle(o).getPropertyValue(n.name).trim()||i()||t;return r.map.set(t,a),a}var O=()=>"undefined"!=typeof performance?performance.now():Date.now();function W(e,t){const n=e();return Number.isFinite(n)?n:t}var q=class{constructor(e={}){this.randomSource=Math.random,this.subscribers=new Set,this.now=()=>this.advance(),this.random=()=>this.randomSource(),this.clock=e.clock??O,this.lastWallTime=W(this.clock,0),this.logicalTime=this.lastWallTime,this.pausedValue=!0===e.paused,this.visibleValue=!1!==e.visible,this.setRandomSource(e.random,e.seed)}get isActive(){return!this.pausedValue&&this.visibleValue}get paused(){return this.pausedValue}get seed(){return this.seedValue}get visible(){return this.visibleValue}configure(e){this.setClock(e.clock),this.setRandomSource(e.random,e.seed)}setPaused(e){this.pausedValue!==e&&(this.advance(),this.pausedValue=e,this.emit())}setVisible(e){this.visibleValue!==e&&(this.advance(),this.visibleValue=e,this.emit())}snapshot(){return{now:this.now(),paused:this.pausedValue,seed:this.seedValue,visible:this.visibleValue}}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}advance(){const e=W(this.clock,this.lastWallTime),t=Math.max(0,e-this.lastWallTime);return this.lastWallTime=e,this.isActive&&(this.logicalTime+=t),this.logicalTime}emit(){for(const e of this.subscribers)e()}setClock(e){const t=e??O;t!==this.clock&&(this.advance(),this.clock=t,this.lastWallTime=W(t,this.lastWallTime))}setRandomSource(e,t){const n=function(e){return"number"==typeof e&&Number.isFinite(e)?Math.trunc(e):void 0}(t);e===this.randomInput&&n===this.seedValue||(this.randomInput=e,this.seedValue=n,this.randomSource=e??(void 0===n?Math.random:function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(n)))}},F="undefined"==typeof window?m.useEffect:m.useLayoutEffect,z={requestAnimationFrame:e=>("undefined"==typeof window?globalThis:window).requestAnimationFrame(e),cancelAnimationFrame:e=>("undefined"==typeof window?globalThis:window).cancelAnimationFrame(e)};function L(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}var Y=require("react"),H="undefined"!=typeof window?Y.useLayoutEffect:Y.useEffect,_=()=>()=>{},G=()=>!1,X=()=>!0;function V(){const e=(0,Y.useSyncExternalStore)(_,G,X);return(0,Y.useRef)(e).current}var U=require("react"),K=require("react/jsx-runtime");function Q({children:e,size:t,margin:n,overflowVisible:i=!1}){return e?(0,K.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:t[0],height:t[1],pointerEvents:"none",overflow:i?"visible":void 0},children:(0,K.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:e})}):null}var Z=c(require("react")),J=require("d3-shape");function ee(e){return{type:"hatch",background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle}}var te=null;var ne=require("react/jsx-runtime");function ie(e){return"object"==typeof e&&null!==e&&"hatch"===e.type}function oe(e){return["hatch",e.background??"transparent",e.stroke??"#000",e.lineWidth??1.5,e.spacing??6,e.angle??45,e.lineOpacity??1].join("|")}function re(e,t){let n=2166136261;const i=oe(t);for(let e=0;i.length>e;e++)n^=i.charCodeAt(e),n=Math.imul(n,16777619);return`${e}-hatch-${(n>>>0).toString(36)}`}var se=new Map;function ae(e,t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45,lineOpacity:a=1}=e,c=Math.max(8,Math.ceil(2*r));return(0,ne.jsxs)("pattern",{id:t,width:c,height:c,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[n&&"transparent"!==n&&(0,ne.jsx)("rect",{width:c,height:c,fill:n}),(0,ne.jsx)("line",{x1:0,y1:0,x2:0,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a}),(0,ne.jsx)("line",{x1:r,y1:0,x2:r,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a})]},t)}function ce(e,t,n="#4e79a7"){if(ie(e)){const n=re(t,e);return{fill:`url(#${n})`,def:ae(e,n)}}return e&&"string"==typeof e?{fill:e}:{fill:n}}var le=require("d3-shape");function de(e){switch(e){case"monotoneX":return le.curveMonotoneX;case"monotoneY":return le.curveMonotoneY;case"cardinal":return le.curveCardinal;case"catmullRom":return le.curveCatmullRom;case"step":return le.curveStep;case"stepBefore":return le.curveStepBefore;case"stepAfter":return le.curveStepAfter;case"basis":return le.curveBasis;case"natural":return le.curveNatural;default:return null}}function ue(e,t,n){if(null==t)return n;if(ie(t)){const i=function(e,t){const n="undefined"!=typeof window&&window.devicePixelRatio||1,i=`${oe(e)}@${n}`,o=se.get(i);if(void 0!==o)return o;const r=function(e={},t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45}=e,a={background:n,stroke:i,lineWidth:o,spacing:r,angle:s},c=Math.max(8,Math.ceil(2*r));let l;try{l=function(e){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,e):(te||(te=document.createElement("canvas")),te.width=e,te.height=e,te)}(c)}catch{return ee(a)}const d=l.getContext("2d");if(!d)return ee(a);n&&"transparent"!==n?(d.fillStyle=n,d.fillRect(0,0,c,c)):d.clearRect(0,0,c,c),d.strokeStyle=i,d.lineWidth=o,d.lineCap="square";const u=s*Math.PI/180;if(45===s||-45===s){const e=s>0?1:-1;for(let t=-c;2*c>=t;t+=r)d.beginPath(),d.moveTo(t,0),d.lineTo(t+e*c,c),d.stroke()}else{d.save(),d.translate(c/2,c/2),d.rotate(u);const e=2*c;for(let t=-e;e>=t;t+=r)d.beginPath(),d.moveTo(-e,t),d.lineTo(e,t),d.stroke();d.restore()}return(t||d).createPattern(l,"repeat")}({background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},t),s=ie(r)?null:r;return se.set(i,s),s}(t,e);return i||t.background&&N(e,t.background)||n}return"string"!=typeof t?t:N(e,t)||n}function he(e,t,n){let i=n;for(const n of t)"lesser"===n.thresholdType?n.value>e&&(i=n.color):e>n.value&&(i=n.color);return i}var pe=[40,40],me=[.5,.5];function fe(e,t,n,i){if("none"!==e)return"color"===e||null==e?t??i:"accent"===e?n:e}var ye=require("d3-shape"),ge={circle:ye.symbolCircle,square:ye.symbolSquare,triangle:ye.symbolTriangle,diamond:ye.symbolDiamond,star:ye.symbolStar,cross:ye.symbolCross,wye:ye.symbolWye};var be=require("react/jsx-runtime");function xe(e,t="#4e79a7"){return ie(e)?e.background&&"transparent"!==e.background?e.background:t:e&&"string"==typeof e?e:t}function ve(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"s_"+t:t}function we(e,t){const n=e.filter(e=>Number.isFinite(e.offset)&&(null==e.opacity||Number.isFinite(e.opacity))).map(e=>({offset:Math.max(0,Math.min(1,e.offset)),color:e.color??t,opacity:null==e.opacity?void 0:Math.max(0,Math.min(1,e.opacity))}));return 2>n.length?null:n.map((e,t)=>(0,be.jsx)("stop",{offset:e.offset,stopColor:e.color,stopOpacity:e.opacity},t))}var ke=require("react/jsx-runtime");function Me(e,t,n,i){if(!e||2>t.length)return null;const o=we(e.stops,i);return o?(0,ke.jsx)("linearGradient",{id:n,gradientUnits:"userSpaceOnUse",x1:t[0][0],y1:0,x2:t[t.length-1][0],y2:0,children:o}):null}function Ie(e,t,n){switch(e.type){case"line":{const i=e;if(0===i.path.length)return null;const o=de(i.curve),r=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.path)??"":"M"+i.path.map(([e,t])=>`${e},${t}`).join("L"),s=ve(`${n?n+"-":""}line-${t}-stroke-gradient`),a=Me(i.strokeGradient,i.path,s,i.style.stroke||"#4e79a7");return(0,ke.jsxs)(Z.Fragment,{children:[a&&(0,ke.jsx)("defs",{children:a}),(0,ke.jsx)("path",{d:r,fill:"none",stroke:a?`url(#${s})`:i.style.stroke||"#4e79a7",strokeWidth:i.style.strokeWidth||2,strokeDasharray:i.style.strokeDasharray,opacity:i.style.opacity})]},"line-"+t)}case"area":{const i=e;if(0===i.topPath.length)return null;const o=de(i.curve),r=!o||2>i.topPath.length||2>i.bottomPath.length?`M${i.topPath.map(([e,t])=>`${e},${t}`).join("L")}L${[...i.bottomPath].reverse().map(([e,t])=>`${e},${t}`).join("L")}Z`:(0,J.area)().x(([e])=>e).y0((e,t)=>i.bottomPath[t][1]).y1(([,e])=>e).curve(o)(i.topPath)??"",s=`${n?n+"-":""}area-${t}-hatch`,a=ie(i.style.fill)?ae(i.style.fill,s):void 0,c=ve(`${n?n+"-":""}area-${t}-gradient`),l=function(e,t){const n=e.fillGradient;if(!n||"object"!=typeof n)return null;let i=1/0;for(const[,t]of e.topPath)i=Math.min(i,t);let o=-1/0;for(const[,t]of e.bottomPath)o=Math.max(o,t);if(!Number.isFinite(i)||!Number.isFinite(o))return null;const r=we(n.stops,xe(e.style.fill));return r?(0,ke.jsx)("linearGradient",{id:t,gradientUnits:"userSpaceOnUse",x1:0,y1:i,x2:0,y2:o,children:r}):null}(i,c),d=l?`url(#${c})`:a?`url(#${s})`:xe(i.style.fill),u=l?void 0:i.style.fillOpacity??i.style.opacity??.7,h=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.topPath)??"":"M"+i.topPath.map(([e,t])=>`${e},${t}`).join("L"),p=ve(`${n?n+"-":""}area-${t}-stroke-gradient`),m=!(!i.colorThresholds?.length||!i.rawValues||i.rawValues.length!==i.topPath.length),f=!!i.strokeColorBands?.length,y=m||f?null:Me(i.strokeGradient,i.topPath,p,i.style.stroke||"#4e79a7"),g=i.style.strokeWidth||2;let b=1/0,x=-1/0;for(const[e]of i.topPath)b>e&&(b=e),e>x&&(x=e);const v=f?i.strokeColorBands.map((e,i)=>ve(`${n?n+"-":""}area-${t}-stroke-band-${i}`)):[],w=f?i.strokeColorBands.map((e,t)=>(0,ke.jsx)("clipPath",{id:v[t],children:(0,ke.jsx)("rect",{x:b-g,y:e.y,width:x-b+2*g,height:e.height})},v[t])):null,k=i.style.stroke&&"none"!==i.style.stroke?f?i.strokeColorBands.map((e,n)=>(0,ke.jsx)("path",{d:h,fill:"none",stroke:e.color??xe(i.style.stroke),strokeWidth:g,opacity:i.style.opacity,clipPath:`url(#${v[n]})`},`area-${t}-stroke-band-${n}`)):m?function(e,t,n,i){if(2>e.length||t.length!==e.length||0===n.length)return[];const o=[],r=(e,t,n)=>{const i=o[o.length-1];i?.color===e?i.path.push(n):o.push({color:e,path:[t,n]})};for(let o=1;e.length>o;o++){const[s,a]=e[o-1],[c,l]=e[o],d=t[o-1],u=t[o]-d,h=[0,...0===u?[]:n.map(({value:e})=>(e-d)/u).filter(e=>e>0&&1>e&&Number.isFinite(e)).sort((e,t)=>e-t).filter((e,t,n)=>0===t||e!==n[t-1]),1];for(let e=1;h.length>e;e++){const t=h[e-1],o=h[e];r(he(d+u*((t+o)/2),n,i),[s+(c-s)*t,a+(l-a)*t],[s+(c-s)*o,a+(l-a)*o])}}return o}(i.topPath,i.rawValues,i.colorThresholds,xe(i.style.stroke)).map((e,n)=>(0,ke.jsx)("path",{d:"M"+e.path.map(([e,t])=>`${e},${t}`).join("L"),fill:"none",stroke:e.color,strokeWidth:g,opacity:i.style.opacity},`area-${t}-threshold-${n}`)):(0,ke.jsx)("path",{d:h,fill:"none",stroke:y?`url(#${p})`:xe(i.style.stroke),strokeWidth:g,opacity:i.style.opacity}):null;if(i.clipRect){const e=`${n?n+"-":""}area-clip-${t}`;return(0,ke.jsxs)("g",{children:[(0,ke.jsxs)("defs",{children:[l,!l&&a,y,w,(0,ke.jsx)("clipPath",{id:e,children:(0,ke.jsx)("rect",{x:i.clipRect.x,y:i.clipRect.y,width:i.clipRect.width,height:i.clipRect.height})})]}),(0,ke.jsxs)("g",{clipPath:`url(#${e})`,children:[(0,ke.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),k]})]},"area-"+t)}return(0,ke.jsxs)(Z.Fragment,{children:[(l||a||y||w)&&(0,ke.jsxs)("defs",{children:[l,!l&&a,y,w]}),(0,ke.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),k]},"area-"+t)}case"point":{const i=e,o=`${n?n+"-":""}point-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,ke.jsxs)(Z.Fragment,{children:[r&&(0,ke.jsx)("defs",{children:r}),(0,ke.jsx)("circle",{cx:i.x,cy:i.y,r:i.r,fill:r?`url(#${o})`:xe(i.style.fill),opacity:i.style.opacity??i.style.fillOpacity??.8,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"point-"+t)}case"symbol":return function(e,t){const n=function(e,t,n){if(n)return n;const i=e??"circle";return"chevron"===i?function(e){const t=1.5*function(e){return Math.sqrt(Math.max(1,e)/Math.PI)}(e),n=.92*t;return`M0,${-t}L${n},${(.78*t).toFixed(3)}L0,${(.28*t).toFixed(3)}L${-n},${(.78*t).toFixed(3)}Z`}(t):(0,ye.symbol)(ge[i]??ye.symbolCircle,Math.max(1,t))()??""}(e.symbolType,e.size,e.path);return(0,be.jsx)("path",{d:n,transform:e.rotation?`translate(${e.x},${e.y}) rotate(${180*e.rotation/Math.PI})`:`translate(${e.x},${e.y})`,fill:e.style.fill?xe(e.style.fill):"none",fillOpacity:e.style.fillOpacity,opacity:e.style.opacity,stroke:e.style.stroke,strokeWidth:e.style.strokeWidth},"symbol-"+t)}(e,t);case"glyph":return function(e,t,n,i){const o=e.glyph;if(!o?.parts?.length||0>=e.size)return null;const r=function(e,t){const[n,i]=e.viewBox??pe,[o,r]=e.anchor??me,s=i>0?i:1,a=Math.max(0,t)/s,c=(n>0?n:s)*a,l=s*a;return{width:c,height:l,scale:a,offsetX:-o*c,offsetY:-r*l}}(o,e.size);if(0>=r.scale)return null;const s=`translate(${t},${n})${e.rotation?` rotate(${180*e.rotation/Math.PI})`:""} translate(${r.offsetX},${r.offsetY}) scale(${r.scale})`,a=e.color??("string"==typeof e.style.fill?e.style.fill:void 0),c=function(e,t,n=0,i="horizontal"){const[o,r]=e.viewBox??pe,s=Math.min(1,Math.max(0,n)),a=Math.min(1,Math.max(0,t));return a>s?s>0||1>a?"vertical"===i?{x:0,y:r*(1-a),width:o,height:r*(a-s)}:{x:o*s,y:0,width:o*(a-s),height:r}:null:{x:0,y:0,width:0,height:0}}(o,e.fraction??1,e.fractionStart??0,e.fractionDirection??"horizontal"),l=c?ve(i+"-clip"):void 0,d=(e.style.opacity??1)*(e._decayOpacity??1)*(e.style.fillOpacity??1),u=t=>o.parts.map((n,i)=>{const o=t?"none"===n.fill?void 0:t:fe(n.fill,a,e.accent),r=t?n.stroke&&"none"!==n.stroke?t:void 0:fe(n.stroke??"none",a,e.accent);return o||r?(0,be.jsx)("path",{d:n.d,fill:o??"none",stroke:r,strokeWidth:r?n.strokeWidth??1:void 0,strokeLinecap:n.strokeLinecap,strokeLinejoin:n.strokeLinejoin,opacity:n.opacity},i):null});return(0,be.jsxs)("g",{transform:s,opacity:1===d?void 0:d,children:[c&&l&&(0,be.jsx)("clipPath",{id:l,children:(0,be.jsx)("rect",{x:c.x,y:c.y,width:c.width,height:c.height})}),c&&e.ghostColor?(0,be.jsx)("g",{children:u(e.ghostColor)}):null,c&&l?(0,be.jsx)("g",{clipPath:`url(#${l})`,children:u()}):u()]},i)}(e,e.x,e.y,`${n??""}glyph-${e.pointId??t}`);case"rect":{const i=e,o=`${n?n+"-":""}xyrect-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,ke.jsxs)(Z.Fragment,{children:[r&&(0,ke.jsx)("defs",{children:r}),(0,ke.jsx)("rect",{x:i.x,y:i.y,width:i.w,height:i.h,fill:r?`url(#${o})`:xe(i.style.fill),opacity:i.style.opacity,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"rect-"+t)}case"heatcell":{const n=e;if(n.showValues&&null!=n.value&&n.w>=20&&n.h>=20){const e=n.valueFormat?n.valueFormat(n.value):Number.isInteger(n.value)?n.value+"":100>Math.abs(n.value)?1>Math.abs(n.value)?n.value.toPrecision(3):n.value.toFixed(1):n.value.toFixed(0),[i,o,r]=function(e){if(e.startsWith("#")){let t=e.slice(1);if(3===t.length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6===t.length)return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[+t[1],+t[2],+t[3]]:[128,128,128]}(n.fill),s=.299*i+.587*o+.114*r>128?"#000":"#fff",a=Math.max(10,Math.min(16,.3*Math.min(n.w,n.h)));return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth}),(0,ke.jsx)("text",{x:n.x+n.w/2,y:n.y+n.h/2,textAnchor:"middle",dominantBaseline:"middle",fill:s,fontSize:a+"px",children:e})]},"heatcell-"+t)}return(0,ke.jsx)("rect",{x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth},"heatcell-"+t)}case"candlestick":{const n=e;if(n.isRange){const e=n.dotRadius??Math.max(2,n.bodyWidth/2);return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,ke.jsx)("circle",{cx:n.x,cy:n.highY,r:e,fill:n.wickColor}),(0,ke.jsx)("circle",{cx:n.x,cy:n.lowY,r:e,fill:n.wickColor})]},"candle-"+t)}const i=Math.min(n.openY,n.closeY),o=Math.max(Math.abs(n.openY-n.closeY),1),r=n.isUp?n.upColor:n.downColor;return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,ke.jsx)("rect",{x:n.x-n.bodyWidth/2,y:i,width:n.bodyWidth,height:o,fill:r,stroke:r,strokeWidth:1})]},"candle-"+t)}default:return null}}var Se="undefined"==typeof window||"undefined"==typeof document;var je=c(require("react")),Ae=["name","label","title"],Ce=["type","kind","category","group","class","status","role","shape"],Re=["value","amount","total","count","weight","score"],$e=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function Pe(e,t){for(const n of t){const t=e.find(e=>e.lower===n);if(t)return t}}var De=require("react/jsx-runtime"),Be={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function Te(e,t){return"function"==typeof t?t(e):e[t]}function Ee(e,t){if(t)return t(e);if(null==e)return"";if("number"==typeof e){if(!Number.isFinite(e))return e+"";const t=Number.isInteger(e)?e:parseFloat(e.toPrecision(6));return Math.abs(t)>9999?t.toLocaleString():t+""}return e instanceof Date?e.toLocaleDateString():"object"==typeof e&&null!==e?void 0!==e.id?e.id+"":void 0!==e.name?e.name+"":JSON.stringify(e):e+""}function Ne(e={}){const{fields:t,title:n,format:i,style:o={},className:r=""}=e;return e=>{if(!e||"object"!=typeof e)return null;let s;const a=[];if(n){const t=Te(e,n);s=Ee(t,i)}if(t&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const s=Te(e,o);a.push({label:n,value:Ee(s,r)})});else if(!n){const t=["value","y","name","id","label"];for(const n of t)if(void 0!==e[n]){s=Ee(e[n],i);break}if(!s){const t=Object.keys(e).filter(e=>!e.startsWith("_"));t.length>0&&(s=Ee(e[t[0]],i))}}const c={...Be,...o};return(0,De.jsxs)("div",{className:("semiotic-tooltip "+r).trim(),style:c,children:[s&&(0,De.jsx)("div",{style:{fontWeight:a.length>0?"bold":"normal"},children:s}),a.map((e,t)=>(0,De.jsxs)("div",{style:{marginTop:0===t&&s?"4px":0},children:[e.label&&(0,De.jsxs)("span",{children:[e.label,": "]}),e.value]},t))]})}}function Oe(e){if(!0!==e){if("function"==typeof e){const t=e;return e=>{let n=Array.isArray(i=!0===e?.__semioticHoverData||e&&void 0!==e.data&&"number"==typeof e.x&&"number"==typeof e.y&&e&&("node"===e.type||"edge"===e.type||void 0!==e.nodeOrEdge||void 0!==e.allSeries||void 0!==e.stats||void 0!==e.__chartType)?e.data??{}:e)?i[0]:i;var i;if(!n)return null;if(("node"===e?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===e?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;const o=t(n);return null==o?null:(0,De.jsx)("div",{className:"semiotic-tooltip",style:Be,children:o})}}return!1!==e&&void 0!==e&&("object"==typeof e&&null!==e&&("fields"in e||"title"in e)?Ne(e):"multi"===e?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(e={}){const{fields:t=[],title:n,format:i,style:o={},className:r="",showLabels:s=!0,separator:a=": "}=e;return e=>{if(!e||"object"!=typeof e)return null;const c=[];if(n){const t=Te(e,n);c.push({value:Ee(t,i)})}if(t&&Array.isArray(t)&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const a=Ee(Te(e,o),r);c.push({label:s?n:void 0,value:a})});else{const t=function(e,t={}){if(!e||"object"!=typeof e)return{entries:[]};const n=t.maxEntries??6,i=!1!==t.skipPositional,o=[];for(const[t,n]of Object.entries(e)){if(t.startsWith("_"))continue;if("data"===t)continue;if(i&&$e.has(t.toLowerCase()))continue;if(null==n)continue;const e=typeof n;("string"===e||"number"===e||"boolean"===e||n instanceof Date)&&o.push({key:t,lower:t.toLowerCase(),value:n})}if(0===o.length)return{entries:[]};let r=o.findIndex(e=>Ae.includes(e.lower));const s=r>=0;0>r&&(r=o.findIndex(e=>"id"===e.lower)),0>r&&(r=o.findIndex(e=>"string"==typeof e.value));const a=0>r?void 0:o[r];let c=o.filter((e,t)=>t!==r);s&&(c=c.filter(e=>"id"!==e.lower));const l=Pe(c,Ce),d=Pe(c,Re),u=new Set(Ce),h=new Set(Re),p=[];l&&p.push({key:l.key,value:l.value}),d&&p.push({key:d.key,value:d.value});for(const e of c){if(p.length>=n)break;e!==l&&e!==d&&(u.has(e.lower)||h.has(e.lower)||p.push({key:e.key,value:e.value}))}return{titleKey:a?.key,title:a?.value,entries:p}}(e,{skipPositional:!1});null!=t.title&&c.push({label:void 0,value:Ee(t.title,i),bold:!0}),t.entries.forEach(e=>{c.push({label:s?e.key:void 0,value:Ee(e.value,i)})})}const l={...Be,...o};return Array.isArray(c)&&0!==c.length?(0,De.jsx)("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+r).trim(),style:l,children:c.map((e,t)=>(0,De.jsxs)("div",{style:{marginBottom:c.length-1>t?"4px":0,fontWeight:e.bold?"bold":void 0},children:[e.label&&(0,De.jsxs)("strong",{children:[e.label,a]}),e.value]},t))}):null}}()):Ne())}}var We=require("react/jsx-runtime");function qe({x:e,y:t,containerWidth:n,containerHeight:i,margin:o,children:r,className:s="stream-frame-tooltip",zIndex:a=1}){const c=Number.isFinite(e)&&Number.isFinite(t),l=je.useRef(null),[d,u]=je.useState(null);je.useLayoutEffect(()=>{const e=l.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect();Number.isFinite(t.width)&&Number.isFinite(t.height)&&u(e=>e&&.5>Math.abs(e.width-t.width)&&.5>Math.abs(e.height-t.height)?e:{width:t.width,height:t.height})};if(t(),"undefined"==typeof ResizeObserver)return;const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s,n,i,c]);let h;h=d?`translate(${d.width+12>n-e?"calc(-100% - 12px)":"12px"}, ${d.height+12>i-t?"calc(-100% - 4px)":"4px"})`:`translate(${e>.7*n?"calc(-100% - 12px)":"12px"}, ${.3*i>t?"4px":"calc(-100% - 4px)"})`;const p=function(e){if(!je.isValidElement(e))return!1;const t=e.type;if("string"!=typeof t&&t&&!0===t.ownsChrome)return!0;const n=e.props;if(!0===n["data-semiotic-tooltip-chrome"])return!0;if("true"===n["data-semiotic-tooltip-chrome"])return!0;const i=n.style;if(i&&"object"==typeof i){if(null!=i.background&&""!==i.background&&"transparent"!==i.background)return!0;if(null!=i.backgroundColor&&""!==i.backgroundColor&&"transparent"!==i.backgroundColor)return!0}return!1}(r),m=p?null:Be;return c?(0,We.jsx)("div",{ref:l,className:p?s:(s+" semiotic-tooltip").trim(),style:{...m||{},position:"absolute",left:o.left+e,top:o.top+t,transform:h,pointerEvents:"none",zIndex:a,width:"max-content"},children:r}):null}var Fe={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},ze={names:["--semiotic-border","--surface-3"],fallback:"#334155"},Le={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},Ye={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},He={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},_e={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},Ge={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},Xe={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Ve={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},Ue={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function Ke(e,t){const n=e.canvas;if("function"!=typeof getComputedStyle||!n)return t.fallback;const i=getComputedStyle(n);for(const n of t.names){const t=i.getPropertyValue(n).trim();if(t)return N(e,t)??t}return t.fallback}function Qe(e,t){const n=Math.max(0,Math.min(1,t)),i=e.trim(),o=i.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,i]=o;return Qe(`#${e}${e}${t}${t}${i}${i}`,n)}const r=i.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,i]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(i,16)}, ${n})`}const s=i.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${n})`;const a=i.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${n})`:i}var Ze=c(require("react")),Je=require("d3-scale"),et=c(require("react"));function tt(e){return"object"==typeof e&&null!==e&&"legendGroups"in e&&Array.isArray(e.legendGroups)}function nt(e){return"object"==typeof e&&null!==e&&"gradient"in e}var it=16,ot=6,rt=10,st=22,at=100,ct=10;function lt(e){return Math.ceil(7*e.length)}function dt(e){const t=Math.max(1,e?.swatchSize??it),n=Math.max(t,e?.rowHeight??st);return{swatchSize:t,labelGap:Math.max(0,e?.labelGap??ot),itemGap:Math.max(0,e?.itemGap??rt),rowHeight:n,align:"left"===e?.align?"start":"right"===e?.align?"end":e?.align??"start",maxWidth:e?.maxWidth}}var ut=require("react/jsx-runtime"),ht={fill:(e,t)=>(0,ut.jsx)("rect",{style:e,width:t,height:t}),line:(e,t)=>(0,ut.jsx)("line",{style:e,x1:0,y1:0,x2:t,y2:t})};function pt(e,t,n,i,o){let r;return r="function"==typeof n?n(e):(0,ht[n])(i(e,t),o),r}function mt({swatchSize:e}){return(0,ut.jsx)("path",{d:`M${.25*e},${.55*e} L${.45*e},${.75*e} L${.8*e},${.3*e}`,fill:"none",stroke:"white",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}function ft(e,t,n){return n&&n.size>0?n.has(e.label)?1:.3:null!=t?e.label===t?1:.3:1}var yt=(e,t,n,i,o,r,s,a,c,l,d)=>{const{type:u="fill",styleFn:h,items:p}=e,m=[];let f=0;const y=!(!t&&!n),g="isolate"===l||void 0===l&&null!=o,{swatchSize:b,labelGap:x,rowHeight:v}=d;return p.forEach((e,l)=>{const d=pt(e,l,u,h,b),w=ft(e,i,o),k=o&&o.size>0&&o.has(e.label);m.push((0,ut.jsxs)("g",{transform:`translate(0,${f})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:y?a===r&&l===s?0:-1:void 0,role:y?"option":void 0,"aria-selected":y&&g?k||!1:void 0,"aria-current":y&&!g&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:y?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowDown"===n.key||"ArrowUp"===n.key){n.preventDefault();const e=(l+("ArrowDown"===n.key?1:-1)+p.length)%p.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:y?t=>{c(a,l),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:y?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:y?"pointer":"default",opacity:w,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[y&&(0,ut.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:b+x+2+7*e.label.length,height:b+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),d,k&&(0,ut.jsx)(mt,{swatchSize:b}),(0,ut.jsx)("text",{y:b/2,x:b+x,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+l)),f+=v}),m},gt=({legendGroups:e,width:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:s,focusedItemIndex:a,onFocusedIndexChange:c,legendInteraction:l,metrics:d})=>{const u=[],h=function(e,t){let n=24;return e.map(({hasLabel:e,itemCount:i})=>{n+=5;const o=n;let r;n+=8,e&&(n+=16,r=n,n+=8);const s=n;return n+=i*t+8,{lineY:o,labelY:r,itemsY:s,endY:n}})}(e.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),d.rowHeight);return e.forEach((e,p)=>{const m=h[p];u.push((0,ut.jsx)("line",{stroke:"gray",x1:0,y1:m.lineY,x2:t,y2:m.lineY},"legend-top-line legend-symbol-"+p)),e.label&&null!=m.labelY&&u.push((0,ut.jsx)("text",{y:m.labelY,className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label},"legend-text-"+p)),u.push((0,ut.jsx)("g",{className:"legend-item",transform:`translate(0,${m.itemsY})`,children:yt(e,n,i,o,r,s,a,p,c,l,d)},"legend-group-"+p))}),u},bt=({legendGroups:e,height:t,width:n,customClickBehavior:i,customHoverBehavior:o,highlightedCategory:r,isolatedCategories:s,focusedGroupIndex:a,focusedItemIndex:c,onFocusedIndexChange:l,legendInteraction:d,metrics:u})=>{let h=0;const p=[];e.forEach((e,t)=>{let m=0;e.label&&(m+=16);const f=((e,t,n,i,o,r,s,a,c,l,d,u)=>{const{type:h="fill",styleFn:p,items:m}=e,f=[],{swatchSize:y,labelGap:g,itemGap:b,rowHeight:x,align:v}=d,w=!(!t&&!n),k="isolate"===l||void 0===l&&null!=o,M=m.map(e=>y+g+7*e.label.length),I=[];let S=0,j=0;M.forEach((e,t)=>{const n=0===j?e:j+b+e;u&&u>0&&j>0&&n>u?(I.push({start:S,end:t,width:j}),S=t,j=e):j=n}),m.length>0&&I.push({start:S,end:m.length,width:j}),I.forEach((e,l)=>{let d="center"===v?Math.max(0,((u??e.width)-e.width)/2):"end"===v?Math.max(0,(u??e.width)-e.width):0;for(let u=e.start;e.end>u;u++){const e=m[u],v=pt(e,u,h,p,y),I=ft(e,i,o),S=o&&o.size>0&&o.has(e.label);f.push((0,ut.jsxs)("g",{transform:`translate(${d},${l*x})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:w?a===r&&u===s?0:-1:void 0,role:w?"option":void 0,"aria-selected":w&&k?S||!1:void 0,"aria-current":w&&!k&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:w?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowRight"===n.key||"ArrowLeft"===n.key){n.preventDefault();const e=(u+("ArrowRight"===n.key?1:-1)+m.length)%m.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:w?t=>{c(a,u),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:w?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:w?"pointer":"default",opacity:I,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[w&&(0,ut.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:y+g+2+7*e.label.length,height:y+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),v,S&&(0,ut.jsx)(mt,{swatchSize:y}),(0,ut.jsx)("text",{y:y/2,x:y+g,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+u)),d+=M[u]+b}});const A=Math.max(0,...I.map(e=>e.width)),C=I.length;return{items:f,offset:A,totalRows:C,totalHeight:C*x}})(e,i,o,r,s,a,c,t,l,d,u,u.maxWidth??n);m+=f.offset+5,p.push({label:e.label,...f,offset:m,totalRows:f.totalRows,totalHeight:f.totalHeight}),h+=m+12});const m=u.maxWidth??n;let f=h>m?0:"center"===u.align?Math.max(0,(m-h)/2):"end"===u.align?Math.max(0,m-h):0;const y=[];return p.forEach((n,i)=>{const o=e[i];o.label&&(y.push((0,ut.jsx)("text",{transform:`translate(${f},0) rotate(90)`,textAnchor:"start",className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:o.label},"legend-text-"+i)),f+=16),y.push((0,ut.jsx)("g",{className:"legend-item",transform:`translate(${f},0)`,children:n.items},"legend-group-"+i)),f+=n.offset+5,e[i+1]&&y.push((0,ut.jsx)("line",{stroke:"gray",x1:f,y1:-8,x2:f,y2:(n.totalHeight||t)+0+8},"legend-top-line legend-symbol-"+i)),f+=12}),(0,ut.jsx)("g",{children:y})};function xt({config:e,orientation:t="vertical",width:n=100}){const{colorFn:i,domain:o,label:r,format:s}=e,a=s||(e=>Math.round(100*e)/100+""),c="grad-legend-"+et.useId();if("horizontal"===t){const e=12,t=Math.min(n,200),s=Math.max(0,(n-t)/2),l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ut.jsx)("stop",{offset:100*t+"%",stopColor:i(o[0]+t*(o[1]-o[0]))},e))}return(0,ut.jsxs)("g",{"aria-label":r||"Gradient legend",children:[(0,ut.jsx)("defs",{children:(0,ut.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:l})}),r&&(0,ut.jsx)("text",{x:s+t/2,y:-4,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ut.jsx)("rect",{x:s,y:0,width:t,height:e,fill:`url(#${c})`,rx:2}),(0,ut.jsx)("text",{x:s,y:e+12,textAnchor:"start",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])}),(0,ut.jsx)("text",{x:s+t,y:e+12,textAnchor:"end",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])})]})}const l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ut.jsx)("stop",{offset:100*t+"%",stopColor:i(o[1]-t*(o[1]-o[0]))},e))}return(0,ut.jsxs)("g",{"aria-label":r||"Gradient legend",children:[r&&(0,ut.jsx)("text",{x:0,y:-6,textAnchor:"start",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ut.jsx)("defs",{children:(0,ut.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:l})}),(0,ut.jsx)("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),(0,ut.jsx)("text",{x:19,y:10,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])}),(0,ut.jsx)("text",{x:19,y:100,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])})]})}function vt(e){const{legendGroups:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,legendInteraction:s,title:a="Legend",width:c=100,height:l=20,orientation:d="vertical",legendLayout:u}=e,h=dt(u),[p,m]=et.useState(0),[f,y]=et.useState(0),g=et.useCallback((e,t)=>{m(e),y(t)},[]),b="vertical"===d?gt({legendGroups:t||[],width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}):bt({legendGroups:t||[],title:a,height:l,width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}),x=!(!n&&!i);return(0,ut.jsxs)("g",{role:x?"listbox":void 0,"aria-multiselectable":!(!x||"isolate"!==s&&(void 0!==s||null==r))||void 0,"aria-label":"Chart legend",style:{fontFamily:"var(--semiotic-font-family, sans-serif)"},children:[void 0!==a&&""!==a&&"vertical"===d&&(0,ut.jsx)("text",{className:"legend-title",y:16,x:c/2,textAnchor:"middle",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:a}),b]})}var wt=require("react/jsx-runtime");function kt(e){const{legend:t,totalWidth:n,totalHeight:i,margin:o,legendPosition:r="right",legendLayout:s,legendHoverBehavior:a,legendClickBehavior:c,legendHighlightedCategory:l,legendIsolatedCategories:d,legendInteraction:u}=e;if(!t)return null;const h="top"===r||"bottom"===r,p=Math.max(0,n-o.left-o.right),m=Math.max(1,h?s?.maxWidth??p:function(e,t){if(tt(e)){const n=dt(t),i=e.legendGroups.flatMap(e=>[e.label?lt(e.label):0,...e.items.map(e=>n.swatchSize+n.labelGap+lt(e.label))]);return Math.max(at,...i)}if(nt(e)){const{gradient:t}=e,n=t.format||(e=>Math.round(100*e)/100+""),i=Math.max(lt(n(t.domain[0])),lt(n(t.domain[1]))),o=t.label?lt(t.label):0;return Math.max(at,19+i,o)}return at}(t,s)),f=function(e){return(tt(e)||nt(e))&&Number.isFinite(e.legendDistance)?Math.max(0,e.legendDistance):ct}(t),y=(g=s,Math.max(0,g?.sideGutter??0));var g;const b=function(e,t,n){if(nt(e))return e.gradient.label?34:26;if(!tt(e))return 20;const i=dt(n),o=Math.max(1,n?.maxWidth??t);let r=i.rowHeight;for(const t of e.legendGroups){let e=0,n=0;for(const r of t.items){const t=i.swatchSize+i.labelGap+lt(r.label),s=0===n?t:n+i.itemGap+t;n>0&&s>o?(e+=1,n=t):n=s}t.items.length>0&&(e+=1),r=Math.max(r,e*i.rowHeight,t.label?lt(t.label):0)}return r+(e.legendGroups.length>1?16:0)}(t,p,s);let x,v;return"left"===r?(x=o.left-y-m-f,v=o.top):"top"===r?(x=o.left,v=o.top-f-b):"bottom"===r?(x=o.left,v=i-o.bottom+f):(x=n-o.right+y+f,v=o.top),(0,wt.jsx)("g",{transform:`translate(${x}, ${v})`,children:nt(t)?(0,wt.jsx)(xt,{config:t.gradient,orientation:h?"horizontal":"vertical",width:m}):tt(t)?(0,wt.jsx)(vt,{legendGroups:t.legendGroups,title:"",width:m,orientation:h?"horizontal":"vertical",legendLayout:s,customHoverBehavior:a,customClickBehavior:c,highlightedCategory:l,isolatedCategories:d,legendInteraction:u}):t})}var Mt=require("react/jsx-runtime"),It={secondary:0,primary:3},St=1,jt=2,At=.6,Ct="0.88em",Rt=.95,$t=.72,Pt=.06,Dt=".annotation-deferred{opacity:0;pointer-events:none;transition:opacity .12s ease}.stream-xy-frame:hover .annotation-deferred,.stream-ordinal-frame:hover .annotation-deferred,.stream-network-frame:hover .annotation-deferred,.stream-geo-frame:hover .annotation-deferred,.stream-xy-frame:focus-within .annotation-deferred,.stream-ordinal-frame:focus-within .annotation-deferred,.stream-network-frame:focus-within .annotation-deferred,.stream-geo-frame:focus-within .annotation-deferred{opacity:1;pointer-events:auto}@media (prefers-reduced-motion:reduce){.annotation-deferred{transition:none}}",Bt=".annotation-cohesion--layer text,.annotation-cohesion--layer tspan{fill:var(--semiotic-annotation-color,var(--semiotic-text-secondary,#666));font-style:italic}";function Tt(e){return!0===e?._annotationDeferred}function Et(e){return"blended"===e?.cohesion||"layer"===e?.cohesion?e.cohesion:null}function Nt(e){const t=e?.provenance?.confidence;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null}function Ot(e){return Math.max($t,Rt-e*Pt)}var Wt=c(require("react")),qt=require("react/jsx-runtime");function Ft(e,t=120,n=8){if(!e)return[];const i=Math.max(1,Math.floor(t/n)),o=e.split(/\s+/),r=[];let s="";for(const e of o)s&&s.length+1+e.length>i?(r.push(s),s=e):s=s?`${s} ${e}`:e;return s&&r.push(s),r}function zt(e,t,n,i){return"curly"===e?i?`M0,0 C${.6*n},0 ${.4*n},${t/2} ${n},${t/2} C${.4*n},${t/2} ${.6*n},${t} 0,${t}`:`M0,0 C0,${.6*n} ${t/2},${.4*n} ${t/2},${n} C${t/2},${.4*n} ${t},${.6*n} ${t},0`:i?`M0,0 L${n},0 L${n},${t} L0,${t}`:`M0,0 L0,${n} L${t},${n} L${t},0`}function Lt(e,t,n,i){if(!e)return(0,qt.jsx)("g",{className:"annotation-note"});const{label:o,title:r,orientation:s,align:a,wrap:c=120,noWrap:l}=e;if(!o&&!r)return(0,qt.jsx)("g",{className:"annotation-note"});let d=s;d||(d=Math.abs(t)>Math.abs(n)?"leftRight":"topBottom");let u=a;u&&"dynamic"!==u||(u="topBottom"===d?0>t?"right":"left":0>n?"bottom":"top");let h="start";"topBottom"===d?"right"===u?h="end":"middle"===u&&(h="middle"):h=0>t?"end":"start";const p=16,m=r?l?[r]:Ft(r,c):[],f=o?l?[o]:Ft(o,c):[],y="leftRight"===d?"end"===h?-4:4:0;let g=0;const b=[],x=i||"var(--semiotic-annotation-color, var(--semiotic-text, #333))";e.useHTML||e.html?b.push((0,qt.jsx)("foreignObject",{className:"annotation-note-html",x:"end"===h?y-c:"middle"===h?y-c/2:y,y:-16,width:c,height:Math.max(p,(m.length+f.length)*p+(r&&o?2:0))+p,style:{overflow:"visible"},children:(0,qt.jsxs)("div",{xmlns:"http://www.w3.org/1999/xhtml",style:{color:x,fontSize:"12px",lineHeight:"16px",overflow:"visible",textAlign:"end"===h?"right":"middle"===h?"center":"left",whiteSpace:l?"nowrap":"normal",wordBreak:"break-word"},children:[r&&(0,qt.jsx)("div",{className:"annotation-note-title",style:{fontWeight:"bold"},children:r}),o&&(0,qt.jsx)("div",{className:"annotation-note-label",children:o})]})},"annotation-note-html")):(m.length>0&&(b.push((0,qt.jsx)("text",{className:"annotation-note-title",fill:x,textAnchor:h,fontWeight:"bold",children:m.map((e,t)=>(0,qt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-title")),g=m.length*p),f.length>0&&b.push((0,qt.jsx)("text",{className:"annotation-note-label",fill:x,textAnchor:h,y:g,children:f.map((e,t)=>(0,qt.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-label")));let v=null;if((r||o)&&(0!==t||0!==n))if("topBottom"===d){const e=Math.min(c,120);let t=0,n=e;"end"===h?(t=-e,n=0):"middle"===h&&(t=-e/2,n=e/2),v=(0,qt.jsx)("line",{className:"note-line",x1:t,x2:n,y1:0,y2:0,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}else{const e=(m.length+f.length)*p+(f.length>0?p:0);let t=0,n=e;"bottom"===u?(t=-e,n=0):"middle"===u&&(t=-e/2,n=e/2),v=(0,qt.jsx)("line",{className:"note-line",x1:0,x2:0,y1:t,y2:n,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}const w=Math.max(0,m.length+f.length-1)*p;let k=0;return"topBottom"===d?k=0>n?-(w+2):18:"leftRight"===d&&(k="middle"===u?-(w+p+(f.length>0&&m.length>0?2:0))/2+8:"bottom"===u||0>n?-(w+2):18),(0,qt.jsxs)("g",{className:"annotation-note",transform:`translate(${t},${n})`,children:[(0,qt.jsx)("g",{className:"annotation-note-content",transform:0!==k?`translate(0,${k})`:void 0,children:b}),v]})}function Yt(e,t,n,i,o){const r=[];switch(e){case"callout-circle":{const e=(t?.radius||0)+(t?.radiusPadding||0);e>0&&r.push((0,qt.jsx)("circle",{r:e,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-circle"));break}case"callout-rect":{const e=t?.width||0,i=t?.height||0;(e>0||i>0)&&r.push((0,qt.jsx)("rect",{width:e,height:i,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-rect"));break}case"callout-custom":t?.custom&&r.push(...Array.isArray(t.custom)?t.custom:[t.custom]);break;case"xy-threshold":{const e=i||0,s=o||0;if(void 0!==t?.x){const i=(t.x||0)-e;r.push((0,qt.jsx)("line",{x1:i,y1:(t.y1||0)-s,x2:i,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else if(void 0!==t?.y){const i=(t.y||0)-s;r.push((0,qt.jsx)("line",{x1:(t.x1||0)-e,y1:i,x2:(t.x2||0)-e,y2:i,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else void 0!==t?.x1||void 0!==t?.x2?r.push((0,qt.jsx)("line",{x1:(t.x1||0)-e,y1:0,x2:(t.x2||0)-e,y2:0,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line")):void 0===t?.y1&&void 0===t?.y2||r.push((0,qt.jsx)("line",{x1:0,y1:(t.y1||0)-s,x2:0,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"));break}case"bracket":{const e=t?.type||"curly",i=t?.width??t?.height;void 0!==i&&r.push((0,qt.jsx)("path",{d:zt(e,i,t?.depth||30,void 0===t?.width),fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"bracket-path"));break}}return(0,qt.jsx)("g",{className:"annotation-subject",children:r})}function Ht(e,t,n,i,o,r){const s=[];let a=0,c=0;if("callout-circle"!==o&&"label"!==o||!r?.radius){if("callout-rect"===o&&r){const n=r.width||0,i=r.height||0;if(n>0||i>0){const o=n/2,r=i/2,s=e-o,l=t-r;if(0!==s||0!==l){const e=Math.abs(s),t=Math.abs(l),d=n/2,u=i/2,h=e*u>t*d?d/e:u/t;a=o+s*h,c=r+l*h}}}else if("bracket"===o&&r){const e=r.width,t=r.height,n=r.depth||30;void 0!==e?(a=e/2,c=n):void 0!==t&&(a=n,c=t/2)}}else{const n=(r.radius||0)+(r.radiusPadding||0);if(n>0&&(0!==e||0!==t)){const i=Math.atan2(t,e);a=Math.cos(i)*n,c=Math.sin(i)*n}}const l=Math.sqrt((e-a)**2+(t-c)**2);if(l>.5){const o=i||"var(--semiotic-text-secondary, currentColor)",r="curve"===n?.type;let d=Math.atan2(t-c,e-a);if(r){const i=(a+e)/2,r=(c+t)/2,u=-(t-c)/l,h=(e-a)/l,p=(n?.curve??.25)*l,m=i+u*p,f=r+h*p;s.push((0,qt.jsx)("path",{className:"connector-curve",d:`M${a},${c}Q${m},${f} ${e},${t}`,fill:"none",stroke:o},"connector-line")),d=Math.atan2(f-c,m-a)}else s.push((0,qt.jsx)("line",{x1:a,y1:c,x2:e,y2:t,stroke:o},"connector-line"));if("arrow"===n?.end){const e=10,t=16/180*Math.PI;s.push((0,qt.jsx)("path",{d:`M${a},${c}L${a+e*Math.cos(d+t)},${c+e*Math.sin(d+t)}L${a+e*Math.cos(d-t)},${c+e*Math.sin(d-t)}Z`,fill:o,stroke:"none"},"connector-arrow"))}}return(0,qt.jsx)("g",{className:"annotation-connector",children:s})}function _t(e){const{x:t=0,y:n=0,dx:i,dy:o,nx:r,ny:s,note:a,connector:c,subject:l,type:d,color:u,className:h,disable:p,opacity:m,strokeDasharray:f,events:y={},"data-testid":g}=e,b=Array.isArray(t)?t[0]??0:t,x=Array.isArray(n)?n[0]??0:n,v=new Set(Array.isArray(p)?p:[]);let w=i||0,k=o||0;null!=r&&(w=r-b),null!=s&&(k=s-x);const M="string"==typeof d?d:"label";if("bracket"===M&&l&&0===w&&0===k)if(void 0!==l.width){w=l.width/2;const e=l.depth||30;k=e+(0>e?-5:5)}else if(void 0!==l.height){const e=l.depth||30;w=e+(0>e?-5:5),k=l.height/2}return(0,qt.jsxs)("g",{className:("annotation "+(h||"")).trim(),transform:`translate(${b},${x})`,"data-testid":g,...null!=m&&{opacity:m},...f&&{strokeDasharray:f},...y,children:[!v.has("connector")&&Ht(w,k,c,u,M,l),!v.has("subject")&&Yt(M,l,u,b,x),!v.has("note")&&Lt(a,w,k,u)]})}function Gt(e){const{noteData:t}=e,{screenCoordinates:n}=t,i="string"==typeof t.type?t.type:"label",o=t.eventListeners||t.events||{};if(t.coordinates&&n){const e=t.nx||n[0][0]+(t.dx??0),o=t.ny||n[0][1]+(t.dy??0),r=n.map((n,r)=>{const s=Object.assign({},t,{note:0===r?t.note:{label:""},x:n[0],y:n[1],nx:e,ny:o});return(0,qt.jsx)(_t,{"data-testid":"semiotic-annotation",...s,type:i},"multi-annotation-"+r)});return(0,qt.jsx)("g",{children:r})}const r=t.note||{title:"none",label:t.label},s=`${r.label}-${r.title}-${t.i}`;return(0,qt.jsx)(_t,{"data-testid":"semiotic-annotation",events:o,...t,type:i},s)}var Xt=require("d3-hierarchy"),Vt=require("d3-shape"),Ut=2;function Kt(e){const t=10**Ut;return Math.round(e*t)/t}function Qt(e,t=2){const n=[],i=[],o=t+1;for(let t=0;o>t;t++){let r=0;for(const[n,i]of e)null!==i&&(r+=n**t*i);n.push(r);const s=[];for(let n=0;o>n;n++){let i=0;for(const[o,r]of e)null!==r&&(i+=o**(t+n));s.push(i)}i.push(s)}i.push(n);const r=function(e,t){const n=e,i=e.length-1,o=[t];for(let e=0;i>e;e++){let t=e;for(let o=e+1;i>o;o++)Math.abs(n[e][o])>Math.abs(n[e][t])&&(t=o);for(let o=e;i+1>o;o++){const i=n[o][e];n[o][e]=n[o][t],n[o][t]=i}for(let t=e+1;i>t;t++)for(let o=i;o>=e;o--)n[o][t]-=n[o][e]*n[e][t]/n[e][e]}for(let e=i-1;e>=0;e--){let t=0;for(let r=e+1;i>r;r++)t+=n[r][e]*o[r];o[e]=(n[i][e]-t)/n[e][e]}return o}(i,o).map(Kt);return{points:e.map(([e])=>[Kt(e),Kt(r.reduce((t,n,i)=>t+n*e**i,0))]),equation:[...r].reverse()}}function Zt(e,t){const n=t.scales?.x??t.scales?.time;return n?null!=e.x?n(e.x):t.xAccessor&&null!=e[t.xAccessor]?n(e[t.xAccessor]):null:null}function Jt(e,t){const n=t.scales?.y??t.scales?.value;return n?null!=e.y?n(e.y):t.yAccessor&&null!=e[t.yAccessor]?n(e[t.yAccessor]):null:null}function en(e){return null==e?null:e+""}function tn(e,t,n){return t.stickyPositionCache?.set(e,n),n}function nn(e,t,n){const i=e.anchor||e.lifecycle?.anchor||"fixed";if("latest"===i){if(null!=e.pointId&&n.pointNodes&&n.pointNodes.length>0)for(let i=n.pointNodes.length-1;i>=0;i--){const o=n.pointNodes[i];if(o.pointId===e.pointId)return tn(t,n,{x:o.x,y:o.y})}const i=function(e){const t=e.data;if(!t||0===t.length)return null;const n=t[t.length-1],i=e.scales?.x??e.scales?.time,o=e.scales?.y??e.scales?.value;if(!i||!o)return null;const r=n[e.xAccessor||"x"],s=n[e.yAccessor||"y"];return null==r||null==s?null:{x:i(r),y:o(s)}}(n);return i?tn(t,n,i):null}if("semantic"===i){const i=function(e,t,n){const i=function(e){return en(e.provenance?.stableId??e.stableId)}(e);if(!i)return null;const o=n.pointNodes?.find(e=>en(e.pointId)===i);if(o)return tn(t,n,{x:o.x,y:o.y});const r=n.data?.find(e=>function(e){return en(e.stableId??e.id??e.provenance?.stableId)}(e)===i);if(!r)return null;const s=Zt(r,n),a=Jt(r,n);return null==s||null==a?null:tn(t,n,{x:s,y:a})}(e,t,n);if(i)return i}let o=null,r=null;if(null!=e.pointId&&n.pointNodes){const t=n.pointNodes.find(t=>t.pointId===e.pointId);t&&(o=t.x,r=t.y)}if(null!=o&&null!=r||(o=Zt(e,n),r=Jt(e,n)),null!=o&&null!=r)return tn(t,n,{x:o,y:r});if("sticky"===i){const e=n.stickyPositionCache?.get(t);if(e)return e}return null}function on(e,t,n,i=50){return!(-i>e||e>(n.width||0)+i||-i>t||t>(n.height||0)+i)}function rn(e){let t=1/0,n=-1/0;for(const i of e)t>i&&(t=i),i>n&&(n=i);return[t,n]}var sn=c(require("react")),[an,cn]=g(e=>({observations:[],maxObservations:100,version:0,pushObservation(t){e(e=>{const n=e.observations;return n.push(t),n.length>e.maxObservations&&n.shift(),{version:e.version+1}})},clearObservations(){e(()=>({observations:[],version:0}))}}));function ln(e,t={}){const n=function(e){const t=e.provenance,n=e.id??e.stableId??t?.stableId;return null==n||""===n?void 0:n+""}(e);return{"data-semiotic-annotation-widget":"",...n?{"data-semiotic-annotation-id":n}:{},onClickCapture(i){const o=function(e){const t=e.nativeEvent;return"touch"===t.pointerType?"touch":0===t.detail?"keyboard":"pointer"}(i);t.onAnnotationActivate?.({annotation:e,annotationId:n,chartId:t.chartId,inputType:o}),n&&t.onObservation&&t.onObservation({type:"annotation-activate",annotationId:n,inputType:o,timestamp:Date.now(),chartType:t.chartType??"unknown",chartId:t.chartId})}}}var dn=16,un=20,hn=require("react/jsx-runtime"),pn="var(--semiotic-bg, #ffffff)",mn=.85;function fn(e){const{x:t,y:n,text:i,fill:o,fontSize:r=12,fontWeight:s,fontFamily:a,textAnchor:c="start",dominantBaseline:l,background:d,className:u}=e,h=function(e){return void 0===e||!0===e||"halo"===e?{type:"halo"}:!1===e||"none"===e?null:"box"===e?{type:"box"}:{type:e.type??"halo",...e}}(d),p=e=>(0,hn.jsx)("text",{x:t,y:n,textAnchor:c,dominantBaseline:l,fill:o,fontSize:r,fontWeight:s,fontFamily:a,className:u,...e?{stroke:e.stroke,strokeWidth:e.strokeWidth,paintOrder:"stroke"}:{},children:i});if(!h)return p();if("halo"===h.type)return p({stroke:h.fill??pn,strokeWidth:h.haloWidth??3});const m=h.padding??{x:6,y:3},f="number"==typeof m?m:m.x,y="number"==typeof m?m:m.y,g=function(e,t){return(e+"").length*t*.6}(i,r),b=r+2*y;let x,v;return x="middle"===c?t-g/2-f:"end"===c?t-g-f:t-f,v="middle"===l||"central"===l?n-b/2:"hanging"===l||"text-before-edge"===l?n-y:n-.8*r-y,(0,hn.jsxs)("g",{className:u,children:[(0,hn.jsx)("rect",{x:x,y:v,width:g+2*f,height:b,rx:h.radius??3,ry:h.radius??3,fill:h.fill??pn,fillOpacity:h.opacity??mn,stroke:h.stroke,strokeWidth:h.strokeWidth}),p()]})}var yn=require("react/jsx-runtime"),gn={linear:Vt.curveLinear,monotoneX:Vt.curveMonotoneX,monotoneY:Vt.curveMonotoneY,step:Vt.curveStep,stepAfter:Vt.curveStepAfter,stepBefore:Vt.curveStepBefore,basis:Vt.curveBasis,cardinal:Vt.curveCardinal,catmullRom:Vt.curveCatmullRom};var bn=new Set(["label","callout","callout-circle","callout-rect","text","widget"]);function xn(e){return!!e&&"object"==typeof e&&bn.has(function(e){return"string"==typeof e?.type?e.type:""}(e))}new Set(["label","callout","callout-circle","callout-rect"]);var vn=2e4,wn=1;function kn(e){return"primary"===e?.emphasis||!0===e?.defensive}function Mn(e,t,n={}){return"number"==typeof n.maxAnnotations&&Number.isFinite(n.maxAnnotations)?Math.max(0,Math.floor(n.maxAnnotations)):e>0&&t>0?Math.max(1,Math.round(e*t/(n.areaPerAnnotation&&n.areaPerAnnotation>0?n.areaPerAnnotation:vn))):1/0}function In(e){let t;const n=e?.emphasis;t="primary"===n?100:"secondary"===n?10:50;const i=e?.provenance?.confidence;switch("number"==typeof i&&Number.isFinite(i)&&(t+=15*Math.max(0,Math.min(1,i))),e?.lifecycle?.freshness){case"fresh":t+=8;break;case"aging":t+=4;break;case"stale":t+=1;break;case"expired":t-=200}return t}var Sn=32,jn=6,An=4,Cn=8,Rn=72,$n=30,Pn=-30,Dn=8,Bn=480,Tn=3;var En={ai:"AI",agent:"agent",watcher:"watcher",system:"system",import:"imported",computed:"computed",user:"you"};function Nn(e){if(!On(e))return e;const t=("string"==typeof e.mobileText?e.mobileText:void 0)??("string"==typeof e.shortText?e.shortText:void 0);return!t||"string"!=typeof e.label&&null!=e.label?e:{...e,label:t}}function On(e){return xn(e)}function Wn(e,t){if(!e)return[];const n=Math.max(1,Math.floor(t/7)),i=e.split(/\s+/).filter(Boolean),o=[];let r="";for(const e of i)r&&r.length+e.length+1>n?(o.push(r),r=e):r=r?`${r} ${e}`:e;return r&&o.push(r),o}function qn(e,t,n,i,o){const r=e+n,s=t+i;return Math.abs(n)>Math.abs(i)?{x:0>n?r-o.width-4:r+4,y:0>i?s-o.height:s,width:o.width,height:o.height}:{x:0>n?r-o.width:r,y:0>i?s-o.height-4:s+4,width:o.width,height:o.height}}function Fn(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function zn(e,t){return Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function Ln(e,t,n,i,o,r,s,a){const c=Fn(e,s);let l=.4*Math.hypot(t.dx,t.dy)+80*function(e,t,n,i){const o=Math.max(0,i-e.x),r=Math.max(0,i-e.y);return(o+Math.max(0,e.x+e.width-(t-i)))*e.height+(r+Math.max(0,e.y+e.height-(n-i)))*e.width}(c,o,r,a);for(const e of n)l+=12*zn(c,e);for(const e of i)l+=4*zn(c,e);return l}function Yn(e){const{annotations:t,context:n,defaultOffset:i=Sn,notePadding:o=jn,markPadding:r=An,edgePadding:s=Cn,preserveManualOffsets:a=!0,routeLongConnectors:c=!0,connectorThreshold:l=Rn,density:d,progressiveDisclosure:u=!1,redundantCues:h=!1,responsive:p,mobile:m,cohesion:f,audience:y}=e,g=n.width||0,b=n.height||0,x="object"==typeof m?m:{},v=x.breakpoint??Bn,w=!!m&&v>=g,k=w&&!1!==x.preferShortText?t.map(Nn):t,M=w&&!d?{maxAnnotations:x.maxAnnotations??("callout-list"===x.strategy?1:2),minVisible:x.minVisible??1}:d,I=u||w&&(!1!==x.progressiveDisclosure||"callout-list"===x.strategy),S=w&&!p?x.responsive??{minWidth:v}:p,j=w&&!f?x.cohesion:f;if(0===k.length||0>=g||0>=b)return k.slice();const A=[],C=function(e,t){return(e.pointNodes||[]).map(e=>{const n=Math.max(1,e.r||1)+t;return{x:e.x-n,y:e.y-n,width:2*n,height:2*n}})}(n,r);let R=!1;const $=k.map((e,t)=>{if(!On(e))return e;const r=function(e,t,n){if("widget"===e.type&&"number"==typeof e.px&&"number"==typeof e.py)return{x:e.px,y:e.py};const i=e.pointId??e.nodeId;if(null!=i&&n.pointNodes){const e=n.pointNodes.find(e=>e.pointId===i);if(e)return{x:e.x,y:e.y}}const o=e.coordinates,r=n.scales?.geoProjection;if(Array.isArray(o)&&o.length>=2&&r){const e=o[0],t=o[1];if("number"==typeof e&&"number"==typeof t){const n=r([e,t]);if(n&&"number"==typeof n[0]&&"number"==typeof n[1])return{x:n[0],y:n[1]}}}return n.scales||"number"!=typeof e.x||"number"!=typeof e.y?nn(e,t,n):{x:e.x,y:e.y}}(e,t,n);if(!r)return e;const d=function(e){if("widget"===e.type)return{width:"number"==typeof e.width?e.width:32,height:"number"==typeof e.height?e.height:32};const t="number"==typeof e.wrap?e.wrap:120,n=[...Wn("string"==typeof e.title?e.title:void 0,t),...Wn("string"==typeof e.label?e.label:void 0,t)],i=n.reduce((e,t)=>Math.max(e,t.length),0);return{width:Math.max(24,Math.min(t,7*i)+10),height:Math.max(18,16*n.length+6)}}(e);if(a&&("number"==typeof(u=e).dx||"number"==typeof u.dy)){const t=function(e){return"text"===e.type||"widget"===e.type?{dx:0,dy:0}:{dx:$n,dy:Pn}}(e);return A.push(Fn(qn(r.x,r.y,"number"==typeof e.dx?e.dx:t.dx,"number"==typeof e.dy?e.dy:t.dy,d),o)),e}var u;let h=null,p=1/0;for(const e of function(e){const t=1.6*e;return[{dx:e,dy:-e},{dx:-e,dy:-e},{dx:e,dy:e},{dx:-e,dy:e},{dx:e,dy:0},{dx:-e,dy:0},{dx:0,dy:-e},{dx:0,dy:e},{dx:t,dy:-t},{dx:-t,dy:-t},{dx:t,dy:t},{dx:-t,dy:t}]}(i)){const t=Ln(qn(r.x,r.y,e.dx,e.dy,d),e,A,C,g,b,o,s);p>t&&(h=e,p=t)}if(!h)return e;const m=Fn(qn(r.x,r.y,h.dx,h.dy,d),o);A.push(m);const f=Math.hypot(h.dx,h.dy),y=c&&f>=l&&"text"!==e.type&&"widget"!==e.type?{...e.connector||{end:"arrow"},type:"curve"}:e.connector;return R=!0,{...e,dx:h.dx,dy:h.dy,...y?{connector:y}:{}}}),P=R?$:k.slice();let D=P;if(h){let e=!1;const t=P.map(t=>{const n=function(e){return"text"!==e.type||"string"!=typeof e.color||Math.hypot("number"==typeof e.dx?e.dx:0,"number"==typeof e.dy?e.dy:0)<Dn?e:{...e,_redundantConnector:!0}}(t);return n!==t&&(e=!0),n});D=e?t:P}{let e=!1;const t=D.map(t=>{if(!0!==t?.defensive)return t;const n=function(e){const t=e?.provenance;if(!t||"object"!=typeof t)return e;const n="string"==typeof t.source?En[t.source]??t.source:null,i="number"==typeof t.confidence&&Number.isFinite(t.confidence)?Math.round(100*Math.max(0,Math.min(1,t.confidence)))+"%":null;if(!n&&!i)return e;if(null!=e.label&&"string"!=typeof e.label)return e;const o=[n,i].filter(Boolean).join(" · "),r="string"==typeof e.label?e.label:"";return r.includes(`(${o})`)?e:{...e,label:r?`${r} (${o})`:`(${o})`}}(t);return n!==t&&(e=!0),n});D=e?t:D}const B=new Set;if(M){const e="object"==typeof M?M:{},t=function(e){if(!e)return 1;const t=function(e){const t=e?.familiarity;if(!t)return Tn;const n=Object.values(t).filter(e=>"number"==typeof e&&Number.isFinite(e));return 0===n.length?Tn:n.reduce((e,t)=>e+t,0)/n.length}(e);return t>2?4>t?1:.6:1.5}(y),n=1===t?e:{...e,maxAnnotations:Math.max(0,Math.round((e.maxAnnotations??Mn(g,b,e))*t))},{deferred:i}=function(e){const{annotations:t,width:n,height:i}=e,o=Math.max(0,e.minVisible??wn),r=Mn(n,i,e),s=t.map((e,t)=>{return{annotation:e,index:t,note:(n=e,xn(n))};var n}),a=s.filter(e=>e.note);if(0===a.length||r>=a.length)return{visible:t.slice(),deferred:[],budget:r};const c=a.filter(e=>kn(e.annotation)),l=a.filter(e=>!kn(e.annotation)).sort((e,t)=>In(t.annotation)-In(e.annotation)||e.index-t.index),d=Math.min(l.length,Math.max(Math.max(0,r-c.length),Math.max(0,o-c.length))),u=new Set([...c.map(e=>e.index),...l.slice(0,d).map(e=>e.index)]),h=[],p=[];for(const{annotation:e,index:t,note:n}of s)!n||u.has(t)?h.push(e):p.push(e);return{visible:h,deferred:p,budget:r}}({annotations:D,width:g,height:b,...n});for(const e of i)B.add(e)}if(S&&("object"==typeof S&&"number"==typeof S.minWidth?S.minWidth:Bn)>=g)for(const e of D)On(e)&&"secondary"===e.emphasis&&B.add(e);if(B.size>0)for(const e of D)!0===e?.defensive&&B.delete(e);let T;return T=0===B.size?D:I?D.map(e=>B.has(e)?{...e,_annotationDeferred:!0}:e):D.filter(e=>!B.has(e)),j?function(e,t){let n=!1;const i=e.map(e=>On(e)?"blended"===e.cohesion||"layer"===e.cohesion?e:(n=!0,{...e,cohesion:t}):e);return n?i:e}(T,j):T}var Hn=require("react/jsx-runtime");function _n(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Gn(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,_n(e))}))}function Xn(e){const{width:t,height:n,pointNodes:i=[],data:o}=e;return{scales:{x:(0,Je.scaleLinear)().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:(0,Je.scaleLinear)().domain([0,Math.max(1,n)]).range([0,Math.max(1,n)])},width:t,height:n,frameType:"network",pointNodes:i,data:o,xAccessor:"x",yAccessor:"y"}}function Vn(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function Un(e){const{width:t,height:n,totalWidth:i,totalHeight:o,margin:r,title:s,legend:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendPosition:h="right",legendLayout:p,pointNodes:m=[],annotations:f,onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x,autoPlaceAnnotations:v,svgAnnotationRules:w,children:k}=e,M=function(e){const t=cn(e=>e.pushObservation),n=sn.useCallback(n=>{e.onObservation?.(n),t?.(n)},[e,t]);return sn.useMemo(()=>({...e,onObservation:n}),[n,e])}({onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x}),I=Ze.useMemo(()=>Vn(f),[f]),S=Ze.useMemo(()=>Xn({width:t,height:n,pointNodes:m}),[n,m,t]),j=Ze.useMemo(()=>I&&v?Yn({annotations:I,context:S,..."object"==typeof v?v:{}}):I,[S,v,I]),A=Ze.useMemo(()=>function(e,t={}){return function(e,n,i){switch(e.type){case"label":case"callout":case"callout-circle":case"callout-rect":{const t=nn(e,n,i);if(!t)return null;const{x:o,y:r}=t;if(!on(o,r,i))return null;const s="callout"===e.type?"callout-circle":e.type,a="callout-circle"===s?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===s?{width:e.width,height:e.height}:void 0;return(0,yn.jsx)(Gt,{noteData:{x:o,y:r,dx:e.dx??30,dy:e.dy??-30,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:s,...a?{subject:a}:{},connector:e.connector||{end:"arrow"},color:e.color,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-"+n)}case"x-threshold":{const t=Zt(null!=e.value?{...e,x:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"top";let s;s="bottom"===r?(i.height||0)-4:"center"===r?(i.height||0)/2:dn;const a=t>.6*(i.width||0),c=a?t-4:t+4,l=a?"end":"start";return(0,yn.jsxs)("g",{opacity:e.opacity,children:[(0,yn.jsx)("line",{x1:t,y1:0,x2:t,y2:i.height||0,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,yn.jsx)(fn,{x:c,y:s,text:e.label,textAnchor:l,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"y-threshold":{const t=Jt(null!=e.value?{...e,y:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"right";let a,c;"left"===r?(a=4,c="start"):"center"===r?(a=(i.width||0)/2,c="middle"):(a=(i.width||0)-4,c="end");const l=un>(s=t)?Math.min((i.height||0)-4,s+dn):s-4;return(0,yn.jsxs)("g",{opacity:e.opacity,children:[(0,yn.jsx)("line",{x1:0,y1:t,x2:i.width||0,y2:t,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,yn.jsx)(fn,{x:a,y:l,text:e.label,textAnchor:c,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"enclose":{const t=(e.coordinates||[]).map(e=>({x:Zt({...e,type:"point"},i),y:Jt({...e,type:"point"},i),r:1})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=(0,Xt.packEnclose)(t),r=e.padding||10;return(0,yn.jsxs)("g",{children:[(0,yn.jsx)("circle",{cx:o.x,cy:o.y,r:o.r+r,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,yn.jsx)(fn,{x:o.x,y:o.y-o.r-r-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"rect-enclose":{const t=(e.coordinates||[]).map(e=>({x:Zt({...e,type:"point"},i),y:Jt({...e,type:"point"},i)})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=e.padding||10,r=t.map(e=>e.x),s=t.map(e=>e.y),[a,c]=rn(r),[l,d]=rn(s),u=a-o,h=c+o,p=l-o;return(0,yn.jsxs)("g",{children:[(0,yn.jsx)("rect",{x:u,y:p,width:h-u,height:d+o-p,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,yn.jsx)(fn,{x:(u+h)/2,y:p-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"highlight":{const t=i.data||[],o="function"==typeof e.filter?t.filter(e.filter):e.field&&null!=e.value?t.filter(t=>t[e.field]===e.value):[],r={stroke:e.color||"#f97316",strokeWidth:2,fill:"none"};return(0,yn.jsx)("g",{children:o.map((t,n)=>{const o=Zt(t,i),s=Jt(t,i);if(null==o||null==s)return null;const a="function"==typeof e.r?e.r(t):e.r||6,c="function"==typeof e.style?e.style(t):e.style||r;return(0,yn.jsx)("circle",{cx:o,cy:s,r:a,...c},"hl-"+n)})},"ann-"+n)}case"bracket":{const t=Zt(e,i),o=Jt(e,i);return(0,yn.jsx)(Gt,{noteData:{x:t??0,y:o??0,dx:e.dx||0,dy:e.dy||0,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:"bracket",subject:{type:e.bracketType||"curly",width:e.width,height:e.height,depth:e.depth||30},color:e.color}},"ann-"+n)}case"trend":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s="ordinal"===i.frameType,a="horizontal"===i.projection,c=s?o:null,l=s?r:null;let d;const u=[],h=new Map;if(s&&c&&l){for(const e of t){const t=e[c];if(null==t)continue;const n=t+"";h.has(n)||(h.set(n,u.length),u.push(n))}d=t.map(e=>{const t=e[c],n=e[l];if(null==t||null==n)return null;const i=h.get(t+"");return null!=i?[i,+n]:null}).filter(e=>null!==e)}else d=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]);if(2>d.length)return null;const p=i.scales?.x??i.scales?.time,m=i.scales?.y??i.scales?.value;if(!p||!m)return null;const f=e=>t=>{const n=Math.max(0,Math.floor(t)),i=Math.min(u.length-1,n+1),o=t-n,r=e(u[n]);return r+(e(u[i])-r)*o},y=p,g=m;let b;if(s)if(a){const e=f(g);b=(t,n)=>[y(n),e(t)]}else{const e=f(y);b=(t,n)=>[e(t),g(n)]}else b=(e,t)=>[y(e),g(t)];const x=e.method||"linear";let v;if("loess"===x)v=function(e,t=.3){const n=e.length;if(2>n)return e.slice();const i=e.slice().sort((e,t)=>e[0]-t[0]),o=i.map(e=>e[0]),r=i.map(e=>e[1]),s=Math.max(2,Math.ceil(t*n)),a=[];for(let e=0;n>e;e++){const t=o[e],i=o.map(e=>Math.abs(e-t)),c=i.slice().sort((e,t)=>e-t)[Math.min(s-1,n-1)]||1,l=[];for(let e=0;n>e;e++){const t=0===c?0:i[e]/c;l[e]=1>t?Math.pow(1-Math.pow(t,3),3):0}let d=0,u=0,h=0,p=0,m=0;for(let e=0;n>e;e++){const t=l[e];0!==t&&(d+=t,u+=t*o[e],h+=t*r[e],p+=t*o[e]*o[e],m+=t*o[e]*r[e])}if(0===d){a.push([t,r[e]]);continue}const f=d*p-u*u;if(1e-12>Math.abs(f))a.push([t,h/d]);else{const e=(d*m-u*h)/f;a.push([t,(h-e*u)/d+e*t])}}return a}(d,e.bandwidth??.3);else{const t="polynomial"===x?Qt(d,e.order||2):function(e){const t=[0,0,0,0];let n=0;for(const[i,o]of e)null!==o&&(n++,t[0]+=i,t[1]+=o,t[2]+=i*i,t[3]+=i*o);const i=n*t[2]-t[0]*t[0],o=0===i?0:Kt((n*t[3]-t[0]*t[1])/i),r=Kt(t[1]/n-o*t[0]/n);return{points:e.map(([e])=>[Kt(e),Kt(o*e+r)]),equation:[o,r]}}(d);v=t.points}const w=v.map(([e,t])=>{const[n,i]=b(e,t);return`${n},${i}`}).join(" "),k=e.color||"#6366f1",M=v[v.length-1],[I,S]=b(M[0],M[1]);return(0,yn.jsxs)("g",{children:[(0,yn.jsx)("polyline",{points:w,fill:"none",stroke:k,strokeWidth:e.strokeWidth||2,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,yn.jsx)("text",{x:I+4,y:S-4,fill:k,fontSize:11,children:e.label})]},"ann-"+n)}case"band":{const t=i.scales?.y??i.scales?.value,s=t?.domain?.(),a=e.y0??s?.[0],c=e.y1??s?.[1],l=null!=a&&t?t(a):0,d=null!=c&&t?t(c):i.height||0,u=ce(e.fill,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,yn.jsxs)("g",{opacity:e.opacity,children:[u.def&&(0,yn.jsx)("defs",{children:u.def}),(0,yn.jsx)("rect",{x:0,y:Math.min(l,d),width:i.width||0,height:Math.abs(d-l),fill:u.fill,fillOpacity:e.fillOpacity||.1}),e.label&&(0,yn.jsx)(fn,{x:(i.width||0)-4,y:(o=l,r=d,Math.max(Math.min(o,r),0)+dn),textAnchor:"end",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"x-band":{const t=i.scales?.x??i.scales?.time,o=t?.domain?.(),r=e.x0??o?.[0],s=e.x1??o?.[1],a=null!=r&&t?t(r):null,c=null!=s&&t?t(s):null;if(null==a||null==c)return null;const l=ce(e.fill||e.color,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,yn.jsxs)("g",{opacity:e.opacity,children:[l.def&&(0,yn.jsx)("defs",{children:l.def}),(0,yn.jsx)("rect",{x:Math.min(a,c),y:0,width:Math.abs(c-a),height:i.height||0,fill:l.fill,fillOpacity:e.fillOpacity??.1}),e.label&&(0,yn.jsx)(fn,{x:Math.min(a,c)+4,y:dn,textAnchor:"start",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"envelope":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=e.upperAccessor||"upperBounds",c=e.lowerAccessor||"lowerBounds",l=e.filter,d=t.filter(e=>null!=e[a]&&null!=e[c]&&!(l&&!l(e))).sort((e,t)=>e[o]-t[o]);if(2>d.length)return null;const u=gn[i.curve||"linear"]||Vt.curveLinear,h=(0,Vt.area)().x(e=>r(e[o])).y0(e=>s(e[c])).y1(e=>s(e[a])).curve(u)(d);if(!h)return null;const p=e.fill||"#6366f1";return(0,yn.jsxs)("g",{children:[(0,yn.jsx)("path",{d:h,fill:p,fillOpacity:e.fillOpacity??.15,stroke:"none"}),e.label&&d.length>0&&(0,yn.jsx)("text",{x:r(d[d.length-1][o])+4,y:s(d[d.length-1][a])-4,fill:p,fontSize:11,children:e.label})]},"ann-"+n)}case"anomaly-band":{const t=i.data||[];if(2>t.length)return null;const o=i.yAccessor||"y",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=t.map(e=>e[o]).filter(e=>null!=e&&isFinite(e));if(2>a.length)return null;const c=a.reduce((e,t)=>e+t,0)/a.length,l=a.reduce((e,t)=>e+(t-c)**2,0)/a.length,d=Math.sqrt(l),u=e.threshold??2,h=c-u*d,p=!1!==e.showBand,m=e.fill||"#6366f1",f=e.fillOpacity??.1,y=e.anomalyColor||"#ef4444",g=e.anomalyRadius??6,b=s(c+u*d),x=s(h),v=t.filter(e=>{const t=e[o];return null!=t&&Math.abs(t-c)>u*d});return(0,yn.jsxs)("g",{children:[p&&(0,yn.jsx)("rect",{x:0,y:Math.min(b,x),width:i.width||0,height:Math.abs(x-b),fill:m,fillOpacity:f}),v.map((e,t)=>{const n=Zt(e,i),o=Jt(e,i);return null==n||null==o?null:(0,yn.jsx)("circle",{cx:n,cy:o,r:g,fill:y,fillOpacity:.7,stroke:y,strokeWidth:1.5},"anomaly-"+t)}),e.label&&(0,yn.jsx)("text",{x:(i.width||0)-4,y:Math.min(b,x)-4,textAnchor:"end",fill:m,fontSize:11,children:e.label})]},"ann-"+n)}case"forecast":{const t=i.data||[];if(3>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s=i.scales?.x??i.scales?.time,a=i.scales?.y??i.scales?.value;if(!s||!a)return null;const c=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]);if(3>c.length)return null;let l;if("polynomial"===(e.method||"linear")){const t=Qt(c,e.order||2).equation;l=e=>t.reduce((t,n,i)=>t+n*Math.pow(e,i),0)}else{const e=c.length;let t=0,n=0,i=0,o=0;for(const[e,r]of c)t+=e,n+=r,i+=e*e,o+=e*r;const r=e*i-t*t;if(1e-12>Math.abs(r))return null;const s=(e*o-t*n)/r,a=(n-s*t)/e;l=e=>a+s*e}const d=c.length,u=c.map(([e,t])=>t-l(e)),h=u.reduce((e,t)=>e+t*t,0),p=Math.sqrt(h/Math.max(d-2,1)),m=c.reduce((e,t)=>e+t[0],0)/d,f=c.reduce((e,t)=>e+(t[0]-m)**2,0),y=e.confidence??.95,g=.99>y?.95>y?.9>y?1:1.645:1.96:2.576,b=e.steps??5,x=c[d-1][0],v=(x-c[0][0])/Math.max(d-1,1),w=[];for(let e=1;b>=e;e++)w.push(x+e*v);const k=[];for(const e of w){const t=l(e),n=p*Math.sqrt(1+1/d+(f>0?(e-m)**2/f:0))*g;k.push({x:e,yCenter:t,yUpper:t+n,yLower:t-n})}const M=`M${k.map(e=>`${s(e.x)},${a(e.yUpper)}`).join(" L")} L${k.slice().reverse().map(e=>`${s(e.x)},${a(e.yLower)}`).join(" L")} Z`,I=k.map(e=>`${s(e.x)},${a(e.yCenter)}`).join(" "),S=`${s(x)},${a(l(x))}`,j=e.strokeColor||"#6366f1";return(0,yn.jsxs)("g",{children:[(0,yn.jsx)("path",{d:M,fill:e.fill||"#6366f1",fillOpacity:e.fillOpacity??.15,stroke:"none"}),(0,yn.jsx)("polyline",{points:`${S} ${I}`,fill:"none",stroke:j,strokeWidth:e.strokeWidth??2,strokeDasharray:e.strokeDasharray??"6,3"}),e.label&&k.length>0&&(0,yn.jsx)("text",{x:s(k[k.length-1].x)+4,y:a(k[k.length-1].yCenter)-4,fill:j,fontSize:11,children:e.label})]},"ann-"+n)}case"widget":{let o,r;if(null!=e.px&&null!=e.py)o=e.px,r=e.py;else{const t=nn(e,n,i);if(!t)return null;o=t.x,r=t.y}if(!on(o,r,i))return null;const s=e.dx??0,a=e.dy??0,c=e.width??32,l=e.height??32,d=e.content??(0,yn.jsx)("span",{style:{fontSize:18,cursor:"default"},title:e.label||"Info",children:"ℹ️"});return(0,yn.jsx)("foreignObject",{x:o+s-c/2,y:r+a-l/2,width:c,height:l,style:{overflow:"visible",pointerEvents:"auto"},children:(0,yn.jsx)("div",{...ln(e,t),style:{width:c,height:l,display:"flex",alignItems:"center",justifyContent:"center"},children:d})},"ann-"+n)}case"text":{const t=nn(e,n,i);if(!t)return null;const{x:o,y:r}=t,s=o+(e.dx||0),a=r+(e.dy||0),c=e.color||"var(--semiotic-text, #333)",l=(0,yn.jsx)("text",{x:s,y:a,fill:c,fontSize:e.fontSize||11,opacity:e.opacity,strokeDasharray:e.strokeDasharray,dominantBaseline:"middle",style:{fontFamily:"inherit"},children:e.label});return!0!==e._redundantConnector?Wt.cloneElement(l,{key:"ann-text-"+n}):(0,yn.jsxs)("g",{opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:[(0,yn.jsx)("line",{x1:o,y1:r,x2:s,y2:a,stroke:c,strokeWidth:1,strokeOpacity:.5,style:{pointerEvents:"none"}}),Wt.cloneElement(l,{opacity:void 0,strokeDasharray:void 0})]},"ann-text-"+n)}case"category-highlight":{const t=e.category;if(null==t)return null;const o=e=>"function"==typeof e&&"function"==typeof e.bandwidth,r=i.scales?.o,s=i.scales?.x,a=i.scales?.y,c=o(r)?r:o(s)?s:o(a)?a:null;if(!c)return null;const l=c(t+"");if(null==l)return null;const d=c.bandwidth(),u=e.color||"var(--semiotic-primary, #4589ff)",h=e.opacity??.15,p=e.label;return(0,yn.jsxs)("g",(i.projection?"vertical"===i.projection:c===s)?{children:[(0,yn.jsx)("rect",{x:l,y:0,width:d,height:i.height||0,fill:u,fillOpacity:h}),p&&(0,yn.jsx)(fn,{x:l+d/2,y:dn,textAnchor:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]}:{children:[(0,yn.jsx)("rect",{x:0,y:l,width:i.width||0,height:d,fill:u,fillOpacity:h}),p&&(0,yn.jsx)(fn,{x:12,y:l+d/2,dominantBaseline:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]},"ann-"+n)}default:return null}var o,r,s}}(0,M),[M]),C=j?function(e,t,n,i){const o=[];return e.forEach((e,r)=>{let s;if(n){const o=n(e,r,i);s=null!=o?o:t(e,r,i)}else s=t(e,r,i);s&&o.push({node:s,annotation:e})}),function(e){const t=e.map((e,t)=>{return{p:e,i:t,emphasis:(n=e.annotation,"primary"===n?.emphasis||"secondary"===n?.emphasis?n.emphasis:null),confidence:Nt(e.annotation),readingOrder:null,rank:St};var n}),n=t.some(e=>null!=e.emphasis||null!=e.confidence),i=e.some(e=>Tt(e.annotation)),o=e.some(e=>null!=Et(e.annotation)),r=e.some(e=>"layer"===Et(e.annotation));if(!n&&!i&&!o)return e.map(e=>e.node);const s=t.filter(e=>null==e.emphasis&&null!=e.confidence).slice().sort((e,t)=>(t.confidence??0)-(e.confidence??0)||e.i-t.i);s.forEach((e,t)=>{e.readingOrder=t,e.rank=jt-t/Math.max(1,s.length)});for(const e of t)e.emphasis&&(e.rank=It[e.emphasis]);const a=t.sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>{const{p:t,i:n,emphasis:i,readingOrder:o}=e,r=Tt(t.annotation);let s=t.node;if("primary"===i||"secondary"===i||null!=o){const e=null==i&&null!=o;s=(0,Mt.jsx)("g",{className:e?"annotation-emphasis annotation-emphasis--inferred":"annotation-emphasis annotation-emphasis--"+i,..."secondary"===i?{opacity:At,fontSize:Ct}:{},...e?{opacity:Ot(o),"data-annotation-reading-order":o}:{},children:t.node},"annotation-emphasis-"+n)}const a=Et(t.annotation);return a&&(s=(0,Mt.jsx)("g",{className:"annotation-cohesion--"+a,children:s},"annotation-cohesion-"+n)),r&&(s=(0,Mt.jsx)("g",{className:"annotation-deferred","data-annotation-disclosure":"deferred",children:s},"annotation-deferred-"+n)),s});return i&&a.unshift((0,Mt.jsx)("style",{children:Dt},"annotation-disclosure-style")),r&&a.unshift((0,Mt.jsx)("style",{children:Bt},"annotation-cohesion-style")),a}(o)}(j,A,w,S):null,R=!0===j?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return(0,Hn.jsxs)(Hn.Fragment,{children:[R?(0,Hn.jsx)("style",{children:Dt},"physics-annotation-disclosure-style"):null,(0,Hn.jsxs)("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:i,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[(0,Hn.jsxs)("g",{transform:`translate(${r.left},${r.top})`,children:[C,k]}),s&&"string"==typeof s?(0,Hn.jsx)("text",{x:i/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:s}):s?(0,Hn.jsx)("foreignObject",{x:0,y:0,width:i,height:Math.max(r.top,28),children:s}):null,a?kt({legend:a,totalWidth:i,totalHeight:o,margin:r,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u}):null]})]})}function Kn(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Qn(e,t){const n="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Kn(e.thickness)??Kn(n)??Kn(t.thickness)??4)}var Zn=2500;function Jn(e){return"function"==typeof e}function ei(e){return void 0===e||!1===e||!Jn(e.binAccessor)&&!Jn(e.labelAccessor)&&!Jn(e.valueAccessor)}function ti(e){if(void 0!==e){if(!1===e)return!1;if(!ei(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function ni(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function ii(e){return function(e){return!Jn(e?.timeAccessor)}(e)}function oi(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:n,sediment:i,...o}=e;return{...o,observation:ni(n),sediment:ti(i)}}var ri={};function si(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var ai=class{constructor(e=function(){const e="string"==typeof ri.url&&ri.url?new URL("./physicsWorker.js",ri.url):function(e){if("undefined"!=typeof __filename){const t=__filename.replace(/\\/g,"/"),n=t.startsWith("/")?t:"/"+t;return new URL("./"+e,"file:"+n)}throw Error("Cannot resolve module worker asset: "+e)}("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,n=this.pending.get(t.requestId);n&&(this.pending.delete(t.requestId),n.cleanup(),t.ok?n.resolve(t.payload):n.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(si());const n=this.nextRequestId;this.nextRequestId+=1;const i={command:e,requestId:n};return new Promise((e,o)=>{const r=()=>{this.pending.delete(n),t?.removeEventListener("abort",r),o(si())},s=()=>t?.removeEventListener("abort",r);this.pending.set(n,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(i)}catch(e){this.pending.delete(n),s(),o(e)}})}async init(e,t,n,i){if(!ii(n))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:oi(e),initialSpawns:t,initialSpawnPacing:n},i);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const n=await this.request({type:"restore",snapshot:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame restore response");return n.frame}async initFromSnapshot(e,t,n){const i=await this.request({type:"init",config:oi(e),snapshot:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame init response");return i.frame}async enqueue(e,t,n){if(!ii(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const i=await this.request({type:"enqueue",spawns:e,pacing:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame enqueue response");return i.frame}async tick(e,t){const n=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame tick response");return n.frame}async settle(e,t){const n=await this.request({type:"settle",maxSteps:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame settle response");return n.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const n=await this.request({type:"remove",ids:e},t);if("removed"!==n.type)throw Error("Physics worker returned a non-remove response");return{frame:n.frame,removed:n.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,n]of this.pending)this.pending.delete(t),n.cleanup(),n.reject(e)}};function ci(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var li={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},di=1e-9,ui=.005;function hi(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function pi(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function mi(e,t,n){return Math.max(t,Math.min(n,e))}function fi(e){return 0>e?-1:1}function yi(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,n=e.shape.height/2;return{minX:e.x-t,minY:e.y-n,maxX:e.x+t,maxY:e.y+n}}function gi(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,n=t.height/2;return{minX:t.x-e,minY:t.y-n,maxX:t.x+e,maxY:t.y+n}}const n=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-n,minY:Math.min(t.y1,t.y2)-n,maxX:Math.max(t.x1,t.x2)+n,maxY:Math.max(t.y1,t.y2)+n}}function bi(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function xi(e,t,n,i,o,r,s,a){const c=o-e,l=(n+s)/2-Math.abs(c);if(0>=l)return null;const d=r-t,u=(i+a)/2-Math.abs(d);return u>0?u>l?{nx:fi(c),ny:0,penetration:l}:{nx:0,ny:fi(d),penetration:u}:null}function vi(e,t,n,i,o,r,s){const a=r/2,c=s/2;let l=e-mi(e,i-a,i+a),d=t-mi(t,o-c,o+c);const u=l*l+d*d;if(u>n*n)return null;if(di>=u){const r=Math.abs(e-(i-a)),s=Math.abs(e-(i+a)),u=Math.abs(t-(o-c)),h=Math.abs(t-(o+c)),p=Math.min(r,s,u,h);return p===r?(l=-1,d=0,{nx:l,ny:d,penetration:n+r}):p===s?(l=1,d=0,{nx:l,ny:d,penetration:n+s}):p===u?(l=0,d=-1,{nx:l,ny:d,penetration:n+u}):(l=0,d=1,{nx:l,ny:d,penetration:n+h})}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:n-h}}function wi(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,n,i,o,r){const s=i-e,a=o-t,c=n+r,l=s*s+a*a;if(l>=c*c)return null;if(di>=l)return{nx:1,ny:0,penetration:c};const d=Math.sqrt(l);return{nx:s/d,ny:a/d,penetration:c-d}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return xi(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const n=vi(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return n?{nx:-n.nx,ny:-n.ny,penetration:n.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?vi(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function ki(e,t){const n=t.shape;return"aabb"===n.type?"circle"===e.shape.type?vi(e.x,e.y,e.shape.radius,n.x,n.y,n.width,n.height):xi(n.x,n.y,n.width,n.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,n,i,o,r,s,a=0){const c=r-i,l=s-o,d=c*c+l*l,u=d>di?mi(((e-i)*c+(t-o)*l)/d,0,1):0,h=n+a/2,p=e-(i+c*u),m=t-(o+l*u),f=p*p+m*m;if(f>=h*h)return null;if(di>=f){const e=Math.sqrt(d);return e>di?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(f);return{nx:p/y,ny:m/y,penetration:h-y}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,n.x1,n.y1,n.x2,n.y2,n.thickness??0)}function Mi(e,t){return`${e}\0${t}`}function Ii(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Si(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:hi(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function ji(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function Ai(e){return{id:e.id,shape:pi(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:ji(e.bodyFilter),index:e.index}}function Ci(e,t){return!!t?.some(t=>Object.is(e,t))}function Ri(e,t){const n=e.bodyFilter;if(!n)return!0;if("function"==typeof n)return n(t);const i=function(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(t,n.property);return!("equals"in n&&!Object.is(i,n.equals)||"notEquals"in n&&Object.is(i,n.notEquals)||n.oneOf&&!Ci(i,n.oneOf)||n.notOneOf&&Ci(i,n.notOneOf))}var $i=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...li,...e},this.random=ci(this.options.seed)}init(e={}){this.options={...li,...e},this.random=ci(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(di,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:hi(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))Ii(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:pi(t.shape),bodyFilter:ji(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,n){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=n/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const n=this.sortedBodies();for(const e of n)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of n)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const n=i/t;e.vx*=n,e.vy*=n}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(n),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(n,o,0===e),this.resolveColliders(n,r,0===e);this.updateSensors(n),this.updateSleeping(n,t)}settle(e=1200,t=this.options.fixedDt){let n=0;for(;e>n&&!this.allSleeping();)this.step(t),n+=1;return n}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:hi(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(Ii)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(Si),colliders:this.sortedColliders().map(Ai),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=ci(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=Si(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=Ai(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const n=this.bodies.get(t.bodyId);if(!n||n.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const o=i.x-n.x,r=i.y-n.y,s=Math.sqrt(o*o+r*r);if(di>=s)continue;const a=o/s,c=r/s,l=(s-t.restLength)*t.stiffness+((("vx"in i?i.vx:0)-n.vx)*a+(("vy"in i?i.vy:0)-n.vy)*c)*t.damping;n.vx+=l*a*e/n.mass,n.vy+=l*c*e/n.mass}}resolveBodyPairs(e,t,n){for(const i of t){const[t,o]=i.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=wi(r,s);a&&(this.resolveDynamicCollision(r,s,a),n&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),n=new Map;for(let i=0;e.length>i;i+=1){if(!1===e[i].bodyCollisions)continue;const o=yi(e[i]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=n.get(o);r?r.push(i):n.set(o,[i])}}const i=new Set;for(const t of Array.from(n.keys()).sort()){const o=n.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let n=t+1;o.length>n;n+=1){const r=o[t],s=o[n];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&bi(yi(e[r]),yi(e[s]))&&i.add(`${r}:${s}`)}}return Array.from(i).sort((e,t)=>{const[n,i]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return n===o?i-r:n-o})}resolveDynamicCollision(e,t,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const i=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=i+o;if(di>=r)return;const s=Math.max(0,n.penetration-ui)/r;e.x-=n.nx*s*i,e.y-=n.ny*s*i,t.x+=n.nx*s*o,t.y+=n.ny*s*o;const a=(t.vx-e.vx)*n.nx+(t.vy-e.vy)*n.ny;if(a>0)return;const c=Math.abs(a),l=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*a/r,d=l*n.nx,u=l*n.ny;e.vx-=d*i,e.vy-=u*i,t.vx+=d*o,t.vy+=u*o,this.applyFriction(e,t,n,l,i,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,n,i,o,r){const s=-n.ny,a=n.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=o+r;if(di>=Math.abs(c)||di>=l)return;const d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),u=mi(-c/l,-i*d,i*d),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,n){for(const i of e)for(const e of t){if(!Ri(e,i))continue;if(!bi(yi(i),gi(e)))continue;const t=ki(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),n&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,n){e.x+=n.nx*Math.max(0,n.penetration-ui),e.y+=n.ny*Math.max(0,n.penetration-ui);const i=e.vx*n.nx+e.vy*n.ny;if(0>i){const o=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+o)*i*n.nx,e.vy-=(1+o)*i*n.ny;const r=-n.ny,s=n.nx,a=e.vx*r+e.vy*s,c=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,n=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=yi(i);for(const o of n){if(!Ri(o,i))continue;if(!bi(e,gi(o)))continue;if(!ki(i,o))continue;const n=Mi(o.id,i.id);t.add(n),this.activeSensors.has(n)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:n,bodyId:i}=Ii(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:n})}this.activeSensors=t}updateSleeping(e,t){const n=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e)Math.sqrt(i.vx*i.vx+i.vy*i.vy)>=this.options.sleepSpeed||Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY))>=this.options.sleepSpeed*t||n&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,i.sleeping||this.options.sleepAfter>i.sleepTime||(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}contactOpposesGravity(e,t){const{x:n,y:i}=this.options.gravity,o=Math.hypot(n,i);return 1e-9>=o||-.2>(e*n+t*i)/o}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Pi=class{constructor(e={}){this.id="builtin",this.capabilities={...(new $i).capabilities,engine:"builtin"},this.world=new $i(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function Di(e={}){return new Pi(e)}function Bi(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Di(t)}var Ti=["binId","targetBin","category","windowIndex","lane","group"];function Ei(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const n=t-e.mean;e.mean+=n/e.count,e.m2+=n*(t-e.mean)}function Ni(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Oi(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function Wi(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function qi(e,t,n){return"function"==typeof e?e(t,n):"string"==typeof e?Wi(t,e):void 0}function Fi(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function zi(e){const t=Ni(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:Ni(e.x),y:Ni(e.y),value:t}}var Li=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const n=Fi(qi(this.config.binAccessor,e,t))??function(e){for(const t of Ti){const n=Fi(Wi(e,t));if(n)return n}return"sediment"}(e),i=Fi(qi(this.config.labelAccessor,e,t))??n,o=function(e,t,n){if("number"==typeof e)return e;const i="function"==typeof e?e(t,n):"string"==typeof e?Wi(t,e):1,o="number"==typeof i?i:Number(i);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(n);return s||(s={id:n,label:i,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(n,s)),s.label=i,s.lastBodyId=e.id,s.lastDatum=e.datum,Ei(s.x,e.x),Ei(s.y,e.y),Ei(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),zi(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(zi)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Oi(t.x),y:Oi(t.y),value:Oi(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function Yi(e,t={}){const{baselineY:n=0,binWidth:i=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*r),d=a?.(e,t)??t*(i+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:n-l,width:i,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Hi(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function _i(e){const t=Math.max(0,Math.floor(e.liveBodies)),n=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+n,o=Hi(e.bodyLimit),r=Hi(e.engineMaxBodiesHint),s=function(e,t,n){if(!1===n)return;const i=Hi(n?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>i?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:n,state:c,warnAt:s}}var Gi={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Xi={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Vi(e={},t=Xi){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function Ui(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Ki(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Qi(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function Zi(e){return{...Ui(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Ji(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function eo(e){return!1!==e&&{...e}}function to(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function no(e){return{...e,gravity:{...e.gravity}}}function io(e,t,n,i){if("circle"===e.shape.type){const o=e.x-t,r=e.y-n,s=e.shape.radius+i,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(n-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>i*i?null:s}function oo(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ro(e,t={}){const{idPrefix:n="plot",includeFloor:i=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return i&&l.push({id:n+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&l.push({id:n+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&l.push({id:n+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:n+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function so(e){const{idPrefix:t="bin",count:n,domainStart:i,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],f=s+(a-s)/2,y=Math.abs(a-s),g=l?n:n-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&n>e)continue;const s=r(i+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:f,width:c,height:y}})}if(null!=u)for(let e=0;n>e;e+=1){const n=i+e*o,s=n+o;if(s>=u)continue;const a=r(n),l=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return m}var ao={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function co(e,t){const n={...e};for(const e of t)n[ao[e]]++;return n}function lo(e,t,n){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:co(n,i)}}var uo=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=lo({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const n=lo(e,t,this.revisions);this.revisions=n.revisions,this.latest=n;for(const e of[...this.listeners])e();return n}},ho=require("d3-quadtree"),po=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,n,i,o,r=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,r)+this.maxSearchRadius,d=i-l,u=i+l,h=o-l,p=o+l;return s.visit((e,t,s,l,m)=>{if(d>l||t>u||h>m||s>p)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e){const t=io(e,i,o,Math.max(0,r));null!=t&&(c>t||t===c&&n.indexOf(e.id)>n.indexOf(a?.id??""))&&(a=e,c=t)}f=f.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const n=e.readState();return 0===n.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=n.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=(0,ho.quadtree)().x(e=>e.x).y(e=>e.y).addAll(n),this.revision=t,this.tree)}},mo=["data","scene-geometry","data-paint","accessibility","evidence"],fo=["scene-geometry","data-paint","accessibility","evidence"],yo=["overlay","accessibility","evidence"],go=(e,t)=>({retainedData:e,invalidations:t}),bo=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],xo=["scene-geometry","data-paint","accessibility","evidence"],vo=[],wo={engine:go("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:go("preserve",xo),colliders:go("preserve",xo),sediment:go("preserve",xo),bodyBudget:go("preserve",bo),bodyLimit:go("preserve",bo),eviction:go("preserve",bo),fixedDt:go("preserve",vo),maxDeltaSeconds:go("preserve",vo),maxSubsteps:go("preserve",vo),settleStepLimit:go("preserve",vo),timeScale:go("preserve",vo),observation:go("preserve",vo)},ko=go("preserve",bo);function Mo(e){let t="preserve";const n=new Set;for(const i of e){const e=wo[i]??ko;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)n.add(t)}return{retainedData:t,invalidations:n}}var Io=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function So(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&Io.every(n=>e[n]===t[n])}function jo(e,t,n,i){return e||!t?"paused":n||!i?"running":"settled"}var Ao=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,n){if(n>0)return void(this.seconds=0);const i=e.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,t):0}},Co=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new po,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new uo,this.simulationState="settled",this.visible=!0,this.quiescence=new Ao;const{bodyBudget:t,colliders:n,engine:i,kernel:o,observation:r,sediment:s,...a}=e;this.config={...Gi,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=Vi(r),this.sediment=new Li(s??!1),this.world=Bi(i,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),n&&this.world.setColliders(Ji(n))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(n=>"kernel"===n?!So(e.kernel,t.kernel):e[n]!==t[n])}(e,this.configInput),{colliders:n,bodyBudget:i,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=Bi(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!So(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=Vi(s,this.observation)),this.sediment.updateConfig(a),n&&(this.world.setColliders(Ji(n)),this.revision+=1),this.configInput={...this.configInput,...e};const l=Mo(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Ji(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},Mo(["colliders"]).invalidations)}enqueue(e,t){const n=Array.isArray(e)?e:[e],i=t?function(e,t={}){const n=Ki(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,n)=>function(e,t,n){return"function"==typeof n?Ki(n(e,t)):"string"==typeof n?Ki(Qi(e,n)):Ki(e.spawnAt)??Ki(Qi(e,"arrivalTime"))??Ki(Qi(e,"timestamp"))??Ki(Qi(e,"time"))??Ki(Qi(e,"eventTime"))}(e,n,t.timeAccessor)),o=i.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=Ki(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=i[t],s=null==o?0:Math.max(0,o-r);return{...Ui(e),spawnAt:n+s/a}})}if("object"==typeof i){const t=Ki(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...Ui(e),spawnAt:n+i/t}))}return e.map(e=>({...Ui(e),spawnAt:n}))}(n,{...t,startAt:t.startAt??this.elapsedSeconds}):n;for(const e of i)this.queue.push({...Ui(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(to),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?mo:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Ui(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},mo)}materializeDueSpawns(){const e=this.revision,t=[],n=[];return this.spawnDue(t,n),0===t.length||(this.observeBodyBudget(n),this.evictOverflow(n),this.syncSimulationState(n),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?mo:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},mo)}tick(e){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(n,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);i.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,n.length),(d>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(d,n,i,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?n.length||i.length||o.length?mo:fo:[]),u}settle(e=this.config.settleStepLimit){const t=this.revision;this.spawnDue([],[]);const n=this.world.settle(e,this.config.fixedDt);return n>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:n},this.revision!==t?fo:[]),n}settleWithObservations(e=this.config.settleStepLimit){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,s);const a=this.observeBodyBudget(s),c=this.evictOverflow(s);i.push(...c.evicted),o.push(...c.sedimented),this.syncSimulationState(s);let l=0;for(n.length>0&&this.quiescence.reset();e>l&&!this.atRest();){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),l+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(l>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const d=this.result(l,n,i,o,r,s,void 0,a);return this.updateResults.record({kind:"settle",count:l},this.revision!==t?n.length||i.length||o.length?mo:fo:[]),d}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Yi(this.readSediment(),e)}hitTest(e,t,n=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:n,chartId:i,...o}=e,r={...o,timestamp:t??this.elapsedSeconds,chartType:n??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?yo:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?yo:[])}remove(e){const t=new Set(e),n=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>n.has(e)||i.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?mo:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},fo),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},fo)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},fo)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,n,i)=>e.applyImpulse(t,n,i),clear:()=>e.clear(),hitTest:(t,n,i)=>e.hitTest(t,n,i),pause:()=>e.setPaused(!0),push:(t,n)=>e.enqueue(t,n),pushMany:(t,n)=>e.enqueue(t,n),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:eo(this.bodyBudget),config:{...this.config,kernel:no(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(Zi),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:eo(e.bodyBudget??{}),kernel:no(e.world.options)},this.bodyBudget=eo(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(Zi).sort(to),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??jo(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},mo)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const n=this.queue.shift();if(!n)return;this.spawnOne(n,t),e.push(n.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const n=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:n?.datum??e.datum,x:n?.x??e.x,y:n?.y??e.y},t)}result(e,t,n,i,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:n,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,n){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);n.emit({type:"physics-settle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,n){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:i,bodyId:r}=oo(t),s=n.observation.sensors[i],a=o.get(r);n.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:s?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())i.has(e)||r("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const n of e)t.has(oo(n).bodyId)&&e.delete(n)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return _i({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const n=`${t.state}:${t.action}`;return n===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=n,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=jo(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const n=this.simulationState;this.simulationState=t,function(e,t,n){n.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||n.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,simulationState:t,previousSimulationState:e})}(n,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:n,liveBodyOrder:i}=function(e,t,n,i,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===n)return s;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const l=function(e,t,n){if("sleeping-first"!==t)return n.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),o=[],r=[];for(const e of n)i.get(e)?o.push(e):r.push(e);return[...o,...r]}(e,n,o),d=l.slice(0,c);if(0===d.length)return s;const u=function(e,t,n,i){const o=new Map(e.readState().map(e=>[e.id,e])),r=[];for(const e of n){const n=o.get(e);if(!n)continue;const s=t.add(n);s&&(r.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:n.datum,x:n.x,y:n.y,binId:s.id,count:s.count,total:s.total}))}return r}(e,t,d,r);e.remove(d);const h=new Set(d);return{evicted:d,sedimented:u,liveBodyOrder:o.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:n}}};function Ro(e,t,n){const i=new Co(e);return t?.length&&(i.enqueue(t,n),i.materializeDueSpawns()),i}function $o(){return"undefined"!=typeof performance?performance.now():Date.now()}var Po=c(require("react-dom/server"));function Do(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Bo={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function To(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function Eo(e,t){const n="function"==typeof t?t(e):t;return{...Bo,...n??{}}}function No(e,t={}){const n=e.settle(t.maxSteps),i=e.readBodies(),o=e.snapshot(),r=function(e,t={}){return e.map(e=>function(e,t={}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),i={label:t.getBodyLabel?.(e)??To(e)},o={style:Eo(e,t.bodyStyle),datum:n,accessibleDatum:n,accessibility:i,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...o}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...o}}(e,t))}(i,t),s=function(e,t={}){const n=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),i=n.filter(e=>e.sleeping).length;return{bodyCount:n.length,sleepingCount:i,settled:"settled"===e.simulationState&&0===e.queue.length&&i===n.length,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:Do(t.projectionRows)}}(o,{bodies:i,projectionRows:t.projectionRows,stepsRun:n});return{snapshot:o,bodies:i,sceneNodes:r,evidence:s,stepsRun:n}}var Oo=require("react/jsx-runtime"),Wo={top:0,right:0,bottom:0,left:0};function qo(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}function Fo(e,t){if("function"==typeof t){const n=t(e);return Number.isFinite(n)&&n>0?Number(n):1}const n=e.datum;if(t&&n&&"object"==typeof n){const e=Number(n[t]);if(Number.isFinite(e)&&e>0)return e}const i=Number(n?.work??n?.reviewWork??n?.value);return Number.isFinite(i)&&i>0?i:1}function zo(e,t){if("function"==typeof t){const n=t(e);if(null!=n&&(n+"").length>0)return n+""}else if(t){const n=Yo(e.datum,t),i=Yo(e,t),o=n??i;if(null!=o&&(o+"").length>0)return o+""}return e.id}function Lo(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const n=Math.max(0,Math.min(1,t))*(e.length-1),i=Math.floor(n);return e[i]+(e[Math.ceil(n)]-e[i])*(n-i)}function Yo(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Ho(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Yo(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function _o(e){const t=e.regionId,n=Math.max(0,e.unitsPerSecond),i=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,m=new Map,f=new Map,y=new Map,g=[];let b=0,x=new Map,v=new Map,w=0,k=0,M=0,I=null,S=0,j=0,A=0,C=0,R=0,$=0,P=0,D=0,B=0,T=0,E=0,N=0,O=-1,W=!1;function q(e,n){const i=n(e);return!!i&&i.activeRegionIds.includes(t)}function F(){N+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function L(n,i,o,r){const s={bodyId:n.id,jobId:i.jobId,visitId:i.visitId,visit:i.visit,remaining:i.work,total:i.work,queuedAt:i.queuedAt,sequence:r};return d.set(i.jobId,s),y.delete(n.id),f.set(n.id,i.jobId),j+=1,A+=i.work,F(),function(n,i,o){const r=z(i);e.onQueued?.(n,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,queueDepth:d.size})}(n,s,o),s}function Y(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const n of t){if(d.size>=s)break;const t=m.get(n.jobId);t&&h.has(n.jobId)?(u.delete(n.jobId),y.delete(n.bodyId),L(t,n,e,n.sequence)):u.delete(n.jobId)}}function H(){let e=0;for(const t of d.values())e+=t.remaining;return e}function _(){B=Math.max(B,d.size),T=Math.max(T,H())}function G(){const e=M-a,t=Math.max(0,Math.min(a,M-(I??M)));let i=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;i+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const n=t.end-t.start;c+=n>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/n):t.processedWork}const l=t>0?o/t:0;return{seconds:t,arrivals:i,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?i/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&n>0?Math.max(0,Math.min(1,c/(n*t))):0,pressure:n>0?l/n:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:i=>{const o=i.controls.readBodies(),r=new Map,j=new Map;for(const t of o){if(r.set(t.id,t),!q(t.id,i.getRegionState))continue;if(!Ho(t,e.bodyFilter))continue;const n=zo(t,e.jobKey),o=j.get(n)??[];o.push(t),j.set(n,o)}const A=Number.isFinite(i.dt)?Math.max(0,i.dt):0;if(!W){const e=Number.isFinite(i.elapsed)?Math.max(0,i.elapsed):A;M=Math.max(0,e-A),W=!0}const B=M,T=B+A;M=T,I=null==I?B:Math.min(I,B);const N={start:B,end:T,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},H=new Map;for(const[e,t]of j){const n=h.get(e)?.bodyId,i=t.find(e=>e.id===n)??t[0];H.set(e,i),m.set(e,i)}for(const[n,o]of h){if(H.has(n))continue;const s=d.get(n),a=r.get(o.bodyId)??m.get(n);if(s){d.delete(n),f.delete(s.bodyId),P+=1,D+=s.remaining,F();const r={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&e.onAbandoned?.(a,r),i.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:n,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:r.queueSeconds,queueDepth:d.size})}u.delete(n),y.delete(o.bodyId),h.delete(n),m.delete(n)}for(const[n,o]of H){if(h.has(n))continue;const r=(p.get(n)??0)+1;p.set(n,r);const a=Fo(o,e.unitAccessor),c={bodyId:o.id,jobId:n,visitId:`${t}:${n}:${r}`,visit:r,regionId:t,work:a,queuedAt:M};h.set(n,c),S+=1,N.arrivals+=1,N.arrivalWork+=a;const l=b++;if(s>d.size)L(o,c,i,l);else{const s={...c,blockedAt:M,sequence:l};u.set(n,s),y.set(o.id,n),$+=1,F(),e.onBlocked?.(o,s),i.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:n,visitId:c.visitId,visit:r,queuedAt:M,blockedAt:M,queueDepth:d.size,blockedDepth:u.size})}}Y(i),_();const G=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let X=n*A;for(const n of G){if(0>=X)break;const o=Math.min(n.remaining,X);if(n.remaining-=o,X-=o,C+=o,N.processedWork+=o,n.remaining>1e-6)continue;d.delete(n.jobId),f.delete(n.bodyId),k+=1,R+=n.total,N.completions+=1,N.completedWork+=n.total;const s=Math.max(0,M-n.queuedAt);E+=s,F();const a=r.get(n.bodyId);if(!a)continue;i.controls.applyImpulse(n.bodyId,l.x??0,l.y??0);const c={...z(n),completedAt:M,queueSeconds:s};e.onProcessed?.(a,c),i.controls.recordObservation({type:"physics-capacity-processed",bodyId:n.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,completedAt:M,queueSeconds:s,queueDepth:d.size})}Y(i),_(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=M-a;for(;g.length>0&&t>g[0].end;)g.shift()}(N);const V=Math.floor(M/c);V!==O&&(O=V,F())},getSnapshot:()=>{const e=H(),i=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=d.size,r=Array.from(d.values()).map(e=>Math.max(0,M-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:k,unitsPerSecond:n,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+i,blockedDepth:u.size,blockedWork:i,arrivalCount:S,admittedCount:j,admittedWork:A,processedWork:C,completedWork:R,blockedCount:$,abandonedCount:P,abandonedWork:D,peakQueueDepth:B,peakRemainingWork:T,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:Lo(r,.5),p95Seconds:Lo(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:k>0?E/k:0,window:G(),simulatedAt:M,metricRevision:N}},bodyForce:e=>{if("none"===i)return null;const n=f.get(e.body.id),s=y.get(e.body.id),a=n?d.get(n):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?x.get(e.body.id):v.get(e.body.id);if(null==l)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-l*(.15*o))-e.body.x)*r,y:(h.y-(l-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*r*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function Go(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Xo(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Go(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Vo(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),n=new Map(t.map(e=>[e.bodyId,e])),i=new Map,o=new Map,r=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const n=i.get(e);if(n)return n;const r=t.find(e=>!o.has(e.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:e,assignedAt:d};return i.set(e,s),o.set(r.id,s),u+=1,s},release:e=>{const t=i.get(e);return!!t&&(i.delete(e),o.delete(t.resourceId),u+=1,!0)},getAssignment:e=>i.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of i)l.has(e)&&l.has(t.resourceBodyId)||(i.delete(e),o.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-o.size,assigned:o.size,assignments:Array.from(i.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=n.get(e.body.id);if(t){const n=o.get(t.id),i=n?l.get(n.caseBodyId):void 0,a=n?r:s;return{x:((i?i.x+(c.x??0):t.home.x)-e.body.x)*a,y:((i?i.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=i.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function Uo(e,t){const n="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):Go(e.datum,t.deadlineAccessor)??Go(e,t.deadlineAccessor);return Number.isFinite(Number(n))?Math.max(0,Number(n)):0}function Ko(e){const t=new Map;let n=0,i=0;function o(n){t.set(n.bodyId,n),i+=1,e.onStateChange?.({...n})}function r(e){const i=t.get(e);return!(!i||null!=i.completedAt||(o({...i,completedAt:n,state:"unhappy"===i.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const i=t.get(e);return!(!i||null!=i.completedAt||"unhappy"===i.state||(o({...i,state:"protected",protectedAt:n}),0))},complete:r,getCase:e=>t.get(e),tick:i=>{n=Math.max(n,i.elapsed);for(const s of i.controls.readBodies()){if(!Xo(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=Uo(s,e);o({bodyId:s.id,openedAt:n,deadlineAt:n+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&i.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>n||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),o=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:n,metricRevision:i}}}}function Qo(e){const t=new Set;let n=0,i=0,o=0,r=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{n=Math.max(n,s.elapsed);const a=r;var c;c=n,r=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const n of l){const i=s.getRegionState(n.id)?.activeRegionIds.includes(e.regionId);i&&Xo(n,e.bodyFilter)&&(r||t.has(n.id)||(t.add(n.id),o+=1,e.onHeld?.(n)))}if(r&&!a){for(const n of t){const t=d.get(n);t&&(s.controls.applyImpulse(n,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),i+=1,e.onReleased?.(t))}t.clear(),o+=1}for(const e of t)d.has(e)||(t.delete(e),o+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:r,blocked:t.size,released:i,simulatedAt:n,metricRevision:o}),bodyForce:n=>{if(r||!t.has(n.body.id))return null;const i=n.regions?.find(t=>t.id===e.regionId),o=i?.shape;if(!o||"aabb"!==o.type)return{x:.8*-n.body.vx,y:.8*-n.body.vy};const s=e.holdForce??.4;return{x:(o.x-n.body.x)*s-.45*n.body.vx,y:(o.y-n.body.y)*s-.45*n.body.vy}}}}function Zo(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Jo(e){if(!e?.length)return null;const t=e.slice(),n=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:n,onTick:(e,n,i)=>{const o={result:e,controls:n,dt:i.dt,elapsed:i.elapsed,getRegionState:i.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let n=null;for(const i of t)i.bodyForce&&(n=Zo(n,i.bodyForce(e)));return n}}}function er(e){const t=new Set,n=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:i=>{const o=i.controls.readBodies();for(const r of o){const o=i.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),i.controls.applyImpulse(r.id,n.x??0,n.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}var tr=require("react");function nr(){return"undefined"==typeof document||!document.hidden}var ir=require("react/jsx-runtime"),or="var(--semiotic-focus, #005fcc)";function rr({active:e,hoverPoint:t,margin:n,size:i,shape:o="circle",width:r,height:s,pathData:a}){if(!e||!t)return null;const c=t.x+n.left,l=t.y+n.top;let d;if("geoarea"!==o&&"path"!==o||!a)if("rect"===o&&null!=r&&null!=s){const e=Math.max(r,4),t=Math.max(s,4);d=(0,ir.jsx)("rect",{x:c-e/2-3,y:l-t/2-3,width:e+6,height:t+6,rx:3,fill:"none",stroke:or,strokeWidth:2,strokeDasharray:"4,2"})}else d=(0,ir.jsx)("circle","wedge"===o?{cx:c,cy:l,r:12,fill:"none",stroke:or,strokeWidth:2.5,strokeDasharray:"6,3"}:{cx:c,cy:l,r:8,fill:"none",stroke:or,strokeWidth:2,strokeDasharray:"4,2"});else d=(0,ir.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:(0,ir.jsx)("path",{d:a,fill:"none",stroke:or,strokeWidth:2.5,strokeDasharray:"6,3"})});return(0,ir.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:i[0],height:i[1],pointerEvents:"none",zIndex:2},"aria-hidden":"true",children:d})}var sr=require("react"),ar={sceneGeometry:0,layout:0,domain:0};function cr(e){const{domain:t,layout:n,sceneGeometry:i}=e.revisions;return{domain:t,layout:n,sceneGeometry:i}}function lr(e,t){return{sceneGeometry:Math.max(e.sceneGeometry,t.sceneGeometry),layout:Math.max(e.layout,t.layout),domain:Math.max(e.domain,t.domain)}}var dr="production"!==process.env.NODE_ENV,ur={revisions:ar,signature:"",sawSignals:!1,wasUnconsumed:!1,warnUnconsumed:!1},hr=class{constructor(e="scene host"){this.hostName=e,this.lastConsumed=ar,this.lastObserved=ar,this.lastDuplicateWarning="",this.lastUnconsumedWarning=""}observeUpdateResult(e){dr&&(this.lastObserved=lr(this.lastObserved,cr(e)))}beforeCompute(e,t){if(!dr)return ur;const n=lr(cr(e),this.lastObserved),i=function(e){return`${e.sceneGeometry}|${e.layout}|${e.domain}`}(n),o=!((r=n).sceneGeometry===(s=this.lastConsumed).sceneGeometry&&r.layout===s.layout&&r.domain===s.domain);var r,s;return{revisions:n,signature:i,sawSignals:e.changed.has("scene-geometry")||e.changed.has("layout")||e.changed.has("domain"),wasUnconsumed:o,warnUnconsumed:!t&&o&&this.lastUnconsumedWarning!==i}}afterCompute(e,t,n){if(dr){if(t&&e.wasUnconsumed&&(this.lastConsumed=e.revisions),e.warnUnconsumed&&!t)return console.warn(`[semiotic] ${this.hostName} observed scene-affecting revisions without a scene rebuild: ${e.signature}.`),void(this.lastUnconsumedWarning=e.signature);t&&e.sawSignals&&!e.wasUnconsumed&&!n&&this.lastDuplicateWarning!==e.signature?(console.warn(`[semiotic] ${this.hostName} performed scene rebuild with unchanged scene revisions: ${e.signature}.`),this.lastDuplicateWarning=e.signature):t&&!e.sawSignals&&(this.lastDuplicateWarning="")}}},pr=(0,sr.memo)(function({store:e,diagnostics:t}){return(0,sr.useEffect)(()=>{const n=()=>t.observeUpdateResult(e.getUpdateSnapshot());return n(),e.subscribeUpdateResult(n)},[t,e]),null}),mr=(c(require("react")),c(require("react"))),fr=(require("react/jsx-runtime"),mr.createContext(null)),yr=require("react/jsx-runtime"),gr={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0};function br({hoverPoint:e}){let t="";if(e){const n=e.data||e;t="object"==typeof n?"Data point: "+Object.entries(n).filter(([,e])=>"object"!=typeof e&&"function"!=typeof e).map(([e,t])=>`${e}: ${t}`).join(", "):"Data point: "+n}return(0,yr.jsx)("div",{"aria-live":"polite","aria-atomic":"true",style:gr,children:t})}var xr=require("react/jsx-runtime");function vr({summary:e}){return e?(0,xr.jsx)("div",{role:"note",style:gr,children:e}):null}function wr({tableId:e}){return(0,xr.jsx)("a",{href:"#"+e,style:gr,onClick:t=>{t.preventDefault();const n=document.getElementById(e);n&&requestAnimationFrame(()=>n.focus())},onFocus:e=>{Object.assign(e.currentTarget.style,{position:"absolute",width:"auto",height:"auto",overflow:"visible",clip:"auto",whiteSpace:"normal",padding:"4px 8px",background:"var(--semiotic-bg, #fff)",color:"var(--semiotic-text, #000)",border:"2px solid var(--semiotic-focus, #005fcc)",borderRadius:"4px",zIndex:"10",fontSize:"12px",top:"4px",left:"4px"})},onBlur:e=>{const t=e.currentTarget;t.removeAttribute("style"),Object.assign(t.style,gr)},children:"Skip to data table"})}function kr(e,t,n){const i=function(e,t){if(null==t)return;const n=ue(e,t,"");return""===n?void 0:n}(e,n.fill)??"#4e79a7",o=n.stroke,r=n.strokeWidth??0,s=n.opacity??1,a=n.fillOpacity??1,c=function(e,t){const n=t.mark;if(n)return n;const i=e.datum,o=i?.__physicsMark??i?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}(t,n),l="circle"===t.shape.type?n.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=s,e.beginPath(),"pill"===c||"square"===c||"aabb"===t.shape.type){const n="pill"===c?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,i="pill"===c?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,o=t.x-n/2,r=t.y-i/2,s="pill"===c?i/2:Math.min(4,n/4);e.moveTo(o+s,r),e.arcTo(o+n,r,o+n,r+i,s),e.arcTo(o+n,r+i,o,r+i,s),e.arcTo(o,r+i,o,r,s),e.arcTo(o,r,o+n,r,s),e.closePath()}else if("diamond"===c)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===c){const n=6;for(let i=0;n>i;i+=1){const o=2*Math.PI*i/n-Math.PI/2,r=t.x+Math.cos(o)*l,s=t.y+Math.sin(o)*l;0===i?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);i&&(e.save(),e.globalAlpha*=a,e.fillStyle=i,e.fill(),e.restore()),"halo"===c&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=o??i,e.lineWidth=Math.max(1.5,r||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&r>0&&(e.strokeStyle=o,e.lineWidth=r,n.strokeDasharray&&e.setLineDash(n.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function Mr(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Ir(e){return e.sensorId??"stream-region-"+e.id}function Sr(e){const t=Ir(e),n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const i=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...n,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:i}},{...n,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:i}},{...n,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:i}},{...n,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:i}}]}return e.collider?[{...n,id:t+"-collider",shape:e.shape}]:[]}function jr(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function Ar(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}function Cr(e){if(!1===e.semanticItem)return null;const t=e.shape,n=e.semanticItem??{},i="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...i,...n,id:n.id??i.id}}function Rr(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function $r(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}var Pr=[];function Dr(e){const t=e.store.controls(),n=e.store.snapshot(),i=Math.max(0,e.result.steps*(n.config.fixedDt||1/60)),o=function(e,t,n,i){const o=Number.isFinite(i)?Math.max(0,i):0;if(0>=o||!Rr(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const i=n.get(t.id);if(!i||!i.activeRegionIds.size)continue;const s=jr(i);if(s)for(const n of i.activeRegionIds){const i=r.get(n);if(!i)continue;const c=Ar(i.force,{body:t,region:i,regionState:s}),l=Number(i.damping??0),d=(c?.x??0)*o-(Number.isFinite(l)?t.vx*l*o:0),u=(c?.y??0)*o-(Number.isFinite(l)?t.vy*l*o:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,i),r=function(e,t,n,i,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(n.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let n=0;c.length>n;n+=1){const r=c[n],d=i.get(r.id),u=jr(d);let h=Pr;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const n=a.get(t);n&&e.push(n)}h=e}const p=$r(t,{body:r,bodies:c,index:n,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,f=(p.y??0)*s;(m||f)&&(e.applyImpulse(r.id,m,f),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,n.simulationState,i);return e.composed&&e.composed.onTick(e.result,t,{dt:i,elapsed:e.result.elapsedSeconds,getRegionState:t=>jr(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:n}}function Br(e,t,n,i,o,r,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:d,simulationState:t,regionState:r,regions:s},h="function"==typeof n?n(e,u):n,p=s.reduce((t,n)=>n.bodyStyle?{...t,..."function"==typeof n.bodyStyle?n.bodyStyle(e,u):n.bodyStyle}:t,{}),m=d?"function"==typeof i?i(e,u):i:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...m}}var Tr=require("react"),Er=c(require("react")),Nr=require("react/jsx-runtime"),Or={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Wr="semiotic-accessible-data-table",qr=Wr+" semiotic-accessible-data-table-hidden",Fr=Wr+" semiotic-accessible-data-table-visible",zr={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},Lr={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Yr={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},Hr={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},_r={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},Gr={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Xr={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},Vr={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function Ur(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function Kr(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function Qr(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function Zr(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function Jr(e){const t=es(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function es(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const n=Ur(t);return null==n?null:[e,n]}).filter(e=>null!=e).slice(0,8):[]}function ts({hover:e}){const t=es(e.data);return(0,Nr.jsxs)("div",{className:"semiotic-tooltip",style:Be,children:[(0,Nr.jsx)("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>(0,Nr.jsxs)("div",{children:[(0,Nr.jsxs)("span",{style:{opacity:.72},children:[e,": "]}),(0,Nr.jsx)("span",{children:t})]},e))]})}function ns(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const n=Ur(t);return null==n?null:`${e}: ${n}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function is(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],n=new Map;for(const t of e)t.group&&n.set(t.group,(n.get(t.group)??0)+1);return n.size&&t.push(Array.from(n).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function os(e){const{chartTitle:t,items:n,tableId:i}=e,[o,r]=Er.useState(!1),[s,a]=Er.useState(5),c=mr.useContext(fr),l=c?.visible??!1,d=o||l,u=Er.useRef(null),h="Data summary for "+(t??"physics chart");Er.useEffect(()=>{d||a(5)},[d]);const p=Er.useCallback(e=>{e.target===e.currentTarget&&(o||l||r(!0))},[o,l]),m=Er.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||r(!1)},[l]);if(!n.length)return(0,Nr.jsx)("span",{id:i,tabIndex:-1,style:Or});if(!d)return(0,Nr.jsx)("div",{id:i,className:qr,role:"region","aria-label":h,tabIndex:-1,style:Or,onFocus:p,children:(0,Nr.jsxs)("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",n.length," semantic items)"]})});const f=Math.min(s,n.length),y=n.slice(0,f),g=n.length-f;return(0,Nr.jsxs)("div",{ref:u,id:i,className:Fr,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:zr,children:[(0,Nr.jsx)("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),r(!1)},style:Yr,children:"×"}),(0,Nr.jsx)("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Lr,children:is(n)}),(0,Nr.jsxs)("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:Hr,children:[(0,Nr.jsx)("caption",{className:"semiotic-accessible-data-table-caption",style:Xr,children:g>0?`First ${f} of ${n.length} semantic items`:`All ${n.length} semantic items`}),(0,Nr.jsx)("thead",{children:(0,Nr.jsxs)("tr",{children:[(0,Nr.jsx)("th",{scope:"col",style:_r,children:"Item"}),(0,Nr.jsx)("th",{scope:"col",style:_r,children:"Description"}),(0,Nr.jsx)("th",{scope:"col",style:_r,children:"Group"}),(0,Nr.jsx)("th",{scope:"col",style:_r,children:"Position"}),(0,Nr.jsx)("th",{scope:"col",style:_r,children:"Data"})]})}),(0,Nr.jsx)("tbody",{children:y.map((e,t)=>(0,Nr.jsxs)("tr",{children:[(0,Nr.jsx)("th",{scope:"row",style:Gr,children:e.label}),(0,Nr.jsx)("td",{style:Gr,children:e.description??e.label}),(0,Nr.jsx)("td",{style:Gr,children:e.group??""}),(0,Nr.jsxs)("td",{style:Gr,children:[Math.round(e.x),", ",Math.round(e.y)]}),(0,Nr.jsx)("td",{style:Gr,children:ns(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?(0,Nr.jsxs)("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:Vr,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}ts.ownsChrome=!0;var rs=require("react/jsx-runtime"),ss=[640,360],as={top:0,right:0,bottom:0,left:0},cs=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),ls="StreamPhysicsFrame",ds=(0,h.memo)((0,h.forwardRef)(function(e,t){const{accessibleTable:n=!0,annotations:i,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:a,bodySemanticItemLimit:c=200,bodySemanticItems:l=!1,bodySemanticUpdateMs:d=200,bodyForces:f,bodyStyle:y,chartId:g,className:b,frameScheduler:x,clock:v,random:w,seed:k,color:M,config:I,controllers:S,continuous:A=!1,description:R,emphasis:P,chartMode:B,enableHover:T=!0,foregroundGraphics:E,hoverRadius:N=16,initialSpawns:O,initialSpawnPacing:W,legend:_,legendClickBehavior:G,legendHighlightedCategory:X,legendHoverBehavior:K,legendIsolatedCategories:Z,legendLayout:J,legendPosition:ee,margin:te,onClick:ne,onObservation:ie,onRegionEvent:oe,onSimulationExecutionChange:re,onBodyHover:se,onBodyPointerDown:ae,onSemanticItemActivate:ce,onSemanticItemFocus:le,onTick:de,opacity:ue,paused:he=!1,regionEffects:pe=[],responsiveHeight:me,responsiveWidth:fe,selectedBodyStyle:ye={stroke:"#111827",strokeWidth:2,opacity:1},selection:ge,semanticItems:be=[],simulationExecution:xe="auto",size:ve=ss,stroke:we,strokeWidth:ke,summary:Me,suspendWhenHidden:je=!0,svgAnnotationRules:Ae,title:Ce,tooltipContent:Re,workerBodyThreshold:$e=Zn,renderBody:Pe,beforePaint:De,afterPaint:Be}=e,Te=u.useMemo(()=>({color:M,stroke:we,strokeWidth:ke,opacity:ue}),[M,ue,we,ke]),Ee=(0,h.useRef)(ie);Ee.current=ie;const Ne=(0,h.useRef)(g);Ne.current=g;const Oe=(0,h.useRef)(new Map),We=(0,h.useRef)(pe);We.current=pe;const Ze=(0,h.useRef)(f);Ze.current=f;const Je=(0,h.useRef)(de);Je.current=de;const et=u.useMemo(()=>Jo(S),[S]),tt=(0,h.useRef)(et);tt.current=et;const nt=A||!!et?.continuous,it=(0,h.useRef)(nt);it.current=nt;const ot=u.useMemo(()=>{if(!f&&!et?.bodyForce)return f;if(!et?.bodyForce)return f;if(!f)return et.bodyForce;const e=et.bodyForce;return t=>{const n="function"==typeof f?f(t):f,i="function"==typeof e?e(t):e;return n||i?{x:(n?.x??0)+(i?.x??0),y:(n?.y??0)+(i?.y??0)}:null}},[f,et]);Ze.current=ot;const rt=u.useMemo(()=>new Map(pe.map(e=>[Ir(e),e])),[pe]),st=u.useMemo(()=>new Map(pe.map(e=>[e.id,e])),[pe]),at=u.useMemo(()=>pe.map(Cr).filter(e=>null!=e),[pe]),[ct,lt]=u.useState([]),dt=u.useMemo(()=>ct.length||at.length?[...be,...ct,...at]:be,[ct,at,be]),ut=u.useMemo(()=>Rr(pe),[pe]),ht=!!ot,pt=(0,h.useRef)(null),mt=(0,h.useRef)(v??$o);mt.current=v??$o;const ft=(0,h.useCallback)((e,t,n)=>{const i=pt.current;if(!i||!n)return!1;const o=i.readBodies().find(t=>t.id===e),r=jr(Oe.current.get(e));if(!o||!r)return!1;const s=Ar(n,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(i.applyImpulse(e,s.x??0,s.y??0),0))},[]),yt=(0,h.useCallback)((e,t,n)=>{if(!n.bodyId)return;const i=jr(Oe.current.get(n.bodyId));if(!i)return;const o={bodyId:n.bodyId,datum:n.datum,observation:n,region:t,regionState:i,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),oe?.(o)},[oe]),gt=(0,h.useCallback)(e=>{const t=e.sensorId?rt.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const n=function(e,t){let n=e.get(t);return n||(n={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,n)),n}(Oe.current,e.bodyId),i=pt.current?.readBodies().find(t=>t.id===e.bodyId),o=jr(n),r=i&&o?{body:i,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(n.activeRegionIds.add(t.id),n.regionIds.add(t.id),n.energy+=t.energyDelta??0,r){!function(e,t,n){const i="function"==typeof e.attributes?e.attributes(t):e.attributes;i&&(n.attributes={...n.attributes,...i})}(t,r,n);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(n.charges[t.id]=e)}ft(e.bodyId,t,t.impulseOnEnter),yt("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(n.activeRegionIds.delete(t.id),ft(e.bodyId,t,t.impulseOnExit),yt("region-exit",t,e))},[ft,yt,rt]),bt=u.useMemo(()=>{if(!i?.length)return[];const e=i.filter(e=>"barrier"===e.physics||"sensor"===e.physics);return e.length?function(e=[],t={}){const n=t.idPrefix?t.idPrefix+"-":"",i=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=Qn(o,t),s=o.colliderId??`${n}${o.id}`;let a;if("x"===e){const e=Kn(o.x),n=Kn(o.y1)??Kn(t.plotBounds?.y)??Kn(o.y),i=Kn(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Kn(o.y);if(null==e||null==n||null==i)continue;a={type:"segment",x1:e,y1:n,x2:e,y2:i,thickness:r}}else{const e=Kn(o.y),n=Kn(o.x1)??Kn(t.plotBounds?.x)??Kn(o.x),i=Kn(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Kn(o.x);if(null==e||null==n||null==i)continue;a={type:"segment",x1:n,y1:e,x2:i,y2:e,thickness:r}}i.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:Kn(o.restitution)??Kn(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:Kn(o.friction)??Kn(t.barrierFriction)}})}return i}(e,{idPrefix:g?g+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:ve?.[0]??ss[0],height:ve?.[1]??ss[1]}}):[]},[i,g,ve]),xt=u.useMemo(()=>{const e=void 0===k||void 0!==I?.kernel?.seed?I:{...I,kernel:{...I?.kernel,seed:k}},t=pe.flatMap(e=>[{id:Ir(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...Sr(e)]),n=Object.fromEntries(pe.map(e=>[Ir(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),i=e?.observation,o=pe.length>0;return o||t.length>0||bt.length>0||null!=g||i?{...e,colliders:[...e?.colliders??[],...t,...bt],observation:{...i,chartId:g??i?.chartId,chartType:i?.chartType??ls,sensors:{...i?.sensors??{},...n},onObservation:e=>{o&&gt(e),i?.onObservation?.(e)}}}:e},[bt,g,I,gt,pe,k]);if(!pt.current){const e=Ro(xt,O,W);e.setPaused(he),je&&e.setVisible(nr()),pt.current=e}const vt=(0,h.useRef)(-1),wt=(0,h.useRef)(null),kt=(0,h.useRef)(!0),Mt=(0,sr.useRef)(new hr("StreamPhysicsFrame")),It=(0,h.useRef)(""),St=(0,h.useId)().replace(/:/g,""),jt=(0,h.useRef)(!1),At=(0,h.useRef)(!1),Ct=(0,h.useRef)(0),Rt=(0,h.useRef)(!1),$t=(0,h.useRef)(null),Pt=(0,h.useRef)(!1),Dt=function(e){const t=C(),n=(0,m.useRef)(t);n.current=t;const[i,o]=$(e.sizeProp,e.responsiveWidth,e.responsiveHeight),r=!!e.title,s=!!e.legend&&"top"===e.legendPosition,a=(0,m.useMemo)(()=>function(e,t,n=!1){const i=n?t?58:34:t?36:0;return i>e.top?{...e,top:i}:e}({...e.marginDefault,...e.userMargin},r,s),[e.marginDefault,e.userMargin,r,s]),c=o[0]-a.left-a.right,l=o[1]-a.top-a.bottom,d=L(e.foregroundGraphics,o,a),u=L(e.backgroundGraphics,o,a),h=j(e=>e.theme),{transition:f,introEnabled:y}=function(e,t){if(!1===e)return{transition:void 0,introEnabled:!1};const n="undefined"!=typeof window&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return{transition:e?!0===e?{duration:300}:{duration:e.duration??300,easing:"linear"===e.easing?"linear":"ease-out"}:t,introEnabled:!(n||!e||!0!==e&&!1===e.intro)}}(e.animate,e.transitionProp),g="semiotic-table-"+p.useId(),b=(0,m.useRef)(null);if(!b.current){const t=!e.suspendWhenHidden||"undefined"==typeof document||!document.hidden;b.current=new q({clock:e.clock,random:e.random,seed:e.seed,paused:e.paused,visible:t})}const x=b.current;x.configure({clock:e.clock,random:e.random,seed:e.seed});const v=(0,m.useRef)(null),w=(0,m.useRef)(e.frameScheduler??z);w.current=e.frameScheduler??z;const k=(0,m.useRef)(null),M=(0,m.useRef)(!1),I=(0,m.useRef)(()=>{}),S=(0,m.useCallback)(()=>{if(null!==v.current||M.current)return;const e=w.current;let t=!1,n=!1;const i=e.requestAnimationFrame(()=>{t=!0;const e=!n;e&&(M.current=!0),v.current=null,k.current=null;try{I.current()}finally{e&&(M.current=!1)}});n=!0,t||(v.current=i,k.current=e)},[]),A=(0,m.useCallback)(()=>{null!==v.current&&((k.current??w.current).cancelAnimationFrame(v.current),v.current=null,k.current=null)},[]);F(()=>{x.setPaused(!0===e.paused)},[x,e.paused]),(0,m.useEffect)(()=>{if(!e.suspendWhenHidden||"undefined"==typeof document)return void x.setVisible(!0);const t=()=>x.setVisible(!document.hidden);return t(),document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[x,e.suspendWhenHidden]),(0,m.useEffect)(()=>()=>{A()},[A]);const R=(0,m.useRef)(()=>{}),P=(0,m.useRef)(()=>{}),B=(0,m.useRef)(null),T=(0,m.useRef)(null),E=(0,m.useRef)(null),N=(0,m.useCallback)(()=>{const e=B.current;B.current=null,e&&R.current(e)},[]),O=(0,m.useCallback)(e=>{if(B.current={clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType},null===T.current){const e=w.current;let t=!1;const n=e.requestAnimationFrame(()=>{t=!0,T.current=null,E.current=null,N()});t||(T.current=n,E.current=e)}},[N]),W=(0,m.useCallback)(()=>{B.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null),P.current()},[]);(0,m.useEffect)(()=>()=>{B.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null)},[]);const Y=e.themeDirtyRef;return F(()=>{Y&&(D++,Y.current=!0,S())},[h,S,Y]),{reducedMotion:t,reducedMotionRef:n,responsiveRef:i,size:o,margin:a,adjustedWidth:c,adjustedHeight:l,resolvedForeground:d,resolvedBackground:u,currentTheme:h,transition:f,introEnabled:y,tableId:g,frameRuntime:x,rafRef:v,renderFnRef:I,scheduleRender:S,cancelRender:A,hoverHandlerRef:R,hoverLeaveRef:P,onPointerMove:O,onPointerLeave:W}}({sizeProp:ve,responsiveWidth:fe,responsiveHeight:me,userMargin:te,marginDefault:as,foregroundGraphics:E,backgroundGraphics:a,frameScheduler:x,clock:v,random:w,seed:k,paused:he,suspendWhenHidden:je}),{margin:Bt,rafRef:Tt,reducedMotionRef:Et,renderFnRef:Nt,cancelRender:Ot,resolvedBackground:Wt,resolvedForeground:qt,responsiveRef:Ft,scheduleRender:zt,size:Lt,frameRuntime:Yt}=Dt,Ht=(0,h.useRef)(Yt.now);Ht.current=Yt.now;const _t=function(){const[e,t]=(0,Y.useState)(!1);return H(()=>{t(!0)},[]),e}(),Gt=V(),[Xt,Vt]=u.useState(null),[Ut,Kt]=u.useState(null),Qt=(0,h.useRef)(null),Zt=(0,h.useRef)(0),Jt=(0,h.useRef)(new Map),en=St+"-physics-live",tn=(0,h.useCallback)((e,t,n=!1)=>{if(!l)return void lt(e=>e.length?[]:e);const i=Ht.current();if(!n&&d>0&&d>i-Zt.current)return;Zt.current=i;const o=function(e,t,n,i){if(!n)return[];const o=Math.max(0,Math.floor(i));if(!o)return[];const r=[];for(let i=0;e.length>i&&o>r.length;i+=1){const o=e[i],s="function"==typeof n?n(o,{index:i,simulationState:t}):void 0;if(!1===s)continue;const a=Qr(o);r.push({datum:o.datum??o,description:Jr(o),group:"body",label:Zr(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(e,t,l,c);lt(e=>function(e,t){if(e.length!==t.length)return!0;for(let n=0;e.length>n;n+=1){const i=e[n],o=t[n];if(i.id!==o.id||i.label!==o.label||i.description!==o.description||i.group!==o.group||i.bodyId!==o.bodyId||Math.round(i.x)!==Math.round(o.x)||Math.round(i.y)!==Math.round(o.y))return!0}return!1}(e,o)?o:e)},[c,l,d]),nn=(0,h.useCallback)(e=>{if(!dt.length)return;const t=Math.max(0,Math.min(e,dt.length-1));vt.current=t;const n=dt[t];if(Qt.current=n.bodyId??null,Vt(n),le?.(n),n.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=Kr(e);Kt(t),se?.(e,t)}}},[dt,se,le]),on=(0,h.useCallback)(()=>{vt.current=-1,Qt.current=null,Vt(null),le?.(null)},[le]),rn=function({onObservationRef:e,chartIdRef:t,wallClockRef:n}){return(0,Tr.useCallback)((i,o)=>{const r=e.current;if(!r)return;const s={timestamp:n.current(),chartType:"StreamPhysicsFrame",chartId:t.current};r("hover"===i||"click"===i?{...s,type:i,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===i?{...s,type:i,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===i?{...s,type:i,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:i})},[t,e,n])}({onObservationRef:Ee,chartIdRef:Ne,wallClockRef:mt}),sn=(0,h.useCallback)(()=>{Kt(e=>e?(se?.(null,null),rn("hover-end"),null):e)},[rn,se]),an=(0,h.useCallback)(e=>{if(!T||!pt.current)return;const t=e.currentTarget.getBoundingClientRect(),n=pt.current.hitTest(e.clientX-t.left,e.clientY-t.top,N);if(!n)return void sn();const i=Kr(n);Kt(e=>e&&e.id===i.id&&e.x===i.x&&e.y===i.y?e:(se?.(n,i),rn("hover",{datum:n.datum,x:n.x,y:n.y}),i))},[sn,rn,T,N,se]),cn=(0,h.useCallback)(e=>{on();const t=pt.current,n=e.currentTarget.getBoundingClientRect(),i=e.clientX-n.left,o=e.clientY-n.top,r=t?t.hitTest(i,o,Math.max(16,N)):null;ae?.(r,e),r?(rn("click",{datum:r.datum,x:r.x,y:r.y}),rn("activate",{datum:r.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),ne?.(r.datum??null,{x:r.x,y:r.y,body:r})):(rn("click-end"),ne?.(null,{x:i,y:o,body:null}),sn())},[sn,on,rn,N,ae,ne]);(0,h.useEffect)(()=>{if(!dt.length)return void on();const e=vt.current;if(dt.length>e){if(e>=0){const t=dt[e];if(Qt.current=t.bodyId??null,Vt(e=>null!=e&&e.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t),t.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=Kr(e);Kt(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else nn(dt.length-1)},[dt,on,nn]),(0,h.useEffect)(()=>{T||sn()},[sn,T]);const ln=(0,h.useCallback)(e=>{if(function(e){const t=e.target;return t instanceof Element&&t!==e.currentTarget&&null!=t.closest("button, a[href], input, select, textarea, summary, [contenteditable='true'], [role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch']")}(e))return;if(!dt.length)return;if("Escape"===e.key)return e.preventDefault(),void on();if(("Enter"===e.key||" "===e.key)&&vt.current>=0){e.preventDefault();const t=dt[vt.current];return rn("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void ce?.(t)}if(!cs.has(e.key))return;e.preventDefault();const t=vt.current;if(0>t){nn(0);const e=dt[0];return void rn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*dt.length));let i=t;if("Home"===e.key?i=0:"End"===e.key?i=dt.length-1:"PageDown"===e.key?i=Math.min(dt.length-1,t+n):"PageUp"===e.key?i=Math.max(0,t-n):"ArrowRight"===e.key||"ArrowDown"===e.key?i=Math.min(dt.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(i=Math.max(0,t-1)),nn(i),i!==t){const e=dt[i];rn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[on,rn,nn,ce,dt]),[dn,un]=u.useState([]),hn=(0,h.useRef)(0),pn=!!i?.length&&i.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:mn}=function(e,t){return function(e){const{cancelRender:t,dirtyRef:n,frameRuntime:i,manageFrameRuntime:o,scheduleRender:r}=e,s=(0,U.useRef)(null),a=(0,U.useRef)(null),c=(0,U.useRef)(!1);return function(e){const{hydrated:t,wasHydratingFromSSR:n,storeRef:i,dirtyRef:o,renderFnRef:r,cancelRender:s,cleanup:a}=e;H(()=>{const e=i.current;t&&n&&e?.cancelIntroAnimation?.(),!n&&e?.sceneNodes&&e.sceneNodes.length>0&&e?.markStylePaintPending?e.markStylePaintPending():o.current=!0,s?.(),r.current()},[t,n]);const c=(0,Y.useRef)(a);c.current=a,(0,Y.useEffect)(()=>()=>c.current?.(),[])}({hydrated:e.hydrated,wasHydratingFromSSR:e.wasHydratingFromSSR,storeRef:e.storeRef,dirtyRef:e.dirtyRef,renderFnRef:e.renderFnRef,cancelRender:e.cancelRender,cleanup:e.cleanup}),(0,U.useEffect)(()=>{if(!1!==o)return i.subscribe(()=>{i.isActive?(n.current=!0,r()):t()})},[t,n,i,o,r]),(0,U.useEffect)(()=>{!c.current&&(c.current=!0,e.skipInitialCanvasPaintInvalidation)||(e.dirtyRef.current=!0,e.scheduleRender())},e.canvasPaintDependencies),{canvasRef:s,interactionCanvasRef:a}}({...t,renderFnRef:e.renderFnRef,scheduleRender:e.scheduleRender,cancelRender:e.cancelRender,frameRuntime:e.frameRuntime})}(Dt,{hydrated:_t,wasHydratingFromSSR:Gt,storeRef:pt,dirtyRef:kt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,a,zt]}),fn=(0,h.useCallback)(()=>{const e=mn.current,t=pt.current;if(!e||!t)return;const n=Mt.current.beforeCompute(t.getLastUpdateResult(),!1),i=function(){if("undefined"==typeof window)return 1;const e=window.devicePixelRatio||1,t=function(){if("undefined"==typeof window)return!1;const e="function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches,t=768>Math.min(window.innerWidth||1/0,window.innerHeight||1/0);return e||t}()?2:3;return Math.max(1,Math.min(e,t))}(),o=function(e,t,n,i){const o=e.getContext("2d");if(!o)return null;const r=Math.round(t[0]*i),s=Math.round(t[1]*i),a=r/t[0],c=s/t[1],l=t[0]+"px",d=t[1]+"px";return e.style.width!==l&&(e.style.width=l),e.style.height!==d&&(e.style.height=d),e.width===r&&e.height===s||(e.width=r,e.height=s),o.setTransform(a,0,0,c,0,0),o.translate(n.left,n.top),o}(e,Lt,Bt,i);if(!o)return void Mt.current.afterCompute(n,!1,!1);const r=function(e){const t=Ke(e,_e),n=Ke(e,Le),i=Ke(e,Ue),o=Ke(e,Ge),r=Ke(e,ze),s=Ke(e,Fe),a=Ke(e,Xe),c=Ke(e,Ve),l=Ke(e,Ye),d=Ke(e,He);return{annotationBackground:Qe(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:Qe(n,.08),closedWindowStroke:Qe(n,.55),danger:n,focus:l,grid:d,gutterFill:Qe(c,.14),lateFill:i,openWindowFill:Qe(t,.07),openWindowStroke:Qe(t,.3),primary:t,selectedFill:i,selectedStroke:l,success:o,text:a,textSecondary:c,warning:i}}(o);o.clearRect(-Bt.left,-Bt.top,Lt[0],Lt[1]),a||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-Bt.left,-Bt.top,Lt[0],Lt[1]));const c=t.snapshot(),l=t.readBodies();if(tn(l,c.simulationState),pn){const e=Ht.current();if(e-hn.current>=100){hn.current=e;const t=Gn(l);un(e=>e.length===t.length&&e.every((e,n)=>e.pointId===t[n].pointId&&Math.round(e.x)===Math.round(t[n].x)&&Math.round(e.y)===Math.round(t[n].y))?e:t)}}De&&(o.save(),De(o,l),o.restore());for(const e of l){const t=Oe.current.get(e.id),n=t?Array.from(t.activeRegionIds).map(e=>st.get(e)).filter(e=>null!=e):[],i=Br(e,c.simulationState,y,ye,ge,jr(t),n,r.primary,r.text,Te);Pe?(o.save(),Pe(o,e,i),o.restore()):kr(o,e,i)}Be&&(o.save(),Be(o,l),o.restore()),function(e,t,n){let i=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(n-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}i=!0;const a=1-Math.pow(1-s,3),{body:c}=r,l=r.scale>0?r.scale:1,d=(r.radius+28*a)*l,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*l),e.beginPath(),e.arc(c.x,c.y,d,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*d,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.lineWidth=Math.max(.5,1.8*l);for(let t=0;8>t;t+=1){const n=t*(Math.PI/4)+1.4*s,i=(r.radius+5+12*a)*l,o=(r.radius+12+34*a)*l;e.beginPath(),e.moveTo(c.x+Math.cos(n)*i,c.y+Math.sin(n)*i),e.lineTo(c.x+Math.cos(n)*o,c.y+Math.sin(n)*o),e.stroke()}e.restore()}}(o,Jt.current,Ht.current()),Mt.current.afterCompute(n,!0,!1),kt.current=!1},[mn,Mt,Lt,Bt,a,s,tn,pn,De,Be,y,ye,ge,Te,Pe,st]),yn=(0,h.useCallback)((e,t)=>{const n=pt.current,i=`${xe}:${e}:${t??""}`;It.current!==i&&(It.current=i,re?.({execution:e,liveBodies:n?.liveBodyCount()??0,queuedBodies:n?.queueSize()??0,reason:t,requested:xe}))},[re,xe]),gn=(0,h.useCallback)((e,t=!0)=>{Ct.current+=1,jt.current=!1,Rt.current=!1,Pt.current=!1,$t.current?.terminate(),$t.current=null,t&&yn("sync",e)},[yn]),bn=(0,h.useCallback)(()=>_t?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":ut?"runtime region effects require sync":ht?"body forces require sync":et?"physics controllers require sync":function(e){return!e||!e.engine&&ei(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(xt??{})?ii(W)?At.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[xt,et,ht,ut,_t,W]),xn=(0,h.useCallback)(()=>{const e=pt.current,t=bn();if(!e||t)return{reason:t,useWorker:!1};const n=e.liveBodyCount(),i=e.queueSize(),o=function(e,t,n=0,i=Zn){return"sync"!==e&&("worker"===e||t+n>=i)}(xe,n,i,$e);return{reason:o?"worker"===xe?"forced worker":"body threshold":"below threshold",useWorker:o}},[xe,$e,bn]),vn=(0,h.useCallback)(e=>{const t=pt.current;return t&&e.snapshot?(t.restore(e.snapshot),kt.current=!0,t):t},[]),wn=(0,h.useCallback)((e,t=!0)=>{const n=vn(e);if(!n)return;t&&de?.(e.result,n.controls()),fn();const i=n.snapshot();!e.result.shouldContinue&&Jt.current.size<=0||i.paused||!i.visible||Et.current||zt()},[vn,de,fn,Et,zt]),kn=(0,h.useCallback)(e=>{At.current=!0,gn("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[gn]),Mn=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return!1;const t=xn();if(!t.useWorker)return jt.current||Pt.current?gn(t.reason??"sync fallback"):yn("sync",t.reason??"sync"),!1;if(jt.current||Pt.current)return!0;const n=$t.current??new ai;$t.current=n,Pt.current=!0;const i=Ct.current+1;return Ct.current=i,n.initFromSnapshot(xt??{},e.snapshot()).then(e=>{if(Ct.current!==i)return;Pt.current=!1,jt.current=!0,At.current=!1,vn(e),yn("worker",t.reason??"worker"),fn();const n=pt.current?.snapshot();e.result.shouldContinue&&n&&!n.paused&&n.visible&&!Et.current&&(wt.current=null,zt())}).catch(e=>{Ct.current===i&&kn(e)}),!0},[vn,xt,kn,fn,Et,yn,zt,gn,xn]),In=(0,h.useCallback)(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),Sn=(0,h.useCallback)((e,t=!0)=>{const n=$t.current;if(!n||!jt.current)return;const i=Ct.current;n.request(e).then(e=>{if(Ct.current!==i)return;const n=In(e);n&&wn(n,t)}).catch(kn)},[wn,In,kn]),jn=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return;const t=Mn(),n=e.snapshot(),i=nt||ht||ut||!!et;n.paused||!n.visible||!e.hasPendingWork()&&!i||Et.current?Nt.current():t&&Pt.current||zt()},[et,nt,ht,ut,Et,Nt,zt,Mn]),An=(0,h.useCallback)(()=>{Ot(),Tt.current=null;const e=pt.current;if(!e)return;if(jt.current&&$t.current){if(Rt.current)return;let t=0;if(!Et.current){const e=Ht.current();t=null!==wt.current?(e-wt.current)/1e3:0,wt.current=e}const n=$t.current,i=Ct.current;return Rt.current=!0,void(Et.current?n.settle():n.tick(t)).then(e=>{Rt.current=!1,Ct.current===i&&wn(e)}).catch(n=>{if(Rt.current=!1,Ct.current!==i)return;kn(n);const o=Et.current?e.settleWithObservations():e.tick(t);Dr({store:e,result:o,regionEffects:We.current,regionState:Oe.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),fn()})}let t;if(Et.current)t=e.settleWithObservations();else{const n=Ht.current(),i=null!==wt.current?(n-wt.current)/1e3:0;wt.current=n,t=e.tick(i)}const n=tt.current,{regionEffectsApplied:i,bodyForcesApplied:o,snapshot:r}=Dr({store:e,result:t,regionEffects:We.current,regionState:Oe.current,bodyForces:Ze.current,composed:n,onTick:Je.current});fn(),(it.current||t.shouldContinue||i||o||n||Jt.current.size>0)&&!r.paused&&r.visible&&!Et.current&&zt()},[wn,kn,fn,Ot,zt,Et,Tt]);Nt.current=An,(0,h.useEffect)(()=>{At.current=!1,(jt.current||Pt.current)&&gn("config changed",!1),pt.current?.updateConfig(xt??{}),jn()},[xt,gn]),(0,h.useEffect)(()=>{At.current=!1,jn()},[_t,xe,$e]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:n,paused:i,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=(0,tr.useRef)(o);c.current=o;const l=(0,tr.useRef)(r);l.current=r,(0,tr.useEffect)(()=>{const o=s.current;o&&(t.setPaused(i),o.setPaused(i),i&&(n.current=null,e()),c.current({type:"setPaused",paused:i},!1),l.current())},[e,t,i]),(0,tr.useEffect)(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const i=()=>{const i=s.current;if(!i)return;const o=nr();t.setVisible(o),i.setVisible(o),o||(n.current=null,e()),c.current({type:"setVisible",visible:o},!1),l.current()};return i(),document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[e,t,a])}({cancelRender:Ot,frameRuntime:Yt,lastFrameTimeRef:wt,paused:he,postWorkerCommand:Sn,requestRender:jn,storeRef:pt,suspendWhenHidden:je}),(0,h.useEffect)(()=>()=>gn("unmount",!1),[gn]),(0,h.useEffect)(()=>{fn()},[fn]),(0,h.useImperativeHandle)(t,()=>({...pt.current.controls(),applyImpulse:(e,t,n)=>{pt.current.applyImpulse(e,t,n),Sn({type:"applyImpulse",id:e,ix:t,iy:n}),jn()},clear:()=>{pt.current.clear(),Oe.current.clear(),Jt.current.clear(),Sn({type:"clear"}),jn()},clearRegionState:e=>{e?Oe.current.delete(e):Oe.current.clear(),jn()},getData:()=>pt.current.readBodies(),getRegionState:e=>e?jr(Oe.current.get(e)):function(e){const t={};return e.forEach((e,n)=>{const i=jr(e);i&&(t[n]=i)}),t}(Oe.current),getStore:()=>pt.current,pause:()=>{Yt.setPaused(!0),wt.current=null,Ot(),pt.current.setPaused(!0),Sn({type:"setPaused",paused:!0},!1),jn()},push:(e,t)=>{pt.current.enqueue(e,t),ii(t)?Sn({type:"enqueue",spawns:[e],pacing:t}):(jt.current||Pt.current)&&gn("spawn pacing is not worker-cloneable"),jn()},pushMany:(e,t)=>{pt.current.enqueue(e,t),ii(t)?Sn({type:"enqueue",spawns:e,pacing:t}):(jt.current||Pt.current)&&gn("spawn pacing is not worker-cloneable"),jn()},popBodies:(e,t={})=>{const n=pt.current,i=new Map(n.readBodies().map(e=>[e.id,e])),o=n.remove(e),r=Ht.current();for(const e of o){const n=i.get(e);n&&(Oe.current.delete(e),Jt.current.set(e,{body:n,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??Mr(n),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:r}),Qt.current===e&&(Qt.current=null,Vt(null)),Kt(t=>t?.id===e?null:t))}return o.length&&(Sn({type:"remove",ids:o}),jn()),o},remove:e=>{const t=pt.current.remove(e);for(const t of e)Oe.current.delete(t);return Sn({type:"remove",ids:e}),jn(),t},restore:e=>{pt.current.restore(e),Oe.current.clear(),Jt.current.clear(),Sn({type:"restore",snapshot:e},!1),jn()},resume:()=>{Yt.setPaused(!1),wt.current=null,pt.current.setPaused(!1),Sn({type:"setPaused",paused:!1},!1),jn()},settle:e=>{const t=pt.current.settle(e);return Sn({type:"settle",maxSteps:e}),jn(),t},settleWithObservations:e=>{const t=pt.current.settleWithObservations(e);return Sn({type:"settle",maxSteps:e}),jn(),t},step:e=>{const t=pt.current,n=t.tick(e);return Dr({store:t,result:n,regionEffects:We.current,regionState:Oe.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),Sn({type:"tick",deltaSeconds:e}),fn(),n}}),[Ot,Yt,fn,Sn,jn,gn]);const Cn=Se||!_t&&Gt,Rn=["stream-physics-frame",B?"stream-physics-frame--mode-"+B:null,P?"stream-physics-frame--emphasis-"+P:null,b].filter(Boolean).join(" "),$n=R??("string"==typeof Ce?Ce:void 0)??"Physics chart",Pn=St+"-physics-table",Dn=Math.max(1,Lt[0]-Bt.left-Bt.right),Bn=Math.max(1,Lt[1]-Bt.top-Bt.bottom),Tn=T&&Ut?Re?Re(Ut):(0,rs.jsx)(ts,{hover:Ut}):null,En=Tn&&Ut?(0,rs.jsx)(qe,{x:Ut.x-Bt.left,y:Ut.y-Bt.top,containerWidth:Math.max(1,Lt[0]-Bt.left-Bt.right),containerHeight:Math.max(1,Lt[1]-Bt.top-Bt.bottom),margin:Bt,className:"stream-physics-tooltip",children:Tn}):null;if(Cn){const e=pt.current??Ro(xt,O,W),t="string"==typeof Ce?Ce:void 0,{svg:n}=function(e,t={}){const{width:n=640,height:i=360,title:o,description:r,background:s,backgroundGraphics:a,className:c,foregroundGraphics:l,idPrefix:d="physics",margin:u,renderBodySVG:h,...p}=t,m=No(e,p),f={...Wo,...u},y=[n,i],g=qo(a,y,f),b=qo(l,y,f),x=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(d),v=o?x+"-title":void 0,w=r?x+"-desc":void 0,k=[v,w].filter(Boolean).join(" ")||void 0;return{svg:Po.renderToStaticMarkup((0,Oo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:c??"stream-physics-frame",width:n,height:i,viewBox:`0 0 ${n} ${i}`,role:"img","aria-labelledby":k,children:[o&&(0,Oo.jsx)("title",{id:v,children:o}),r&&(0,Oo.jsx)("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?(0,Oo.jsx)("rect",{x:0,y:0,width:n,height:i,fill:s}):null,g,(0,Oo.jsx)("g",{id:x+"-data-area",children:m.sceneNodes.map((e,t)=>{const n=m.bodies[t];return(n&&h?h(n,e.style??{},t,x):void 0)??Ie(e,t,x)})}),b]})),scene:m,evidence:m.evidence}}(e,{width:Lt[0],height:Lt[1],title:t,description:R,background:a||"transparent"===s?void 0:s,backgroundGraphics:Wt,className:"stream-physics-frame__svg",foregroundGraphics:qt,idPrefix:"physics-"+St,margin:Bt});return(0,rs.jsxs)("div",{ref:Ft,className:Rn,"data-semiotic-mode":B,role:"img","aria-label":$n,style:{width:Lt[0],height:Lt[1]},children:[(0,rs.jsx)(vr,{summary:Me}),(0,rs.jsx)("div",{dangerouslySetInnerHTML:{__html:n}})]})}return(0,rs.jsxs)("div",{ref:Ft,className:Rn,"data-semiotic-mode":B,role:"group","aria-label":$n,"aria-describedby":Xt?en:void 0,tabIndex:0,style:{position:"relative",width:Lt[0],height:Lt[1]},onKeyDown:ln,children:["production"!==process.env.NODE_ENV&&pt.current&&(0,rs.jsx)(pr,{store:pt.current,diagnostics:Mt.current}),n?(0,rs.jsx)(wr,{tableId:Pn}):null,n?(0,rs.jsx)(os,{chartTitle:"string"==typeof Ce?Ce:$n,items:dt,tableId:Pn}):null,(0,rs.jsx)(vr,{summary:Me}),(0,rs.jsx)(br,{hoverPoint:Ut}),(0,rs.jsx)("div",{id:en,"aria-live":"polite","aria-atomic":"true",style:Or,children:Xt?Xt.description??Xt.label:""}),(0,rs.jsxs)("div",{role:"img","aria-label":$n,style:{position:"relative",width:"100%",height:"100%"},children:[(0,rs.jsx)(Q,{size:Lt,margin:Bt,children:Wt}),(0,rs.jsx)("canvas",{ref:mn,width:Lt[0],height:Lt[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:cn,onPointerMove:T?an:void 0,onPointerLeave:T?sn:void 0}),qt,(0,rs.jsx)(Un,{width:Dn,height:Bn,totalWidth:Lt[0],totalHeight:Lt[1],margin:Bt,title:Ce,legend:_,legendPosition:ee,legendLayout:J,legendHoverBehavior:K,legendClickBehavior:G,legendHighlightedCategory:X,legendIsolatedCategories:Z,pointNodes:dn,annotations:i,onAnnotationActivate:o,onObservation:ie,chartId:g,chartType:ls,autoPlaceAnnotations:r,svgAnnotationRules:Ae}),(0,rs.jsx)(rr,{active:null!=Xt,hoverPoint:Xt?{x:Xt.x,y:Xt.y}:null,margin:Bt,size:Lt,shape:Xt?.shape,width:Xt?.width,height:Xt?.height,pathData:Xt?.pathData}),En]})]})}));ds.displayName="StreamPhysicsFrame";var us=ds;function hs(e){if(null==e)return()=>{};const t="function"==typeof e?e:t=>t[e];return e=>ps(t(e))}function ps(e){if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}}function ms(e,t,n){const i=null!=e.axis?n[e.axis]:null!=e.field?t[e.field]:n.value;if(void 0!==e.eq&&i!==e.eq)return!1;if(void 0!==e.ne&&i===e.ne)return!1;if(void 0!==e.in&&!e.in.includes(i))return!1;if(void 0===e.gt&&void 0===e.gte&&void 0===e.lt&&void 0===e.lte&&void 0===e.within&&void 0===e.outside)return!0;const o=ps(i);if(void 0===o)return!1;if(void 0!==e.gt&&e.gt>=o)return!1;if(void 0!==e.gte&&e.gte>o)return!1;if(void 0!==e.lt&&o>=e.lt)return!1;if(void 0!==e.lte&&o>e.lte)return!1;if(void 0!==e.within){const[t,n]=e.within;if(t>o||o>n)return!1}if(void 0!==e.outside){const[t,n]=e.outside;if(o>=t&&n>=o)return!1}return!0}function fs(e,t,n){const i=e.when;return void 0===i||!0===i||!1!==i&&("function"==typeof i?i(t,n):ms(i,t,n))}function ys(e,t,n){if(!t||0===t.length)return{};let i={};for(const o of t){if(!fs(o,e,n))continue;const t="function"==typeof o.style?o.style(e,n):o.style;t&&(i={...i,...t})}return i}function gs(e,t,n,i=e=>e){const o=e??(()=>({}));return t&&0!==t.length?(e,r)=>{const s=i(e),a={...o(e,r)};return Object.assign(a,ys(s,t,n(s,r))),a}:o}function bs(e){const[t,n]=e,i=160>t||116>n,o=i?Math.min(12,Math.max(2,.08*t)):32,r=i?Math.min(8,Math.max(2,.12*n)):24,s=i?r:34;return{width:t,height:n,plot:{x:o,y:r,width:Math.max(1,t-2*o),height:Math.max(1,n-r-s)}}}function xs(e){const t=(e??"")+"";if(!t)return"#4e79a7";const n=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return n[i%n.length]}function vs(e,t="#4e79a7",n){const i=n?.styleRules,o=!!i&&i.length>0,r=o?hs(n?.valueAccessor):void 0;return n=>{const s=n.datum,a=s&&e?"function"==typeof e?e(s,0):s[e]:void 0,c={fill:null==a?t:xs(a),stroke:"#111827",strokeWidth:1,opacity:.9};return o&&s&&Object.assign(c,ys(s,i,{value:r?r(s):void 0,category:null==a?void 0:a+""})),c}}function ws(e,t,n,i){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:n},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...i}}}function ks(e,t,n){if(!e.length)return[];const i=bs(t),o=i.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*i.plot.height,a=i.plot.y+i.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),l=`${n} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${n}-${e.label}`,label:l,description:l,datum:e,x:i.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:n}})}function Ms(e,t,n){return"function"==typeof n?n(e,t):e[n]}function Is(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Ss(e,t,n){return Math.max(t,Math.min(n,e))}function js(e,t){const n=Is(e);return null!=n&&n>0?n:t}function As(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Cs(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}var Rs=require("d3-scale");function $s(e){const{data:t,valueAccessor:n,bins:i,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=bs(s),l=t.map((e,t)=>Is(Ms(e,t,n))).filter(e=>null!=e),d=function(e){if(!e)return;const t=Is(e[0]),n=Is(e[1]);return null!=t&&null!=n?t>n?[n,t]:[t,n]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,m=(0,Rs.scaleLinear)().domain([0,i]).range([c.plot.x,c.plot.x+c.plot.width]),f=Array.from({length:i},()=>0),y=[];t.forEach((e,t)=>{const r=Is(Ms(e,t,n));if(null==r)return;const s=Math.max(0,Math.min(i-1,Math.floor((r-u)/p*i)));f[s]+=1,y.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:ws(r,[...ro({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...so({idPrefix:"galton-bin",count:i,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:f.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:i,plot:c.plot,valueExtent:[u,h]}}}var Ps=require("d3-scale");function Ds(e){const{count:t,idPrefix:n,wallThickness:i,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),l=Math.max(1,r-c);return{id:`${n}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+l/2,width:i,height:l}}})}function Bs(e){const{data:t,timeAccessor:n,arrivalAccessor:i,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=bs(c),h=t.map((e,t)=>Is(Ms(e,t,n))).filter(e=>null!=e),p=Is(l?.[0]),m=Is(l?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+o.size,g=Math.min(p??f,f),b=Math.max(m??y,y),x=Math.floor(g/o.size)*o.size,v=Math.max(1,Math.ceil((b-x+o.size)/o.size)),w=h.length?Math.max(...h):0,k="function"==typeof r?r(w):Is(r?.value)??w-(r?.delay??o.size),M=Math.max(0,Math.min(v,Array.from({length:v},(e,t)=>t).reduce((e,t)=>x+(t+1)*o.size>k?e:e+1,0))),I=function(e,t){const n=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:n,height:e.plot.height},windowPlot:{x:e.plot.x+n,y:e.plot.y,width:Math.max(40,e.plot.width-n),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),S=x+v*o.size,j=(0,Ps.scaleLinear)().domain([x,S]).range([I.windowPlot.x,I.windowPlot.x+I.windowPlot.width]),A=Array.from({length:v},()=>({value:0,secondary:0})),C=[];t.forEach((e,t)=>{const r=Is(Ms(e,t,n));if(null==r)return;const a=Is(Ms(e,t,i))??r,c=Math.max(0,Math.min(v-1,Math.floor((r-x)/o.size))),l=k>=x+(c+1)*o.size;A[c].value+=l?0:1,A[c].secondary+=l?1:0,C.push({id:(e.id??"event-"+t)+"",x:Math.max(I.windowPlot.x+s,Math.min(I.windowPlot.x+I.windowPlot.width-s,j(r))),y:u.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:c,late:l}})});const R=u.plot.y+u.plot.height,$=function(e,t){const n=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!n)return[];const i=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=(0,Ps.scaleLinear)().domain([i,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+n*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;n>t;t+=1){const n=e.windowStart+t*e.windowSize,i=n+e.windowSize,o=r(n),s=r(i);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:l(o),x2:s,y2:l(s)})}return d}({closedWindowCount:M,gutter:I.gutter,plot:u.plot,windowCount:v,windowPlot:I.windowPlot,windowSize:o.size,windowStart:x},u.plot.y+.28*u.plot.height);return{config:ws(a,[...ro({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...Ds({idPrefix:"eventdrop-window",count:v,xScale:e=>j(x+e*o.size),yTop:I.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>M)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?I.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...$.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:C,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:A.map((e,t)=>({label:`${x+t*o.size}-${x+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:I.gutter,lidSegments:$,lateCount:A.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:I.windowPlot,watermarkValue:k,windowCount:v,windowSize:o.size,windowStart:x}}}function Ts(e,t,n){const i=e.width/Math.max(1,t),o=Math.max(2,2*n),r=Math.min(.7*i,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:i,tubeWidth:r,ballDiameter:o,perRow:s,centerX:t=>e.x+(t+.5)*i,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function Es(e){const{data:t,categoryAccessor:n,valueAccessor:i,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=js(o,1),l=bs(a),d=[],u=new Map,h=new Map,p=[];function m(e){let t=u.get(e);return null==t&&(t=d.length,d.push(e),u.set(e,t)),t}t.forEach((e,t)=>{m((Ms(e,t,n)??"unknown")+"")});const f=Math.max(1,d.length),y=Ts(l.plot,f,r),g=Math.max(0,y.tubeWidth/2-r-1),b=d.map(()=>[]);t.forEach((e,t)=>{const o=(Ms(e,t,n)??"unknown")+"",s=m(o),a=i?Is(Ms(e,t,i)):1,d=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let n=0;d>n;n+=1){const i=h.get(o)??0,a=y.perRow>1?((y.perRow>1?i%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(o,i+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${n}`,x:u+a,y:l.plot.y+r+2,vx:(n%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:n}})}});const x=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;x>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const v=l.plot.y+l.plot.height,w=[...ro({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=l.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const n of[-1,1])w.push({id:`pile-tube-${e}-${0>n?"l":"r"}`,shape:{type:"aabb",x:t+n*y.tubeWidth/2,y:(k+v)/2,width:6,height:v-k}})}return{config:ws(s,w,"PhysicsPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}var Ns=require("d3-scale");function Os(e){const{data:t,xAccessor:n,groupAccessor:i,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=bs(a),h=Cs(s),p=[],m=[],f=new Map;t.forEach((e,t)=>{const s=Is(Ms(e,t,n));if(null==s)return;const a=i?(Ms(e,t,i)??"All")+"":"All",c=o?Is(Ms(e,t,o)):null,l=Ss(null!=c&&c>0?c:r,2,18);!function(e){let t=f.get(e);null==t&&(t=m.length,m.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const y=p.map(e=>e.value),g=c?Is(c[0]):null,b=c?Is(c[1]):null,x=y.length?Math.min(...y):0,v=y.length?Math.max(...y):1;let w=g??x,k=b??v;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const M=Math.max(r,...p.map(e=>e.radius)),I=u.plot.x+M+8,S=u.plot.x+u.plot.width-M-8,j=(0,Ns.scaleLinear)().domain([w,k]).range([I,S]),A=Math.max(1,m.length),C=Math.min(Math.max(28,3*M),u.plot.height/4),R=u.plot.y+C,$=Math.max(0,u.plot.y+u.plot.height-C-R),P=e=>{const t=f.get(e)??0;return 1===A?u.plot.y+.54*u.plot.height:R+t/(A-1)*$},D=new Map,B=p.map((e,t)=>{D.set(e.group,(D.get(e.group)??0)+1);const n=j(e.value),i=P(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?n+o:Ss(n+(t%9-4)*e.radius*2.5,I,S),y:d?i+r:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:n,targetY:i},springs:[{target:{type:"point",x:n,y:i},restLength:0,stiffness:34,damping:5.5}]}});return{config:ws(s,ro({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:B,projectionRows:m.map(e=>({label:e,value:D.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[I,S],groups:m.map(e=>({label:e,y:P(e),count:D.get(e)??0})),plot:u.plot}}}function Ws(e){if(Array.isArray(e)&&e.length>=2){const t=Is(e[0]),n=Is(e[1]);return null!=t&&null!=n?{x:t,y:n}:null}if(e&&"object"==typeof e){const t=e,n=Is(t.x),i=Is(t.y);return null!=n&&null!=i?{x:n,y:i}:null}return null}function qs(e){return Array.isArray(e)?e.map(Ws).filter(e=>null!=e):[]}function Fs(e,t,n){return"normalized"===n?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:Ss(e.x,t.plot.x,t.plot.x+t.plot.width),y:Ss(e.y,t.plot.y,t.plot.y+t.plot.height)}}function zs(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}function Ls(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const n=Ss(t,0,1)*zs(e);let i=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(i+s>=n){const e=(n-i)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}i+=s}}return{...e[e.length-1]}}function Ys(e,t){const n=Ls(e,Math.max(0,t-.02)),i=Ls(e,Math.min(1,t+.02)),o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function Hs(e){const{coordinateMode:t,flowSpeed:n,links:i,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:f,sourceAccessor:y,targetAccessor:g,throughputAccessor:b}=e,x=bs(f),v=Cs(m),w=new Map,k=new Map,M=[];function I(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const n=(Ms(e,t,r)??e.id??t)+"",i=Is(Ms(e,t,s)),o=Is(Ms(e,t,a));if(null!=i&&null!=o){const e={x:i,y:o};w.set(n,e),M.push(e)}k.set(n,(e.label??e.name??n)+"")});const S=[];i.forEach((e,t)=>{const n=I(Ms(e,t,y)),i=I(Ms(e,t,g)),o=Math.max(0,Is(Ms(e,t,b))??0),r=qs(u?Ms(e,t,u):void 0),s=r.length?r:qs(e.path??e.points??e.route);s.forEach(e=>M.push(e)),S.push({id:(e.id??`physical-flow-${n}-${i}-${t}`)+"",link:e,index:t,source:n,target:i,throughput:o,rawPath:s})});const j=(C=M,"normalized"===(A=t)||"pixels"===A?A:C.length>0&&C.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var A,C;const R=new Map;for(const[e,t]of w)R.set(e,Fs(t,x,j));const $=[];for(const e of S){let t=e.rawPath.map(e=>Fs(e,x,j));if(2>t.length){const n=R.get(e.source),i=R.get(e.target);n&&i&&(t=[n,i])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),$.push({...e,path:t,packetCount:0}))}const P=js(d,.12),D=Math.max(1,Math.round(o)),B=$.map(e=>Math.max(1,Math.round(e.throughput*P))),T=B.reduce((e,t)=>e+t,0),E=T>D?D/T:1;$.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(B[t]*E))});let N=$.reduce((e,t)=>e+t.packetCount,0);for(;N>D;){const e=$.reduce((e,t,n)=>t.packetCount>1&&(-1===e||t.packetCount>$[e].packetCount)?n:e,-1);if(-1===e)break;$[e].packetCount-=1,N-=1}const O=new Map,W=new Map,q=[],F=js(n,90),z=js(l,4);$.forEach((e,t)=>{O.set(e.target,(O.get(e.target)??0)+e.throughput),W.set(e.source,(W.get(e.source)??0)+e.throughput);const n=zs(e.path);for(let i=0;e.packetCount>i;i+=1){const o=(i+.5)/e.packetCount,r=p?o:Ss(.12+.84*o+.04*(v()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*v())),a=Ls(e.path,s),c=Ls(e.path,r),l=Ys(e.path,s),d={x:-l.y,y:l.x},u=(v()-.5)*z*1.5;q.push({id:`${e.id}-packet-${i}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*F+10*(v()-.5),vy:p?0:l.y*F+10*(v()-.5),mass:.8,spawnAt:p?0:.04*t+i/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:i,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:n,flowRouteId:e.id,flowSpeed:F,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*z),Y=Array.from(R,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+As(e),point:t})),H=Y.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:L,height:L}})),_=Object.fromEntries(Y.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),G=ws(m,[...ro({x:x.plot.x,y:x.plot.y,width:x.plot.width,height:x.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...H],"PhysicalFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});G.bodyLimit=D,G.eviction="oldest",G.observation={...G.observation,sensors:_};const X=Array.from(R,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+As(e),incoming:O.get(e)??0,outgoing:W.get(e)??0})),V=$.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:G,initialSpawns:q,projectionRows:X.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:j,particleCount:q.length,totalThroughput:$.reduce((e,t)=>e+t.throughput,0),plot:x.plot,nodes:X,links:V}}}function _s(e,t){if("region-enter"!==t.type)return e;const n=t.region.id,i=e[n]??{id:n,label:t.region.label??n,count:0,bodyIds:[]};if(i.bodyIds.includes(t.bodyId))return e;const o=[...i.bodyIds,t.bodyId];return{...e,[n]:{...i,count:o.length,bodyIds:o}}}function Gs(e,t){return(t??Object.keys(e)).map(t=>e[t]).filter(e=>null!=e).map(e=>({label:e.label??e.id,value:e.count}))}function Xs(e,t){const n=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],i=t.filter(e=>!n.has(e)),o=t.length-i.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(n.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===r?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?l>=(u??c):0===i.length),absorbed:o,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:i}})}function Vs(e,t,n){return Math.max(t,Math.min(n,e))}function Us(e,t,n={}){const i=n.random??Math.random,o=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],r=Vs(n.along??.5,.05,.95),s=n.jitterX??0,a=n.padY??20,c=o.x0+(o.x1-o.x0)*r+(2*i()-1)*s,l=Math.min(1,o.width/2),d=Vs(c,o.x0+l,o.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+i()*Math.max(1,h-u):e.midY}}function Ks(e){return"bowtie"===e.shape?[{id:"incoming",role:"incoming",points:[[e.left,e.topY],[e.centerLeft,e.pinchTop],[e.centerLeft,e.pinchBottom],[e.left,e.bottomY]]},{id:"center",role:"center",points:[[e.centerLeft,e.pinchTop],[e.centerRight,e.pinchTop],[e.centerRight,e.pinchBottom],[e.centerLeft,e.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[e.centerRight,e.pinchTop],[e.right,e.topY],[e.right,e.bottomY],[e.centerRight,e.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[e.left,e.topY],[e.right,"funnel"===e.shape?e.pinchTop:e.topY],[e.right,"funnel"===e.shape?e.pinchBottom:e.bottomY],[e.left,e.bottomY]]}]}function Qs(e,t,n){return Math.max(t,Math.min(n,e))}function Zs(e,t,n,i,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:n,x2:i,y2:o,thickness:r.thickness??8}}}function Js(e){const t=e.shape??"lane",n=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=n-o,c=r,l=i-Math.max(24,Math.round(.45*r)),d=(c+l)/2,u=Math.max(1,l-c),h=Qs(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,f=Qs(u*h+m,.06*u,.5*u),y=f/2,g=d-y,b=d+y,x=e.idPrefix??"process",v=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,M=e.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const I=Qs(e.centerStageIndex??Math.floor(M.length/2),0,M.length-1),S=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(M),j=a-s;let A=s;const C=M.map((e,t)=>{const n=A,i=t===M.length-1?a:A+(e.share??1)/S*j;return A=i,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:n,x1:i,x:(n+i)/2,width:i-n,y:d,height:u}}),R=C[I],$=R.x0,P=R.x1,D=(e,n)=>{if("lane"===t)return"top"===n?c:l;if("funnel"===t){const t=Qs((e-s)/Math.max(1,a-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if($>=e){const t=Qs((e-s)/Math.max(1,$-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if(P>=e)return"top"===n?g:b;const i=Qs((e-P)/Math.max(1,a-P),0,1);return"top"===n?g+(c-g)*i:b+(l-b)*i},B=C.map(e=>{const t=Math.min(D(e.x0,"top"),D(e.x1,"top")),n=Math.max(D(e.x0,"bottom"),D(e.x1,"bottom"));return{...e,y:(t+n)/2,height:Math.max(1,n-t)}}),T={thickness:k,friction:v,restitution:w},E=[];"lane"===t?E.push(Zs(x+"-top",s,c,a,c,T),Zs(x+"-bottom",s,l,a,l,T),Zs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Zs(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)})):"funnel"===t?E.push(Zs(x+"-top",s,c,a,g,T),Zs(x+"-bottom",s,l,a,b,T),Zs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Zs(x+"-right",a,g,a,b,{...T,thickness:Math.max(6,k)})):E.push(Zs(x+"-left-top",s,c,$,g,T),Zs(x+"-left-bottom",s,l,$,b,T),Zs(x+"-center-top",$,g,P,g,T),Zs(x+"-center-bottom",$,b,P,b,T),Zs(x+"-right-top",P,g,a,c,T),Zs(x+"-right-bottom",P,b,a,l,T),Zs(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),Zs(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)}));const N=e.membraneDampingScale??.5,O=s,W=Math.max(1,("bowtie"===t?$:a)-O),q=(e.membranes??[]).map(e=>{const t=O+Qs(e.offset,0,1)*W,n=e.width??18+18*e.cost,i=u-16,o=d+.25*(e.wobble??0);return{...e,x:t,y:o,width:n,height:i}}),F=!1===e.includeMembraneRegions?[]:q.map(e=>na({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??N,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:n,height:i,padX:o,padY:r,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:$,centerRight:P,pinchHeight:f,pinchTop:g,pinchBottom:b,stages:B,membranes:q,colliders:E,regionEffects:F,boundaryY:D}}function ea(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,n=e.y,i=e.width,o=e.height,{type:"aabb",x:t,y:n,width:i,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,n,i,o}function ta(e,t={}){const n=t.idPrefix??"stage",i=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...ea({id:n?`${n}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*i),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function na(e){const t=e.dampingScale??.5,n=e.energyScale??1,i=Qs(e.cost,0,2);return{...ea({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:i,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i*t,energyDelta:-i*n}}function ia(e){return{...ea({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function oa(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...ea({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function ra(e){const t=e.pressure??e.occupancy??0,n=e.baseDamping??.08,i=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...ea({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n+t*i,energyDelta:o?-t*o:void 0,force:e.force}}function sa(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...ea({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function aa(e){return{...ea({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function ca(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...ea({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function la(e){return{...ea({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function da(e){const t=e.x??e.anchor?.x??0,n=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:n,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:n},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function ua(e){const t=e.idPrefix??"lane",n={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},i=[Zs(t+"-top",e.left,e.top,e.right,e.top,n),Zs(t+"-bottom",e.left,e.bottom,e.right,e.bottom,n)];return e.openEnds||i.push(Zs(t+"-left",e.left,e.top,e.left,e.bottom,n),Zs(t+"-right",e.right,e.top,e.right,e.bottom,n)),i}function ha(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}function pa(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const n=e.size,i=bs(n),o=Ss(e.ballRadius??6,2,18),r=e.seed??1,s=Cs(r),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),m=e.springStiffness??.28,f=e.springDamping??.72,y=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=Js({width:n[0],height:n[1],shape:"lane",padX:Math.max(28,i.plot.x),padY:Math.max(36,i.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),x=new Map(b.stages.map((e,t)=>[e.id,t])),v=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,k=b.stages[0],M=new Set(t.filter(e=>e.absorb).map(e=>e.id)),I=t.map(e=>{const t=v.get(e.id)??k;return function(e,t){const n={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return ca({...n,kind:e.kind??"sink",force:ha(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...n.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return aa({...n,kind:e.kind??"force-field",force:ha(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...n.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return sa({...n,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:ha(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...n.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return ra({...n,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:ha(e.force,8),attributes:{...n.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?oa({...n,kind:e.kind??"force-field",force:ha(e.force,14),damping:e.damping??.02,attributes:{...n.attributes,primitive:"routeSurface"}}):la({...n,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...n.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});I.unshift(oa({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(b.left+b.right)/2,y:b.midY,width:b.right-b.left,height:b.bottomY-b.topY-12,force:8,damping:.012,semanticItem:!1}));const S=new Map;for(const e of b.stages)S.set(e.id,0);const j=[];e.data.forEach((e,t)=>{const n=(a?Ms(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",i=(Ms(e,t,c)??w)+"",r=x.has(i)?i:w;S.set(r,(S.get(r)??0)+1);const s=l?(Ms(e,t,l)??"")+"":void 0,p=s&&d?(Ms(e,t,d)??s)+"":s,m=u?Is(Ms(e,t,u))??1:1,f=h?Is(Ms(e,t,h)):null,y=Ss(null!=f&&f>0?f:o,2,18);j.push({datum:e,id:n,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:y,index:t})});const A=new Map,C=new Map;for(const e of j){if(!e.groupId)continue;const t=A.get(e.groupId)??[];t.push(e.id),A.set(e.groupId,t),e.groupLabel&&C.set(e.groupId,e.groupLabel)}const R=Ss(e.groupAnchorAlong??.55,.15,.9),$=b.left+(b.right-b.left)*R,P=Array.from(A.keys()),D=P.map((e,n)=>{const i=A.get(e)??[],o=P.length>1?b.topY+28+n/Math.max(1,P.length-1)*(b.bottomY-b.topY-56):b.midY;return da({id:e,label:C.get(e)??e,bodyIds:i,anchor:{x:$,y:o},x:$,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),B=Xs(D,j.filter(e=>M.has(e.stageId)).map(e=>e.id)),T=new Map(D.map(e=>[e.id,e])),E=j.map((e,t)=>{const n=v.get(e.stageId)??k,i=n.x+(s()-.5)*Math.min(24,.2*n.width),o=b.boundaryY(i,"top")+e.radius+10,r=b.boundaryY(i,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=y?i:b.left+18+t%7*4,l=y?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,d=[{target:{type:"point",x:i,y:a},restLength:.45*e.radius,stiffness:m,damping:f}];if(e.groupId){const t=T.get(e.groupId);t?.anchor&&!M.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:y?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),N={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:b.colliders,fixedDt:1/60,maxSubsteps:8},O=b.stages.map(e=>({label:e.label??e.id,value:S.get(e.id)??0})),W=t.map(e=>{const t=v.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:S.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:N,initialSpawns:E,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:O,metadata:{kind:"process-flow",plot:i.plot,volume:b,stages:W,groups:D,groupCompletion:B,regionEffects:I}}}var ma=require("react");function fa(e,t){if(!t?.length)return[e];const n=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const n=t.datum;return!(!n||"object"!=typeof n||null==n.id)&&n.id+""===e}).map(e=>e.id);return n.length?n:[e]}function ya(e,t,n){if("function"==typeof n)return n(e,t)+"";if("string"==typeof n){const t=e[n];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function ga(e,t){const n=e?.getData().find(e=>e.id===t),i=n?.datum;if(i&&"object"==typeof i)return i}function ba(e,t){const{frameRef:n,spawnDatum:i,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=(0,ma.useRef)(new Map),l=(0,ma.useRef)(new Map),d=(0,ma.useRef)(""),u=o?o.map((e,t)=>ya(e,t,r)).join("\0"):"";if(u!==d.current&&(d.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],n=ya(t,e,r);c.current.set(n,t),l.current.set(n,s?.(t,n,e)??fa(n,a))}(0,ma.useImperativeHandle)(e,()=>{const e=c.current,t=l.current;function o(e,t){const n=i(e,t);return{datumId:n.datumId||ya(e,t,r),spawns:n.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(i){const o=[];for(const{datum:n,result:r}of i)e.set(r.datumId,n),t.set(r.datumId,r.spawns.map(e=>e.id)),o.push(...r.spawns);if(!o.length)return;const r=n.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(i){const o=e.get(i);if(o)return o;const r=t.get(i)??[i];for(const o of r){const r=ga(n.current,o);if(r)return e.set(i,r),t.has(i)||t.set(i,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const n=e.size;s(t.map((e,t)=>({datum:e,result:o(e,n+t)})))},remove:i=>{const o=Array.isArray(i)?i:[i],r=[],s=[];for(const n of o){const i=a(n);i&&r.push(i),e.delete(n),s.push(...t.get(n)??[n]),t.delete(n)}return s.length&&n.current?.remove(s),r},update:(i,r)=>{const c=Array.isArray(i)?i:[i],l=[];for(const i of c){const c=a(i);if(!c)continue;l.push(c);const d=t.get(i)??[i];n.current?.remove(d),e.delete(i),t.delete(i);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",n.current?.clear()},getData:()=>{const t=n.current;if(!t)return Array.from(e.values());const i=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return i.length?i:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}},[n,r,i])}var xa=require("react"),va=c(require("react")),wa=require("react/jsx-runtime");function ka({componentName:e,message:t,diagnosticHint:n,width:i,height:o}){return(0,wa.jsx)("div",{role:"alert",style:{width:i,height:Math.max(o,120),display:"flex",alignItems:"center",justifyContent:"center",border:"1px dashed rgba(128, 128, 128, 0.4)",borderRadius:8,background:"rgba(128, 128, 128, 0.04)",padding:24,boxSizing:"border-box"},children:(0,wa.jsxs)("div",{style:{textAlign:"center",maxWidth:400},children:[(0,wa.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"rgba(128, 128, 128, 0.7)",marginBottom:6,fontFamily:"monospace"},children:e}),(0,wa.jsx)("div",{style:{fontSize:14,color:"rgba(128, 128, 128, 0.9)",lineHeight:1.5},children:t}),n&&(0,wa.jsx)("div",{"data-testid":"semiotic-diagnostic-hint",style:{marginTop:10,padding:"8px 12px",background:"rgba(128, 128, 128, 0.06)",borderRadius:4,fontSize:12,color:"rgba(128, 128, 128, 0.8)",fontFamily:"monospace",textAlign:"left",whiteSpace:"pre-wrap",lineHeight:1.6},children:n})]})})}var Ma=require("react/jsx-runtime"),Ia=class extends va.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.error){const{fallback:e}=this.props,t=this.state.error;return"function"==typeof e?e(t):void 0!==e?e:(0,Ma.jsx)(ka,{componentName:"ChartErrorBoundary",message:t.message||"An unexpected error occurred while rendering this chart.",width:600,height:400})}return this.props.children}},Sa=require("react/jsx-runtime");function ja({componentName:e,width:t,height:n,children:i}){return(0,Sa.jsx)(Ia,{fallback:i=>(0,Sa.jsx)(ka,{componentName:e,message:i.message,width:t,height:n}),children:i})}"undefined"!=typeof process&&process;var Aa={display:"flex",alignItems:"center",justifyContent:"center",color:"var(--semiotic-text-secondary, #666)",fontSize:13,fontFamily:"inherit",border:"1px dashed var(--semiotic-border, #ddd)",borderRadius:4,boxSizing:"border-box"},Ca={background:"var(--semiotic-border, #e0e0e0)",borderRadius:2};function Ra(e){return[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)]}function $a(e,t,n){const i=e=>e.toString(16).padStart(2,"0");return`#${i(e)}${i(t)}${i(n)}`}function Pa(e){const t=e.map(Ra),n=t.length-1;return e=>{if(0>=e){const[e,n,i]=t[0];return $a(e,n,i)}if(e>=1){const[e,i,o]=t[n];return $a(e,i,o)}const i=e*n,o=Math.floor(i),r=i-o,[s,a,c]=t[o],[l,d,u]=t[o+1];return $a(Math.round(s+(l-s)*r),Math.round(a+(d-a)*r),Math.round(c+(u-c)*r))}}require("react"),require("d3-scale");var Da=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Ba=Pa(["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]),Ta=Pa(["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]),Ea=Pa(["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]),Na=Pa(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]),Oa=Pa(["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]),Wa=Pa(["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]),qa={blues:Ba,reds:Ta,greens:Ea,viridis:Pa(["#440154","#482878","#3e4989","#31688e","#26828e","#1f9e89","#35b779","#6ece58","#b5de2b","#fde725"]),oranges:Na,purples:Oa,greys:Wa,plasma:Pa(["#0d0887","#41049d","#6a00a8","#8f0da4","#b12a90","#cb4679","#e16462","#f1844b","#fca636","#fcce25","#f0f921"]),inferno:Pa(["#000004","#160b39","#420a68","#6a176e","#932667","#bc3754","#dd513a","#f3771a","#fca50a","#f6d746","#fcffa4"]),magma:Pa(["#000004","#140e36","#3b0f70","#641a80","#8c2981","#b73779","#de4968","#f7705c","#fe9f6d","#fecf92","#fcfdbf"]),cividis:Pa(["#00224e","#123570","#3b496c","#575d6d","#707173","#8a8678","#a59c74","#c3b369","#e1cc55","#fee838","#ffea46"]),turbo:Pa(["#23171b","#4a58dd","#3f9ee9","#46c7af","#7eed5a","#cdf134","#fbb91f","#f56918","#c52f06","#7a0403"])},Fa=(Pa(["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]),Pa(["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]),Pa(["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]),Pa(["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]),Pa(["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]),Pa(["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]),Pa(["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]),{category10:Da,tableau10:["#4e79a7","#f28e2c","#e15759","#76b7b2","#59a14f","#edc949","#af7aa1","#ff9da7","#9c755f","#bab0ab"],set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],...qa}),za=Da;function La(e,t){if(null==t||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];return"string"==typeof n&&n.length>0?n:void 0}function Ya(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var Ha={enabled:!0,tapToSelect:!0,tapToLockTooltip:!0,clearSelection:"backgroundTap",targetSize:44,snap:"nearestDatum",brushHandleSize:44,standardControls:!1,enabled:!1,tapToSelect:!1,tapToLockTooltip:!1};function _a(e,t={}){const n=t.mobileSemantics?.interaction,i="number"==typeof n?.targetSize?n.targetSize:"number"==typeof t.mobileSemantics?.minimumHitTarget?t.mobileSemantics.minimumHitTarget:void 0,o="mobile"===t.mode||"number"==typeof t.width&&480>=t.width,r=!!n||void 0!==i,s=e&&"object"==typeof e?e:void 0;if(!1===e||!1===s?.enabled||void 0===e&&!o&&!r)return Ha;const a=s??{};return{enabled:!0,tapToSelect:a.tapToSelect??!0,tapToLockTooltip:a.tapToLockTooltip??!0,clearSelection:a.clearSelection??"backgroundTap",targetSize:a.targetSize??i??44,snap:a.snap??"nearestDatum",brushHandleSize:a.brushHandleSize??44,standardControls:a.standardControls??!1}}var Ga={primary:{width:600,height:400,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:void 0,showLabels:void 0,marginDefaults:{top:50,bottom:60,left:70,right:40}},context:{width:400,height:250,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:10,bottom:10,left:10,right:10}},sparkline:{width:120,height:24,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:2,bottom:2,left:0,right:0}},mobile:{width:390,height:300,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:!1,showLabels:!0,marginDefaults:{top:28,bottom:42,left:44,right:16}}};function Xa(e,t,n){if(!1!==t)return e;const i={...e};return"horizontal"===n?i.left=Math.min(i.left,15):i.bottom=Math.min(i.bottom,15),i}function Va(e,t,n){return function(e,t,n){const i=Ga[e||"primary"],o=e&&"primary"!==e||!n?.width?i.width:n.width,r=e&&"primary"!==e||!n?.height?i.height:n.height,s=function(e,t,n=e.responsiveRules){if(!Array.isArray(n)||0===n.length)return{props:e,matches:[]};const i=n.map((e,t)=>({rule:e,index:t})).filter(e=>function(e,t){const{when:n}=e,i=t.width,o=t.height,r=function(e){if("number"==typeof e.height&&e.height>0)return e.width/e.height}(t),s=function(e){if("number"==typeof e.height&&e.height>0)return e.height>e.width?"portrait":"landscape"}(t);return!("number"==typeof n.minWidth&&n.minWidth>i||"number"==typeof n.maxWidth&&i>n.maxWidth||"number"==typeof n.minHeight&&("number"!=typeof o||n.minHeight>o)||"number"==typeof n.maxHeight&&("number"!=typeof o||o>n.maxHeight)||"number"==typeof n.minAspectRatio&&("number"!=typeof r||n.minAspectRatio>r)||"number"==typeof n.maxAspectRatio&&("number"!=typeof r||r>n.maxAspectRatio)||n.orientation&&s!==n.orientation)}(e.rule,t)).sort((e,t)=>("number"==typeof e.rule.priority?e.rule.priority:e.index)-("number"==typeof t.rule.priority?t.rule.priority:t.index));return{props:i.reduce((e,t)=>function(e,t){const n={...e,...t};for(const i of["margin","frameProps","mobileSemantics","style"])Ya(e[i])&&Ya(t[i])&&(n[i]={...e[i],...t[i]});return"string"==typeof e.className&&"string"==typeof t.className&&(n.className=`${e.className} ${t.className}`),n}(e,t.rule.transform),e),matches:i}}({...t,mode:e},{width:t.width??o,height:t.height??r}).props,a=s.mode||e||"primary",c=Ga[a],l="context"===a||"sparkline"===a,d="primary"===a&&n?.width?n.width:c.width;return{mode:a,width:s.width??d,height:s.height??("primary"===a&&n?.height?n.height:c.height),showAxes:s.showAxes??c.showAxes,showGrid:s.showGrid??c.showGrid,enableHover:s.enableHover??(!!s.linkedHover||c.enableHover),showLegend:s.showLegend??c.showLegend,showLabels:s.showLabels??c.showLabels,title:l?void 0:s.title,description:s.description,summary:s.summary,accessibleTable:s.accessibleTable,xLabel:l?void 0:s.xLabel,yLabel:l?void 0:s.yLabel,categoryLabel:l?void 0:s.categoryLabel,valueLabel:l?void 0:s.valueLabel,marginDefaults:Xa(c.marginDefaults,s.showCategoryTicks,s.orientation),compactMode:l,mobileInteraction:_a(s.mobileInteraction,{mode:a,width:s.width??d,mobileSemantics:s.mobileSemantics}),mobileSemantics:s.mobileSemantics}}(e,t,n)}var Ua=require("react/jsx-runtime"),Ka=new Set(["sample","mechanical"]);function Qa(e,t,n,i){const[o,r]=(0,xa.useState)(0),s=(0,xa.useRef)(null),a=(0,xa.useRef)(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),l=(0,xa.useRef)(c),d=(0,xa.useRef)(!!n),u=(0,xa.useRef)(i);l.current=c,d.current=!!n,u.current=i;const h=(0,xa.useCallback)(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=(0,xa.useCallback)(()=>{h();const e=l.current;null!=e&&!d.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(e=>e+1)},e))},[h]);(0,xa.useEffect)(()=>{null==c||n?h():a.current&&p()},[h,c,n,p]),(0,xa.useEffect)(()=>h,[h]);const m=e?.observation?.onSimulationStateChange,f=(0,xa.useCallback)((e,t)=>{if(m?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,m,p]);return{config:(0,xa.useMemo)(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:f}},[e,c,f]),rerunKey:o}}function Za(e,t,n){const i=n?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&Ka.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=Va(i.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=(0,xa.useMemo)(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),d=o.compactMode?"sparkline"===i.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=e.showProjection??!o.compactMode,h=e.showChrome??!o.compactMode,p=nc(e.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??e.title,y=[e.className,i.chartMode&&"primary"!==i.chartMode?"semiotic-physics--"+i.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:i.chartMode,simulationMode:i.simulationMode,resolved:o,chartSize:l,margin:d,showProjection:u,showChrome:h,enableHover:m,title:f,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:y,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function Ja(e){const[t,n]=e.size,i=function(e,t,n,i){if(!e)return null;if(!1===i)return null;if(null!=i)return(0,Sa.jsx)("div",{style:{width:t,height:n,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:i});const o=Math.min(5,Math.floor(n/40)),r=Math.max(8,Math.floor(n/(3*o))),s=Math.max(6,Math.floor(n/(2.5*o))),a=Math.floor((n-(o*(r+s)-s))/2);return(0,Sa.jsx)("div",{style:{width:t,height:n,position:"relative",overflow:"hidden",border:"1px solid var(--semiotic-border, #e0e0e0)",borderRadius:4,boxSizing:"border-box"},children:Array.from({length:o},(e,n)=>(0,Sa.jsx)("div",{className:"semiotic-loading-bar",style:{...Ca,position:"absolute",top:a+n*(r+s),left:Math.floor(.1*t),width:30+(37*n+13)%50+"%",height:r,opacity:.5+n%2*.2}},n))})}(e.loading,t,n,e.loadingContent);return i||function(e,t,n,i){return!1===i||null==e||Array.isArray(e)&&e.length>0?null:Array.isArray(e)?(0,Sa.jsx)("div",{style:{...Aa,width:t,height:n},children:i||"No data available"}):null}(e.data,t,n,e.emptyContent)}function ec(e,t,n){return(0,Ua.jsx)(ja,{componentName:e,width:t[0],height:t[1],children:n})}function tc(e,t){return e?t?n=>(0,Ua.jsxs)(Ua.Fragment,{children:["function"==typeof e?e(n):e,"function"==typeof t?t(n):t]}):e:t}function nc(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:Oe(e)||t?.tooltipContent}}function ic(e,t,n,i){return{accessibleTable:i?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:i?.chartMode??t?.chartMode,className:i?.className??e.className??t?.className,color:e.color??t?.color,description:i?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:i?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:i?.margin??t?.margin,onClick:null!=e.onClick?(t,n)=>{t&&e.onClick?.(t,{x:n.x,y:n.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,semanticItems:t?.semanticItems??n,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:i?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:i?.title??e.title??t?.title}}var oc=require("react/jsx-runtime"),rc=(0,d.forwardRef)(function(e,t){const{data:n,valueAccessor:i="value",styleRules:o,bins:r=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:l,frameProps:u,loading:h,loadingContent:p,mechanicalCount:m,paused:f,pegRows:y,referenceLines:g,rerunMS:b,responsiveHeight:x,responsiveWidth:v,seed:w=1,valueExtent:k}=e,M=Za(e,[700,420],{hasSimulationMode:!0}),{chartSize:I,simulationMode:S,showProjection:j,className:A,title:C,chartMode:R,margin:$,enableHover:P,description:D,summary:B,accessibleTable:T}=M,E=s??("sparkline"===R?1.5:"context"===R?4:6),N=(0,d.useRef)(null),O=Math.max(1,Math.round(y??r-1)),W=(0,d.useMemo)(()=>"mechanical"===S?[0,O]:function(e){if(!e)return;const t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?t>n?[n,t]:[t,n]:void 0}(k),[O,S,k]),q=(0,d.useMemo)(()=>"mechanical"===S?function(e){const t=Math.max(2,Math.round(e.bins)),n=Math.max(1,Math.round(e.pegRows??t-1)),i=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=Ss(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Cs(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:i},(e,t)=>{let i=0;for(let e=0;n>e;e+=1)r()<o&&(i+=1);const a=n/2;return{id:`${s}-${t}`,value:i,mechanical:!0,pegRows:n,branchProbability:o,pathRights:i,side:a>i?"left":i>a?"right":"center"}})}({bins:r,branchProbability:c,count:m,pegRows:O,seed:w}):n??[],[r,c,n,m,O,w,S]),F=(0,d.useMemo)(()=>$s({data:q,valueAccessor:i,bins:r,ballRadius:E,seed:w,size:I,valueExtent:W}),[r,q,I,E,W,w,i]),z=Qa(F.config,b,f);ba(t,{frameRef:N,spawnDatum:(0,d.useCallback)((e,t)=>{const n=$s({data:[e],valueAccessor:i,bins:r,ballRadius:E,seed:w+t+1,size:I,valueExtent:W}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:bs(I).plot.x,y:bs(I).plot.y,mass:1,shape:{type:"circle",radius:E},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[r,I,E,W,w,i]),seedRows:q,seedSpawns:F.initialSpawns});const L="mechanical"===S&&null==a?"side":a,Y=(0,d.useMemo)(()=>vs(L,"#4e79a7",{styleRules:o,valueAccessor:i}),[L,o,i]),H=(0,d.useMemo)(()=>ks(F.projectionRows,I,"bin"),[I,F.projectionRows]),_=Ja({data:"mechanical"===S?q:n,emptyContent:l,loading:h,loadingContent:p,size:I});if(_)return _;const G=function(e,t,n,i,o){const r=Array.isArray(o)?o:o?[o]:[];if(!1!==n||0!==r.length)return({size:o})=>{const s=[Number(o[0])||700,Number(o[1])||420],a=bs(s),c=Math.max(2,Math.round(t)),l=a.plot.width/c,d=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==n,[p,m]=i?.valueExtent??[0,c],f=m===p?1:m-p,y=e.map((e,t)=>{const n=d-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*l).toFixed(1)} ${n.toFixed(1)}`}).join(" ");return(0,oc.jsxs)("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?(0,oc.jsxs)(oc.Fragment,{children:[Array.from({length:c+1},(e,t)=>{const n=a.plot.x+t*l;return(0,oc.jsx)("line",{"data-testid":"galton-board-bin-wall",x1:n,x2:n,y1:a.plot.y,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),(0,oc.jsx)("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,oc.jsx)("path",{d:y,fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?(0,oc.jsx)("text",{x:a.plot.x+(t+.5)*l,y:Math.max(a.plot.y+10,d-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,r.map((e,t)=>{const n=Number(e.value);if(!Number.isFinite(n))return null;const i=a.plot.x+Math.max(0,Math.min(1,(n-p)/f))*a.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===e.labelPosition?Math.min(s[1]-8,d+16):a.plot.y+16;return(0,oc.jsxs)("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[(0,oc.jsx)("line",{x1:i,x2:i,y1:a.plot.y+8,y2:d-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:(0,oc.jsx)("text",{x:Math.min(a.plot.x+a.plot.width-4,i+6),y:r,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${n}`)})]})}}(F.projectionRows,r,j,F.metadata,g),X=nc(e.tooltip,u),V=ic(e,u,H,{chartMode:R,className:A,title:C,description:D,summary:B,accessibleTable:T,enableHover:P,margin:$});return ec("GaltonBoardChart",I,(0,oc.jsx)(us,{...u,...X,...V,ref:N,config:z.config,foregroundGraphics:tc(G,u?.foregroundGraphics),initialSpawns:F.initialSpawns,initialSpawnPacing:F.initialSpawnPacing,paused:f,responsiveHeight:x,responsiveWidth:v,size:I,bodyStyle:Y},z.rerunKey))}),sc=require("react"),ac=require("react/jsx-runtime"),cc=(0,sc.forwardRef)(function(e,t){const{arrivalAccessor:n="arrivalTime",ballRadius:i=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:l,loadingContent:d,paused:u,responsiveHeight:h,responsiveWidth:p,seed:m=1,timeAccessor:f="time",timeExtent:y,timeScale:g=1,watermark:b,windows:x={size:10}}=e,v=Za(e,[760,360]),{chartSize:w,showProjection:k,className:M,title:I,chartMode:S,margin:j,enableHover:A,description:C,summary:R,accessibleTable:$}=v,P=(0,sc.useRef)(null),D=(0,sc.useMemo)(()=>s??[],[s]),B=(0,sc.useMemo)(()=>Bs({data:D,timeAccessor:f,arrivalAccessor:n,windows:x,watermark:b,ballRadius:i,seed:m,size:w,timeExtent:y,timeScale:g}),[n,i,w,D,m,f,y,g,b,x]),T=B.metadata;ba(t,{frameRef:P,spawnDatum:(0,sc.useCallback)((e,t)=>{const o=T?function(e,t,n,i){const o=Is(Ms(e,t,i.timeAccessor));if(null==o)return null;const r=Is(Ms(e,t,i.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=n,u=a+c*l,h=(0,Ps.scaleLinear)().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/l))),m=d>=a+(p+1)*l,{ballRadius:f}=i;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+f,Math.min(s.x+s.width-f,h(o))),y:s.y+f+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:f},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(e,t,T,{timeAccessor:f,arrivalAccessor:n,ballRadius:i}):null,r=o??{id:(e.id??"event-push-"+t)+"",x:bs(w).plot.x,y:bs(w).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??r.id)+"",spawns:[r]}},[n,i,w,T,f]),seedRows:D,seedSpawns:B.initialSpawns});const E=(0,sc.useMemo)(()=>vs(o,"#4e79a7",{styleRules:r,valueAccessor:f}),[o,r,f]),N=(0,sc.useMemo)(()=>function(e,t,n){if(!t)return ks(e,n,"window");const i=t.windowPlot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),r=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,n)=>{const a=Math.max(8,(e.value+(e.secondary??0))/o*r),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(n+.5)*i,y:s-a/2,shape:"rect",width:Math.max(12,.58*i),height:a,group:"window"}})}(B.projectionRows,T,w),[w,B.projectionRows,T]),O=Ja({data:s,emptyContent:a,loading:l,loadingContent:d,size:w});if(O)return O;const W=function(e,t,n){if(!1!==n&&t)return({size:n})=>{const i=[Number(n[0])||760,Number(n[1])||360],o=bs(i),r=Math.max(1,t.windowCount),s=t.plot??o.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,l=c.width/r,d=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,m=t.windowStart+r*t.windowSize,f=c.x+Math.max(0,Math.min(1,m===p?0:(t.watermarkValue-p)/(m-p)))*c.width;return(0,ac.jsxs)("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,ac.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?(0,ac.jsxs)("g",{children:[(0,ac.jsx)("rect",{x:a.x,y:h,width:a.width,height:d-h,fill:"var(--semiotic-negative, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),(0,ac.jsx)("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:r},(n,o)=>{const r=e[o],s=c.x+o*l,a=t.closedWindowCount>o,h=r?.secondary??0;return(0,ac.jsxs)("g",{children:[(0,ac.jsx)("rect",{x:s,y:u,width:l,height:d-u,fill:a?"var(--semiotic-negative, #e15759)":"var(--semiotic-accent, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===o).map(e=>(0,ac.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,(0,ac.jsxs)("text",{x:s+l/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),(0,ac.jsx)("text",{x:s+l/2,y:Math.min(i[1]-8,d+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>(0,ac.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-negative, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),(0,ac.jsx)("line",{x1:s.x,x2:s.x+s.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,ac.jsx)("line",{"data-testid":"event-drop-watermark",x1:f,x2:f,y1:s.y+8,y2:d,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),(0,ac.jsxs)("text",{x:Math.min(s.x+s.width-4,f+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?(0,ac.jsxs)("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-negative, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(B.projectionRows,B.metadata,k),q=nc(e.tooltip,c),F=ic(e,c,N,{chartMode:S,className:M,title:I,description:C,summary:R,accessibleTable:$,enableHover:A,margin:j});return ec("EventDropChart",w,(0,ac.jsx)(us,{...c,...q,...F,ref:P,config:B.config,foregroundGraphics:tc(W,c?.foregroundGraphics),initialSpawns:B.initialSpawns,initialSpawnPacing:B.initialSpawnPacing,paused:u,responsiveHeight:h,responsiveWidth:p,size:w,bodyStyle:E}))}),lc=require("react"),dc=require("react/jsx-runtime"),uc=(0,lc.forwardRef)(function(e,t){const{ballRadius:n=8,categoryAccessor:i="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:l,mechanicalCategories:d,mechanicalCount:u,paused:h,responsiveHeight:p,responsiveWidth:m,seed:f=1,unitValue:y=1,valueAccessor:g,styleRules:b}=e,x=Za(e,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:w,showProjection:k,className:M,title:I,chartMode:S,margin:j,enableHover:A,description:C,summary:R,accessibleTable:$}=x,P=(0,lc.useRef)(null),D="mechanical"===w&&null==g?"value":g,B=(0,lc.useMemo)(()=>"mechanical"===w?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),n=t.length?t:["Intake"],i=Math.max(n.length,Math.round(e.count??Math.max(48,12*n.length))),o=js(e.unitValue,1),r=Cs(e.seed??1),s=e.idPrefix??"mechanical-pile",a=n.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,l=i-n.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=i-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return n.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/i}))}({categories:d,count:u,seed:f,unitValue:y}):r??[],[r,d,u,f,w,y]),T=(0,lc.useMemo)(()=>Es({data:B,categoryAccessor:i,valueAccessor:D,unitValue:y,ballRadius:n,seed:f,size:v}),[n,i,v,B,D,f,y]);ba(t,{frameRef:P,spawnDatum:(0,lc.useCallback)((e,t)=>{const o=Es({data:[e],categoryAccessor:i,valueAccessor:D,unitValue:y,ballRadius:n,seed:f+t+1,size:v}),r={id:(e.id??"pile-push-"+t)+"",x:bs(v).plot.x,y:bs(v).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(e.id??s[0].id)+"",spawns:s}},[n,i,v,D,f,y]),seedRows:B,seedSpawns:T.initialSpawns});const E="mechanical"===w&&null==o?"category":o,N=(0,lc.useMemo)(()=>vs(E,"#4e79a7",{styleRules:b,valueAccessor:g}),[E,b,g]),O=(0,lc.useMemo)(()=>ks(T.projectionRows,v,"category"),[v,T.projectionRows]),W=Ja({data:"mechanical"===w?B:r,emptyContent:s,loading:c,loadingContent:l,size:v});if(W)return W;const q=function(e,t,n){if(!1!==n&&0!==e.length)return({size:n})=>{const i=[Number(n[0])||700,Number(n[1])||380],o=bs(i),r=Ts(o.plot,e.length,t),s=o.plot.y+o.plot.height;return(0,dc.jsxs)("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,dc.jsx)("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const n=Math.min(o.plot.height,r.pileHeight(e.value)),a=r.tubeWidth,c=r.centerX(t),l=s-n;return(0,dc.jsxs)("g",{children:[(0,dc.jsx)("rect",{x:c-a/2,y:l,width:a,height:n,rx:3,fill:"var(--semiotic-accent, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-accent, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),(0,dc.jsx)("text",{x:c,y:Math.max(o.plot.y+12,l-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),(0,dc.jsx)("text",{x:c,y:Math.min(i[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(T.projectionRows,n,k),F=nc(e.tooltip,a),z=ic(e,a,O,{chartMode:S,className:M,title:I,description:C,summary:R,accessibleTable:$,enableHover:A,margin:j});return ec("PhysicsPileChart",v,(0,dc.jsx)(us,{...a,...F,...z,ref:P,config:T.config,foregroundGraphics:tc(q,a?.foregroundGraphics),initialSpawns:T.initialSpawns,initialSpawnPacing:T.initialSpawnPacing,paused:h,responsiveHeight:p,responsiveWidth:m,size:v,bodyStyle:N}))}),hc=require("react"),pc=Object.freeze([]);function mc(e){if(!e)return pc;let t=!1;for(let n=0;e.length>n;n++){const i=e[n];if(null==i||"object"!=typeof i){t=!0;break}}if(!t)return e;const n=[];for(const t of e)null!=t&&"object"==typeof t&&n.push(t);return n}var fc=require("d3-scale");function yc(e,t){const n=t&&"object"==typeof t&&!Array.isArray(t)?t:void 0;return 0===e.length?e=>n&&La(n,e)||"#4e79a7":t=>{if(n){const e=La(n,t);if(e)return e}let i=0;for(let e=0;t.length>e;e++)i=31*i+t.charCodeAt(e)|0;return e[Math.abs(i)%e.length]??"#4e79a7"}}function gc(e,t){const n=t.config??{},i=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...i],r=[...e.colliders??[],...n.colliders??[],...o];return{...e,...n,observation:{...e.observation,...n.observation},...r.length>0&&{colliders:r}}}function bc(e){const t=function(e,t,n){const i=e?.observation;return{...e,observation:{...i,chartId:t??i?.chartId??"physics-custom",chartType:i?.chartType??"PhysicsCustomChart",onObservation:n??i?.onObservation}}}(e.config,e.chartId,e.onObservation),n=function(e,t,n=za){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=Object.values(e).filter(e=>"string"==typeof e&&e.length>0);if(t.length>0)return t}if(Array.isArray(e)&&e.length>0)return e;if("string"==typeof e){const t=Fa[e];if(Array.isArray(t)&&t.length>0)return t}return t&&t.length>0?t:n}(e.colorScheme,e.themeCategorical,Da),i=bs(e.size),o={data:e.data,scales:{x:(0,fc.scaleLinear)().domain(e.xExtent??[0,1]).range([i.plot.x,i.plot.x+i.plot.width]),y:(0,fc.scaleLinear)().domain(e.yExtent??[0,1]).range([i.plot.y+i.plot.height,i.plot.y])},dimensions:i,theme:{semantic:e.semantic,categorical:[...n]},resolveColor:yc(n,e.colorScheme),config:e.layoutConfig??{},world:new Co(t)},r=e.skipLayout?{}:e.layout(o)??{},s=function(e,t){if(!t?.length)return e;const n=new Map;for(const e of t){const{bodyId:t,...i}=e,o=n.get(t)??[];o.push(i),n.set(t,o)}return e.map(e=>{const t=n.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...r.initialSpawns??r.bodies??[]],r.constraints);return{config:gc(t,r),context:o,initialSpawnPacing:r.initialSpawnPacing,initialSpawns:s,result:r}}var xc=require("react/jsx-runtime"),vc=(0,hc.forwardRef)(function(e,t){const{chartId:n,color:i,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:f,opacity:y,paused:g,spawnDatum:b,stroke:x,strokeWidth:v,title:k,xExtent:M,yExtent:I}=e,S=Za(e,[700,380]),{chartSize:A,className:C,title:R,chartMode:$,margin:P,enableHover:D,description:B,summary:T,accessibleTable:E}=S,N=(0,hc.useRef)(null),O=(0,hc.useRef)(null),W=(0,hc.useRef)(""),q=Ja({data:c,emptyContent:l,loading:p,loadingContent:m,size:A}),F=null!=q,z=(0,hc.useMemo)(()=>mc(c??[]),[c]),L=j(e=>e.theme),Y=(0,hc.useMemo)(()=>function(e){if(!e?.colors)return;const t=e.colors;return{primary:t.primary,secondary:t.secondary||t.primary,surface:t.surface||t.background,success:t.success,danger:t.danger,warning:t.warning,error:t.error,info:t.info,text:t.text,textSecondary:t.textSecondary,border:t.border,grid:t.grid}}(L)??{},[L]),H=L?.colors?.categorical??w.colors.categorical,_=(0,hc.useMemo)(()=>[A[0],A[1],z.length,z.map((e,t)=>(e.id??t)+"").join("|"),M?.join(",")??"",I?.join(",")??""].join("::"),[A,z,M,I]),G=(0,hc.useMemo)(()=>bc({chartId:n,colorScheme:r,config:s,data:z,layout:u,layoutConfig:h,onObservation:f,semantic:Y,skipLayout:F,size:A,themeCategorical:H,xExtent:M,yExtent:I}),[n,A,r,s,u,h,f,z,Y,F,H,M,I]);W.current===_&&null!=O.current||(W.current=_,O.current=G.initialSpawns);const X=O.current,V=(0,hc.useMemo)(()=>{const e=[...G.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,G.result.controllers]),U=(0,hc.useMemo)(()=>{const e=[...G.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,G.result.regionEffects]),K=(0,hc.useCallback)(e=>{const t=e.datum,n=t&&o?function(e,t,n){return"function"==typeof n?n(e,0):e[n]}(t,0,o)+"":e.id;return{fill:i??G.context.resolveColor(n,t),stroke:x??"#111827",strokeWidth:v??1,opacity:y??.9}},[i,o,y,G.context,x,v]);ba(t,{frameRef:N,spawnDatum:(0,hc.useCallback)((e,t)=>{const i=e;if(b)return function(e,t,n){return Array.isArray(n)?{datumId:(e.id??n[0]?.id??"physics-custom-"+t)+"",spawns:n}:"spawns"in n?n:{datumId:(e.id??n.id??"physics-custom-"+t)+"",spawns:[n]}}(e,t,b(i,t,G.context));const o=bc({chartId:n,colorScheme:r,config:s,data:[i],layout:u,layoutConfig:h,onObservation:f,semantic:Y,size:A,themeCategorical:H,xExtent:M,yExtent:I}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[n,A,r,s,b,u,h,f,G.context,Y,H,M,I]),seedRows:z,seedSpawns:X});const Q=(0,hc.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(q)return q;const Z=nc(e.tooltip,d),J=ic(e,d,G.result.semanticItems,{chartMode:$,className:C,title:R??k,description:B,summary:T,accessibleTable:E,enableHover:D,margin:P});return ec("PhysicsCustomChart",A,(0,xc.jsx)(us,{...d,...Z,...J,ref:N,backgroundGraphics:tc(d.backgroundGraphics,G.result.backgroundOverlays),bodyForces:G.result.bodyForces??d.bodyForces,bodyStyle:G.result.bodyStyle??d.bodyStyle??K,config:G.config,controllers:V,foregroundGraphics:tc(d.foregroundGraphics,G.result.overlays),initialSpawnPacing:G.initialSpawnPacing,initialSpawns:X,onBodyPointerDown:Q,paused:g,regionEffects:U,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:G.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});vc.displayName="PhysicsCustomChart";var wc=require("react"),kc=require("react/jsx-runtime");function Mc(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var Ic=(0,wc.forwardRef)(function(e,t){const{colorBy:n,styleRules:i,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:l,loadingContent:d,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:m,responsiveHeight:f,responsiveWidth:y,seed:g=1,settle:b,xAccessor:x="x",xExtent:v}=e,w=Za(e,[700,360]),{chartSize:k,showProjection:M,className:I,title:S,chartMode:j,margin:A,enableHover:C,description:R,summary:$,accessibleTable:P}=w,D=h??("sparkline"===j?2:"context"===j?4:5),B=(0,wc.useRef)(null),T=(0,wc.useMemo)(()=>r??[],[r]),E=(0,wc.useMemo)(()=>Os({data:T,xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:D,seed:g,size:k,xExtent:v,collisionIterations:o,settle:b}),[T,k,o,c,D,p,g,b,x,v]),N=Qa(E.config,m,u);ba(t,{frameRef:B,spawnDatum:(0,wc.useCallback)((e,t)=>{const n=Os({data:[e],xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:D,seed:g+t+1,size:k,xExtent:v,collisionIterations:o,settle:b}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:bs(k).plot.x,y:bs(k).plot.y,mass:1,shape:{type:"circle",radius:D},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[k,o,c,D,p,g,b,x,v]),seedRows:T,seedSpawns:E.initialSpawns});const O=n??c,W=(0,wc.useMemo)(()=>vs(O,"#4e79a7",{styleRules:i,valueAccessor:x}),[O,i,x]),q=Ja({data:r,emptyContent:s,loading:l,loadingContent:d,size:k});if(q)return q;const F=function(e,t){if(!1!==t&&e)return({size:t})=>{const n=[Number(t[0])||700,Number(t[1])||360],i=bs(n),o=i.plot.y+i.plot.height,[r,s]=e.xExtent,a=r+(s-r)/2,c=[{label:Mc(r),x:e.xRange[0]},{label:Mc(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:Mc(s),x:e.xRange[1]}];return(0,kc.jsxs)("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.map(e=>(0,kc.jsxs)("g",{children:[(0,kc.jsx)("line",{x1:i.plot.x,x2:i.plot.x+i.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),(0,kc.jsx)("text",{x:i.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),(0,kc.jsxs)("text",{x:i.plot.x+i.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),(0,kc.jsx)("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>(0,kc.jsxs)("g",{children:[(0,kc.jsx)("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),(0,kc.jsx)("text",{x:e.x,y:Math.min(n[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(E.metadata,M),z=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),n=e.xRange[0]+t/2;return e.groups.map(e=>{const i=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:i,description:i,datum:e,x:n,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(E.metadata),L=nc(e.tooltip,a),Y=ic(e,a,z,{chartMode:j,className:I,title:S,description:R,summary:$,accessibleTable:P,enableHover:C,margin:A});return ec("CollisionSwarmChart",k,(0,kc.jsx)(us,{...a,...L,...Y,ref:B,config:N.config,foregroundGraphics:tc(F,a?.foregroundGraphics),initialSpawns:E.initialSpawns,paused:u,responsiveHeight:f,responsiveWidth:y,size:k,bodyStyle:W},N.rerunKey))}),Sc={fresh:1,aging:1.5,stale:3};function jc(e,t,n={}){return Number.isFinite(t)&&t>0?Number.isNaN(e)?"fresh":e===1/0?"expired":0>e||t*(n.fresh??Sc.fresh)>e?"fresh":t*(n.aging??Sc.aging)>e?"aging":t*(n.stale??Sc.stale)>e?"stale":"expired":"fresh"}function Ac(e,t,n){if(null!=e)return"function"==typeof e?e(t,n):"object"==typeof e&&null!==e&&"constant"in e?e.constant:t[e]}function Cc(e){const{data:t,encoding:n}=e,i=[],o=new Map;return t.forEach((e,t)=>{const r=Ac(n.id,e,t);if(null==r||""===r)throw Error(`[semiotic] Motion encoding row ${t} resolved an empty id.`);const s=r+"";if(o.has(s))throw Error(`[semiotic] Duplicate motion encoding id "${s}".`);const a=Ac(n.process?.group,e,t),c=Ac(n.process?.stage,e,t),l=Ac(n.accessible?.group,e,t)??(null!=a?a+"":null!=c?c+"":void 0),d={};for(const i of Object.keys(n.evidence??{}))d[i]=Ac(n.evidence?.[i],e,t);const u={id:s,datum:e,time:{arrival:Ac(n.time?.arrival,e,t),basis:n.time?.basis,unit:n.time?.unit},placement:{x:Ac(n.placement?.x,e,t),y:Ac(n.placement?.y,e,t),lane:Ac(n.placement?.lane,e,t),space:n.placement?.space},kinematics:{velocityX:Ac(n.kinematics?.velocityX,e,t),velocityY:Ac(n.kinematics?.velocityY,e,t),space:n.kinematics?.space},process:{group:a,stage:c,target:Ac(n.process?.target,e,t),work:Ac(n.process?.work,e,t)},evidence:d,accessible:{description:Ac(n.accessible?.description,e,t),group:l,label:Ac(n.accessible?.label,e,t)??s}};i.push(u),o.set(s,u)}),{rows:i,byId:o}}function Rc(e){const t=e.now-e.arrival;return{age:t,progress:Number.isFinite(t)&&Number.isFinite(e.ttl)&&e.ttl>0?Math.max(0,t)/e.ttl:t===1/0&&Number.isFinite(e.ttl)&&e.ttl>0?1/0:0,lifecycle:jc(t,e.ttl,e.thresholds)}}function $c(e){const t=Math.max(0,Math.min(1,e.minOpacity??.1));if(Number.isNaN(e.age))return 1;if(e.age===1/0)return t;if(!Number.isFinite(e.extent)||0>=e.extent)return 1;const n=Math.max(0,e.age);if("step"===e.type)return(e.threshold??.5*e.extent)>n?1:t;if("exponential"===e.type){const i=e.halfLife??e.extent/2;return t+Math.pow(.5,n/(i>0?i:e.extent/2))*(1-t)}return t+Math.max(0,Math.min(1,1-n/e.extent))*(1-t)}function Pc(e,t){const n=Number.isFinite(e)?e:0,i=Number.isFinite(t)?t:0;return{velocityX:n,velocityY:i,speed:Math.hypot(n,i),direction:Math.atan2(i,n)}}function Dc(e,t,n){return Number.isFinite(n)&&n>0?Pc((t.x-e.x)/n,(t.y-e.y)/n):Pc(0,0)}function Bc(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=Cc({data:t,encoding:n}),s=[],a=new Map,c=[],l=[],d=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:u}=e,h=Math.max(0,Ac(n.appearance?.size,u,t)??i.size??6),p=Ac(n.appearance?.shape,u,t)??i.shape??{type:"circle",radius:h},m=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(m):m,g=o?.y?o.y(f):f,b=Ac(n.appearance?.color,u,t)??i.color,x=Ac(n.appearance?.opacity,u,t)??i.opacity,v=Ac(n.appearance?.stroke,u,t)??i.stroke,w=Ac(n.appearance?.strokeWidth,u,t)??i.strokeWidth,k=Ac(n.time?.spawnAt,u,t)??e.time.arrival,M=e.kinematics.velocityX,I=e.kinematics.velocityY,S=Ac(n.dynamics?.mass,u,t)??i.mass??1,j=Ac(n.dynamics?.friction,u,t),A=Ac(n.dynamics?.restitution,u,t),C=Ac(n.dynamics?.bodyCollisions,u,t),R={id:r,x:y,y:g,mass:S,shape:{...p},datum:u,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=I&&{vy:I},...null!=j&&{friction:j},...null!=A&&{restitution:A},...null!=C&&{bodyCollisions:C}},$={...null!=b&&{fill:b},...null!=x&&{opacity:x},...null!=v&&{stroke:v},...null!=w&&{strokeWidth:w}},P={id:r,datum:u,appearance:{color:b,opacity:x,shape:p,size:h,stroke:v,strokeWidth:w},placement:{x:y,y:g,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:I,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:C,friction:j,mass:S,restitution:A},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:R};s.push(P),a.set(r,P),c.push(R),d.set(r,$),l.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:u,x:y,y:g,group:e.accessible.group})}),{rows:s,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function Tc(e){return t=>{const n=Bc({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}var Ec=require("react");function Nc(e,t={}){const n=t.id??"physics-process-boundary",i={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...i,id:n,shape:e}];const o=t.thickness??8,r=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...i,id:n+"-top",shape:{type:"segment",x1:r,y1:a,x2:s,y2:a,thickness:o}},{...i,id:n+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:o}},{...i,id:n+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:r,y2:c,thickness:o}},{...i,id:n+"-left",shape:{type:"segment",x1:r,y1:c,x2:r,y2:a,thickness:o}}]}function Oc(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},n=e.shape,i="aabb"===n.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:n.x,y:n.y,width:n.width,height:n.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(n.x1+n.x2)/2,y:(n.y1+n.y2)/2,pathData:`M ${n.x1} ${n.y1} L ${n.x2} ${n.y2}`};return{...i,...t,id:t.id??i.id}}function Wc(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function qc(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},n={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...n,...t,id:t.id??n.id}]})}var Fc="gauntlet-core",zc="gauntlet-positive",Lc="gauntlet-negative";function Yc(e){const t=Kc(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function Hc(e,t,n,i){return n?"function"==typeof n?n(e,t):e[n]??i:i}function _c(e){return e?.label??e?.id??"property"}function Gc(e){return`gauntlet:${e}:core`}function Xc(e,t){return`gauntlet:${e}:positive:${t}`}function Vc(e,t,n){return`gauntlet:${e}:negative:${t}:${n}`}var Uc={left:28,top:76,rightInset:30,thickness:8};function Kc(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return Uc;const n=Math.max(1,Math.min(e.width,t)),i=Math.max(2,.04*e.width);return{left:i,top:Math.max(2,.08*t),rightInset:i,thickness:Math.max(1,Math.min(4,.04*n))}}function Qc(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function Zc(e,t,n,i){const o=Kc(i),r=Math.max(2,n+2),s=o.top+o.thickness/2+r,a=i.floorY-r,c=(e,t,n)=>t>n?(t+n)/2:Math.max(t,Math.min(n,e));return{x:c(e,o.left+o.thickness/2+r,i.width-o.rightInset-o.thickness/2-r),y:c(t,s,a)}}function Jc(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function el(e,t,n,i){const o=Jc(n),r=i?.(e,t,n)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function tl(e,t,n=1){const i=[...e].sort((e,t)=>e.localeCompare(t)),o=Math.max(0,i.indexOf(t));return{angle:.82*-Math.PI+(i.length>1?o/(i.length-1):.5)*Math.PI*.64,index:o,radius:(48+o%2*6)*n}}function nl(e,t,n){const i=e.activePositiveIds.reduce((e,n)=>e+(t.get(n)?.value??1),0),o=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(n.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*i-8*r-1.2*e.delay-5*o))}function il(e,t,n,i,o){const r=Hc(e,t,n.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=i.map(e=>e.id),a=[...Hc(e,t,n.positiveAccessor,s)],c=[...Hc(e,t,n.negativeAccessor,[])].filter(e=>o.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Hc(e,t,n.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Hc(e,t,n.startTimeAccessor,0))||0),stage:"project filed",viability:Hc(e,t,n.initialViability,100)}}function ol(e,t,n,i,o,r,s){const a=Qc(n),c=Math.max(3,28*a),l=i.startX,d=i.startY+(i.startY===n.routeY?38*t*a:0),u=s?.(e,t,n,i)??{},h=u.x??l,p=u.y??d,m={__gauntlet:!0,kind:Fc,projectId:e.id,sourceDatum:e.datum},f=[{...u,id:Gc(e.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??e.startedAt,datum:m}],y=Zc(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,n);f[0].x=y.x,f[0].y=y.y;for(const t of e.activePositiveIds){const i=o.get(t);if(!i)continue;const r=tl(e.activePositiveIds,t,a),s=i.radius??Math.max(2,10*a),c=Zc(y.x+Math.cos(r.angle)*r.radius,y.y+Math.sin(r.angle)*r.radius,s,n);f.push({id:Xc(e.id,t),x:c.x,y:c.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:i.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:zc,projectId:e.id,property:i,sourceDatum:e.datum},springs:!1===i.spring?[]:[{target:{type:"body",bodyId:Gc(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...i.spring??{}}]})}return e.negativeIds.forEach((t,i)=>{const o=r.get(t);o&&f.push(rl(e,o,i,y.x,y.y,n,u.spawnAt??e.startedAt))}),f}function rl(e,t,n,i,o,r,s){const a=Qc(r),c=t.radius??Math.max(2,7.2*a),l=Zc(i+(n%4*12-12)*a,o+(54+12*Math.floor(n/4))*a,c,r);return{id:Vc(e.id,t.id,n),x:l.x,y:l.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:Lc,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Gc(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+n%4*3)*a),...t.spring??{}}]}}function sl(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function al(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function cl(e,t){return al(e.activePositiveIds,t.popPositive)}function ll(e){const t=Number(e.budget),n=Number.isFinite(t)?Math.max(0,t):0,i=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),o=e.candidates?new Set(e.candidates):null,r=e.attachedIds.map((e,t)=>{const n=i.get(e),o=Number(n?.work??1),r=Number(n?.priority??t);return{id:e,index:t,priority:Number.isFinite(r)?r:t,work:Number.isFinite(o)&&o>0?o:1}}).filter(e=>!o||o.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of r)c+e.work>n+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:n,remaining:Math.max(0,n-c),skippedIds:a}}function dl(e,t){if(!t.from||!t.to||t.from===t.to)return{};const n=Math.max(0,Math.floor(Number(t.count??1)||0)),i=e.negativeIds.filter(e=>e===t.from).length,o=Math.min(n,i);return o?{addNegative:{[t.to]:o},popNegative:{ids:Array.from({length:o},()=>t.from)}}:{}}function ul(e,t){const n=al(e.negativeIds,t.popNegative);if(!n.length)return[];const i=new Map;for(const e of n)i.set(e,(i.get(e)??0)+1);const o=[];return e.negativeIds.forEach((e,t)=>{const n=i.get(e)??0;n>0&&(o.push({propertyId:e,index:t}),i.set(e,n-1))}),o}function hl(e,t,n){if(t.when&&!t.when(n))return e;let i={...e};const o=cl(i,t);o.length&&(i={...i,activePositiveIds:i.activePositiveIds.filter(e=>!o.includes(e)),poppedPositiveIds:Array.from(new Set([...i.poppedPositiveIds,...o]))});const r=ul(i,t);if(r.length){const e=new Set(r.map(e=>e.index));i={...i,negativeIds:i.negativeIds.filter((t,n)=>!e.has(n)),poppedNegativeIds:[...i.poppedNegativeIds,...r.map(e=>e.propertyId)]}}const s=sl(t.addPositive);s.length&&(i={...i,activePositiveIds:Array.from(new Set([...i.activePositiveIds,...s])),missingPositiveIds:i.missingPositiveIds.filter(e=>!s.includes(e))});const a=sl(t.addNegative);if(a.length&&(i={...i,negativeIds:[...i.negativeIds,...a]}),t.delayDelta&&(i={...i,delay:i.delay+t.delayDelta}),t.metricsDelta){const e={...i.metrics};for(const[n,i]of Object.entries(t.metricsDelta))e[n]=Number(e[n]??0)+i;i={...i,metrics:e}}return t.viabilityDelta&&(i={...i,viability:i.viability+t.viabilityDelta}),t.stage&&(i={...i,stage:t.stage}),t.outcome&&(i={...i,outcome:t.outcome}),i}function pl(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function ml(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}function fl(e,t){const n=e.datum;return!(!n?.__gauntlet||n.projectId!==t||n.kind!==Lc)}function yl(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),n=Number(t);return Number.isFinite(n)?n:-1}function gl(e,t){return 2>Math.hypot(e.vx,e.vy)&&4>Math.hypot(t.x,t.y)?null:t}var bl=require("react/jsx-runtime");function xl(e){const t=e.data;return t?.__gauntlet?(0,bl.jsxs)("div",{className:"semiotic-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(15, 23, 42, 0.94))",color:"var(--semiotic-tooltip-text, #f8fafc)",padding:"8px 12px",borderRadius:6,boxShadow:"var(--semiotic-tooltip-shadow, 0 8px 24px rgba(0,0,0,0.35))",maxWidth:280},children:[(0,bl.jsx)("strong",{children:t.kind===Fc?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:_c(t.property)}),(0,bl.jsx)("div",{children:t.kind===zc?"Positive property":t.kind===Lc?"Negative property":"Project core"})]}):null}function vl(e,t,n){const i=t.datum;if(!i?.__gauntlet)return;const o="circle"===t.shape.type?t.shape.radius:8;if(e.save(),e.translate(t.x,t.y),i.kind===Fc)e.fillStyle=wl(e,n.fill,"#0f766e"),e.strokeStyle=wl(e,n.stroke,"#f8fafc"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke();else{const t=i.property;e.fillStyle=wl(e,n.fill??t?.color,"#38bdf8"),e.strokeStyle=wl(e,n.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),i.kind===Lc?e.rect(-o,-o,2*o,2*o):e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=wl(e,"var(--semiotic-background, #07111f)","#07111f"),e.font=`900 ${i.kind===Lc?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function wl(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function kl({layout:e,compact:t,showLabels:n}){const i=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),o=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);return(0,bl.jsx)(bl.Fragment,{children:e.gates.map(r=>(0,bl.jsxs)("g",{children:[(0,bl.jsx)("rect",{x:r.x-r.width/2,y:i,width:r.width,height:o,rx:t?2:12,fill:r.color??"var(--semiotic-accent, #38bdf8)",fillOpacity:.1,stroke:r.color??"var(--semiotic-accent, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),n?(0,bl.jsx)("text",{x:r.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:r.label??r.id}):null]},r.id))})}function Ml({layout:e,states:t,compact:n=!1}){return n?(0,bl.jsx)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:(0,bl.jsx)(kl,{layout:e,compact:!0,showLabels:!1})}):(0,bl.jsxs)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,bl.jsx)("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-accent, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),(0,bl.jsx)("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-negative, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),(0,bl.jsx)("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),(0,bl.jsx)(kl,{layout:e,compact:!1,showLabels:!0}),(0,bl.jsxs)("g",{children:[(0,bl.jsx)("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-positive, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-positive, #22c55e)",strokeWidth:1.5}),(0,bl.jsx)("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),(0,bl.jsxs)("g",{children:[(0,bl.jsx)("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-negative, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-negative, #ef4444)",strokeOpacity:.7}),(0,bl.jsx)("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-negative, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),(0,bl.jsx)("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function Il(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===Fc?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${_c(t.property)} ${t.kind===zc?"positive":"negative"} property`,group:t.kind===zc?"positive property":"negative property",description:`${_c(t.property)} attached to ${t.projectId}.`})}function Sl({states:e,layout:t}){const n=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!n.length)return null;const i=Math.max(1,...n.map(e=>e.value)),o=Math.max(40,(t.width-80)/n.length);return(0,bl.jsxs)("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,bl.jsx)("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),n.map((e,t)=>{const n=40+t*o,r=Math.max(2,e.value/i*28),s=/kill|crash|block|grave/i.test(e.outcome);return(0,bl.jsxs)("g",{children:[(0,bl.jsx)("rect",{x:n+.18*o,y:28-r+22,width:Math.max(10,.45*o),height:r,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),(0,bl.jsx)("text",{x:n+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}var jl=require("react/jsx-runtime"),Al=require("react"),Cl=[],Rl=(0,Ec.forwardRef)(function(e,t){const{bodyGroups:n,coreBody:i,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:l,frameProps:d={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:f,onCapacityChange:y,onClick:g,onStateChange:b,outcome:x,paused:v,positiveProperties:w=Cl,projectPlacement:k,rerunMS:M,responsiveHeight:I,responsiveWidth:S,showTethers:j=!0,terminalBehavior:A="outcome",viability:C}=e,R=(0,Ec.useRef)(null),$=(0,Ec.useMemo)(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),P=Za(e,[900,520]),{chartSize:D,showProjection:B,showChrome:T,className:E,title:N,chartMode:O,margin:W,enableHover:q,description:F,summary:z,accessibleTable:L}=P,Y=Ja({data:a,emptyContent:c,loading:p,loadingContent:m,size:D}),H=(0,Ec.useMemo)(()=>mc(a??[]),[a]),_=(0,Ec.useMemo)(()=>H.map((e,t)=>Hc(e,t,$.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[H,$.idAccessor]),G=(0,Ec.useMemo)(()=>new Map(w.map(e=>[e.id,e])),[w]),X=(0,Ec.useMemo)(()=>new Map(f.map(e=>[e.id,e])),[f]),V=(0,Ec.useMemo)(()=>function(e,t,n){const[i,o]=e,r=220>i||160>o,s=Math.round(.48*o),a=r?o-Math.max(3,Math.min(12,.1*o)):o-36,c=(t??[]).filter(e=>!1!==e.enabled),l=Math.max(1,c.length),d=.22*i,u=l>1?(.78*i-d)/(l-1):0,h=r?Math.max(Math.round(.12*i),.08*i+6):Math.max(Math.round(.14*i),110);return{crashY:a-(r?Math.min(n,Math.max(3,.22*o)):n),floorY:a,gates:c.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(d+t*u),width:e.width??Math.max(r?8:54,Math.round(.07*i))})),graveyardX:Math.round(i*(r?.72:.84)),graveyardY:a-4,height:o,routeY:s,socketX:Math.round(i*(r?.82:.92)),startX:h,width:i}}(D,u,s),[D,s,u]),U=(0,Ec.useMemo)(()=>new Map(V.gates.map(e=>[e.id,e])),[V.gates]),K=(0,Ec.useMemo)(()=>V.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:Fc}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:V.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(220>V.width?12:96,e.width*(220>V.width?2:6)):Math.max(e.width,220>V.width?10:54),height:Math.max(4,Math.min(360,V.height-(160>V.height?8:170)))}})),[V.gates,V.height,V.routeY,V.width]),[Q,Z]=(0,Ec.useState)(()=>H.map((e,t)=>{const n=il(e,t,$,w,X);return{...n,viability:C?.(n,{negativeProperties:X,positiveProperties:G})??nl(n,G,X)}})),J=(0,Ec.useRef)(Q),ee=(0,Ec.useRef)(0),te=(0,Ec.useRef)(new Map),ne=(0,Ec.useRef)([]),ie=(0,Ec.useRef)(y);ie.current=y;const oe=(0,Ec.useRef)(H);oe.current=H;const re=(0,Ec.useRef)(b);re.current=b;const se=(0,Ec.useRef)({negativeById:X,positiveById:G,positiveProperties:w,stateAccessors:$,viability:C});se.current={negativeById:X,positiveById:G,positiveProperties:w,stateAccessors:$,viability:C};const ae=(0,Ec.useCallback)((e,t,n=0)=>{const i=se.current,o=il(e,t,i.stateAccessors,i.positiveProperties,i.negativeById);return i.stateAccessors.startTimeAccessor||(o.startedAt=Math.max(0,n)),{...o,viability:i.viability?.(o,{negativeProperties:i.negativeById,positiveProperties:i.positiveById})??nl(o,i.positiveById,i.negativeById)}},[]),ce=(0,Ec.useCallback)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=oe.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae]),le=Qa((0,Ec.useMemo)(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...d.config?.kernel??{}},colliders:[...Yc(V),...d.config?.colliders??[]]}),[d.config?.colliders,d.config?.kernel,V]),M,v,ce),de=(0,Ec.useMemo)(()=>function(e){const{dataKey:t,gates:n,statesRef:i,processedGateVisitsRef:o}=e;return n.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[_o({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Fc},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const n=t.datum,o=n?.sourceDatum,r=e.capacity?.unitAccessor,s=i.current.find(e=>e.id===n?.projectId);let a;"function"==typeof r?a=s?r(s):void 0:r&&(a=o?.[r]);const c=Number(a??o?.reviewWork??o?.work??s?.metrics.reviewWork??o?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:t=>{const n=t.datum;if(!n?.projectId)return;const i=`${n.projectId}:${e.id}`;o.current.set(i,(o.current.get(i)??0)+1)}})]:[])}({dataKey:`${_}:${le.rerunKey}`,gates:V.gates,statesRef:J,processedGateVisitsRef:te}),[_,V.gates,le.rerunKey]),ue=(0,Ec.useMemo)(()=>[...de,...d.controllers??[]],[de,d.controllers]);(0,Ec.useEffect)(()=>{te.current.clear(),ne.current=[],ee.current=0;const e=oe.current.map((e,t)=>ae(e,t));J.current=e,Z(e)},[ae,_]),(0,Ec.useEffect)(()=>{J.current=Q,re.current?.(Q)},[Q]);const he=(0,Ec.useCallback)(e=>[...("function"==typeof l?l(e,V):l)??[]].sort((e,t)=>e.time-t.time),[l,V]),pe=(0,Ec.useCallback)((e,t,n)=>{if(!t.gateId||!U.get(t.gateId)?.capacity)return!0;const i=Number(t.gateVisit),o=Number.isFinite(i)&&i>0?Math.floor(i):n.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return o>0&&(te.current.get(`${e.id}:${t.gateId}`)??0)>=o},[U]),me=(0,Ec.useCallback)(()=>{if(!de.length)return;const e=de.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,n;(t=ne.current).length===(n=e).length&&t.every((e,t)=>{const i=n[t];return!!i&&e.regionId===i.regionId&&e.queueDepth===i.queueDepth&&e.blockedDepth===i.blockedDepth&&e.processedCount===i.processedCount&&e.metricRevision===i.metricRevision})||(ne.current=e,ie.current?.(e))},[de]),fe=(0,Ec.useMemo)(()=>Q.flatMap((e,t)=>{const n=el(e,t,V,k);return ol(e,t,V,n,G,X,i)}),[i,V,X,G,k,Q]),ye=(0,Ec.useCallback)((e,t)=>{let n=!1;const i=J.current.map(i=>{if(i.id!==e)return i;const o=t(i);return n=n||o!==i,o});n&&(J.current=i,Z(i))},[]);(0,Ec.useImperativeHandle)(t,()=>function(e){const{statesRef:t,setStates:n,elapsedRef:i,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:l,createState:d}=e;return{push:e=>{const u=d(e,t.current.length,i.current),h=el(u,t.current.length,r,s),p=ol(u,t.current.length,r,h,a,c,l),m=[...t.current,u];t.current=m,n(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=i.current;e.forEach(e=>{const t=d(e,u.length,p),n=el(t,u.length,r,s);h.push(...ol(t,u.length,r,n,a,c,l)),u.push(t)}),t.current=u,n(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:e=>{const i=Array.isArray(e)?e:[e],r=[],s=[];for(const e of i){const n=t.current.find(t=>t.id===e);n&&(r.push(n.datum),s.push(Gc(n.id),...n.activePositiveIds.map(e=>Xc(n.id,e))),n.negativeIds.forEach((e,t)=>{s.push(Vc(n.id,e,t))}))}return t.current=t.current.filter(e=>!i.includes(e.id)),n(t.current),o.current?.remove(s),r},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const n=t.current.find(t=>t.id===e);if(!n)continue;const h=t.current.findIndex(t=>t.id===e);p.push(n.datum);const m=u(n.datum),f=d(m,0>h?t.current.length:h,n.startedAt??i.current),y=el(f,0>h?t.current.length:h,r,s);o.current?.remove([Gc(n.id),...n.activePositiveIds.map(e=>Xc(n.id,e)),...n.negativeIds.map((e,t)=>Vc(n.id,e,t))]),o.current?.pushMany(ol(f,0>h?t.current.length:h,r,y,a,c,l)),t.current=t.current.map(t=>t.id===e?f:t)}return n(t.current),p},clear:()=>{t.current=[],n([]),o.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(e,t)=>o.current?.popBodies(e,t)??[]}}({statesRef:J,setStates:Z,elapsedRef:ee,frameRef:R,layout:V,projectPlacement:k,positiveById:G,negativeById:X,coreBody:i,createState:ae}),[i,ae,V,X,G,k]);const ge="sparkline"===O?.22:"mobile"===O?.55:1,be=(0,Ec.useCallback)((e,t,n)=>{!function(e){const{project:t,effect:n,controls:i,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c,popScale:l}=e,d=i.readBodies().find(e=>e.id===Gc(t.id)),u=i.readBodies(),h=d?.x??o.startX,p=d?.y??o.routeY,m=function(e,t){let n=-1;for(const i of t)fl(i,e.id)&&(n=Math.max(n,yl(i)));return Math.max(e.negativeIds.length,n+1)}(t,u),f=sl(n.addNegative).flatMap((e,n)=>{const i=s.get(e);return i?[rl(t,i,m+n,h,p,o)]:[]}),y=sl(n.addPositive).flatMap(e=>{if(!r.get(e)||t.activePositiveIds.includes(e))return[];const n={...Jc(o),routeY:p,socketY:p,startX:h,startY:p};return ol({...t,activePositiveIds:[e],negativeIds:[]},0,o,n,r,s,a).filter(e=>e.id.includes(":positive:"))});(f.length||y.length)&&i.pushMany([...f,...y]);const g=cl(t,n);for(const e of g){const n=r.get(e);c([Xc(t.id,e)],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??10)+3,scale:l})}const b=ul(t,n),x=function(e,t,n){const i=t.filter(t=>fl(t,e.id)).sort((e,t)=>yl(e)-yl(t)||e.id.localeCompare(t.id)),o=new Set;return n.map(t=>{const n=i.find(e=>!o.has(e.id)&&e.datum.property?.id===t.propertyId);return n?(o.add(n.id),n.id):Vc(e.id,t.propertyId,t.index)})}(t,u,b);b.forEach((e,t)=>{const n=s.get(e.propertyId);c([x[t]],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??7)+3,scale:l})})}({project:e,effect:t,controls:n,layout:V,positiveById:G,negativeById:X,coreBody:i,popBodies:(e,t)=>R.current?.popBodies(e,t),popScale:ge})},[i,V,X,G,ge]),xe=(0,Ec.useCallback)(({body:e,bodies:t})=>function(e){const{body:t,bodies:n,layout:i,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:l,coreForceMode:d,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(e=>e.id===p.projectId),f=0>m?void 0:o[m];if(!f)return null;const y=el(f,m,i,r),g=n.find(e=>e.id===Gc(f.id)),b=Qc(i),x=f.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),v=f.killed?0:58*Math.max(.25,b);if(p.kind!==Fc){if(!g)return null;let e;const o=p.property;if(o?.target){const r=n.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===f.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,r.findIndex(e=>e.id===t.id));e=o.target({body:t,bodies:n,core:g,index:s,layout:i,placement:y,project:f})??{x:g.x,y:g.y}}else if(p.kind===zc&&p.property){const t=tl(f.activePositiveIds,p.property.id,b);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const i=n.filter(e=>e.datum?.kind===Lc&&e.datum.projectId===f.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),o=Math.max(0,i.findIndex(e=>e.id===t.id)),r=Math.floor(o/4);e={x:g.x+18*(o%4-(Math.min(4,i.length-4*r)-1)/2)*b,y:g.y+(54+13*r)*b}}const r="circle"===t.shape.type?t.shape.radius:8;e=Zc(e.x,e.y,r,i);const s=Zc(t.x,t.y,r,i);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==zc||f.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===Lc?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return gl(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*v,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a})}if(f.killed)return gl(t,{x:44*((f.crashX??f.metrics.lastX??t.x)-t.x)-9*t.vx,y:(160+12*x)*b-1.6*t.vy});const w=c(f),k=function(e,t,n,i,o,r,s){const a=Qc(n);if(t.killed)return{x:t.metrics.lastX??i.graveyardX,y:i.graveyardY};const c=o[o.length-1];if(!c)return{x:i.socketX,y:i.routeY};const l=o.find(n=>e>=n.time&&!t.eventsApplied.includes(n.id)&&!(!n.gateId||!r.get(n.gateId)?.capacity)),d=l?Math.min(e,l.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(d>c.time+.85){if("hold-last"===s){const e=c.gateId?r.get(c.gateId):void 0;return{x:c.routeX??e?.x??i.socketX,y:c.routeY??i.routeY}}return u?{x:i.socketX,y:i.socketY}:{x:i.graveyardX,y:i.graveyardY-14}}const h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:i.startX,y:i.startY},...o.map(e=>{const t=e.gateId?r.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??i.startX,y:e.routeY??i.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time);let m=p[0],f=p[p.length-1];for(let e=1;p.length>e;e+=1){if(p[e].time>=d){f=p[e];break}m=p[e]}const y=Math.max(0,Math.min(1,(d-m.time)/Math.max(.1,f.time-m.time))),g=y*y*(3-2*y);return{x:m.x+(f.x-m.x)*g,y:m.y+(f.y-m.y)*g+7*Math.sin(2.6*d)*a}}(Math.max(0,h-(f.startedAt??0)),f,i,y,w,l,u),M=f.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return gl(t,"net"===d?{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:1.25*(y.routeY-t.y)-1.4*t.vy+32*(x-M)}:{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:15*(k.y-t.y)-1.8*t.vy+13*x-2.2*M})}({body:e,bodies:t,layout:V,states:J.current,projectPlacement:k,positiveById:G,negativeById:X,projectEvents:he,gateById:U,coreForceMode:o,terminalBehavior:A,elapsed:ee.current}),[o,U,V,X,G,he,k,A]),ve=(0,Ec.useCallback)((e,t)=>{!function(e,t,n){const{frameProps:i,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:l,capacityEventReady:d,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:f,outcome:y,reportCapacity:g}=n;i.onTick?.(e,t),o.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of r.current){const n=t.readBodies().find(t=>t.id===Gc(e.id));if(!n)continue;if(s&&!e.killed&&n.y+("circle"===n.shape.type?n.shape.radius:28)>=a.crashY){t.readBodies().forEach(n=>{const i=n.datum;i?.__gauntlet&&i.projectId===e.id&&t.applyImpulse(n.id,-n.vx*n.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,o.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(e.startedAt??0))};return{...e,crashX:n.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:n.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const i=Math.max(0,o.current-(e.startedAt??0)),r=c(e),g=r.filter(t=>i>=t.time&&!e.eventsApplied.includes(t.id)&&d(e,t,r));let b=e;for(const n of g){const o=n.gateId?l.get(n.gateId):void 0,r=n.effects??[];for(const e of r){const i={event:n,gate:o,negativeProperties:f,positiveProperties:m,project:b};e.when&&!e.when(i)||(u(b,e,t),b=hl(b,e,i))}const s={...pl(n,r),appliedAt:i};b=ml(b,s),h(e.id,e=>{let t=ml(e,s);if(t===e)return e;for(const e of r)t=hl(t,e,{event:n,gate:o,negativeProperties:f,positiveProperties:m,project:t});const i=p?.(t,{negativeProperties:f,positiveProperties:m})??nl(t,m,f);return t={...t,viability:i},n.final&&(t={...t,outcome:n.outcome??y?.(t,{layout:a,negativeProperties:f,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:d,elapsedRef:ee,statesRef:J,crashDetection:r,layout:V,projectEvents:he,gateById:U,capacityEventReady:pe,addBodiesForEffect:be,updateProjectState:ye,viability:C,positiveById:G,negativeById:X,outcome:x,reportCapacity:me})},[be,pe,r,d,U,V,X,x,G,he,me,ye,C]),we=(0,Ec.useCallback)((e,t)=>{const n="function"==typeof d.bodyStyle?d.bodyStyle(e,t):d.bodyStyle,i=e.datum;return i?.__gauntlet?{fill:i.kind===Fc?"var(--semiotic-accent, #0f766e)":i.property?.color??"var(--semiotic-accent, #38bdf8)",stroke:i.kind===Fc?"#f8fafc":"#0f172a",opacity:.96,...n}:n??{}},[d]),ke=(0,Ec.useMemo)(()=>"function"==typeof n?n(Q,V):n??[],[n,V,Q]),Me=(0,Ec.useMemo)(()=>qc(ke),[ke]),Ie=(0,Ec.useMemo)(()=>B?function(e,t){if(!e.length)return[];const n=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const i=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:i,description:i,datum:e,x:40+(t+.5)*n,y:28,shape:"rect",width:Math.max(16,.55*n),height:22,group:"settled projection"}})}(Q,V):[],[V,B,Q]),Se=(0,Ec.useMemo)(()=>[...Ie,...Me],[Me,Ie]),je=(0,Ec.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]),Ae=(0,Ec.useCallback)((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),Ce=(0,Ec.useCallback)((e,t)=>{d.beforePaint?.(e,t),j&&function(e,t){const n=new Map(t.filter(e=>e.datum?.kind===Fc).map(e=>[e.datum.projectId,e]));e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const i of t){const t=i.datum;if(!t?.__gauntlet||t.kind===Fc)continue;const o=n.get(t.projectId);o&&(e.globalAlpha=t.kind===Lc?.24:.36,e.strokeStyle=t.kind===Lc?"#d94a45":"#7a8794",e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}(e,t)},[d,j]),Re=(0,Ec.useMemo)(()=>[...K,...d.regionEffects??[]],[d.regionEffects,K]);if(Y)return Y;const $e=nc(e.tooltip,d),Pe=ic(e,d,Se,{chartMode:O,className:E,title:N,description:F,summary:z,accessibleTable:L,enableHover:q,margin:W}),De=B?(0,jl.jsx)(Sl,{states:Q,layout:V}):void 0,Be=tc(T?(0,jl.jsx)(Ml,{layout:V,states:Q,compact:P.resolved.compactMode}):void 0,d.backgroundGraphics),Te=tc(De,d.foregroundGraphics),Ee=d.renderBody??vl,Ne=$e.tooltipContent??xl;return ec("GauntletChart",D,(0,Al.createElement)(us,{...d,...$e,...Pe,key:`${D[0]}x${D[1]}:${_}:${le.rerunKey}`,ref:R,accessibleTable:e.accessibleTable??d.accessibleTable,backgroundGraphics:Be,bodyForces:xe,bodySemanticItems:d.bodySemanticItems??Il,bodyStyle:we,beforePaint:Ce,onClick:g?Ae:Pe.onClick,config:le.config,controllers:ue,enableHover:$e.enableHover??!0,foregroundGraphics:Te,hoverRadius:e.hoverRadius??d.hoverRadius??18,initialSpawns:fe,initialSpawnPacing:h,onBodyPointerDown:je,onTick:ve,paused:v,regionEffects:Re,renderBody:Ee,responsiveHeight:I,responsiveWidth:S,size:D,tooltipContent:Ne}))});Rl.displayName="GauntletChart";var $l=Rl,Pl=require("react"),Dl=require("react/jsx-runtime");function Bl(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function Tl(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}function El(e){if(!e||"object"!=typeof e)return null;const t=e,n=Number(t.x),i=Number(t.y);return Number.isFinite(n)&&Number.isFinite(i)?{x:n,y:i}:null}function Nl(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(El).filter(e=>null!=e):[]}function Ol(e,t){if(2>t.length)return null;let n=0;const i=[];for(let e=1;t.length>e;e+=1){const o=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);i.push(o),n+=o}if(0>=n)return null;let o=null,r=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],l=i[s-1];if(0>=l)continue;const d=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*d+(e.y-a.y)*u)/(l*l))),p={x:a.x+d*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(r+h*l)/n,tangent:{x:d/l,y:u/l},totalLength:n};o&&m.distance>=o.distance||(o=m),r+=l}return o}function Wl(e,t,n){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=n)return{...e[0]};let i=0;const o=Math.max(0,Math.min(1,t))*n;for(let t=1;e.length>t;t+=1){const n=e[t-1],r=e[t],s=Math.hypot(r.x-n.x,r.y-n.y);if(s>0){if(i+s>=o){const e=(o-i)/s;return{x:n.x+(r.x-n.x)*e,y:n.y+(r.y-n.y)*e}}i+=s}}return{...e[e.length-1]}}function ql(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Fl(e,t,n){const i=Math.hypot(e,t);if(n>=i||0>=i)return[e,t];const o=n/i;return[e*o,t*o]}function zl(e,t,n){const i=Ol({...e,x:t[0].x,y:t[0].y},t),o=i?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=ql(e),l=function(e,t){let n=0;for(let t=0;e.length>t;t+=1)n=31*n+e.charCodeAt(t)>>>0;return(n%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*l,y:t[0].y+s*l,vx:s*n,vy:a*n,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var Ll=(0,Pl.forwardRef)(function(e,t){const{chartId:n,colorBy:i,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:l,links:d,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:f="x",nodeYAccessor:y="y",nodes:g,onObservation:b,particleRadius:x=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:k="path",paused:M,reducedMotion:I=!1,responsiveHeight:S,responsiveWidth:j,seed:A=1,showNodeLabels:C=!0,showSensors:R=!1,showStaticFlow:$=!0,sourceAccessor:P="source",styleRules:D,targetAccessor:B="target",throughputAccessor:T="value"}=e,E=Za(e,[760,420]),{chartSize:N,className:O,title:W,chartMode:q,margin:F,enableHover:z,description:L,summary:Y,accessibleTable:H}=E,_=(0,Pl.useRef)(null),G=(0,Pl.useMemo)(()=>g??[],[g]),X=(0,Pl.useMemo)(()=>d??s??r??[],[r,s,d]),V=(0,Pl.useMemo)(()=>Hs({nodes:G,links:X,nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:P,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:A,size:N}),[X,G,N,o,c,p,m,f,y,x,v,w,k,I,A,P,B,T]);ba(t,{frameRef:_,spawnDatum:(0,Pl.useCallback)((e,t)=>{const n=Hs({nodes:G,links:[e],nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:P,targetAccessor:B,throughputAccessor:T,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:A+t+1,size:N}),i={id:(e.id??"physical-flow-push-"+t)+"",x:bs(N).plot.x,y:bs(N).plot.y,mass:1,shape:{type:"circle",radius:x},datum:e},r=n.initialSpawns.length?n.initialSpawns:[i];return{datumId:(e.id??r[0].id)+"",spawns:r}},[G,N,o,c,p,m,f,y,x,v,w,k,I,A,P,B,T]),seedRows:X,seedSpawns:V.initialSpawns});const U=i??"source",K=(0,Pl.useMemo)(()=>vs(U,"#2563eb",{styleRules:D,valueAccessor:T}),[U,D,T]),Q=(0,Pl.useMemo)(()=>function(e,t,n){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PhysicalFlowChart",onObservation:n??e.observation?.onObservation}}}(V.config,n,b),[n,V.config,b]),Z=(0,Pl.useRef)(l?.onTick);Z.current=l?.onTick;const J=(0,Pl.useCallback)((e,t)=>{I||"none"===k||function(e,t){const n=e.readBodies(),i=[],o=[];for(const r of n){const n=Nl(r.datum);if(2>n.length)continue;const s=Ol(r,n);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),l=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*ql(r))){i.push(r.id),o.push(zl(r,n,l));continue}const d=Wl(n,Math.min(1,s.progress+Math.max(.035,Math.min(.12,l/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*l-r.vx)*r.mass*.16+(d.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*l-r.vy)*r.mass*.16+(d.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,f]=Fl(h,p,r.mass*l*.35);e.applyImpulse(r.id,m,f)}i.length&&e.remove(i),o.length&&e.pushMany(o)}(t,c),Z.current?.(e,t)},[c,k,I]),ee=Ja({data:null==d&&null==s&&null==r?void 0:X,emptyContent:a,loading:u,loadingContent:h,size:N});if(ee)return ee;const te=function(e,t){const{showNodeLabels:n,showSensors:i,showStaticFlow:o}=t;if(e&&(o||i))return({size:t})=>{const r=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return(0,Dl.jsxs)("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?e.links.map(e=>{const t=3+e.throughput/s*16,n=e.path[Math.floor(e.path.length/2)];return(0,Dl.jsxs)("g",{children:[(0,Dl.jsx)("path",{d:Tl(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),(0,Dl.jsx)("path",{d:Tl(e.path),fill:"none",stroke:"var(--semiotic-accent, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),n?(0,Dl.jsx)("text",{x:n.x,y:n.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:Bl(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>(0,Dl.jsxs)("g",{children:[i&&a.has(e.sensorId)?(0,Dl.jsx)("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?(0,Dl.jsx)("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,n?(0,Dl.jsx)("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text-primary, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(V.metadata,{showNodeLabels:C,showSensors:R,showStaticFlow:$}),ne=(ie=V.metadata)?ie.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],n=`${e.sourceLabel} to ${e.targetLabel}: ${Bl(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:n,description:n,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:Tl(e.path),group:"flow"}}):[];var ie;const oe=nc(e.tooltip,l),re=ic(e,l,ne,{chartMode:q,className:O,title:W,description:L,summary:Y,accessibleTable:H,enableHover:z,margin:F});return ec("PhysicalFlowChart",N,(0,Dl.jsx)(us,{...l,...oe,...re,ref:_,config:Q,continuous:!I&&"none"!==k,foregroundGraphics:tc(te,l?.foregroundGraphics),initialSpawns:V.initialSpawns,onTick:J,paused:M||I,responsiveHeight:S,responsiveWidth:j,simulationExecution:"none"===k?l?.simulationExecution:"sync",size:N,bodyStyle:K,workerBodyThreshold:l?.workerBodyThreshold??1/0}))});Ll.displayName="PhysicalFlowChart";var Yl=require("react"),Hl=require("react/jsx-runtime"),_l={flow:{fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(96, 165, 250, 0.7)",accent:"#60a5fa"},capacity:{fill:"rgba(251, 146, 60, 0.18)",stroke:"rgba(251, 146, 60, 0.85)",accent:"#fb923c"},portal:{fill:"rgba(244, 114, 182, 0.14)",stroke:"rgba(244, 114, 182, 0.7)",accent:"#f472b6"},absorb:{fill:"rgba(52, 211, 153, 0.18)",stroke:"rgba(52, 211, 153, 0.8)",accent:"#34d399"}},Gl=6.2;function Xl(e,t,n){return Math.max(t,Math.min(n,e))}function Vl(e){return e.length*Gl}function Ul(e,t){const n=e.trim();if(t>=n.length)return n;if(1>=t)return n.slice(0,1);const i=n.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return i.length>1&&t>=i.length?i:t>3?n.slice(0,Math.max(1,t-2))+"..":n.slice(0,t).toUpperCase()}function Kl(e,t,n="auto"){const i=Math.max(1,Math.floor(t/Gl)),o="compact"===n?Ul(e,i):"full"===n?e:Vl(e)>t?Ul(e,i):e;return{text:o,textLength:Vl(o)>t?Math.max(4,t):void 0}}function Ql(e,t={}){const{showFlowSpine:n=!0,showStageCounts:i=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:l,height:d,left:u,right:h,topY:p,bottomY:m,midY:f,stages:y,groups:g=[]}=e,b=m-p;return(0,Hl.jsxs)("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:l,height:d,viewBox:`0 0 ${l} ${d}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[(0,Hl.jsx)("defs",{children:(0,Hl.jsxs)("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Hl.jsx)("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),(0,Hl.jsx)("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),(0,Hl.jsx)("rect",{x:0,y:0,width:l,height:d,fill:"url(#semiotic-process-floor)"}),(0,Hl.jsx)("rect",{x:u-6,y:p-8,width:h-u+12,height:b+16,rx:14,fill:"var(--semiotic-process-lane, var(--semiotic-surface, #111827))",fillOpacity:.45,stroke:"var(--semiotic-process-border, var(--semiotic-border, #334155))",strokeOpacity:.95}),n?(0,Hl.jsx)("line",{x1:u+8,x2:h-8,y1:f,y2:f,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,y.map((e,t)=>{const n=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),r=_l[n],c=Math.max(12,e.width-8),l=Xl(c-8,22,88),u=Kl(e.label,Math.max(8,l-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),x=Kl(g,Math.max(16,c-10),"auto"),v=o&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=Kl(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),I=M-13;return(0,Hl.jsxs)("g",{"data-stage":e.id,"data-role":n,children:[(0,Hl.jsx)("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===n?1:1.6}),y.length-1>t?(0,Hl.jsx)("polygon",{points:`${e.x1-2},${f-7} ${e.x1+8},${f} ${e.x1-2},${f+7}`,fill:r.accent,opacity:.85}):null,h?(0,Hl.jsxs)(Hl.Fragment,{children:[(0,Hl.jsx)("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-l/2,y:I,width:l,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),(0,Hl.jsxs)("text",{x:e.x,y:M,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Hl.jsx)("title",{children:e.label}),u.text]})]}):null,v?(0,Hl.jsxs)("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:x.textLength,lengthAdjust:x.textLength?"spacingAndGlyphs":void 0,children:[(0,Hl.jsx)("title",{children:g}),x.text]}):null,i&&null!=e.count?(0,Hl.jsxs)("text",{x:e.x,y:Math.min(d-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[(0,Hl.jsx)("title",{children:w}),k.text]}):null]},e.id)}),r?g.map((e,t)=>{const n=e.total??0,i=e.absorbed??0,o=e.complete??(n>0&&i>=n),r=!o&&n>0&&i/n>=.75,s=o?"rgba(52, 211, 153, 0.35)":r?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=o?"#34d399":r?"#fbbf24":"var(--semiotic-border, #64748b)",c=n>0?`${i}/${n}${o?" shipped":r?" almost":""}`:"feature "+(t+1),l=Xl(Math.max(54,Vl(e.label)+18,Vl(c)+16),54,104),d=Kl(e.label,l-12,"auto"),u=Kl(c,l-12,"auto");return(0,Hl.jsxs)("g",{"data-group":e.id,children:[(0,Hl.jsx)("rect",{x:e.x-l/2,y:e.y-22,width:l,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),(0,Hl.jsxs)("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:d.textLength,lengthAdjust:d.textLength?"spacingAndGlyphs":void 0,children:[(0,Hl.jsx)("title",{children:e.label}),d.text]}),(0,Hl.jsxs)("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,Hl.jsx)("title",{children:c}),u.text]})]},e.id)}):null]})}var Zl=require("react/jsx-runtime"),Jl=(0,Yl.forwardRef)(function(e,t){const{ballRadius:n=6,chromeOptions:i,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:l,groupCompletion:d,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:f,liveCapacity:y=!0,onCapacityChange:g,selection:b,bodyLimit:x,bodyMark:v,loading:w,loadingContent:k,paused:M,radiusAccessor:I,responsiveHeight:S,responsiveWidth:j,route:A="horizontal",seed:C=1,settle:R,springDamping:$,springStiffness:P,stageAccessor:D="stage",stages:B,workAccessor:T}=e,E=Za(e,[900,420]),{chartSize:N,showProjection:O,showChrome:W,className:q,title:F,chartMode:z,margin:L,enableHover:Y,description:H,summary:_,accessibleTable:G}=E,X=(0,Yl.useRef)(null),V=(0,Yl.useMemo)(()=>mc(r??[]),[r]),U=(0,Yl.useMemo)(()=>({data:V,stages:B,size:N,idAccessor:m,stageAccessor:D,groupBy:l,groupLabelAccessor:u,workAccessor:T,radiusAccessor:I,ballRadius:n,seed:C,route:A,groupCompletion:d,groupAnchorAlong:c,springStiffness:P,springDamping:$,gravityX:h,gravityY:p,settle:R}),[n,N,h,p,c,l,d,u,m,I,A,V,C,R,$,P,D,B,T]),K=(0,Yl.useMemo)(()=>pa(U),[U]),Q=K.metadata;ba(t,{frameRef:X,spawnDatum:(0,Yl.useCallback)((e,t)=>{const i=pa({...U,data:[e],seed:C+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:bs(N).plot.x,y:bs(N).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[n,U,N,C]),seedRows:V,seedSpawns:K.initialSpawns});const Z=(0,Yl.useMemo)(()=>vs(o),[o]),J=(0,Yl.useMemo)(()=>{if(!y)return a.controllers;const e=[...B.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return _o({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(T?"string"==typeof T?T:e=>{const t=e.datum;if(!t)return 1;try{return Number(T(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,y,B,T]),[ee,te]=(0,Yl.useState)({}),ne=(0,Yl.useRef)(J);ne.current=J;const ie=(0,Yl.useRef)(a.onTick);ie.current=a.onTick;const oe=!1!==W||null!=g;(0,Yl.useEffect)(()=>{if(!g)return;const e=Object.values(ee);e.length&&g(e)},[ee,g]);const re=(0,Yl.useCallback)((e,t)=>{if(ie.current?.(e,t),!oe)return;const n=ne.current;if(!n?.length)return;const i={};for(const e of n){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(i[t.regionId]=t)}te(e=>function(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){const n=e[i],o=t[i];if(!o)return!1;if(n.queueDepth!==o.queueDepth||n.blockedDepth!==o.blockedDepth||n.processedCount!==o.processedCount||n.unitsPerSecond!==o.unitsPerSecond||n.regionId!==o.regionId||n.metricRevision!==o.metricRevision)return!1}return!0}(e,i)?e:i)},[oe]),se=(0,Yl.useMemo)(()=>{const e=Z,t=a.bodyStyle;return v||t?(n,i)=>{const o="function"==typeof t?t(n,i):t;return{..."function"==typeof e?e(n):e,...o,mark:o?.mark??n.datum?.__physicsMark??n.datum?.mark??v}}:e},[v,Z,a.bodyStyle]),ae=Ja({data:r,emptyContent:s,loading:w,loadingContent:k,size:N});if(ae)return ae;if(!B?.length)return ec("ProcessFlowChart",N,(0,Zl.jsx)("div",{role:"status",style:{width:N[0],height:N[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const ce=function(e,t,n={},i){if(!1===t||!e)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=e,c=new Map(o.stages.map(e=>[e.id,e])),l=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||o.width,a=Number(e[1])||o.height,d=r.map(e=>{const t=c.get(e.id),i=n["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:i?.queueDepth,processed:i?.processedCount}}),u=s.map(e=>{const t=l.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return Ql({width:t,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:d,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...i})}}(Q,W,ee,i),le=function(e,t,n){if(!1===n||!t||0===e.length)return;const i=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:n})=>{const o=[Number(n[0])||t.volume.width,Number(n[1])||t.volume.height],r=bs(o),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return(0,Zl.jsx)("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,n)=>{const o=e[n];if(!o)return null;const r=i.get(t.id);if(!r)return null;const l=Math.max(2,o.value/s*a),d=Math.max(8,.35*r.width);return(0,Zl.jsx)("rect",{x:r.x-d/2,y:c,width:d,height:l,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(K.projectionRows,Q,O),de=[...ks(K.projectionRows,N,"stage"),...qc(Q?.groups??[])],ue=nc(e.tooltip,a),he=ic(e,a,de,{chartMode:z,className:q,title:F,description:H,summary:_,accessibleTable:G,enableHover:Y,margin:L}),pe=[...Q?.regionEffects??[],...a.regionEffects??[]];return ec("ProcessFlowChart",N,(0,Zl.jsx)(us,{...a,...ue,...he,ref:X,controllers:J,regionEffects:pe,selection:b??a.selection,backgroundGraphics:tc(ce,a.backgroundGraphics),foregroundGraphics:tc(le,a.foregroundGraphics),initialSpawns:K.initialSpawns,initialSpawnPacing:f??K.initialSpawnPacing,onTick:re,paused:M,responsiveHeight:S,responsiveWidth:j,size:N,bodyStyle:se,config:{...K.config,...null!=x?{bodyLimit:x,eviction:"oldest"}:{},...a.config}}))});Jl.displayName="ProcessFlowChart";var ed=[.1,.5,.9],td=1e6,nd=12;function id(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function od(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function rd(e){const t=Number(e.toFixed(nd));return Object.is(t,-0)?0:t}function sd(e,t,n,i){const o=e.flatMap((e,o)=>{const r=id(od(e,o,t,n,"time")),s=id(od(e,o,t,i,"value"));return null==r||null==s?[]:[{time:rd(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function ad(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const c=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function cd(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function ld(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??ed).map(e=>{const t=id(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return rd(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>td)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${td} points`);return Array.from(new Set(e.map(id).filter(e=>null!=e).map(rd))).sort((e,t)=>e-t)}const t=e,n=id(t.start),i=id(t.end),o=id(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>td)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${td} points`);const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(rd(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(rd(i)),s.length>td)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${td} points`);return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>sd(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>ad(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?cd(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?cd(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function dd(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function ud(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=id(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=rd(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function hd(e,t,n){return t>e?"below":e>n?"above":"inside"}function pd(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,u=(r-o)*n,h=hd(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function md(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=sd(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??dd(t,"lower"),a=n.upper??dd(t,"upper"),c=t.points.map(e=>{const t=ad(r,e.time,i,o),n=ud(e,s),c=ud(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":hd(t,n,c)}});let l=0,d=0,u=0,h=0,p=null,m=0,f=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,p=e.time),n>m&&(m=n,f=e.time)}let y=0,g=0,b=0,x=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=pd(t,n);y+=e.below,g+=e.inside,b+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?b+=o:g+=o)}}const v=c[0]?.time,w=c[c.length-1]?.time,k=null==v||null==w?0:Math.max(0,w-v);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:g,aboveDuration:b,peakExcess:h,peakExcessAt:p,peakDeficit:m,peakDeficitAt:f}}function fd(e){return{id:e,furthestStageIndex:-1,visitedStageIds:[],visitsByStage:{},firstEnteredAt:{},lastEnteredAt:{},regressionCount:0}}function yd(e){const t=Array.from(new Set(e.bodyIds??[]));return{stages:e.stages.map(e=>({...e})),bodyIds:t,entities:Object.fromEntries(t.map(e=>[e,fd(e)]))}}function gd(e,t,n={}){if("region-enter"!==t.type)return e;const i=function(e,t){const n=t.stageId?.(e);if(n)return n;const i=e.region.metadata;if(i&&"object"==typeof i){const e=i.stageId;if("string"==typeof e)return e}return e.region.id}(t,n),o=e.stages.findIndex(e=>e.id===i);if(0>o)return e;const r=n.entityId?.(t)??t.bodyId;if(!r)return e;const s=e.entities[r]??fd(r),a=s.currentStageId?e.stages.findIndex(e=>e.id===s.currentStageId):-1,c=!s.visitedStageIds.includes(i),l=Number(t.observation.timestamp),d=Number.isFinite(l)?l:0,u={...s,currentStageId:i,furthestStageId:o>s.furthestStageIndex?i:s.furthestStageId,furthestStageIndex:Math.max(s.furthestStageIndex,o),visitedStageIds:c?[...s.visitedStageIds,i]:s.visitedStageIds,visitsByStage:{...s.visitsByStage,[i]:(s.visitsByStage[i]??0)+1},firstEnteredAt:c?{...s.firstEnteredAt,[i]:d}:s.firstEnteredAt,lastEnteredAt:{...s.lastEnteredAt,[i]:d},regressionCount:a>=0&&a>o?s.regressionCount+1:s.regressionCount};return{...e,bodyIds:e.bodyIds.includes(r)?e.bodyIds:[...e.bodyIds,r],entities:{...e.entities,[r]:u}}}function bd(e){const t=e.bodyIds.map(t=>e.entities[t]??fd(t)),n=t.length;let i=n;return e.stages.map((e,o)=>{const r=t.filter(e=>e.furthestStageIndex>=o).length,s=t.filter(t=>t.visitedStageIds.includes(e.id)).length,a=t.reduce((t,n)=>t+(n.visitsByStage[e.id]??0),0),c={id:e.id,label:e.label??e.id,reached:r,entered:s,total:n,conversion:n>0?r/n:0,fromPrevious:i>0?r/i:0,dropoff:Math.max(0,i-r),visits:a,repeatVisits:Math.max(0,a-s)};return i=r,c})}function xd(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function vd(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function wd(e,t,n){return xd(e[t])??n}function kd(e,t){return"number"==typeof e?e:e?.[t]??0}function Md(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=r?c.length-1:c.length-2,d=[];for(let e=r?0:1;l>=e;e+=1){if(!s&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return d}function Id(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...ro(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...so({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...Md({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...Md({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function Sd(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===u)return[];const p=u>1?(a-s)/(u-1):0,m=t.width/h,f=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?m/2:0;for(let i=0;h>i;i+=1){const a=t.x+m*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*p,width:2*o,height:2*o},restitution:l,friction:d})}}return f}function jd(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=ci(l),p=kd(d,"x"),m=kd(d,"y");return e.map((e,l)=>{const d=vd(t.x,e,l,wd(e,"x",0)),f=vd(t.y,e,l,wd(e,"y",0)),y=vd(i,e,l,5),g="function"==typeof o?o(e,l):o??{type:"circle",radius:y};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*p,y:f+(h()-.5)*m,vx:vd(s,e,l,0),vy:vd(a,e,l,0),mass:vd(r,e,l,1),spawnAt:vd(c,e,l,void 0),shape:g,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function Ad(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,c=Yi(e,a),l=i?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:c,colliders:l}}function Cd(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return xd("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-c:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Rd=require("react"),$d=1e-9;function Pd(e,t){return t>e?-1:e>t?1:0}function Dd(e){return{...e}}function Bd(e){return e.map(e=>({...e,sourceIds:e.sourceIds?[...e.sourceIds]:void 0,productIds:e.productIds?[...e.productIds]:void 0,relationIds:e.relationIds?[...e.relationIds]:void 0,outletIds:e.outletIds?[...e.outletIds]:void 0}))}function Td(e){const t=Object.fromEntries(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:Dd(t.initialMetrics),metrics:Dd(t.metrics),productIds:[...t.productIds],history:Bd(t.history)}])),n=Object.fromEntries(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:Dd(t.metrics),sourceIds:[...t.sourceIds],history:Bd(t.history)}])),i=Object.fromEntries(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?Dd(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:n,relations:i,input:{amount:e.input.amount,metrics:Dd(e.input.metrics)},metrics:Dd(e.metrics),loss:{amount:e.loss.amount,metrics:Dd(e.loss.metrics)},history:Bd(e.history)}}function Ed(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function Nd(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(Pd)}function Od(e,t){return e?Object.entries(e).flatMap(([e,n])=>Number.isFinite(n)?[]:[Ed("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function Wd(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}function qd(e,t,n="selector"){const i=[],o=Object.values(e.components),r=new Set(o.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&i.push(Ed("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,n+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||i.push(Ed("error","invalid-selector-count","Selector count must be a non-negative integer.",n+".count")),i.some(e=>"error"===e.severity))return{ids:[],diagnostics:i};const a=t.ids?new Set(t.ids):null,c=t.categories?new Set(t.categories):null,l=t.statuses?new Set(t.statuses):null,d=t.outletIds?new Set(t.outletIds):null;let u=o.filter(e=>!a||a.has(e.id)).filter(e=>!c||c.has(e.category)).filter(e=>!l||l.has(e.status)).filter(e=>!d||void 0!==e.outletId&&d.has(e.outletId)).map(e=>e.id).sort(Pd);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||i.push(Ed("warning","empty-selector","Selector matched no source components.",n)),{ids:u,diagnostics:i}}function Fd(e,t,n={}){return{eventId:e.event.id,effectType:t.type,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,label:e.event.label,summary:e.event.summary,...n}}function zd(e,t){const n={...t,eventId:e.event.id};e.materializations.push(n),e.observations.push({...n,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function Ld(e,t,n){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(Ed("error","unknown-outlet",`Unknown outlet "${t}".`,n,[t])),1))}function Yd(e,t,n){const i=Nd(t);t.length||e.diagnostics.push(Ed("error","empty-source-list","A product requires at least one source component.",n)),i.length&&e.diagnostics.push(Ed("error","duplicate-source",`Source ids may appear only once: ${i.join(", ")}.`,n,i));const o=t.filter(t=>!e.state.components[t]);o.length&&e.diagnostics.push(Ed("error","unknown-component",`Unknown source component id${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(Ed("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,n,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(Ed("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,n,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function Hd(e,t,n,i,o){const r=i?.amount??0;(!Number.isFinite(r)||0>r||r>t+$d)&&e.diagnostics.push(Ed("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",o+".amount")),e.diagnostics.push(...Od(i?.metrics,o+".metrics"));for(const[t,r]of Object.entries(i?.metrics??{}))(0>r||r>Number(n[t]??0)+$d)&&e.diagnostics.push(Ed("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${o}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function _d(e,t,n,i,o,r,s){return{id:e.id,label:e.label??e.id,description:e.description,category:e.category??"product",color:e.color,order:e.order,declaredAmount:e.amount,amount:r&&void 0!==e.amount?e.amount:n,metrics:r&&e.metrics?{...i,...e.metrics}:i,status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(o.outletIds.has("product")?"product":void 0):void 0,createdByEventId:o.event.id,createdAt:o.context.appliedAt,completedByEventId:r?o.event.id:void 0,completedAt:r?o.context.appliedAt:void 0,history:[s]}}function Gd(e,t,n,i){void 0!==t.amount&&Math.abs(t.amount-n)>$d&&e.diagnostics.push(Ed("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${n}.`,i,[t.id]))}function Xd(e,t,n){const i=`events.${e.event.id}.effects.${n}`,o=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(Ed("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,i+".state")),e.diagnostics.push(...Od(t.metricsDelta,i+".metricsDelta")),Ld(e,t.outletId,i+".outletId");const n=qd(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Ed("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Fd(e,t,{sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of n.ids){const n=o.components[e];n.status=t.state,n.outletId=t.outletId,n.reason=t.reason,t.metricsDelta&&Wd(n.metrics,t.metricsDelta),n.history.push(s)}return o.history.push(s),void(n.ids.length&&zd(e,{type:"retarget-component",sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:n}=t;n.id&&!o.relations[n.id]||e.diagnostics.push(Ed("error","duplicate-relation",`Relation id "${n.id}" is missing or already active.`,i+".relation.id",[n.id]));const r=function(e,t,n){const i=Nd(t),o=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(Ed("error","insufficient-relation-sources","A relation requires at least two source components.",n)),i.length&&e.diagnostics.push(Ed("error","duplicate-source",`Relation source ids must be unique: ${i.join(", ")}.`,n,i)),o.length&&e.diagnostics.push(Ed("error","unknown-component",`Relation references unknown source component${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,n.sourceIds,i+".relation.sourceIds");if(e.diagnostics.push(...Od(n.metrics,i+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;o.relations[n.id]={...n,sourceIds:[...n.sourceIds],metrics:n.metrics?{...n.metrics}:void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=Fd(e,t,{sourceIds:[...n.sourceIds],relationIds:[n.id]});return o.history.push(s),void zd(e,{type:"activate-relation",sourceIds:[...n.sourceIds],relationIds:[n.id]})}if("resolve-relation"===t.type){const n=Nd(t.relationIds),r=t.relationIds.filter(e=>!o.relations[e]),s=t.relationIds.filter(e=>"resolved"===o.relations[e]?.status);if(n.length&&e.diagnostics.push(Ed("error","duplicate-relation","Relation ids must be unique.",i+".relationIds",n)),r.length&&e.diagnostics.push(Ed("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,i+".relationIds",r)),s.length&&e.diagnostics.push(Ed("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,i+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const n of t.relationIds){const i=o.relations[n];i.status="resolved",i.resolution=t.resolution,i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt,i.reason=t.reason}const a=Fd(e,t,{relationIds:[...t.relationIds]});return o.history.push(a),void zd(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const n=e.productDefinitions.get(t.productId);n||e.diagnostics.push(Ed("error","unknown-product",`Product "${t.productId}" has no declared mold.`,i+".productId",[t.productId]));const r=o.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(Ed("error","duplicate-product",`Product "${t.productId}" has already been formed.`,i+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(Ed("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,i+".productId",[t.productId]));const s=Yd(e,t.sourceIds,i+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,c=function(e,t,n,i){if(!t?.length)return[];const o=Nd(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(n),c=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return o.length&&e.diagnostics.push(Ed("error","duplicate-relation","Basis relations must be unique.",i,o)),r.length&&e.diagnostics.push(Ed("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,i,r)),s.length&&e.diagnostics.push(Ed("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,i,s)),c.length&&e.diagnostics.push(Ed("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,i,c)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,i+".basisRelationIds");if(!s||!c||!n||e.diagnostics.some(e=>"error"===e.severity))return;const l=s.reduce((e,t)=>e+t.amount,0),d=function(e){const t={};for(const n of e)Wd(t,n.metrics);return t}(s);if(!Hd(e,l,d,t.loss,i+".loss"))return;const u=l-(t.loss?.amount??0);!function(e,t,n){e.state.loss.amount+=n?.amount??0;for(const[i,o]of Object.entries(n?.metrics??{}))t[i]=Number(t[i]??0)-o,e.state.loss.metrics[i]=Number(e.state.loss.metrics[i]??0)+o}(e,d,t.loss);const h="combine"===t.type&&!1!==t.complete,p=Fd(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let m;if("combine"===t.type){if(h&&Gd(e,n,u,i+".productId"),m=_d(n,t.sourceIds,u,d,e,h,p),h&&!Ld(e,m.outletId,i+".productId"))return;o.products[t.productId]=m}else m=r,m.sourceIds.push(...t.sourceIds),m.amount+=u,Wd(m.metrics,d),m.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return o.history.push(p),function(e,t){if(t.length){for(const n of t)n.status="resolved",n.resolution="combined",n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt;zd(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,c),zd(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(h&&zd(e,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===t.type){const n=o.products[t.productId];return n?void function(e,t,n,i,o,r){const s=e.productDefinitions.get(t.id),a=n??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!Ld(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(Ed("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(Gd(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics={...t.metrics,...s.metrics})),t.status="complete",t.outletId=a,t.reason=i,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const c=Fd(e,o,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(c),e.state.history.push(c),zd(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,n,t.outletId,t.reason,t,i):void e.diagnostics.push(Ed("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,i+".productId",[t.productId]))}if("split"===t.type){const n=Yd(e,[t.sourceId],i+".sourceId");t.products.length||e.diagnostics.push(Ed("error","empty-split","A split requires at least one product allocation.",i+".products"));const r=t.products.map(e=>e.productId),s=Nd(r);s.length&&e.diagnostics.push(Ed("error","duplicate-product","Split product ids must be unique.",i+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),c=r.filter((e,t)=>!a[t]),l=r.filter(e=>o.products[e]);c.length&&e.diagnostics.push(Ed("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,i+".products",c)),l.length&&e.diagnostics.push(Ed("error","duplicate-product",`Split products already exist: ${l.join(", ")}.`,i+".products",l));for(const[n,o]of t.products.entries())void 0===o.amount||Number.isFinite(o.amount)&&o.amount>=0||e.diagnostics.push(Ed("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${i}.products.${n}.amount`)),e.diagnostics.push(...Od(o.metrics,`${i}.products.${n}.metrics`));if(!n?.length||e.diagnostics.some(e=>"error"===e.severity))return;const d=n[0];if(!Hd(e,d.amount,d.metrics,t.loss,i+".loss"))return;const u=d.amount-(t.loss?.amount??0),h=t.products.map((e,t)=>e.amount??a[t]?.amount),p=h.filter(e=>void 0!==e).length;if(0!==p&&p!==h.length)return void e.diagnostics.push(Ed("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",i+".products"));const m=p?h:t.products.map(()=>u/t.products.length),f=m.reduce((e,t)=>e+t,0);if(Math.abs(f-u)>$d)return void e.diagnostics.push(Ed("error","split-amount-mismatch",`Split allocations total ${f}, but ${u} remains after loss.`,i+".products"));const y={...d.metrics};for(const[e,n]of Object.entries(t.loss?.metrics??{}))y[e]=Number(y[e]??0)-n;const g=Fd(e,t,{sourceIds:[d.id],productIds:r});if(t.products.forEach((n,r)=>{const s=a[r],c=u>$d?m[r]/u:1/t.products.length,l=Object.fromEntries(Object.entries(y).map(([e,t])=>[e,t*c])),h=n.metrics??s.metrics??l,p=_d({...s,amount:m[r],metrics:h},[d.id],m[r],{...h},e,!0,g);Ld(e,p.outletId,`${i}.products.${r}.productId`)&&(o.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;d.productIds=r,d.status="consumed",d.outletId=void 0,d.history.push(g),o.loss.amount+=t.loss?.amount??0;for(const[e,n]of Object.entries(t.loss?.metrics??{}))o.loss.metrics[e]=Number(o.loss.metrics[e]??0)+n;o.history.push(g),zd(e,{type:"split-source",sourceIds:[d.id],productIds:r});for(const t of r)zd(e,{type:"complete-product",sourceIds:[d.id],productIds:[t],outletIds:o.products[t].outletId?[o.products[t].outletId]:void 0});return}if("eject"===t.type){Ld(e,t.outletId,i+".outletId");const n=qd(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Ed("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Fd(e,t,{sourceIds:n.ids,outletIds:[t.outletId]});for(const e of n.ids){const n=o.components[e];n.status=t.state??"ejected",n.outletId=t.outletId,n.reason=t.reason,n.history.push(s)}return o.history.push(s),void(n.ids.length&&zd(e,{type:"retarget-component",sourceIds:n.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...Od(t.metricsDelta,i+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let n,r;if("run"===t.target)Wd(o.metrics,t.metricsDelta);else if("components"in t.target){const r=qd(o,t.target.components,i+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;n=r.ids;for(const e of r.ids)Wd(o.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const n=Nd(r),s=r.filter(e=>!o.products[e]);if(n.length&&e.diagnostics.push(Ed("error","duplicate-product","Metric target product ids must be unique.",i+".target.productIds",n)),s.length&&e.diagnostics.push(Ed("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,i+".target.productIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const e of r)Wd(o.products[e].metrics,t.metricsDelta)}return void o.history.push(Fd(e,t,{sourceIds:n,productIds:r}))}t.outcome.trim()?(o.outcome=t.outcome,o.summary=t.summary,o.history.push(Fd(e,t)),e.observations.push({type:"crucible-outcome",eventId:e.event.id,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,outcome:t.outcome})):e.diagnostics.push(Ed("error","invalid-outcome","Outcome must be a non-empty string.",i+".outcome"))}function Vd(e,t,n){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[Ed("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const i=Td(e),o={state:i,event:t,context:n,productDefinitions:new Map(n.products.map(e=>[e.id,e])),outletIds:new Set(n.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[n,i]of t.effects.entries())if(Xd(o,i,n),o.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:o.diagnostics};return i.elapsed=Math.max(i.elapsed,n.appliedAt),i.phaseId=n.phaseId,i.eventsApplied.push(t.id),o.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:n.phaseId,authoredAt:n.authoredAt,appliedAt:n.appliedAt}),{applied:!0,state:i,materializations:o.materializations,observations:o.observations,diagnostics:o.diagnostics}}function Ud(e,t={}){const n=t.groupBy??"outlet",i=new Map,o=e=>{const t=function(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}({...e,status:e.status??"active"},n),o=i.get(t);if(o)return o.count+=1,o.amount+=e.amount,void Wd(o.metrics,e.metrics);i.set(t,{key:t,label:"product"===n&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:{...e.metrics},status:"status"===n?e.status:void 0,outletId:"outlet"===n?e.outletId:void 0,category:"category"===n?e.category:void 0,productId:"product"===n&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||o({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(const t of Object.values(e.products))o({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});const r=new Map((t.order??[]).map((e,t)=>[e,t]));return[...i.values()].sort((e,t)=>(r.get(e.key)??Number.MAX_SAFE_INTEGER)-(r.get(t.key)??Number.MAX_SAFE_INTEGER)||Pd(e.key,t.key))}var Kd=Ud;function Qd(e,t={}){const n=t.field??"amount",i=e=>"amount"===n?e.amount:Number(e.metrics[n]??0),o="amount"===n?e.input.amount:Number(e.input.metrics[n]??0),r=Object.values(e.products).reduce((e,t)=>e+i(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+i(t),0),a="amount"===n?e.loss.amount:Number(e.loss.metrics[n]??0),c=r+s+a,l=c-o;return{field:n,input:o,products:r,unassigned:s,loss:a,output:c,delta:l,conserved:Math.max(0,t.tolerance??1e-6)>=Math.abs(l)}}function Zd(e,t={}){return{history:Bd(e.history),projection:Ud(e,t.projection),conservation:Qd(e,t.conservation)}}var Jd=900,eu=520,tu=[Jd,eu],nu=[{id:"product",label:"Products",side:"bottom",order:0},{id:"retained",label:"Retained",side:"bottom",order:1},{id:"residue",label:"Residue",side:"left",order:2},{id:"failed",label:"Failed",side:"right",order:3},{id:"recovered",label:"Recovered",side:"right",order:4}],iu=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),ou=1e-9;function ru(e,t){return t>e?-1:e>t?1:0}function su(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function au(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(ru)}function cu(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function lu(e,t,n,i,o,r){if(!n)return i;try{return("function"==typeof n?n(e,t):e[n])??i}catch(e){return o.push(su("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),i}}function du(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(su("error","invalid-metrics","Metrics must be a numeric object.",n)),{};const i={};for(const[o,r]of Object.entries(e)){const e=cu(r);null!=e?i[o]=e:t.push(su("error","invalid-metric",`Metric "${o}" must be finite.`,`${n}.${o}`))}return i}function uu(e){const t=[],n={},i=[];let o=0;const r={};e.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",l=((lu(s,a,e.idAccessor,c,t,`data.${a}.id`)??c)+"").trim();if(!l)return void t.push(su("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));i.push(l);const d=cu(lu(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),u=null==d||0>d?0:d;(null==d||0>d)&&t.push(su("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[l]));const h=du(lu(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=lu(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),m=iu.has(p)?p:"active";iu.has(p)||t.push(su("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[l]));const f=lu(s,a,e.labelAccessor,(s.label??s.name??l)+"",t,`data.${a}.label`)+"",y=lu(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";n[l]||(n[l]={id:l,label:f,category:y,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},o+=u,function(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}(r,h))});const s=au(i);s.length&&t.push(su("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=du(e.metrics??{},t,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:e.phases[0]?.id??"",phaseIndex:e.phases.length?0:-1,playing:!1,complete:0===e.phases.length,outcome:"in_process",eventsApplied:[],components:n,products:{},relations:{},input:{amount:o,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:t}}function hu(e){return e.map((e,t)=>({outlet:e,index:t})).sort((e,t)=>(e.outlet.order??e.index)-(t.outlet.order??t.index)||e.index-t.index).map(({outlet:e})=>({...e}))}function pu(e=tu,t=nu){const n=Math.max(1,cu(e[0])??Jd),i=Math.max(1,cu(e[1])??eu),o=360>n||260>i,r=o?Math.max(4,.035*Math.min(n,i)):20,s=o?Math.max(10,.075*i):34,a={x:r,y:r,width:Math.max(1,n-2*r),height:s},c=o?Math.max(16,.14*i):Math.min(78,.16*i),l={x:r,y:i-r-c,width:Math.max(1,n-2*r),height:c},d=o?Math.max(12,.08*n):Math.min(150,.17*n),u=a.y+a.height+(o?12:38),h=l.y-(o?10:34),p={x:d,y:u,width:Math.max(24,n-2*d),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,o?84:180)),f={x:p.x+(p.width-m)/2,y:p.y-(o?10:24),width:m,height:o?12:28},y=hu(t),g={left:y.filter(e=>"left"===(e.side??"bottom")),right:y.filter(e=>"right"===e.side),bottom:y.filter(e=>"bottom"===(e.side??"bottom"))},b=[],x=(e,t)=>{const i=Math.max(8,d-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:n-r-i,y:p.y+a*s,width:i,height:Math.max(8,s-(o?2:8))})})};x("left",g.left),x("right",g.right);const v=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*v,y:p.y+p.height+(o?2:7),width:Math.max(8,v-(o?2:8)),height:Math.max(8,l.y-p.y-p.height-(o?4:12))})}),b.sort((e,t)=>y.findIndex(t=>t.id===e.id)-y.findIndex(e=>e.id===t.id)),{width:n,height:i,phaseRail:a,chamber:p,mouth:f,projection:l,outlets:b}}function mu(e){const{id:t,orientation:n,fixed:i,start:o,end:r,openings:s,thickness:a,friction:c,restitution:l}=e,d=function(e,t,n){const i=n.map(([n,i])=>[Math.max(e,Math.min(n,i)),Math.min(t,Math.max(n,i))]).filter(([e,t])=>t>e+ou).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];let r=e;for(const[e,t]of i)e>r+ou&&o.push([r,e]),r=Math.max(r,t);return t>r+ou&&o.push([r,t]),o}(o,r,s);return d.map(([e,o],r)=>({id:1===d.length?t:`${t}:${r}`,friction:c,restitution:l,shape:"horizontal"===n?{type:"segment",x1:e,y1:i,x2:o,y2:i,thickness:a}:{type:"segment",x1:i,y1:e,x2:i,y2:o,thickness:a}}))}function fu(e){const{chamber:t,mouth:n}=e,i=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),o=Math.max(t.x,n.x),r=Math.min(t.x+t.width,n.x+n.width),s={left:e.outlets.filter(e=>"left"===e.side),right:e.outlets.filter(e=>"right"===e.side),bottom:e.outlets.filter(e=>"bottom"===e.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:t.x,y1:t.y,x2:o,y2:t.y,thickness:i}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:i}}];a.push(...mu({id:"crucible:wall:left",orientation:"vertical",fixed:t.x,start:t.y,end:t.y+t.height,openings:s.left.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...mu({id:"crucible:wall:right",orientation:"vertical",fixed:t.x+t.width,start:t.y,end:t.y+t.height,openings:s.right.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...mu({id:"crucible:wall:bottom",orientation:"horizontal",fixed:t.y+t.height,start:t.x,end:t.x+t.width,openings:s.bottom.map(e=>[e.x,e.x+e.width]),thickness:i,friction:.5,restitution:.08}));for(const t of e.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(t.id),sensor:!0,shape:{type:"aabb",x:t.x+t.width/2,y:t.y+t.height/2,width:t.width,height:t.height}});return a}function yu(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function gu(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?yu(e):1}function bu(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:gu(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function xu(e){return"crucible:component:"+encodeURIComponent(e)}function vu(e){return"crucible:product:"+encodeURIComponent(e)}function wu(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function ku(e,t,n,i){if(void 0!==n&&Number.isFinite(n)&&n>0)return n;const o=Math.min(...t,e),r=Math.max(...t,e);return r-o>ou?i[0]+(i[1]-i[0])*Math.sqrt(Math.max(0,e-o)/(r-o)):(i[0]+i[1])/2}function Mu(e,t){const n=Math.max(.25,Math.min(1,t.width/900,t.height/520)),i=e?.[0]??7*n,o=e?.[1]??18*n,r=Math.max(1,Math.min(i,o));return[r,Math.max(r,Math.max(i,o))]}function Iu(e,t,n={}){const i=Object.values(e.components).sort((e,t)=>ru(e.id,t.id)),o=i.map(e=>e.amount),r=Mu(n.radiusRange,t),s=function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(gu(n.seed)),a=t.mouth.x+t.mouth.width/2,c=t.chamber.y+Math.max(18,.18*t.chamber.height),l=Math.max(4,.28*t.chamber.width),d=Math.max(4,.12*t.chamber.height);return i.map((e,t)=>{const u=t/Math.max(1,i.length)*Math.PI*2+.18*(s()-.5),h=ku(e.amount,o,n.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:xu(e.id),x:a+Math.cos(u)*l*(.45+.45*s()),y:c+Math.sin(u)*d*(.45+.45*s()),vx:24*(s()-.5),vy:18*(s()-.5),mass:Math.max(.25,h*h*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:h},datum:p}})}function Su(e,t){if(!e)return[];const n=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),i=Math.max(1,Math.ceil(e/n));return Array.from({length:e},(e,o)=>({x:t.x+t.width/n*(o%n+.5),y:t.y+(Math.floor(o/n)+.5)*(t.height/i)}))}function ju(e){return e.outletId?e.outletId:"failed"===e.status?"failed":"recovered"===e.status?"recovered":"retained"===e.status?"retained":"ejected"===e.status?"residue":void 0}function Au(e,t){return e.outlets.find(e=>e.id===t)||{x:e.chamber.x+.18*e.chamber.width,y:e.chamber.y+.2*e.chamber.height,width:.64*e.chamber.width,height:.6*e.chamber.height}}function Cu(e,t,n={}){const i=Object.values(e.products).sort((e,t)=>ru(e.id,t.id)),o=Object.values(e.components).sort((e,t)=>ru(e.id,t.id)),r=[...o.map(e=>e.amount),...i.map(e=>e.amount)],s=Mu(n.radiusRange,t),a=function(e,t){const n=new Map;for(const t of e){const e=t.outletId??"__chamber__",i=n.get(e)??[];i.push(t),n.set(e,i)}const i=new Map;for(const[e,o]of n){o.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||ru(e.id,t.id));const n=Su(o.length,Au(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>i.set(e.id,n[t]))}return i}(i,t),c=i.map(e=>{const i=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},o=1.28*ku(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:vu(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.018),bodyCollisions:!1,shape:{type:"circle",radius:o},datum:c}}),l=new Map;for(const e of o.filter(e=>!e.productIds.length)){const t=ju(e)??"__chamber__",n=l.get(t)??[];n.push(e),l.set(t,n)}const d=new Map;for(const[e,n]of l){const i=Su(n.length,Au(t,"__chamber__"===e?void 0:e));n.forEach((e,t)=>d.set(e.id,i[t]))}return[...o.map(e=>{let i=d.get(e.id);if(e.productIds.length){const n=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(n.length){i={x:n.reduce((e,t)=>e+t.x,0)/n.length,y:n.reduce((e,t)=>e+t.y,0)/n.length};const o=yu(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));i={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}i??(i={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const o=ku(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:xu(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.015),shape:{type:"circle",radius:o},datum:c}}),...c]}var Ru=Cu;function $u(e){return Array.isArray(e)?e.map($u):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>ru(e,t)).map(([e,t])=>[e,$u(t)])):e}function Pu(e){return JSON.stringify($u(e))}function Du(e,t){const n=cu(t)??0,i=Math.max(0,Math.min(e.duration,n));if(!e.phases.length)return{elapsed:i,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const o=i>=e.duration-ou,r=o?e.phases[e.phases.length-1]:e.phases.find(e=>i>=e.start&&e.end>i)??e.phases[0];return{elapsed:i,phaseId:r.id,phaseIndex:r.index,phaseElapsed:o?r.duration:Math.max(0,i-r.start),complete:o}}function Bu(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,cu(t)??0));const n=e.phases.find(e=>e.id===t.phaseId);if(!n)return e.duration;const i=Math.max(0,Math.min(1,cu(t.progress??0)??0));return n.start+n.duration*i}function Tu(e,t=e.duration){const n=Du(e,t);let i=Td(e.initialState);const o=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>n.elapsed+ou)break;const a=Vd(i,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});o.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(i=a.state)}return i.elapsed=n.elapsed,i.phaseId=n.phaseId,i.phaseIndex=n.phaseIndex,i.phaseElapsed=n.phaseElapsed,i.complete=n.complete,n.complete&&"in_process"===i.outcome&&(i.outcome="complete"),i.playing=!1,{state:i,diagnostics:o,materializations:r,observations:s}}function Eu(e){const t=function(e){const t=[];e.length||t.push(su("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const n=au(e.map(e=>e.id));n.length&&t.push(su("error","duplicate-phase-id",`Phase ids must be unique: ${n.join(", ")}.`,"phases",n));let i=0;return{phases:e.map((e,n)=>{const o=cu(e.duration),r=null!=o&&o>0?o:0;e.id.trim()||t.push(su("error","invalid-phase-id","Phase ids may not be empty.",`phases.${n}.id`)),null!=o&&o>0||t.push(su("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${n}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(su("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${n}.intensity`,[e.id]));const s={...e,duration:r,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:n,start:i,end:i+r};return i=s.end,s}),diagnostics:t}}(e.phases),n=t.phases.at(-1)?.end??0,i=hu(e.outlets??nu),o=(e.products??[]).map(e=>({...e,metrics:e.metrics?{...e.metrics}:void 0})),r=function(e,t,n){const i=[],o=au(e.map(e=>e.id));o.length&&i.push(su("error","duplicate-event-id",`Event ids must be unique: ${o.join(", ")}.`,"events",o));const r=[];return e.forEach((e,o)=>{let s,a,c;if(e.id.trim()||i.push(su("error","invalid-event-id","Event ids may not be empty.",`events.${o}.id`)),"time"in e.at&&void 0!==e.at.time){const r=cu(e.at.time);if(null==r||0>r||r>n+ou)return void i.push(su("error","event-time-out-of-range",`Event time must fall between 0 and ${n}.`,`events.${o}.at.time`,[e.id]));s=Math.max(0,Math.min(n,r));const l=function(e,t,n){const i=e.find(e=>ou>=Math.abs(e.start-n));if(i)return{phase:i,boundaryRank:1};const o=e.find(e=>n>=e.start&&e.end>n);return o?{phase:o,boundaryRank:0}:ou>=Math.abs(n-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,n,s);a=l.phase,c=l.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void i.push(su("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${o}.at.phaseId`,[e.id,e.at.phaseId]));const n=e.at.progress??0;if(!Number.isFinite(n)||0>n||n>1)return void i.push(su("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${o}.at.progress`,[e.id]));s=a.start+a.duration*n,c=0===n?1:0}a?r.push({...e,index:o,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):i.push(su("error","event-without-phase","Event could not be assigned to a phase.",`events.${o}.at`,[e.id]))}),r.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:r,diagnostics:i}}(e.events??[],t.phases,n),s=uu(e),a=pu(e.size??tu,i),c=fu(a),l=function(e,t){const n=[],i=new Set(t.map(e=>e.id)),o=au(t.map(e=>e.id)),r=au(e.map(e=>e.id));return o.length&&n.push(su("error","duplicate-outlet-id",`Outlet ids must be unique: ${o.join(", ")}.`,"outlets",o)),r.length&&n.push(su("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||n.push(su("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||n.push(su("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||n.push(su("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||n.push(su("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0===e.outletId||i.has(e.outletId)||n.push(su("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),du(e.metrics??{},n,`products.${t}.metrics`)}),n}(o,i),d=Pu({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>ru(e.id,t.id)).map(e=>({id:e.id,label:e.label,category:e.category,amount:e.amount,metrics:e.metrics,status:e.status})),phases:t.phases.map(({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})),products:o,outlets:i,events:r.events.map(({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a}))}),u=Iu(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...l],p={phases:t.phases,events:r.events,products:o,outlets:i,duration:n,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:bu(e.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:d,diagnostics:h},m=Tu(p),f=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),y=f.length?[su("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return p.terminalState=m.state,p.terminalSpawns=Ru(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...y],p}function Nu(e,t){return e.playing=t&&!e.complete,e}function Ou(e,t,n=!1){const i=Tu(e,t);return{...i,state:Nu(i.state,n)}}function Wu(e,t,n,i=t.playing){const o=Ou(e,n,i),r=new Set(t.eventsApplied);return{...o,observations:o.observations.filter(e=>!r.has(e.eventId)),materializations:o.materializations.filter(e=>!r.has(e.eventId))}}function qu(e,t,n={}){return Cu(t,e.layout,n)}function Fu(e,t){return function(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)/4294967295}function zu(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function Lu(e,t,n={}){return new Map(qu(e,t,n).flatMap(e=>{const t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function Yu(e,t){const n=Object.values(e.terminalState.products).map(e=>e.id).sort(),i=Math.max(0,n.indexOf(t))/Math.max(1,n.length)*Math.PI*2-Math.PI/2,o=Math.min(58,.19*e.layout.chamber.width),r=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(i)*o,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(i)*r}}function Hu(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function _u(e){return Number.isFinite(e)?1e3>Math.abs(e)?Number.isInteger(e)?e+"":e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):e.toLocaleString():"0"}function Gu(e){const t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",n=e.reason?` ${e.reason}.`:"";return`${_u(e.amount)} amount; ${e.status}.${t}${n}`}function Xu(e){const t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${_u(e.amount)} amount.${t}`}function Vu(e,t,n){const i=t.datum;if(!i?.__crucible)return;const o="circle"===t.shape.type?t.shape.radius:8,r=Hu(e,n.fill,"product"===i.kind?"#b8792d":"#356b63"),s=Hu(e,n.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof n.opacity?n.opacity:.96,e.fillStyle=r,e.strokeStyle=s,e.lineWidth="number"==typeof n.strokeWidth?n.strokeWidth:1.25,"product"===i.kind){e.shadowColor=r,e.shadowBlur=10,e.beginPath();for(let t=0;6>t;t+=1){const n=-Math.PI/2+t/6*Math.PI*2,i=Math.cos(n)*o,r=Math.sin(n)*o;0===t?e.moveTo(i,r):e.lineTo(i,r)}e.closePath(),e.fill(),e.shadowBlur=0,e.stroke(),e.beginPath(),e.arc(0,0,Math.max(2,.36*o),0,2*Math.PI),e.strokeStyle=Hu(e,"var(--semiotic-background, #fffaf0)","#fffaf0"),e.globalAlpha*=.72,e.stroke()}else e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.beginPath(),e.arc(.25*-o,.28*-o,Math.max(1,.18*o),0,2*Math.PI),e.fillStyle="rgba(255,255,255,0.34)",e.fill();e.restore()}c(require("react")),require("react/jsx-runtime");var Uu=require("react/jsx-runtime"),Ku="var(--semiotic-text, #26323a)",Qu="var(--semiotic-text-secondary, #6c7377)",Zu="var(--semiotic-accent, #b8792d)",Ju="var(--semiotic-negative, #9f3d35)",eh="var(--semiotic-positive, #356b63)";function th(e){const{x:t,y:n,width:i,height:o}=e.chamber,r=Math.min(.14*i,48),s=n+o;return[`M ${t} ${n}`,`L ${t+r} ${s-.16*o}`,`Q ${t+i/2} ${s+.1*o} ${t+i-r} ${s-.16*o}`,`L ${t+i} ${n}`].join(" ")}function nh({layout:e,phases:t,state:n,compact:i=!1}){const o=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return(0,Uu.jsxs)("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[(0,Uu.jsxs)("defs",{children:[(0,Uu.jsxs)("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Uu.jsx)("stop",{offset:"0",stopColor:Zu,stopOpacity:"0.03"}),(0,Uu.jsx)("stop",{offset:"0.66",stopColor:Zu,stopOpacity:"0.1"}),(0,Uu.jsx)("stop",{offset:"1",stopColor:Ju,stopOpacity:"0.18"})]}),(0,Uu.jsx)("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:(0,Uu.jsx)("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:Ku,strokeOpacity:"0.08",strokeWidth:"1"})})]}),(0,Uu.jsx)("rect",{x:e.chamber.x,y:e.chamber.y,width:e.chamber.width,height:e.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:Ku,strokeOpacity:"0.52",strokeWidth:i?1:2.2}),(0,Uu.jsx)("path",{d:th(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),(0,Uu.jsx)("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:Ku,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:i?2:5}),i?null:(0,Uu.jsx)("g",{"data-testid":"crucible-phase-rail",children:t.map((i,r)=>{const s=t.slice(0,r).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/o*e.phaseRail.width,c=Math.max(0,i.duration)/o*e.phaseRail.width,l=i.id===n.phaseId,d=n.phaseIndex>r||n.complete;return(0,Uu.jsxs)("g",{children:[(0,Uu.jsx)("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,c-2),height:e.phaseRail.height,rx:2,fill:l?i.color??Zu:d?eh:Ku,fillOpacity:l?.68:d?.28:.09}),46>c?null:(0,Uu.jsx)("text",{x:a+c/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:l?Ku:Qu,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:l?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(i.label??i.id).toUpperCase()})]},i.id)})}),e.outlets.map(e=>(0,Uu.jsxs)("g",{children:[(0,Uu.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?Ju:eh),fillOpacity:"0.1",stroke:e.color??("left"===e.side?Ju:eh),strokeDasharray:"3 3",strokeOpacity:"0.62"}),i?null:(0,Uu.jsx)("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:Qu,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function ih(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}function oh({rows:e,layout:t,projection:n,amountLabel:i}){if(!e.length)return null;const o=n.measure??"count",r=e.map(e=>Math.max(0,ih(e,o))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),c=t.projection.height>48?21:4,l=Math.max(5,t.projection.height-c-5);return(0,Uu.jsx)("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:e.map((e,n)=>{const d=r[n],u=Math.max(d>0?2:0,d/s*l),h=t.projection.x+n*a+.18*a;return(0,Uu.jsxs)("g",{children:[(0,Uu.jsx)("rect",{x:h,y:t.projection.y+l-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===e.status||"ejected"===e.status?Ju:"complete"===e.status?Zu:eh,fillOpacity:"0.68"}),c>4&&a>=34?(0,Uu.jsxs)(Uu.Fragment,{children:[(0,Uu.jsx)("text",{x:h+.32*a,y:t.projection.y+l+10,fill:Qu,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),(0,Uu.jsxs)("text",{x:h+.32*a,y:t.projection.y+l+19,fill:Ku,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[_u(d),"amount"===o&&i?" "+i:""]})]}):null]},e.key)})})}function rh({controls:e,duration:t,elapsed:n,phaseLabel:i,playing:o,complete:r,playbackRate:s,disabled:a,onPlayPause:c,onReset:l,onStepPhase:d,onPlaybackRateChange:u}){const h=t>0?Math.min(1,Math.max(0,n/t)):1;return(0,Uu.jsxs)("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:Ku,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[e.playPause?(0,Uu.jsx)("button",{type:"button",disabled:a,onClick:c,"aria-pressed":o,children:o?"Pause":r?"Replay":"Play"}):null,e.stepPhase?(0,Uu.jsx)("button",{type:"button",disabled:a,onClick:d,children:"Next phase"}):null,e.reset?(0,Uu.jsx)("button",{type:"button",disabled:a,onClick:l,children:"Reset"}):null,e.timeline?(0,Uu.jsxs)("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[(0,Uu.jsx)("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:i}),(0,Uu.jsx)("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:(0,Uu.jsx)("span",{style:{background:Zu,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),(0,Uu.jsxs)("span",{style:{color:Qu,fontVariantNumeric:"tabular-nums"},children:[n.toFixed(1),"s"]})]}):null,e.speed?(0,Uu.jsxs)("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",(0,Uu.jsxs)("select",{disabled:a,value:s,onChange:e=>u(Number(e.currentTarget.value)),children:[(0,Uu.jsx)("option",{value:.25,children:"¼×"}),(0,Uu.jsx)("option",{value:.5,children:"½×"}),(0,Uu.jsx)("option",{value:1,children:"1×"}),(0,Uu.jsx)("option",{value:2,children:"2×"})]})]}):null]})}function sh(e,t,n,i){const o="function"==typeof i?i(t,n):i,r=t.datum;return{fill:e,stroke:"product"===r?.kind?"var(--semiotic-background, #fffaf0)":Ku,strokeWidth:"product"===r?.kind?1.8:1.1,opacity:.96,...o}}function ah(e,t,n){return{id:e.id??t,at:{...e.at},effects:n,...void 0===e.label?null:{label:e.label},...void 0===e.description?null:{description:e.description},...void 0===e.summary?null:{summary:e.summary}}}function ch(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function lh(e){const{productId:t,form:n,contributions:i=[],complete:o}=e,r=e.idPrefix??t,s=ch(n.loss),a=[ah(n,r+"-form",[{type:"combine",sourceIds:[...n.sourceIds],productId:t,...n.basisRelationIds?{basisRelationIds:[...n.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return i.forEach((e,n)=>{const i=ch(e.loss);a.push(ah(e,`${r}-contribute-${n+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...i?{loss:i}:null}]))}),a.push(ah(o,r+"-complete",[{type:"complete-product",productId:t,...void 0===o.outletId?null:{outletId:o.outletId},...void 0===o.reason?null:{reason:o.reason}}])),a}var dh=require("react/jsx-runtime"),uh=require("react"),hh=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function ph(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function mh(e){return"number"==typeof e&&Number.isFinite(e)?e:ph((e??"crucible")+"")}function fh(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.max(.05,Math.min(8,t)):1}function yh(e,t,n){return"category"===t?e.category:"status"===t?e.status:"outlet"===t?e.outletId??"in chamber":"product"===t?e.productIds[0]??"unalloyed":function(e,t,n){return(("function"==typeof e?e(t,n):t[e])??"unassigned")+""}(t,e.datum,n)}function gh(e){return hh[ph(e)%hh.length]}function bh(e,t){const n=Object.keys(e.components).length,i=Object.keys(e.products).length,o=Object.values(e.products).reduce((e,t)=>e+t.amount,0),r=t?" "+t:" amount",s=e.outcome?` Outcome: ${e.outcome}.`:"";return`${n} source component${1===n?"":"s"}; ${i} product${1===i?"":"s"}; ${o.toLocaleString()}${r} in products.${s}`}var xh=(0,Rd.forwardRef)(function(e,t){const{amountAccessor:n,amountLabel:i,bodyRadius:o,categoryAccessor:r,colorBy:s="category",conservation:a,controls:c,data:l,emptyContent:d,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:f,labelAccessor:y,loading:g,loadingContent:b,metrics:x,metricsAccessor:v,onClick:w,onConservation:k,onCrucibleObservation:M,onDiagnostic:I,onStateChange:S,outlets:j,paused:A,phases:R,playback:P="replay",playbackRate:D=1,products:B,projection:T,radiusRange:E,rerunMS:N,responsiveHeight:O,responsiveWidth:W,seed:q,showBonds:F=!0,snapshotAt:z}=e,L=(0,Rd.useRef)(null),Y=(0,Rd.useRef)(A);Y.current=A;const H=C(),_=V(),G=Za(e,tu),{chartMode:X,chartSize:U,showChrome:K,showProjection:Q,className:Z,title:J,description:ee,summary:te,accessibleTable:ne,enableHover:ie,margin:oe}=G,[re,se]=$(U,W,!1),ae=W?Math.max(1,se[0]):U[0],ce=U[1],le=(0,Rd.useMemo)(()=>[ae,ce],[ce,ae]),de=(0,Rd.useMemo)(()=>mc(l??[]),[l]),ue=(0,Rd.useMemo)(()=>Eu({data:de,phases:R,products:B,outlets:j,events:u,idAccessor:p,labelAccessor:y,categoryAccessor:r,amountAccessor:n,metricsAccessor:v,initialStateAccessor:m,metrics:x,size:le,seed:q,bodyRadius:o,radiusRange:E}),[n,o,r,u,p,m,y,x,v,j,R,B,E,le,de,q]),he=Object.values(ue.initialState.components).map((e,t)=>yh(e,s,t)).join("\0"),pe=`${ue.semanticKey}:${le[0]}x${le[1]}:${(o??"auto")+""}:${E?.join(",")??"auto"}:${he}`,me=(0,Rd.useRef)(ue),fe=(0,Rd.useRef)(pe);fe.current!==pe&&(fe.current=pe,me.current=ue);const ye=me.current,ge="snapshot"===P||H||_,be=ge?function(e,t){return Bu(e,t)}(ye,z):0,xe=!ge,ve=(0,Rd.useMemo)(()=>Ou(ye,be,xe&&!A),[fe.current,be,xe]),[we,ke]=(0,Rd.useState)(ve),Me=(0,Rd.useRef)(we),[Ie,Se]=(0,Rd.useState)(xe),je=(0,Rd.useRef)(Ie),[Ae,Ce]=(0,Rd.useState)(0),[Re,$e]=(0,Rd.useState)(()=>fh(D)),Pe=(0,Rd.useRef)(Lu(ye,ve.state,{seed:q,bodyRadius:o,radiusRange:E})),De=(0,Rd.useRef)(""),Be=(0,Rd.useRef)(S),Te=(0,Rd.useRef)(M),Ee=(0,Rd.useRef)(I),Ne=(0,Rd.useRef)(k);Be.current=S,Te.current=M,Ee.current=I,Ne.current=k;const Oe=(0,Rd.useRef)({seed:q,bodyRadius:o,radiusRange:E});Oe.current={seed:q,bodyRadius:o,radiusRange:E};const We=(0,Rd.useCallback)((e,t=!1)=>{if(Me.current=e,Pe.current=Lu(me.current,e.state,Oe.current),ke(e),t)for(const t of e.observations)Te.current?.(t)},[]);(0,Rd.useEffect)(()=>{$e(fh(D))},[D]),(0,Rd.useEffect)(()=>{const e=!ge,t=Ou(ye,ge?be:0,e&&!Y.current);je.current=e,Se(e),We(t)},[We,ye,be,ge,pe]),(0,Rd.useEffect)(()=>{const e=Me.current,t=je.current&&!A&&!e.state.complete;if(e.state.playing===t)return;const n={...e,state:Td(e.state)};n.state.playing=t,We(n)},[We,A]),(0,Rd.useEffect)(()=>{for(const e of ye.diagnostics)Ee.current?.(e)},[pe,ye.diagnostics]),(0,Rd.useEffect)(()=>{if(Be.current?.(we.state),a){const e=!0===a?{}:a;Ne.current?.(Qd(we.state,e))}},[a,we.state]);const qe=(0,Rd.useCallback)(()=>{De.current="";const e=!ge,t=Ou(me.current,0,e&&!A);je.current=e,Se(e),We(t)},[We,A,ge]),Fe=(0,Rd.useMemo)(()=>({...ye.config,...h.config,fixedDt:h.config?.fixedDt??ye.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??ye.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??ye.config.settleStepLimit,timeScale:Re,colliders:[...ye.config.colliders??[],...h.config?.colliders??[]],kernel:{...ye.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??ye.config.kernel?.gravity??{x:0,y:0}},observation:{...ye.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,Re,ye.config]),ze=ge||!!A||!Ie&&!we.state.complete,Le=Qa(Fe,N,ze,qe),Ye=(0,Rd.useCallback)(()=>{if("number"!=typeof N||!Number.isFinite(N)||0>N)return;const e=`${pe}:${Ae}:${Le.rerunKey}`;De.current!==e&&(De.current=e,Le.config?.observation?.onSimulationStateChange?.("settled","running"))},[Le.config,Le.rerunKey,N,Ae,pe]),He=(0,Rd.useCallback)(()=>{const e=Ou(me.current,0,!1);je.current=!1,Se(!1),We(e),Ce(e=>e+1)},[We]),_e=(0,Rd.useCallback)(()=>{const e=me.current,t=Wu(e,Me.current.state,e.duration,!1);je.current=!1,Se(!1),We(t,!0);const n=qu(e,t.state,Oe.current),i=L.current;i&&(i.clear(),i.pushMany(n),i.step(0),i.settle()),Ye()},[We,Ye]),Ge=(0,Rd.useCallback)(()=>{je.current=!1,Se(!1);const e={...Me.current,state:Td(Me.current.state)};e.state.playing=!1,We(e)},[We]),Xe=(0,Rd.useCallback)(()=>{if(De.current="",ge){const e=Ou(me.current,be,!1);return je.current=!1,Se(!1),We(e),void Ce(e=>e+1)}const e=Ou(me.current,0,!A);je.current=!0,Se(!0),We(e),Ce(e=>e+1)},[We,A,be,ge]),Ve=(0,Rd.useCallback)(()=>{if(ge)return void Xe();if(Me.current.state.complete)return void Xe();je.current=!0,Se(!0);const e={...Me.current,state:Td(Me.current.state)};e.state.playing=!A,We(e)},[We,A,Xe,ge]),Ue=(0,Rd.useCallback)(()=>{const e=me.current,t=function(e,t){const n=e.phases.find(e=>e.end>t+1e-7);return n?.end??e.duration}(e,Me.current.state.elapsed),n=Wu(e,Me.current.state,t,!1);je.current=!1,Se(!1),We(n,!0);const i=L.current;i&&(i.clear(),i.pushMany(qu(e,n.state,Oe.current)),i.step(0))},[We]);(0,Rd.useImperativeHandle)(t,()=>({play:Ve,pause:Ge,reset:He,replay:Xe,stepPhase:Ue,settle:_e,getCrucibleState:()=>Td(Me.current.state)}),[Ge,Ve,Xe,He,_e,Ue]);const Ke=(0,Rd.useCallback)((e,t)=>{if(h.onTick?.(e,t),ge||A||!je.current)return;const n=Me.current.state,i=Math.min(me.current.duration,e.elapsedSeconds);if(n.elapsed+.045>=i&&me.current.duration>i)return;const o=Wu(me.current,n,i,me.current.duration>i),r=o.state.eventsApplied.length!==n.eventsApplied.length;if(r&&function(e,t){const n=new Set(e.readBodies().map(e=>e.id)),i=t.filter(e=>!n.has(e.id));i.length&&e.pushMany([...i]),i.map(e=>e.id)}(t,qu(me.current,o.state,Oe.current)),o.state.complete){je.current=!1,Se(!1);const e=qu(me.current,o.state,Oe.current);t.clear(),t.pushMany(e),t.step(0),t.settle()}We(o,r),o.state.complete&&Ye()},[We,h,A,Ye,ge]),Qe=(0,Rd.useCallback)(({body:e})=>function(e){const t=function(e){const{body:t,plan:n,state:i,targets:o}=e,r=t.datum;if(!r?.__crucible)return null;let s=o.get(`${r.kind}:${r.semanticId}`);if(!s)return null;const a=zu(n,i),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),l=a?.motion??"hold",d=i.elapsed;if("product"===r.kind){const e=i.products[r.semanticId];"forming"===e?.status&&(s=Yu(n,e.id))}else{const e=i.components[r.semanticId],t=e?.productIds.map(e=>i.products[e]).find(e=>"forming"===e?.status);if(t){const i=Yu(n,t.id),o=Fu(e.id,17)*Math.PI*2,r=Math.max(5,Math.min(18,.026*n.layout.width));s={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}const u=r.semanticId,h=Fu(u,23)*Math.PI*2;if(!i.complete&&!(n.layout.chamber.x>s.x||s.x>n.layout.chamber.x+n.layout.chamber.width||n.layout.chamber.y>s.y||s.y>n.layout.chamber.y+n.layout.chamber.height))if("mix"===l){const e=Math.min(34,.1*n.layout.chamber.width)*c,t=Math.min(24,.09*n.layout.chamber.height)*c;s={x:s.x+Math.cos(d*(1.4+Fu(u,29))+h)*e,y:s.y+Math.sin(d*(1.8+Fu(u,31))+h)*t}}else if("press"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.56*n.layout.chamber.height;s={x:e+(s.x-e)*Math.max(.3,1-.32*c),y:t+(s.y-t)*Math.max(.35,1-.26*c)}}else if("separate"===l){const e=.5>Fu(u,41)?-1:1;s={x:s.x+e*Math.min(28,.075*n.layout.chamber.width)*c,y:s.y}}else if("bind"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.5*n.layout.chamber.height;s={x:e+.72*(s.x-e),y:t+.72*(s.y-t)}}else"charge"===l?s={x:s.x,y:s.y+4*Math.sin(2*d+h)*c}:"quench"===l&&(s={x:s.x+2*Math.sin(h)*c,y:s.y});return s}(e);if(!t)return null;const{body:n,state:i}=e,o=t.x-n.x,r=t.y-n.y,s=Math.hypot(o,r),a=Math.hypot(n.vx,n.vy);if(i.complete&&.7>s&&.45>a)return null;const c=!i.complete&&"pour"===zu(e.plan,i)?.motion,l=i.complete?.68:c?.72:.5,d=i.complete?.22:c?.18:.14,u=i.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,o*l-n.vx*d)),y:Math.max(-u,Math.min(u,r*l-n.vy*d))}}({body:e,plan:me.current,state:Me.current.state,targets:Pe.current}),[]),Ze=(0,Rd.useMemo)(()=>new Map(Object.keys(ye.initialState.components).map((e,t)=>[e,t])),[ye.initialState.components]),Je=(0,Rd.useCallback)(t=>{if(e.color)return e.color;const n=t.datum;if(!n?.__crucible)return"var(--semiotic-accent, #b8792d)";if("product"===n.kind){const e=Me.current.state.products[n.semanticId];return e?.color??gh(e?.id??n.semanticId)}const i=Me.current.state.components[n.semanticId];return i?gh(yh(i,s,Ze.get(i.id)??0)):"var(--semiotic-accent, #356b63)"},[s,Ze,e.color]),et=(0,Rd.useCallback)((t,n)=>({...sh(Je(t),t,n,h.bodyStyle),...void 0!==e.stroke?{stroke:e.stroke}:null,...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:null,...void 0!==e.opacity?{opacity:e.opacity}:null}),[Je,h.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),tt=(0,Rd.useCallback)((e,t)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(e,t):void 0)??function(e,t){const n=e.datum;if(!n?.__crucible)return!1;if("component"===n.kind){const e=t.components[n.semanticId];return!!e&&{id:"crucible-component-"+e.id,label:e.label,description:Gu(e),group:"source component · "+e.status,datum:e}}const i=t.products[n.semanticId];return!!i&&{id:"crucible-product-"+i.id,label:i.label,description:Xu(i),group:"derived product · "+i.status,datum:i}}(e,Me.current.state),[h]),nt=(0,Rd.useCallback)(e=>{if(!w||!e||"object"!=typeof e)return;if(!e.__crucible)return;const t=Me.current.state,n="component"===e.kind?t.components[e.semanticId]:t.products[e.semanticId];n&&w(n)},[w]),it=(0,Rd.useCallback)((e,t)=>{h.beforePaint?.(e,t),F&&function(e,t,n){const i=new Map;for(const e of t){const t=e.datum;t?.__crucible&&i.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(const t of Object.values(n.relations)){if("active"!==t.status)continue;const n=t.sourceIds.map(e=>i.get("component:"+e)).filter(e=>!!e);2>n.length||(e.strokeStyle="rejected"===t.category?"#9f3d35":"#b8792d",e.globalAlpha=.4,e.lineWidth=Math.max(.8,1.3*Number(t.strength??1)),e.setLineDash([3,4]),e.beginPath(),n.forEach((t,n)=>{0===n?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(const t of Object.values(n.products)){const n=i.get("product:"+t.id);if(n)for(const o of t.sourceIds){const r=i.get("component:"+o);r&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(n.x,n.y),e.stroke())}}e.restore()}(e,t,Me.current.state)},[h,F]),ot=(0,Rd.useMemo)(()=>T??{groupBy:"outlet",measure:"count"},[T]),rt=(0,Rd.useMemo)(()=>Ud(we.state,ot),[ot,we.state]),st=(0,Rd.useMemo)(()=>Q?function(e,t,n,i){if(!e.length)return[];const o=n.measure??"count",r=t.projection.width/Math.max(1,e.length);return e.map((e,n)=>{const s=ih(e,o),a="amount"===o&&i?`${_u(s)} ${i}`:`${_u(s)} ${o}`;return{id:"crucible-projection-"+e.key,label:`${e.label}: ${a}`,description:`${e.count} source component${1===e.count?"":"s"}; ${_u(e.amount)} amount.`,datum:e,group:"settled composition",x:t.projection.x+(n+.5)*r,y:t.projection.y+t.projection.height/2,shape:"rect",width:Math.max(12,.62*r),height:Math.max(8,t.projection.height-8)}})}(rt,ye.layout,ot,i):[],[i,ye.layout,ot,rt,Q]),at=nc(e.tooltip,h),ct=ic({...e,onClick:void 0},h,st,{chartMode:X,className:Z,title:J??"Crucible",description:ee??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:te??bh(we.state,i),accessibleTable:ne,enableHover:ie,margin:oe}),lt=tc(K?(0,dh.jsx)(nh,{layout:ye.layout,phases:ye.phases,state:we.state,compact:G.compactMode||360>le[0]||260>le[1]}):void 0,h.backgroundGraphics),dt=tc(Q?(0,dh.jsx)(oh,{rows:rt,layout:ye.layout,projection:ot,amountLabel:i}):void 0,h.foregroundGraphics),ut=(0,Rd.useCallback)(e=>function(e,t){const n=e.data;if(!n?.__crucible)return null;const i="component"===n.kind?t.components[n.semanticId]:t.products[n.semanticId];if(!i)return null;const o="product"===n.kind;return(0,Uu.jsxs)("div",{className:"semiotic-tooltip semiotic-crucible-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(38, 50, 58, 0.96))",border:"1px solid rgba(255,255,255,0.2)",borderRadius:3,boxShadow:"0 8px 24px rgba(0,0,0,0.28)",color:"var(--semiotic-tooltip-text, #fffaf0)",maxWidth:290,padding:"9px 12px"},children:[(0,Uu.jsx)("strong",{children:i.label}),(0,Uu.jsx)("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:o?"Product · "+i.status:"Source · "+i.status}),(0,Uu.jsx)("div",{style:{marginTop:4},children:o?Xu(i):Gu(i)})]})}(e,Me.current.state),[]),ht=ge?qu(ye,we.state,Oe.current):ye.initialSpawns,pt=function(e){return e?!0===e?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:e.playPause??!0,reset:e.reset??!0,stepPhase:e.stepPhase??!0,timeline:e.timeline??!0,speed:e.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(c),mt=Object.values(pt).some(Boolean),ft=ye.phases[we.state.phaseIndex],yt=Ja({data:l,emptyContent:d,loading:g,loadingContent:b,size:le});if(yt)return yt;const gt=ye.diagnostics.filter(e=>"error"===e.severity);return gt.length?(0,dh.jsxs)("div",{className:Z,role:"alert",style:{maxWidth:"100%",width:le[0]},children:[(0,dh.jsx)("strong",{children:"CrucibleChart could not compile this treatment tape."}),(0,dh.jsx)("ul",{children:gt.map((e,t)=>(0,dh.jsx)("li",{children:e.message},`${e.code}-${t}`))})]}):ec("CrucibleChart",le,(0,dh.jsxs)("div",{ref:re,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:W?"100%":le[0]},children:[mt?(0,dh.jsx)(rh,{controls:pt,duration:ye.duration,elapsed:we.state.elapsed,phaseLabel:ft?.label??ft?.id??"Complete",playing:Ie&&!A,complete:we.state.complete,playbackRate:Re,disabled:ge,onPlayPause:Ie?Ge:Ve,onReset:He,onStepPhase:Ue,onPlaybackRateChange:$e}):null,(0,uh.createElement)(us,{...h,...at,...ct,key:`${pe}:${Ae}:${Le.rerunKey}:${ge?be:"replay"}`,ref:L,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:lt,bodyForces:Qe,bodySemanticItems:tt,bodyStyle:et,beforePaint:it,config:Le.config,continuous:!ge&&Ie&&!A&&!we.state.complete,enableHover:at.enableHover??ie,foregroundGraphics:dt,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:ht,initialSpawnPacing:f,onClick:w?nt:ct.onClick,onTick:Ke,paused:ze,renderBody:h.renderBody??Vu,responsiveHeight:O,responsiveWidth:!1,seed:mh(q),size:le,tooltipContent:at.tooltipContent??ut})]}))});xh.displayName="CrucibleChart";var vh=require("react");function wh(e,t,n={}){const i=new Set,o=[...e.get(t)??[]];let r=0;for(;o.length>r;){const t=o[r];if(r+=1,!i.has(t)){i.add(t);for(const n of e.get(t)??[])o.push(n)}}return n.includeStart&&i.add(t),i}function kh(e,t,n){return Ac(n,e,t)}function Mh(e,t){return t>e?-1:e>t?1:0}function Ih(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Sh(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function jh(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Ah(e){const t=[],n=new Map,i=[],o=new Set;e.data.forEach((r,s)=>{const a=(kh(r,s,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(kh(r,s,e.laneAccessor)??"Unassigned")+"";o.has(c)||(o.add(c),i.push(c));const l=kh(r,s,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(Mh),u=kh(r,s,e.blockerAccessor),h=kh(r,s,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(kh(r,s,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:s,datum:r,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:kh(r,s,e.startAccessor),end:kh(r,s,e.endAccessor),progress:jh(kh(r,s,e.progressAccessor)),status:h,completionTime:kh(r,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!kh(r,s,e.milestoneAccessor)})});const r=e.laneOrder?[...e.laneOrder,...i.filter(t=>!e.laneOrder?.includes(t))]:i,s=new Map(r.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=s.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((i,o)=>{const r=n.get(i);if(!r)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${i}".`,taskIDs:[e.id,i]});const s={id:Ih(i,e.id),sourceID:i,targetID:e.id,sourceIndex:r.index,targetIndex:e.index,socketID:Sh(e.id,o),socketIndex:o};l.push(s),a.get(e.id)?.push(s),c.get(i)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),r.outgoingEdgeIDs.push(s.id)});for(const e of a.values())e.sort((e,t)=>Mh(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Sh(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>Mh(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const p=[...n.keys()].filter(e=>0===u.get(e)).sort(Mh);let m=0;for(;p.length;){const e=p.shift();m+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const i=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,i),0===i){const e=p.findIndex(e=>e>t.targetID);0>e?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(Mh);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let f=0;const y=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of y)e.level=h.get(e.id)??0,f=Math.max(f,e.level);return{nodes:y,edges:l,byID:n,incoming:a,outgoing:c,lanes:r,maxLevel:f,diagnostics:t,valid:0===t.length}}function Ch(e,t,n={}){const i=Math.max(240,t.width),o=Math.max(220,t.height),r=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(i-2*r)/Math.max(1,e.lanes.length)),l=Math.max(76,(o-s-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,p=Math.max(1,Math.round(n.gutterCount??3)),m=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=m.get(e)??[];n.push(t),m.set(e,n)}for(const e of m.values())e.sort((e,t)=>Mh(e.id,t.id));const f=e.nodes.map(e=>{const t=m.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id));return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:r+c*(e.laneIndex+.5),y:s+l*(e.level+.5)+(n-(t.length-1)/2)*Math.min(18,.3*u),width:d,height:u}}),y=new Map(f.map(e=>[e.taskID,e])),g=[],b=[];e.edges.forEach((t,n)=>{const i=y.get(t.sourceID),o=y.get(t.targetID);if(!i||!o)return;const r=e.incoming.get(t.targetID)??[],s=Math.min(.72*o.width,14*Math.max(1,r.length-1)),a=r.length>1?o.x-s/2+s*t.socketIndex/(r.length-1):o.x,c=o.y-o.height/2-h-2;g.push({id:t.socketID,edgeID:t.id,taskID:o.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:i.x,y:i.y+i.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%p-(p-1)/2));var u;b.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const x=new Map(g.map(e=>[e.id,e])),v=new Map(b.map(e=>[e.edgeID,e]));return{tasks:f,sockets:g,routes:b,taskByID:y,socketByID:x,routeByEdgeID:v}}function Rh(e,t,n="all"){const i=Array.from(new Set(t)).sort(Mh),o=new Set,r=()=>i.every(e=>o.has(e));return{taskID:e,mode:n,incomingEdgeIDs:i,deliver:e=>i.includes(e)?(o.add(e),r()):r(),reset:(e=[])=>{o.clear();for(const t of e)i.includes(t)&&o.add(t)},isSatisfied:r,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...i],deliveredEdgeIDs:[...o].sort(Mh),satisfied:r()})}}function $h(e){return e instanceof Date?e.getTime():Number(e)}function Ph(e,t){const n=$h("object"!=typeof t||t instanceof Date?t:t.currentTime),i=e.map((e,t)=>({event:e,index:t,time:$h(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),o=new Set,r=new Map,s=new Set,a=new Set;for(const{event:e}of i)"task-completed"===e.type?(o.add(e.taskID),r.delete(e.taskID)):"task-blocked"===e.type?r.set(e.taskID,e.reason):"task-unblocked"===e.type?r.delete(e.taskID):"dependency-delivered"===e.type?s.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:i.map(e=>e.event),completedTaskIDs:o,blockedByTaskID:r,deliveredEdgeIDs:s,armedTaskIDs:a}}function Dh(e,t,n={}){const i=new Set(n.completedTaskIDs??[]),o=[...wh(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):i.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),r=Array.from(new Set(o.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:o.length,affectedLaneCount:r.length,downstreamTaskIDs:o.map(e=>e.id),affectedLanes:r}}var Bh=[];function Th(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function Eh(e){if(null==e.completionTime)return null;const t=Th(e.completionTime,NaN);return Number.isFinite(t)?t:null}function Nh(e,t,n,i){const o=new Set;for(const r of e.nodes){const s=e.incoming.get(r.id)??[];(i.has(r.id)||!n.has(r.id)&&s.every(e=>t.has(e.id)))&&o.add(r.id)}return o}function Oh(e,t,n,i){const o=e.nodes.map(Eh).filter(e=>null!=e),r=o.length?Math.min(...o)-1:0,s="replay"!==t||i?n:r,a=new Set,c=new Map;for(const n of e.nodes){const e=Eh(n);(null!=e&&s>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||i)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:Nh(e,l,c,a),blockers:c,previewTaskID:null}}function Wh(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function qh(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Fh(e){const t=qh(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),i=function(e,t){let n=1/0,i=0,o=0;for(let r=1;t.length>r;r+=1){const s=t[r-1],a=t[r],c=a.x-s.x,l=a.y-s.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-s.x)*c+(e.y-s.y)*l)/d)),p=Math.hypot(e.x-(s.x+c*h),e.y-(s.y+l*h));n>p&&(n=p,i=o+h*u),o+=u}return i}(e.body,t.route),o=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let i=1;e.length>i;i+=1){const o=e[i-1],r=e[i],s=r.x-o.x,a=r.y-o.y,c=Math.hypot(s,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:o.x+s*e,y:o.y+a*e},tangent:{x:s/c,y:a/c}}}n+=c}}const i=e[e.length-2],o=e[e.length-1],r=o.x-i.x,s=o.y-i.y,a=Math.hypot(r,s)||1;return{point:o,tangent:{x:r/a,y:s/a}}}(t.route,Math.min(n,i+22));return{x:2.5*(78*o.tangent.x-e.body.vx)+8*(o.point.x-e.body.x),y:2.5*(78*o.tangent.y-e.body.vy)+8*(o.point.y-e.body.y)}}function zh(e,t){const n=t.points[0]??{x:0,y:0},i=t.points[1]??n,o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:o/s*42,vy:r/s*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}var Lh=require("react/jsx-runtime");function Yh({machine:e,layout:t,runtime:n,downstreamSet:i,selectedSet:o,width:r,height:s,seed:a,reduced:c,onSelectTask:l}){return(0,Lh.jsxs)("svg",{"aria-hidden":"true",width:r,height:s,viewBox:`0 0 ${r} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[(0,Lh.jsx)("defs",{children:(0,Lh.jsx)("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:(0,Lh.jsx)("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const i=t.tasks.filter(e=>e.laneIndex===n),o=i[0]?.x??0;return(0,Lh.jsxs)("g",{children:[(0,Lh.jsx)("line",{x1:o,x2:o,y1:32,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),(0,Lh.jsx)("text",{x:o,y:23,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),o=n.inFlight.has(e.edgeID),r=i.has(e.targetID)||i.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");return(0,Lh.jsx)("polyline",{points:s,fill:"none",stroke:r?"var(--semiotic-highlight, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:r?4:o?3:2,strokeOpacity:t||o||r?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return(0,Lh.jsxs)("g",{children:[(0,Lh.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-background, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&(0,Lh.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const r=t.taskByID.get(e.id);if(!r)return null;const s=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=o.has(e.id)||u,p=i.has(e.id),m=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-muted, #75818a)"}(e,n),f=r.x-r.width/2,y=r.y-r.height/2,g=Math.max(2,r.height*e.progress);return(0,Lh.jsxs)("g",{children:[(0,Lh.jsxs)("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[(0,Lh.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,rx:e.milestone?12:4,fill:"var(--semiotic-background, #fff)",stroke:h||p?"var(--semiotic-highlight, #e08a1e)":m,strokeWidth:h?4:p?3:2}),(0,Lh.jsx)("rect",{x:f+3,y:y+r.height-g+1,width:r.width-6,height:Math.max(0,g-4),rx:2,fill:m,opacity:s?.86:.46})]}),d&&(0,Lh.jsxs)("g",{opacity:u?.28:1,children:[(0,Lh.jsx)("line",{x1:f-8,x2:f+14,y1:r.y+9,y2:r.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),(0,Lh.jsx)("circle",{cx:f-8,cy:r.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),(0,Lh.jsxs)("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[(0,Lh.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,fill:"transparent"}),(0,Lh.jsx)("text",{x:r.x,y:r.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),(0,Lh.jsxs)("text",{x:r.x,y:r.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-muted, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}var Hh=require("react/jsx-runtime"),_h={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Gh=(0,vh.forwardRef)(function(e,t){const{data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p,mode:m="snapshot",insight:f="blocker-amplification",currentTime:y,controls:g=!1,selectedTaskIDs:b,onSelectionChange:x,onObservation:v,reducedMotion:w,seed:k=31,width:M=920,height:I=620,responsiveWidth:S,responsiveHeight:j,title:A="Dependency chain reaction",description:C,className:R,accessibleTable:$=!0,enableHover:P=!0}=e,D=(0,vh.useRef)(null),[B,T]=(0,vh.useState)([]),E=b?Array.from(b):B,N=(0,vh.useMemo)(()=>new Set(E),[E]),O=Th(y,1/0),W="settle"===w,q=(0,vh.useMemo)(()=>Ah({data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p}),[n,i,o,r,s,a,c,l,d,u,h,p]),F=(0,vh.useMemo)(()=>Ch(q,{width:M,height:I}),[q,M,I]),[z,L]=(0,vh.useState)(()=>Oh(q,m,O,W)),Y=(0,vh.useRef)(z),H=(0,vh.useCallback)(e=>{Y.current=e,L(e)},[]),_=(0,vh.useCallback)(e=>v?.(e),[v]);(0,vh.useEffect)(()=>{const e=Oh(q,m,O,W);D.current?.clear(),Y.current=e,L(e)},[q,m,O,W]);const G=(0,vh.useCallback)(e=>{const t=N.has(e)?E.filter(t=>t!==e):[e];b||T(t),x?.(t)},[b,x,N,E]),X=(0,vh.useCallback)(e=>{if(W)return;const t=Wh(Y.current),n=[];for(const i of q.outgoing.get(e)??[]){if(t.delivered.has(i.id)||t.inFlight.has(i.id))continue;const e=F.routeByEdgeID.get(i.id);e&&(t.inFlight.add(i.id),n.push(zh(i,e)))}n.length&&(H(t),D.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[H,F,q,W]),V=(0,vh.useCallback)((e,t)=>{const n=q.byID.get(e),i=Y.current;if(!n||i.completed.has(e))return;const o=Wh(i);o.completed.add(e),o.blockers.delete(e),o.armed.add(e),null!=t&&(o.currentTime=t),H(o),_({type:"task-completed",taskID:e,datum:n.datum}),X(e)},[H,_,q,X]),U=(0,vh.useCallback)(e=>{const t=Wh(Y.current),n=[],i=[];for(const i of e){if(t.delivered.has(i))continue;const e=q.edges.find(e=>e.id===i);e&&(t.delivered.add(i),t.inFlight.delete(i),n.push(e))}for(const e of n){const n=q.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(q.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),i.push(n.id))}if(n.length){H(t);for(const e of n)_({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of i)_({type:"task-armed",taskID:e})}},[H,_,q]),K=(0,vh.useCallback)((e,t)=>{const n=[],i=[];for(const e of t.readBodies()){const t=qh(e);if(!t||Y.current.delivered.has(t.edgeID))continue;const o=t.route[t.route.length-1];o&&9>=Math.hypot(e.x-o.x,e.y-o.y)&&(n.push(t.edgeID),i.push(e.id))}i.length&&t.remove(i),n.length&&U(n)},[U]),Q=(0,vh.useCallback)(()=>{const e=Wh(Y.current);for(const t of q.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=Nh(q,e.delivered,e.blockers,e.completed),e.playing=!1,D.current?.settle(),H(e),_({type:"machine-settled"})},[H,_,q]),Z=(0,vh.useCallback)(()=>{const e=Wh(Y.current);e.playing=!1,H(e)},[H]),J=(0,vh.useCallback)(()=>{const e=Y.current,t=q.nodes.map(e=>({node:e,time:Eh(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void V(t.node.id,t.time);Z();const n=[...e.blockers.keys()].map(t=>Dh(q,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&_({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[_,q,Z,V]),ee=(0,vh.useCallback)(()=>{if(W)return void Q();const e=Wh(Y.current);e.playing=!0,H(e)},[H,W,Q]);(0,vh.useEffect)(()=>{if(!z.playing||"replay"!==m||W)return;const e=window.setInterval(J,760);return()=>window.clearInterval(e)},[m,W,z.playing,J]);const te=(0,vh.useCallback)(()=>{D.current?.clear(),H(Oh(q,m,O,W))},[H,q,m,O,W]),ne=(0,vh.useCallback)(e=>{if(!q.byID.has(e))return;const t=Wh(Y.current);t.previewTaskID=e,H(t);const n=Dh(q,e,{completedTaskIDs:t.completed});_({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[H,_,q]),ie=(0,vh.useCallback)(()=>{const e=Wh(Y.current);e.previewTaskID=null,H(e)},[H]),oe=(0,vh.useCallback)((e,t)=>{if(!q.byID.has(e))return;const n=Wh(Y.current);n.blockers.set(e,t),n.armed.delete(e),H(n)},[H,q]),re=(0,vh.useCallback)(e=>{if(!q.byID.has(e))return;const t=Wh(Y.current);t.blockers.delete(e),(q.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),H(t)},[H,q]),se=(0,vh.useCallback)(e=>Dh(q,e,{completedTaskIDs:Y.current.completed}),[q]),ae=(0,vh.useCallback)(()=>{const e=Y.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...E],tasks:q.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:q.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[q,E]);(0,vh.useImperativeHandle)(t,()=>({play:ee,pause:Z,step:J,reset:te,settle:Q,previewResolve:ne,clearPreview:ie,completeTask:V,blockTask:oe,unblockTask:re,getAmplification:se,getMachineState:ae}),[oe,ie,se,ae,Z,V,ee,ne,te,Q,J,re]);const ce=z.previewTaskID??E[0]??null,le=ce?Dh(q,ce,{completedTaskIDs:z.completed}):null,de=(0,vh.useMemo)(()=>new Set(le?.downstreamTaskIDs??[]),[le?.downstreamTaskIDs]),ue=(0,vh.useMemo)(()=>function(e,t,n){return e.nodes.flatMap(i=>{const o=t.taskByID.get(i.id);if(!o)return[];const r=e.incoming.get(i.id)??[],s=r.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(i.id),c=n.completed.has(i.id)?"completed":a?"blocked: "+a:n.armed.has(i.id)?"armed":"waiting";return[{id:i.id,label:`${i.label}, ${i.lane}, ${Math.round(100*i.progress)}%, ${c}`,description:`${s} of ${r.length} prerequisites delivered.`,datum:i.datum,x:o.x,y:o.y,width:o.width,height:o.height,shape:"rect",group:i.lane}]})}(q,F,z),[F,q,z]),he=(0,vh.useMemo)(()=>(0,Hh.jsx)(Yh,{machine:q,layout:F,runtime:z,downstreamSet:de,selectedSet:N,width:M,height:I,seed:k,reduced:W,onSelectTask:G}),[de,I,F,q,W,z,k,G,N,M]),pe=(0,vh.useMemo)(()=>{const e=[...z.blockers.keys()].map(e=>Dh(q,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${q.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[q,z.blockers,z.completed]),me=(0,vh.useMemo)(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:I,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:M-2,y1:0,x2:M-2,y2:I,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:M,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:I-2,x2:M,y2:I-2,thickness:4}}],[I,M]),fe=!0===g?["play","pause","step","reset","settle"]:g||[];return(0,Hh.jsxs)("div",q.valid?{className:R,style:{width:M,maxWidth:"100%",position:"relative"},children:[fe.length>0&&(0,Hh.jsx)("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:fe.map(e=>(0,Hh.jsx)("button",{type:"button",onClick:"play"===e?ee:"pause"===e?Z:"step"===e?J:"reset"===e?te:Q,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),(0,Hh.jsx)(us,{ref:D,size:[M,I],responsiveWidth:S,responsiveHeight:j,title:A,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${le&&"blocker-amplification"===f?` Selected task reaches ${le.downstreamTaskCount} unfinished tasks across ${le.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:P,initialSpawns:Bh,bodyForces:Fh,bodyStyle:{fill:"var(--semiotic-accent, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:ue,onSemanticItemActivate:e=>e.id&&G(e.id),foregroundGraphics:()=>he,paused:W,continuous:z.inFlight.size>0,onTick:K,config:{bodyLimit:Math.max(16,q.edges.length+4),colliders:me,settleStepLimit:2200,kernel:{seed:k,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),$&&(0,Hh.jsxs)("table",{style:_h,children:[(0,Hh.jsx)("caption",{children:pe}),(0,Hh.jsx)("thead",{children:(0,Hh.jsxs)("tr",{children:[(0,Hh.jsx)("th",{children:"Task"}),(0,Hh.jsx)("th",{children:"Lane"}),(0,Hh.jsx)("th",{children:"Progress"}),(0,Hh.jsx)("th",{children:"State"}),(0,Hh.jsx)("th",{children:"Waiting on"}),(0,Hh.jsx)("th",{children:"Downstream reach"})]})}),(0,Hh.jsx)("tbody",{children:q.nodes.map(e=>{const t=Dh(q,e.id,{completedTaskIDs:z.completed});return(0,Hh.jsxs)("tr",{children:[(0,Hh.jsx)("th",{scope:"row",children:e.label}),(0,Hh.jsx)("td",{children:e.lane}),(0,Hh.jsxs)("td",{children:[Math.round(100*e.progress),"%"]}),(0,Hh.jsx)("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),(0,Hh.jsx)("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),(0,Hh.jsxs)("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:R,role:"alert",style:{width:M,maxWidth:"100%"},children:[(0,Hh.jsx)("strong",{children:"ChainReactionChart could not compile this dependency graph."}),(0,Hh.jsx)("ul",{children:q.diagnostics.map((e,t)=>(0,Hh.jsx)("li",{children:e.message},`${e.code}-${t}`))})]})});Gh.displayName="ChainReactionChart";var Xh=us;
2
+ var e,t=Object.create,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,a=(e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))s.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(a=i(t,c))||a.enumerable});return e},c=(e,i,o)=>(o=null!=e?t(r(e)):{},a(!i&&e&&e.__esModule?o:n(o,"default",{value:e,enumerable:!0}),e)),l={};((e,t)=>{for(var i in t)n(e,i,{get:t[i],enumerable:!0})})(l,{BuiltInPhysicsEngineAdapter:()=>Di,ChainReactionChart:()=>Rp,CollisionSwarmChart:()=>Qc,CrucibleChart:()=>np,DEFAULT_CRUCIBLE_HEIGHT:()=>Nu,DEFAULT_CRUCIBLE_OUTLETS:()=>Wu,DEFAULT_CRUCIBLE_SIZE:()=>Fu,DEFAULT_CRUCIBLE_WIDTH:()=>Ou,EventDropChart:()=>Dc,GaltonBoardChart:()=>Rc,GauntletChart:()=>nd,GuantletChart:()=>id,PacketFlowChart:()=>bd,PhysicalFlowChart:()=>xd,PhysicsCustomChart:()=>Xc,PhysicsPileChart:()=>Fc,PhysicsPipelineStore:()=>$o,PhysicsSVGOverlay:()=>Jn,PhysicsSedimentAccumulator:()=>Yi,ProcessFlowChart:()=>$d,StreamPhysicsFrame:()=>ms,UnitPileChart:()=>Nc,absorbRegion:()=>ha,aggregateRegionCounts:()=>Us,applyCrucibleEvent:()=>Pu,arrivalReplay:()=>uu,bodiesToAnnotationAnchors:()=>Kn,bodyGroupSpec:()=>ma,buildCollisionSwarmPhysics:()=>zs,buildCrucibleEvidence:()=>Eu,buildCrucibleInitialSpawns:()=>ah,buildCrucibleLayout:()=>Ku,buildCruciblePhysicsConfig:()=>th,buildCrucibleProductEvents:()=>Jh,buildCrucibleProjection:()=>Bu,buildCrucibleStateSpawns:()=>uh,buildCrucibleTerminalSpawns:()=>hh,buildEventDropPhysics:()=>Ns,buildGaltonBoardPhysics:()=>Ts,buildPhysicalFlowPhysics:()=>Vs,buildPhysicsAnnotationContext:()=>Qn,buildPhysicsPile:()=>Ws,buildProcessFlowPhysics:()=>ga,calculateBlockerAmplification:()=>fp,capacitatedRegion:()=>da,chargeGateRegion:()=>aa,cloneCrucibleState:()=>gu,collidersFromScales:()=>au,comparePhysicsTrace:()=>_d,compileCruciblePlan:()=>bh,compileDependencyMachine:()=>dp,compileMotionEncoding:()=>tl,compilePhysicsEncoding:()=>sl,composePhysicsControllers:()=>tr,composeStyleRules:()=>ws,createCapacityQueueController:()=>Xo,createDefaultPhysicsEngineAdapter:()=>Ti,createDependencyGateController:()=>Jo,createInitialCrucibleState:()=>Vu,createLogicalJoin:()=>hp,createPhysicsEncodingLayout:()=>al,createPortalController:()=>nr,createProcessJourneyLedger:()=>Xd,createServiceLevelController:()=>Zo,createServiceResourcePoolController:()=>Ko,crucibleBondId:()=>oh,crucibleBoundaryColliders:()=>Zu,crucibleComponentBodyId:()=>nh,crucibleProductBodyId:()=>ih,crucibleProjectionRows:()=>Du,crucibleSemanticKey:()=>mh,default:()=>$p,deriveMotionVector:()=>rl,describePhysicsStageGeography:()=>tu,evaluateCrucibleConservation:()=>Tu,evaluatePhysicsBodyBudget:()=>Xi,forceFieldRegion:()=>pa,galtonPegs:()=>cu,groupCompletionRows:()=>Qs,hatchFillId:()=>re,hatchPatternDef:()=>ae,isHatchFill:()=>ie,makeRuleValueResolver:()=>ys,matchesThreshold:()=>bs,membraneRegion:()=>sa,normalizePhysicsAnnotations:()=>Zn,opacityFromAge:()=>il,physicsChargePoint:()=>Jd,physicsDestination:()=>Zd,physicsProcessBoundaryColliders:()=>ll,physicsProcessGroupSemanticItems:()=>hl,physicsProcessRegionSemanticItem:()=>dl,physicsProcessStageSemanticItems:()=>ul,physicsReferenceEnvelope:()=>qd,physicsStageColliders:()=>eu,physicsStageGeography:()=>Qd,planGauntletPropertyWork:()=>Ol,portalRegion:()=>ua,pressureFieldRegion:()=>la,processChrome:()=>Cd,processJourneyRows:()=>Ud,processLaneWalls:()=>fa,processStageLayout:()=>ia,processStageRegions:()=>ra,processVolumePolygons:()=>ea,regionCountsToProjectionRows:()=>Ks,replaceGauntletNegative:()=>Nl,replayCruciblePlan:()=>gh,replayStateTransitions:()=>mp,resolveCrucibleSelector:()=>ku,resolveCrucibleSnapshotAt:()=>yh,resolveCrucibleTime:()=>fh,resolveGauntletTerminalState:()=>od,resolveGauntletTerminalStates:()=>rd,resolveMotionAccessor:()=>el,resolveMotionAge:()=>nl,resolveMotionVector:()=>ol,resolveStyleRules:()=>vs,resolveSvgFill:()=>ce,routeDependencyTracks:()=>up,routeSurfaceRegion:()=>ca,ruleMatches:()=>xs,sedimentBake:()=>du,sedimentHeightfield:()=>_i,spawnFromTokens:()=>lu,stageTargetInVolume:()=>Js,updateProcessJourney:()=>Vd}),module.exports=(e=l,a(n({},"__esModule",{value:!0}),e));var d=require("react"),u=c(require("react")),h=require("react"),p=c(require("react")),m=require("react"),f=require("react"),y=require("react/jsx-runtime");function g(e){let t=null;const n=()=>(t||(t=(0,f.createContext)(null)),t),i=b(e);return[function({children:t,initialState:i}){const o=(0,f.useRef)(i),r=(0,f.useMemo)(()=>b(e,o.current),[]),s=n();return(0,y.jsx)(s.Provider,{value:r,children:t})},(e,t)=>{const o=n(),r=(0,f.useContext)(o)??i,s=(0,f.useRef)(e);s.current=e;const a=(0,f.useRef)({hasValue:!1,value:void 0}),c=(0,f.useCallback)(()=>{const e=s.current(r.getState()),n=a.current;return n.hasValue&&t&&t(n.value,e)?n.value:(a.current={hasValue:!0,value:e},e)},[r,t]),l=(0,f.useCallback)(()=>s.current(r.getState()),[r]);return(0,f.useSyncExternalStore)(r.subscribe,c,l)}]}function b(e,t){const n=new Set;let i={...e(function(e){const t=e(i);if(function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}(t)){i={...i,...t};for(const e of n)e()}}),...t??{}};return{getState:()=>i,subscribe:function(e){return n.add(e),()=>{n.delete(e)}}}}function x(e){if(!e.accessibility)return e;let t=e;if(e.accessibility.colorBlindSafe&&(t={...t,colors:{...t.colors,categorical:v}}),e.accessibility.highContrast){const e="dark"===t.mode;t={...t,colors:{...t.colors,text:e?"#ffffff":"#000000",textSecondary:e?"#cccccc":"#333333",grid:e?"#666666":"#999999",border:e?"#888888":"#000000"}}}return t}var v=["#0072B2","#E69F00","#009E73","#CC79A7","#56B4E9","#D55E00","#F0E442","#000000"],w={mode:"light",colors:{primary:"#00a2ce",secondary:"#6c757d",categorical:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],sequential:"blues",diverging:"RdBu",background:"transparent",surface:"#ffffff",text:"#333",textSecondary:"#666",grid:"#e0e0e0",border:"#ccc",selection:"#00a2ce",selectionOpacity:.15,success:"#2ca02c",danger:"#d62728",warning:"#f0ad4e",error:"#b4181b",info:"#00a2ce"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},k={mode:"dark",colors:{primary:"#4fc3f7",secondary:"#90a4ae",categorical:["#4fc3f7","#ffb74d","#81c784","#ef5350","#ba68c8","#a1887f","#f06292","#90a4ae","#dce775","#4dd0e1"],sequential:"blues",diverging:"RdBu",background:"#1a1a2e",surface:"#252540",text:"#e0e0e0",textSecondary:"#aaa",grid:"#333",border:"#555",selection:"#4fc3f7",selectionOpacity:.15,success:"#81c784",danger:"#ef5350",warning:"#ffb74d",error:"#d84848",info:"#4fc3f7"},typography:{fontFamily:"sans-serif",titleSize:16,labelSize:12,tickSize:12}},M={mode:"light",colors:{primary:"#0000cc",secondary:"#333333",categorical:v,sequential:"blues",diverging:"RdBu",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#333333",grid:"#999999",border:"#000000",focus:"#0000cc",selection:"#0000cc",selectionOpacity:.1,success:"#006400",danger:"#cc0000",warning:"#b15a00",error:"#8b0000",info:"#0000cc"},typography:{fontFamily:"system-ui, sans-serif",titleSize:18,labelSize:14,tickSize:12},tooltip:{background:"#000000",text:"#ffffff",borderRadius:"4px",fontSize:"14px",shadow:"0 2px 8px rgba(0, 0, 0, 0.3)"},borderRadius:"4px"};function I(e,t){if("light"===t)return w;if("dark"===t)return k;if("high-contrast"===t)return M;if("string"==typeof t)return void 0!==console&&console.warn(`[ThemeStore] Unknown theme preset "${t}". Keeping current theme.`),e;if(t.mode&&"auto"!==t.mode){const e="dark"===t.mode?k:w;return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}return x({...e,...t,colors:{...e.colors,...t.colors||{}},typography:{...e.typography,...t.typography||{}}})}var[S,j]=g(e=>({theme:w,setTheme(t){e(e=>({theme:I(e.theme,t)}))}})),A=require("react");function C(){const[e,t]=(0,A.useState)(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return(0,A.useEffect)(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)");return t(e.matches),function(e,t){if("function"==typeof e.addEventListener)return e.addEventListener("change",t),()=>e.removeEventListener("change",t);const n=e;return n.addListener(t),()=>n.removeListener(t)}(e,e=>t(e.matches))},[]),e}var R=require("react");function $(e,t,n){const i=(0,R.useRef)(null),[o,r]=(0,R.useState)(null);return(0,R.useEffect)(()=>{if(!t&&!n)return;const e=i.current;if(!e)return;const o=new ResizeObserver(e=>{for(const t of e){const{width:e,height:n}=t.contentRect;r(t=>t&&t.w===e&&t.h===n?t:{w:e,h:n})}});return o.observe(e),()=>o.disconnect()},[t,n]),[i,[t&&o?o.w:e[0],n&&o?o.h:e[1]]]}var P=new WeakMap,B=0,D=!1,T=null,E=null;function O(e,t){if(!t)return t;const n=function(e){const t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;const n=t.slice(4,-1),i=n.indexOf(",");if(-1===i){const e=n.trim();return e.startsWith("--")?{name:e}:null}const o=n.slice(0,i).trim(),r=n.slice(i+1).trim();return o.startsWith("--")?{name:o,fallback:r||void 0}:null}(t);if(!n)return t;const i=()=>n.fallback?O(e,n.fallback):t,o=e.canvas;if(!o)return i();!function(){if(D)return;if("undefined"==typeof window||"undefined"==typeof document)return;D=!0;const e=()=>{B++};if("undefined"!=typeof MutationObserver&&document.documentElement&&new MutationObserver(e).observe(document.documentElement,{attributes:!0,attributeFilter:["class","style","data-theme","data-semiotic-theme"],subtree:!0}),"function"==typeof window.matchMedia)try{T=window.matchMedia("(prefers-color-scheme: dark)"),E=e,"function"==typeof T.addEventListener?T.addEventListener("change",E):"function"==typeof T.addListener&&T.addListener(E)}catch{}}();let r=P.get(o);r&&r.version===B||(r={version:B,map:new Map},P.set(o,r));const s=r.map.get(t);if(void 0!==s)return s;const a=getComputedStyle(o).getPropertyValue(n.name).trim()||i()||t;return r.map.set(t,a),a}var N=()=>"undefined"!=typeof performance?performance.now():Date.now();function F(e,t){const n=e();return Number.isFinite(n)?n:t}var W=class{constructor(e={}){this.randomSource=Math.random,this.subscribers=new Set,this.now=()=>this.advance(),this.random=()=>this.randomSource(),this.clock=e.clock??N,this.lastWallTime=F(this.clock,0),this.logicalTime=this.lastWallTime,this.pausedValue=!0===e.paused,this.visibleValue=!1!==e.visible,this.setRandomSource(e.random,e.seed)}get isActive(){return!this.pausedValue&&this.visibleValue}get paused(){return this.pausedValue}get seed(){return this.seedValue}get visible(){return this.visibleValue}configure(e){this.setClock(e.clock),this.setRandomSource(e.random,e.seed)}setPaused(e){this.pausedValue!==e&&(this.advance(),this.pausedValue=e,this.emit())}setVisible(e){this.visibleValue!==e&&(this.advance(),this.visibleValue=e,this.emit())}snapshot(){return{now:this.now(),paused:this.pausedValue,seed:this.seedValue,visible:this.visibleValue}}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}advance(){const e=F(this.clock,this.lastWallTime),t=Math.max(0,e-this.lastWallTime);return this.lastWallTime=e,this.isActive&&(this.logicalTime+=t),this.logicalTime}emit(){for(const e of this.subscribers)e()}setClock(e){const t=e??N;t!==this.clock&&(this.advance(),this.clock=t,this.lastWallTime=F(t,this.lastWallTime))}setRandomSource(e,t){const n=function(e){return"number"==typeof e&&Number.isFinite(e)?Math.trunc(e):void 0}(t);e===this.randomInput&&n===this.seedValue||(this.randomInput=e,this.seedValue=n,this.randomSource=e??(void 0===n?Math.random:function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(n)))}},q="undefined"==typeof window?m.useEffect:m.useLayoutEffect,z={requestAnimationFrame:e=>("undefined"==typeof window?globalThis:window).requestAnimationFrame(e),cancelAnimationFrame:e=>("undefined"==typeof window?globalThis:window).cancelAnimationFrame(e)};function L(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}var H=require("react"),Y="undefined"!=typeof window?H.useLayoutEffect:H.useEffect,_=()=>()=>{},G=()=>!1,X=()=>!0;function V(){const e=(0,H.useSyncExternalStore)(_,G,X);return(0,H.useRef)(e).current}var U=require("react"),K=require("react/jsx-runtime");function Q({children:e,size:t,margin:n,overflowVisible:i=!1}){return e?(0,K.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:t[0],height:t[1],pointerEvents:"none",overflow:i?"visible":void 0},children:(0,K.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:e})}):null}var Z=c(require("react")),J=require("d3-shape");function ee(e){return{type:"hatch",background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle}}var te=null;var ne=require("react/jsx-runtime");function ie(e){return"object"==typeof e&&null!==e&&"hatch"===e.type}function oe(e){return["hatch",e.background??"transparent",e.stroke??"#000",e.lineWidth??1.5,e.spacing??6,e.angle??45,e.lineOpacity??1].join("|")}function re(e,t){let n=2166136261;const i=oe(t);for(let e=0;i.length>e;e++)n^=i.charCodeAt(e),n=Math.imul(n,16777619);return`${e}-hatch-${(n>>>0).toString(36)}`}var se=new Map;function ae(e,t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45,lineOpacity:a=1}=e,c=Math.max(8,Math.ceil(2*r));return(0,ne.jsxs)("pattern",{id:t,width:c,height:c,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[n&&"transparent"!==n&&(0,ne.jsx)("rect",{width:c,height:c,fill:n}),(0,ne.jsx)("line",{x1:0,y1:0,x2:0,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a}),(0,ne.jsx)("line",{x1:r,y1:0,x2:r,y2:c,stroke:i,strokeWidth:o,strokeOpacity:a})]},t)}function ce(e,t,n="#4e79a7"){if(ie(e)){const n=re(t,e);return{fill:`url(#${n})`,def:ae(e,n)}}return e&&"string"==typeof e?{fill:e}:{fill:n}}var le=require("d3-shape");function de(e){switch(e){case"monotoneX":return le.curveMonotoneX;case"monotoneY":return le.curveMonotoneY;case"cardinal":return le.curveCardinal;case"catmullRom":return le.curveCatmullRom;case"step":return le.curveStep;case"stepBefore":return le.curveStepBefore;case"stepAfter":return le.curveStepAfter;case"basis":return le.curveBasis;case"natural":return le.curveNatural;default:return null}}function ue(e,t,n){if(null==t)return n;if(ie(t)){const i=function(e,t){const n="undefined"!=typeof window&&window.devicePixelRatio||1,i=`${oe(e)}@${n}`,o=se.get(i);if(void 0!==o)return o;const r=function(e={},t){const{background:n="transparent",stroke:i="#000",lineWidth:o=1.5,spacing:r=6,angle:s=45}=e,a={background:n,stroke:i,lineWidth:o,spacing:r,angle:s},c=Math.max(8,Math.ceil(2*r));let l;try{l=function(e){return"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,e):(te||(te=document.createElement("canvas")),te.width=e,te.height=e,te)}(c)}catch{return ee(a)}const d=l.getContext("2d");if(!d)return ee(a);n&&"transparent"!==n?(d.fillStyle=n,d.fillRect(0,0,c,c)):d.clearRect(0,0,c,c),d.strokeStyle=i,d.lineWidth=o,d.lineCap="square";const u=s*Math.PI/180;if(45===s||-45===s){const e=s>0?1:-1;for(let t=-c;2*c>=t;t+=r)d.beginPath(),d.moveTo(t,0),d.lineTo(t+e*c,c),d.stroke()}else{d.save(),d.translate(c/2,c/2),d.rotate(u);const e=2*c;for(let t=-e;e>=t;t+=r)d.beginPath(),d.moveTo(-e,t),d.lineTo(e,t),d.stroke();d.restore()}return(t||d).createPattern(l,"repeat")}({background:e.background,stroke:e.stroke,lineWidth:e.lineWidth,spacing:e.spacing,angle:e.angle},t),s=ie(r)?null:r;return se.set(i,s),s}(t,e);return i||t.background&&O(e,t.background)||n}return"string"!=typeof t?t:O(e,t)||n}function he(e,t,n){let i=n;for(const n of t)"lesser"===n.thresholdType?n.value>e&&(i=n.color):e>n.value&&(i=n.color);return i}var pe=[40,40],me=[.5,.5];function fe(e,t,n,i){if("none"!==e)return"color"===e||null==e?t??i:"accent"===e?n:e}var ye=require("d3-shape"),ge={circle:ye.symbolCircle,square:ye.symbolSquare,triangle:ye.symbolTriangle,diamond:ye.symbolDiamond,star:ye.symbolStar,cross:ye.symbolCross,wye:ye.symbolWye};var be=require("react/jsx-runtime");function xe(e,t="#4e79a7"){return ie(e)?e.background&&"transparent"!==e.background?e.background:t:e&&"string"==typeof e?e:t}function ve(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"s_"+t:t}function we(e,t){const n=e.filter(e=>Number.isFinite(e.offset)&&(null==e.opacity||Number.isFinite(e.opacity))).map(e=>({offset:Math.max(0,Math.min(1,e.offset)),color:e.color??t,opacity:null==e.opacity?void 0:Math.max(0,Math.min(1,e.opacity))}));return 2>n.length?null:n.map((e,t)=>(0,be.jsx)("stop",{offset:e.offset,stopColor:e.color,stopOpacity:e.opacity},t))}var ke=require("react/jsx-runtime");function Me(e,t,n,i){if(!e||2>t.length)return null;const o=we(e.stops,i);return o?(0,ke.jsx)("linearGradient",{id:n,gradientUnits:"userSpaceOnUse",x1:t[0][0],y1:0,x2:t[t.length-1][0],y2:0,children:o}):null}function Ie(e,t,n){switch(e.type){case"line":{const i=e;if(0===i.path.length)return null;const o=de(i.curve),r=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.path)??"":"M"+i.path.map(([e,t])=>`${e},${t}`).join("L"),s=ve(`${n?n+"-":""}line-${t}-stroke-gradient`),a=Me(i.strokeGradient,i.path,s,i.style.stroke||"#4e79a7");return(0,ke.jsxs)(Z.Fragment,{children:[a&&(0,ke.jsx)("defs",{children:a}),(0,ke.jsx)("path",{d:r,fill:"none",stroke:a?`url(#${s})`:i.style.stroke||"#4e79a7",strokeWidth:i.style.strokeWidth||2,strokeDasharray:i.style.strokeDasharray,opacity:i.style.opacity})]},"line-"+t)}case"area":{const i=e;if(0===i.topPath.length)return null;const o=de(i.curve),r=!o||2>i.topPath.length||2>i.bottomPath.length?`M${i.topPath.map(([e,t])=>`${e},${t}`).join("L")}L${[...i.bottomPath].reverse().map(([e,t])=>`${e},${t}`).join("L")}Z`:(0,J.area)().x(([e])=>e).y0((e,t)=>i.bottomPath[t][1]).y1(([,e])=>e).curve(o)(i.topPath)??"",s=`${n?n+"-":""}area-${t}-hatch`,a=ie(i.style.fill)?ae(i.style.fill,s):void 0,c=ve(`${n?n+"-":""}area-${t}-gradient`),l=function(e,t){const n=e.fillGradient;if(!n||"object"!=typeof n)return null;let i=1/0;for(const[,t]of e.topPath)i=Math.min(i,t);let o=-1/0;for(const[,t]of e.bottomPath)o=Math.max(o,t);if(!Number.isFinite(i)||!Number.isFinite(o))return null;const r=we(n.stops,xe(e.style.fill));return r?(0,ke.jsx)("linearGradient",{id:t,gradientUnits:"userSpaceOnUse",x1:0,y1:i,x2:0,y2:o,children:r}):null}(i,c),d=l?`url(#${c})`:a?`url(#${s})`:xe(i.style.fill),u=l?void 0:i.style.fillOpacity??i.style.opacity??.7,h=o?(0,J.line)().x(([e])=>e).y(([,e])=>e).curve(o)(i.topPath)??"":"M"+i.topPath.map(([e,t])=>`${e},${t}`).join("L"),p=ve(`${n?n+"-":""}area-${t}-stroke-gradient`),m=!(!i.colorThresholds?.length||!i.rawValues||i.rawValues.length!==i.topPath.length),f=!!i.strokeColorBands?.length,y=m||f?null:Me(i.strokeGradient,i.topPath,p,i.style.stroke||"#4e79a7"),g=i.style.strokeWidth||2;let b=1/0,x=-1/0;for(const[e]of i.topPath)b>e&&(b=e),e>x&&(x=e);const v=f?i.strokeColorBands.map((e,i)=>ve(`${n?n+"-":""}area-${t}-stroke-band-${i}`)):[],w=f?i.strokeColorBands.map((e,t)=>(0,ke.jsx)("clipPath",{id:v[t],children:(0,ke.jsx)("rect",{x:b-g,y:e.y,width:x-b+2*g,height:e.height})},v[t])):null,k=i.style.stroke&&"none"!==i.style.stroke?f?i.strokeColorBands.map((e,n)=>(0,ke.jsx)("path",{d:h,fill:"none",stroke:e.color??xe(i.style.stroke),strokeWidth:g,opacity:i.style.opacity,clipPath:`url(#${v[n]})`},`area-${t}-stroke-band-${n}`)):m?function(e,t,n,i){if(2>e.length||t.length!==e.length||0===n.length)return[];const o=[],r=(e,t,n)=>{const i=o[o.length-1];i?.color===e?i.path.push(n):o.push({color:e,path:[t,n]})};for(let o=1;e.length>o;o++){const[s,a]=e[o-1],[c,l]=e[o],d=t[o-1],u=t[o]-d,h=[0,...0===u?[]:n.map(({value:e})=>(e-d)/u).filter(e=>e>0&&1>e&&Number.isFinite(e)).sort((e,t)=>e-t).filter((e,t,n)=>0===t||e!==n[t-1]),1];for(let e=1;h.length>e;e++){const t=h[e-1],o=h[e];r(he(d+u*((t+o)/2),n,i),[s+(c-s)*t,a+(l-a)*t],[s+(c-s)*o,a+(l-a)*o])}}return o}(i.topPath,i.rawValues,i.colorThresholds,xe(i.style.stroke)).map((e,n)=>(0,ke.jsx)("path",{d:"M"+e.path.map(([e,t])=>`${e},${t}`).join("L"),fill:"none",stroke:e.color,strokeWidth:g,opacity:i.style.opacity},`area-${t}-threshold-${n}`)):(0,ke.jsx)("path",{d:h,fill:"none",stroke:y?`url(#${p})`:xe(i.style.stroke),strokeWidth:g,opacity:i.style.opacity}):null;if(i.clipRect){const e=`${n?n+"-":""}area-clip-${t}`;return(0,ke.jsxs)("g",{children:[(0,ke.jsxs)("defs",{children:[l,!l&&a,y,w,(0,ke.jsx)("clipPath",{id:e,children:(0,ke.jsx)("rect",{x:i.clipRect.x,y:i.clipRect.y,width:i.clipRect.width,height:i.clipRect.height})})]}),(0,ke.jsxs)("g",{clipPath:`url(#${e})`,children:[(0,ke.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),k]})]},"area-"+t)}return(0,ke.jsxs)(Z.Fragment,{children:[(l||a||y||w)&&(0,ke.jsxs)("defs",{children:[l,!l&&a,y,w]}),(0,ke.jsx)("path",{d:r,fill:d,fillOpacity:u,opacity:l?i.style.opacity:void 0,stroke:"none"}),k]},"area-"+t)}case"point":{const i=e,o=`${n?n+"-":""}point-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,ke.jsxs)(Z.Fragment,{children:[r&&(0,ke.jsx)("defs",{children:r}),(0,ke.jsx)("circle",{cx:i.x,cy:i.y,r:i.r,fill:r?`url(#${o})`:xe(i.style.fill),opacity:i.style.opacity??i.style.fillOpacity??.8,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"point-"+t)}case"symbol":return function(e,t){const n=function(e,t,n){if(n)return n;const i=e??"circle";return"chevron"===i?function(e){const t=1.5*function(e){return Math.sqrt(Math.max(1,e)/Math.PI)}(e),n=.92*t;return`M0,${-t}L${n},${(.78*t).toFixed(3)}L0,${(.28*t).toFixed(3)}L${-n},${(.78*t).toFixed(3)}Z`}(t):(0,ye.symbol)(ge[i]??ye.symbolCircle,Math.max(1,t))()??""}(e.symbolType,e.size,e.path);return(0,be.jsx)("path",{d:n,transform:e.rotation?`translate(${e.x},${e.y}) rotate(${180*e.rotation/Math.PI})`:`translate(${e.x},${e.y})`,fill:e.style.fill?xe(e.style.fill):"none",fillOpacity:e.style.fillOpacity,opacity:e.style.opacity,stroke:e.style.stroke,strokeWidth:e.style.strokeWidth},"symbol-"+t)}(e,t);case"glyph":return function(e,t,n,i){const o=e.glyph;if(!o?.parts?.length||0>=e.size)return null;const r=function(e,t){const[n,i]=e.viewBox??pe,[o,r]=e.anchor??me,s=i>0?i:1,a=Math.max(0,t)/s,c=(n>0?n:s)*a,l=s*a;return{width:c,height:l,scale:a,offsetX:-o*c,offsetY:-r*l}}(o,e.size);if(0>=r.scale)return null;const s=`translate(${t},${n})${e.rotation?` rotate(${180*e.rotation/Math.PI})`:""} translate(${r.offsetX},${r.offsetY}) scale(${r.scale})`,a=e.color??("string"==typeof e.style.fill?e.style.fill:void 0),c=function(e,t,n=0,i="horizontal"){const[o,r]=e.viewBox??pe,s=Math.min(1,Math.max(0,n)),a=Math.min(1,Math.max(0,t));return a>s?s>0||1>a?"vertical"===i?{x:0,y:r*(1-a),width:o,height:r*(a-s)}:{x:o*s,y:0,width:o*(a-s),height:r}:null:{x:0,y:0,width:0,height:0}}(o,e.fraction??1,e.fractionStart??0,e.fractionDirection??"horizontal"),l=c?ve(i+"-clip"):void 0,d=(e.style.opacity??1)*(e._decayOpacity??1)*(e.style.fillOpacity??1),u=t=>o.parts.map((n,i)=>{const o=t?"none"===n.fill?void 0:t:fe(n.fill,a,e.accent),r=t?n.stroke&&"none"!==n.stroke?t:void 0:fe(n.stroke??"none",a,e.accent);return o||r?(0,be.jsx)("path",{d:n.d,fill:o??"none",stroke:r,strokeWidth:r?n.strokeWidth??1:void 0,strokeLinecap:n.strokeLinecap,strokeLinejoin:n.strokeLinejoin,opacity:n.opacity},i):null});return(0,be.jsxs)("g",{transform:s,opacity:1===d?void 0:d,children:[c&&l&&(0,be.jsx)("clipPath",{id:l,children:(0,be.jsx)("rect",{x:c.x,y:c.y,width:c.width,height:c.height})}),c&&e.ghostColor?(0,be.jsx)("g",{children:u(e.ghostColor)}):null,c&&l?(0,be.jsx)("g",{clipPath:`url(#${l})`,children:u()}):u()]},i)}(e,e.x,e.y,`${n??""}glyph-${e.pointId??t}`);case"rect":{const i=e,o=`${n?n+"-":""}xyrect-${t}-hatch`,r=ie(i.style.fill)?ae(i.style.fill,o):void 0;return(0,ke.jsxs)(Z.Fragment,{children:[r&&(0,ke.jsx)("defs",{children:r}),(0,ke.jsx)("rect",{x:i.x,y:i.y,width:i.w,height:i.h,fill:r?`url(#${o})`:xe(i.style.fill),opacity:i.style.opacity,stroke:i.style.stroke,strokeWidth:i.style.strokeWidth})]},"rect-"+t)}case"heatcell":{const n=e,i={x:n.x,y:n.y,width:n.w,height:n.h,fill:n.fill,stroke:n.style?.stroke,strokeWidth:n.style?.strokeWidth,...null!=n.style?.opacity&&{opacity:n.style.opacity}};if(n.showValues&&null!=n.value&&n.w>=20&&n.h>=20){const e=n.valueFormat?n.valueFormat(n.value):Number.isInteger(n.value)?n.value+"":100>Math.abs(n.value)?1>Math.abs(n.value)?n.value.toPrecision(3):n.value.toFixed(1):n.value.toFixed(0),[o,r,s]=function(e){if(e.startsWith("#")){let t=e.slice(1);if(3===t.length&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),6===t.length)return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[+t[1],+t[2],+t[3]]:[128,128,128]}(n.fill),a=.299*o+.587*r+.114*s>128?"#000":"#fff",c=Math.max(10,Math.min(16,.3*Math.min(n.w,n.h)));return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("rect",{...i}),(0,ke.jsx)("text",{x:n.x+n.w/2,y:n.y+n.h/2,textAnchor:"middle",dominantBaseline:"middle",fill:a,fontSize:c+"px",children:e})]},"heatcell-"+t)}return(0,ke.jsx)("rect",{...i},"heatcell-"+t)}case"candlestick":{const n=e;if(n.isRange){const e=n.dotRadius??Math.max(2,n.bodyWidth/2);return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,ke.jsx)("circle",{cx:n.x,cy:n.highY,r:e,fill:n.wickColor}),(0,ke.jsx)("circle",{cx:n.x,cy:n.lowY,r:e,fill:n.wickColor})]},"candle-"+t)}const i=Math.min(n.openY,n.closeY),o=Math.max(Math.abs(n.openY-n.closeY),1),r=n.isUp?n.upColor:n.downColor;return(0,ke.jsxs)("g",{children:[(0,ke.jsx)("line",{x1:n.x,y1:n.highY,x2:n.x,y2:n.lowY,stroke:n.wickColor,strokeWidth:n.wickWidth}),(0,ke.jsx)("rect",{x:n.x-n.bodyWidth/2,y:i,width:n.bodyWidth,height:o,fill:r,stroke:r,strokeWidth:1})]},"candle-"+t)}default:return null}}var Se="undefined"==typeof window||"undefined"==typeof document;var je=c(require("react")),Ae=["name","label","title"],Ce=["type","kind","category","group","class","status","role","shape"],Re=["value","amount","total","count","weight","score"],$e=new Set(["x","y","z","x0","x1","y0","y1","r","cx","cy","radius","layer","row","rowindex","col","column","depth","index","order","sankeywidth","coincidentpoints","sourcelinks","targetlinks","parent","children","fx","fy","vx","vy"]);function Pe(e,t){for(const n of t){const t=e.find(e=>e.lower===n);if(t)return t}}var Be=require("react/jsx-runtime"),De={background:"var(--semiotic-tooltip-bg, rgba(0, 0, 0, 0.85))",color:"var(--semiotic-tooltip-text, white)",padding:"8px 12px",borderRadius:"var(--semiotic-tooltip-radius, 6px)",fontSize:"var(--semiotic-tooltip-font-size, 14px)",fontFamily:"var(--semiotic-font-family, inherit)",lineHeight:"1.5",boxShadow:"var(--semiotic-tooltip-shadow, 0 2px 8px rgba(0, 0, 0, 0.15))",pointerEvents:"none",maxWidth:"300px",wordWrap:"break-word"};function Te(e,t){return"function"==typeof t?t(e):e[t]}function Ee(e,t){if(t)return t(e);if(null==e)return"";if("number"==typeof e){if(!Number.isFinite(e))return e+"";const t=Number.isInteger(e)?e:parseFloat(e.toPrecision(6));return Math.abs(t)>9999?t.toLocaleString():t+""}return e instanceof Date?e.toLocaleDateString():"object"==typeof e&&null!==e?void 0!==e.id?e.id+"":void 0!==e.name?e.name+"":JSON.stringify(e):e+""}function Oe(e={}){const{fields:t,title:n,format:i,style:o={},className:r=""}=e;return e=>{if(!e||"object"!=typeof e)return null;let s;const a=[];if(n){const t=Te(e,n);s=Ee(t,i)}if(t&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const s=Te(e,o);a.push({label:n,value:Ee(s,r)})});else if(!n){const t=["value","y","name","id","label"];for(const n of t)if(void 0!==e[n]){s=Ee(e[n],i);break}if(!s){const t=Object.keys(e).filter(e=>!e.startsWith("_"));t.length>0&&(s=Ee(e[t[0]],i))}}const c={...De,...o};return(0,Be.jsxs)("div",{className:("semiotic-tooltip "+r).trim(),style:c,children:[s&&(0,Be.jsx)("div",{style:{fontWeight:a.length>0?"bold":"normal"},children:s}),a.map((e,t)=>(0,Be.jsxs)("div",{style:{marginTop:0===t&&s?"4px":0},children:[e.label&&(0,Be.jsxs)("span",{children:[e.label,": "]}),e.value]},t))]})}}function Ne(e){if(!0!==e){if("function"==typeof e){const t=e;return e=>{let n=Array.isArray(i=!0===e?.__semioticHoverData||e&&void 0!==e.data&&"number"==typeof e.x&&"number"==typeof e.y&&e&&("node"===e.type||"edge"===e.type||void 0!==e.nodeOrEdge||void 0!==e.allSeries||void 0!==e.stats||void 0!==e.__chartType)?e.data??{}:e)?i[0]:i;var i;if(!n)return null;if(("node"===e?.nodeOrEdge&&"number"==typeof n?.x0&&"number"==typeof n?.x1||"edge"===e?.nodeOrEdge&&"number"==typeof n?.sankeyWidth)&&n.data&&"object"==typeof n.data&&(n=n.data),!n)return null;const o=t(n);return null==o?null:(0,Be.jsx)("div",{className:"semiotic-tooltip",style:De,children:o})}}return!1!==e&&void 0!==e&&("object"==typeof e&&null!==e&&("fields"in e||"title"in e)?Oe(e):"multi"===e?("undefined"!=typeof process&&"production"!==process.env?.NODE_ENV&&console.warn('[semiotic] tooltip="multi" reached normalizeTooltip — prefer charts that set tooltipMode (LineChart, AreaChart, StackedAreaChart, DifferenceChart). Rendering MultiLineTooltip content as a fallback.'),function(e={}){const{fields:t=[],title:n,format:i,style:o={},className:r="",showLabels:s=!0,separator:a=": "}=e;return e=>{if(!e||"object"!=typeof e)return null;const c=[];if(n){const t=Te(e,n);c.push({value:Ee(t,i)})}if(t&&Array.isArray(t)&&t.length>0)t.forEach(t=>{let n,o,r;"string"==typeof t?(n=t,o=t,r=i):(n=t.label,o=t.accessor||t.key||"",r=t.format||i);const a=Ee(Te(e,o),r);c.push({label:s?n:void 0,value:a})});else{const t=function(e,t={}){if(!e||"object"!=typeof e)return{entries:[]};const n=t.maxEntries??6,i=!1!==t.skipPositional,o=[];for(const[t,n]of Object.entries(e)){if(t.startsWith("_"))continue;if("data"===t)continue;if(i&&$e.has(t.toLowerCase()))continue;if(null==n)continue;const e=typeof n;("string"===e||"number"===e||"boolean"===e||n instanceof Date)&&o.push({key:t,lower:t.toLowerCase(),value:n})}if(0===o.length)return{entries:[]};let r=o.findIndex(e=>Ae.includes(e.lower));const s=r>=0;0>r&&(r=o.findIndex(e=>"id"===e.lower)),0>r&&(r=o.findIndex(e=>"string"==typeof e.value));const a=0>r?void 0:o[r];let c=o.filter((e,t)=>t!==r);s&&(c=c.filter(e=>"id"!==e.lower));const l=Pe(c,Ce),d=Pe(c,Re),u=new Set(Ce),h=new Set(Re),p=[];l&&p.push({key:l.key,value:l.value}),d&&p.push({key:d.key,value:d.value});for(const e of c){if(p.length>=n)break;e!==l&&e!==d&&(u.has(e.lower)||h.has(e.lower)||p.push({key:e.key,value:e.value}))}return{titleKey:a?.key,title:a?.value,entries:p}}(e,{skipPositional:!1});null!=t.title&&c.push({label:void 0,value:Ee(t.title,i),bold:!0}),t.entries.forEach(e=>{c.push({label:s?e.key:void 0,value:Ee(e.value,i)})})}const l={...De,...o};return Array.isArray(c)&&0!==c.length?(0,Be.jsx)("div",{className:("semiotic-tooltip semiotic-tooltip-multiline "+r).trim(),style:l,children:c.map((e,t)=>(0,Be.jsxs)("div",{style:{marginBottom:c.length-1>t?"4px":0,fontWeight:e.bold?"bold":void 0},children:[e.label&&(0,Be.jsxs)("strong",{children:[e.label,a]}),e.value]},t))}):null}}()):Oe())}}var Fe=require("react/jsx-runtime");function We({x:e,y:t,containerWidth:n,containerHeight:i,margin:o,children:r,className:s="stream-frame-tooltip",zIndex:a=1}){const c=Number.isFinite(e)&&Number.isFinite(t),l=je.useRef(null),[d,u]=je.useState(null);je.useLayoutEffect(()=>{const e=l.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect();Number.isFinite(t.width)&&Number.isFinite(t.height)&&u(e=>e&&.5>Math.abs(e.width-t.width)&&.5>Math.abs(e.height-t.height)?e:{width:t.width,height:t.height})};if(t(),"undefined"==typeof ResizeObserver)return;const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s,n,i,c]);let h;h=d?`translate(${d.width+12>n-e?"calc(-100% - 12px)":"12px"}, ${d.height+12>i-t?"calc(-100% - 4px)":"4px"})`:`translate(${e>.7*n?"calc(-100% - 12px)":"12px"}, ${.3*i>t?"4px":"calc(-100% - 4px)"})`;const p=function(e){if(!je.isValidElement(e))return!1;const t=e.type;if("string"!=typeof t&&t&&!0===t.ownsChrome)return!0;const n=e.props;if(!0===n["data-semiotic-tooltip-chrome"])return!0;if("true"===n["data-semiotic-tooltip-chrome"])return!0;const i=n.style;if(i&&"object"==typeof i){if(null!=i.background&&""!==i.background&&"transparent"!==i.background)return!0;if(null!=i.backgroundColor&&""!==i.backgroundColor&&"transparent"!==i.backgroundColor)return!0}return!1}(r),m=p?null:De;return c?(0,Fe.jsx)("div",{ref:l,className:p?s:(s+" semiotic-tooltip").trim(),style:{...m||{},position:"absolute",left:o.left+e,top:o.top+t,transform:h,pointerEvents:"none",zIndex:a,width:"max-content"},children:r}):null}var qe={names:["--semiotic-bg","--surface-1","--surface-0"],fallback:"#f8fafc"},ze={names:["--semiotic-border","--surface-3"],fallback:"#334155"},Le={names:["--semiotic-danger","--viz-4"],fallback:"#dc2626"},He={names:["--semiotic-focus","--accent","--viz-9"],fallback:"#f97316"},Ye={names:["--semiotic-grid","--surface-3"],fallback:"#cbd5e1"},_e={names:["--semiotic-primary","--accent","--viz-5"],fallback:"#0ea5e9"},Ge={names:["--semiotic-success","--viz-2"],fallback:"#22c55e"},Xe={names:["--semiotic-text","--text-primary"],fallback:"#0f172a"},Ve={names:["--semiotic-text-secondary","--text-secondary"],fallback:"#475569"},Ue={names:["--semiotic-warning","--viz-9","--viz-3"],fallback:"#f97316"};function Ke(e,t){const n=e.canvas;if("function"!=typeof getComputedStyle||!n)return t.fallback;const i=getComputedStyle(n);for(const n of t.names){const t=i.getPropertyValue(n).trim();if(t)return O(e,t)??t}return t.fallback}function Qe(e,t){const n=Math.max(0,Math.min(1,t)),i=e.trim(),o=i.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,i]=o;return Qe(`#${e}${e}${t}${t}${i}${i}`,n)}const r=i.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,i]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(i,16)}, ${n})`}const s=i.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${n})`;const a=i.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${n})`:i}var Ze=c(require("react")),Je=require("d3-scale"),et=c(require("react"));function tt(e){return"object"==typeof e&&null!==e&&"legendGroups"in e&&Array.isArray(e.legendGroups)}function nt(e){return"object"==typeof e&&null!==e&&"gradient"in e}var it=16,ot=6,rt=10,st=22,at=100,ct=10;function lt(e){return Math.ceil(7*e.length)}var dt=22,ut=46,ht=64;function pt(e,t){return null!=t?.axisGutter?Math.max(0,t.axisGutter):e?.hasAxis?e.hasAxisLabel?e.rotatedTicks?ht:ut:dt:0}function mt(e){const t=Math.max(1,e?.swatchSize??it),n=Math.max(t,e?.rowHeight??st);return{swatchSize:t,labelGap:Math.max(0,e?.labelGap??ot),itemGap:Math.max(0,e?.itemGap??rt),rowHeight:n,align:"left"===e?.align?"start":"right"===e?.align?"end":e?.align??"start",maxWidth:e?.maxWidth}}var ft=require("react/jsx-runtime"),yt={fill:(e,t)=>(0,ft.jsx)("rect",{style:e,width:t,height:t}),line:(e,t)=>(0,ft.jsx)("line",{style:e,x1:0,y1:0,x2:t,y2:t})};function gt(e,t,n,i,o){let r;return r="function"==typeof n?n(e):(0,yt[n])(i(e,t),o),r}function bt({swatchSize:e}){return(0,ft.jsx)("path",{d:`M${.25*e},${.55*e} L${.45*e},${.75*e} L${.8*e},${.3*e}`,fill:"none",stroke:"white",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})}function xt(e,t,n){return n&&n.size>0?n.has(e.label)?1:.3:null!=t?e.label===t?1:.3:1}var vt=(e,t,n,i,o,r,s,a,c,l,d)=>{const{type:u="fill",styleFn:h,items:p}=e,m=[];let f=0;const y=!(!t&&!n),g="isolate"===l||void 0===l&&null!=o,{swatchSize:b,labelGap:x,rowHeight:v}=d;return p.forEach((e,l)=>{const d=gt(e,l,u,h,b),w=xt(e,i,o),k=o&&o.size>0&&o.has(e.label);m.push((0,ft.jsxs)("g",{transform:`translate(0,${f})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:y?a===r&&l===s?0:-1:void 0,role:y?"option":void 0,"aria-selected":y&&g?k||!1:void 0,"aria-current":y&&!g&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:y?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowDown"===n.key||"ArrowUp"===n.key){n.preventDefault();const e=(l+("ArrowDown"===n.key?1:-1)+p.length)%p.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:y?t=>{c(a,l),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:y?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:y?"pointer":"default",opacity:w,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[y&&(0,ft.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:b+x+2+7*e.label.length,height:b+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),d,k&&(0,ft.jsx)(bt,{swatchSize:b}),(0,ft.jsx)("text",{y:b/2,x:b+x,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+l)),f+=v}),m},wt=({legendGroups:e,width:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:s,focusedItemIndex:a,onFocusedIndexChange:c,legendInteraction:l,metrics:d})=>{const u=[],h=function(e,t){let n=24;return e.map(({hasLabel:e,itemCount:i})=>{n+=5;const o=n;let r;n+=8,e&&(n+=16,r=n,n+=8);const s=n;return n+=i*t+8,{lineY:o,labelY:r,itemsY:s,endY:n}})}(e.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),d.rowHeight);return e.forEach((e,p)=>{const m=h[p];u.push((0,ft.jsx)("line",{stroke:"gray",x1:0,y1:m.lineY,x2:t,y2:m.lineY},"legend-top-line legend-symbol-"+p)),e.label&&null!=m.labelY&&u.push((0,ft.jsx)("text",{y:m.labelY,className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label},"legend-text-"+p)),u.push((0,ft.jsx)("g",{className:"legend-item",transform:`translate(0,${m.itemsY})`,children:vt(e,n,i,o,r,s,a,p,c,l,d)},"legend-group-"+p))}),u},kt=({legendGroups:e,height:t,width:n,customClickBehavior:i,customHoverBehavior:o,highlightedCategory:r,isolatedCategories:s,focusedGroupIndex:a,focusedItemIndex:c,onFocusedIndexChange:l,legendInteraction:d,metrics:u})=>{let h=0;const p=[];e.forEach((e,t)=>{let m=0;e.label&&(m+=16);const f=((e,t,n,i,o,r,s,a,c,l,d,u)=>{const{type:h="fill",styleFn:p,items:m}=e,f=[],{swatchSize:y,labelGap:g,itemGap:b,rowHeight:x,align:v}=d,w=!(!t&&!n),k="isolate"===l||void 0===l&&null!=o,M=m.map(e=>y+g+7*e.label.length),I=[];let S=0,j=0;M.forEach((e,t)=>{const n=0===j?e:j+b+e;u&&u>0&&j>0&&n>u?(I.push({start:S,end:t,width:j}),S=t,j=e):j=n}),m.length>0&&I.push({start:S,end:m.length,width:j}),I.forEach((e,l)=>{let d="center"===v?Math.max(0,((u??e.width)-e.width)/2):"end"===v?Math.max(0,(u??e.width)-e.width):0;for(let u=e.start;e.end>u;u++){const e=m[u],v=gt(e,u,h,p,y),I=xt(e,i,o),S=o&&o.size>0&&o.has(e.label);f.push((0,ft.jsxs)("g",{transform:`translate(${d},${l*x})`,onClick:t?()=>t(e):void 0,onMouseEnter:n?()=>n(e):void 0,onMouseLeave:n?()=>n(null):void 0,tabIndex:w?a===r&&u===s?0:-1:void 0,role:w?"option":void 0,"aria-selected":w&&k?S||!1:void 0,"aria-current":w&&!k&&null!=i&&e.label===i||void 0,"aria-label":e.label,onKeyDown:w?n=>{if("Enter"!==n.key&&" "!==n.key||(n.preventDefault(),t&&t(e)),"ArrowRight"===n.key||"ArrowLeft"===n.key){n.preventDefault();const e=(u+("ArrowRight"===n.key?1:-1)+m.length)%m.length;c(a,e);const t=n.currentTarget.parentElement?.children[e];t instanceof SVGElement&&t.focus()}}:void 0,onFocus:w?t=>{c(a,u),n&&n(e);const i=t.currentTarget.querySelector(".semiotic-legend-focus-ring");i&&i.setAttribute("visibility","visible")}:void 0,onBlur:w?e=>{n&&n(null);const t=e.currentTarget.querySelector(".semiotic-legend-focus-ring");t&&t.setAttribute("visibility","hidden")}:void 0,style:{cursor:w?"pointer":"default",opacity:I,transition:"opacity 150ms ease",pointerEvents:"all",outline:"none"},children:[w&&(0,ft.jsx)("rect",{className:"semiotic-legend-focus-ring",x:-2,y:-2,width:y+g+2+7*e.label.length,height:y+4,fill:"none",stroke:"var(--semiotic-focus, #005fcc)",strokeWidth:2,rx:3,visibility:"hidden"}),v,S&&(0,ft.jsx)(bt,{swatchSize:y}),(0,ft.jsx)("text",{y:y/2,x:y+g,dominantBaseline:"central",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:e.label})]},"legend-item-"+u)),d+=M[u]+b}});const A=Math.max(0,...I.map(e=>e.width)),C=I.length;return{items:f,offset:A,totalRows:C,totalHeight:C*x}})(e,i,o,r,s,a,c,t,l,d,u,u.maxWidth??n);m+=f.offset+5,p.push({label:e.label,...f,offset:m,totalRows:f.totalRows,totalHeight:f.totalHeight}),h+=m+12});const m=u.maxWidth??n;let f=h>m?0:"center"===u.align?Math.max(0,(m-h)/2):"end"===u.align?Math.max(0,m-h):0;const y=[];return p.forEach((n,i)=>{const o=e[i];o.label&&(y.push((0,ft.jsx)("text",{transform:`translate(${f},0) rotate(90)`,textAnchor:"start",className:"legend-group-label",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:o.label},"legend-text-"+i)),f+=16),y.push((0,ft.jsx)("g",{className:"legend-item",transform:`translate(${f},0)`,children:n.items},"legend-group-"+i)),f+=n.offset+5,e[i+1]&&y.push((0,ft.jsx)("line",{stroke:"gray",x1:f,y1:-8,x2:f,y2:(n.totalHeight||t)+0+8},"legend-top-line legend-symbol-"+i)),f+=12}),(0,ft.jsx)("g",{children:y})};function Mt({config:e,orientation:t="vertical",width:n=100}){const{colorFn:i,domain:o,label:r,format:s}=e,a=s||(e=>Math.round(100*e)/100+""),c="grad-legend-"+et.useId();if("horizontal"===t){const e=12,t=Math.min(n,200),s=Math.max(0,(n-t)/2),l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ft.jsx)("stop",{offset:100*t+"%",stopColor:i(o[0]+t*(o[1]-o[0]))},e))}return(0,ft.jsxs)("g",{"aria-label":r||"Gradient legend",children:[(0,ft.jsx)("defs",{children:(0,ft.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:l})}),r&&(0,ft.jsx)("text",{x:s+t/2,y:-4,textAnchor:"middle",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ft.jsx)("rect",{x:s,y:0,width:t,height:e,fill:`url(#${c})`,rx:2}),(0,ft.jsx)("text",{x:s,y:e+12,textAnchor:"start",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])}),(0,ft.jsx)("text",{x:s+t,y:e+12,textAnchor:"end",fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])})]})}const l=[];for(let e=0;64>=e;e++){const t=e/64;l.push((0,ft.jsx)("stop",{offset:100*t+"%",stopColor:i(o[1]-t*(o[1]-o[0]))},e))}return(0,ft.jsxs)("g",{"aria-label":r||"Gradient legend",children:[r&&(0,ft.jsx)("text",{x:0,y:-6,textAnchor:"start",fontSize:11,fill:"var(--semiotic-text, #333)",children:r}),(0,ft.jsx)("defs",{children:(0,ft.jsx)("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:l})}),(0,ft.jsx)("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),(0,ft.jsx)("text",{x:19,y:10,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[1])}),(0,ft.jsx)("text",{x:19,y:100,fontSize:10,fill:"var(--semiotic-text-secondary, #666)",children:a(o[0])})]})}function It(e){const{legendGroups:t,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,legendInteraction:s,title:a="Legend",width:c=100,height:l=20,orientation:d="vertical",legendLayout:u}=e,h=mt(u),[p,m]=et.useState(0),[f,y]=et.useState(0),g=et.useCallback((e,t)=>{m(e),y(t)},[]),b="vertical"===d?wt({legendGroups:t||[],width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}):kt({legendGroups:t||[],title:a,height:l,width:c,customClickBehavior:n,customHoverBehavior:i,highlightedCategory:o,isolatedCategories:r,focusedGroupIndex:p,focusedItemIndex:f,onFocusedIndexChange:g,legendInteraction:s,metrics:h}),x=!(!n&&!i);return(0,ft.jsxs)("g",{role:x?"listbox":void 0,"aria-multiselectable":!(!x||"isolate"!==s&&(void 0!==s||null==r))||void 0,"aria-label":"Chart legend",style:{fontFamily:"var(--semiotic-font-family, sans-serif)"},children:[void 0!==a&&""!==a&&"vertical"===d&&(0,ft.jsx)("text",{className:"legend-title",y:16,x:c/2,textAnchor:"middle",style:{fontSize:"var(--semiotic-legend-font-size, 12px)"},fill:"var(--semiotic-text, #333)",children:a}),b]})}var St=require("react/jsx-runtime");function jt(e){const{legend:t,totalWidth:n,totalHeight:i,margin:o,legendPosition:r="right",legendLayout:s,legendHoverBehavior:a,legendClickBehavior:c,legendHighlightedCategory:l,legendIsolatedCategories:d,legendInteraction:u}=e;if(!t)return null;const h="top"===r||"bottom"===r,p=Math.max(0,n-o.left-o.right),m=Math.max(1,h?s?.maxWidth??p:function(e,t){if(tt(e)){const n=mt(t),i=e.legendGroups.flatMap(e=>[e.label?lt(e.label):0,...e.items.map(e=>n.swatchSize+n.labelGap+lt(e.label))]);return Math.max(at,...i)}if(nt(e)){const{gradient:t}=e,n=t.format||(e=>Math.round(100*e)/100+""),i=Math.max(lt(n(t.domain[0])),lt(n(t.domain[1]))),o=t.label?lt(t.label):0;return Math.max(at,19+i,o)}return at}(t,s)),f=function(e){return(tt(e)||nt(e))&&Number.isFinite(e.legendDistance)?Math.max(0,e.legendDistance):ct}(t),y=(g=s,Math.max(0,g?.sideGutter??0));var g;const b=pt(e.axisChrome,s),x=pt(void 0,s),v=function(e,t,n){if(nt(e))return e.gradient.label?34:26;if(!tt(e))return 20;const i=mt(n),o=Math.max(1,n?.maxWidth??t);let r=i.rowHeight;for(const t of e.legendGroups){let e=0,n=0;for(const r of t.items){const t=i.swatchSize+i.labelGap+lt(r.label),s=0===n?t:n+i.itemGap+t;n>0&&s>o?(e+=1,n=t):n=s}t.items.length>0&&(e+=1),r=Math.max(r,e*i.rowHeight,t.label?lt(t.label):0)}return r+(e.legendGroups.length>1?16:0)}(t,p,s);let w,k;if("left"===r)w=o.left-y-m-f,k=o.top;else if("top"===r)w=o.left,k=o.top-x-f-v;else if("bottom"===r){w=o.left;const e=i-o.bottom;k=Math.max(e+f,Math.min(e+b+f,i-v))}else w=n-o.right+y+f,k=o.top;return(0,St.jsx)("g",{transform:`translate(${w}, ${k})`,children:nt(t)?(0,St.jsx)(Mt,{config:t.gradient,orientation:h?"horizontal":"vertical",width:m}):tt(t)?(0,St.jsx)(It,{legendGroups:t.legendGroups,title:"",width:m,orientation:h?"horizontal":"vertical",legendLayout:s,customHoverBehavior:a,customClickBehavior:c,highlightedCategory:l,isolatedCategories:d,legendInteraction:u}):t})}var At=require("react/jsx-runtime"),Ct={secondary:0,primary:3},Rt=1,$t=2,Pt=.6,Bt="0.88em",Dt=.95,Tt=.72,Et=.06,Ot=".annotation-deferred{opacity:0;pointer-events:none;transition:opacity .12s ease}.stream-xy-frame:hover .annotation-deferred,.stream-ordinal-frame:hover .annotation-deferred,.stream-network-frame:hover .annotation-deferred,.stream-geo-frame:hover .annotation-deferred,.stream-xy-frame:focus-within .annotation-deferred,.stream-ordinal-frame:focus-within .annotation-deferred,.stream-network-frame:focus-within .annotation-deferred,.stream-geo-frame:focus-within .annotation-deferred{opacity:1;pointer-events:auto}@media (prefers-reduced-motion:reduce){.annotation-deferred{transition:none}}",Nt=".annotation-cohesion--layer text,.annotation-cohesion--layer tspan{fill:var(--semiotic-annotation-color,var(--semiotic-text-secondary,#666));font-style:italic}";function Ft(e){return!0===e?._annotationDeferred}function Wt(e){return"blended"===e?.cohesion||"layer"===e?.cohesion?e.cohesion:null}function qt(e){const t=e?.provenance?.confidence;return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):null}function zt(e){return Math.max(Tt,Dt-e*Et)}var Lt=c(require("react")),Ht=require("react/jsx-runtime");function Yt(e,t=120,n=8){if(!e)return[];const i=Math.max(1,Math.floor(t/n)),o=e.split(/\s+/),r=[];let s="";for(const e of o)s&&s.length+1+e.length>i?(r.push(s),s=e):s=s?`${s} ${e}`:e;return s&&r.push(s),r}function _t(e,t,n,i){return"curly"===e?i?`M0,0 C${.6*n},0 ${.4*n},${t/2} ${n},${t/2} C${.4*n},${t/2} ${.6*n},${t} 0,${t}`:`M0,0 C0,${.6*n} ${t/2},${.4*n} ${t/2},${n} C${t/2},${.4*n} ${t},${.6*n} ${t},0`:i?`M0,0 L${n},0 L${n},${t} L0,${t}`:`M0,0 L0,${n} L${t},${n} L${t},0`}function Gt(e,t,n,i){if(!e)return(0,Ht.jsx)("g",{className:"annotation-note"});const{label:o,title:r,orientation:s,align:a,wrap:c=120,noWrap:l}=e;if(!o&&!r)return(0,Ht.jsx)("g",{className:"annotation-note"});let d=s;d||(d=Math.abs(t)>Math.abs(n)?"leftRight":"topBottom");let u=a;u&&"dynamic"!==u||(u="topBottom"===d?0>t?"right":"left":0>n?"bottom":"top");let h="start";"topBottom"===d?"right"===u?h="end":"middle"===u&&(h="middle"):h=0>t?"end":"start";const p=16,m=r?l?[r]:Yt(r,c):[],f=o?l?[o]:Yt(o,c):[],y="leftRight"===d?"end"===h?-4:4:0;let g=0;const b=[],x=i||"var(--semiotic-annotation-color, var(--semiotic-text, #333))";e.useHTML||e.html?b.push((0,Ht.jsx)("foreignObject",{className:"annotation-note-html",x:"end"===h?y-c:"middle"===h?y-c/2:y,y:-16,width:c,height:Math.max(p,(m.length+f.length)*p+(r&&o?2:0))+p,style:{overflow:"visible"},children:(0,Ht.jsxs)("div",{xmlns:"http://www.w3.org/1999/xhtml",style:{color:x,fontSize:"12px",lineHeight:"16px",overflow:"visible",textAlign:"end"===h?"right":"middle"===h?"center":"left",whiteSpace:l?"nowrap":"normal",wordBreak:"break-word"},children:[r&&(0,Ht.jsx)("div",{className:"annotation-note-title",style:{fontWeight:"bold"},children:r}),o&&(0,Ht.jsx)("div",{className:"annotation-note-label",children:o})]})},"annotation-note-html")):(m.length>0&&(b.push((0,Ht.jsx)("text",{className:"annotation-note-title",fill:x,textAnchor:h,fontWeight:"bold",children:m.map((e,t)=>(0,Ht.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-title")),g=m.length*p),f.length>0&&b.push((0,Ht.jsx)("text",{className:"annotation-note-label",fill:x,textAnchor:h,y:g,children:f.map((e,t)=>(0,Ht.jsx)("tspan",{x:y,dy:0===t?0:p,children:e},t))},"annotation-note-label")));let v=null;if((r||o)&&(0!==t||0!==n))if("topBottom"===d){const e=Math.min(c,120);let t=0,n=e;"end"===h?(t=-e,n=0):"middle"===h&&(t=-e/2,n=e/2),v=(0,Ht.jsx)("line",{className:"note-line",x1:t,x2:n,y1:0,y2:0,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}else{const e=(m.length+f.length)*p+(f.length>0?p:0);let t=0,n=e;"bottom"===u?(t=-e,n=0):"middle"===u&&(t=-e/2,n=e/2),v=(0,Ht.jsx)("line",{className:"note-line",x1:0,x2:0,y1:t,y2:n,stroke:i||"var(--semiotic-text-secondary, currentColor)"})}const w=Math.max(0,m.length+f.length-1)*p;let k=0;return"topBottom"===d?k=0>n?-(w+2):18:"leftRight"===d&&(k="middle"===u?-(w+p+(f.length>0&&m.length>0?2:0))/2+8:"bottom"===u||0>n?-(w+2):18),(0,Ht.jsxs)("g",{className:"annotation-note",transform:`translate(${t},${n})`,children:[(0,Ht.jsx)("g",{className:"annotation-note-content",transform:0!==k?`translate(0,${k})`:void 0,children:b}),v]})}function Xt(e,t,n,i,o){const r=[];switch(e){case"callout-circle":{const e=(t?.radius||0)+(t?.radiusPadding||0);e>0&&r.push((0,Ht.jsx)("circle",{r:e,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-circle"));break}case"callout-rect":{const e=t?.width||0,i=t?.height||0;(e>0||i>0)&&r.push((0,Ht.jsx)("rect",{width:e,height:i,fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"subject-rect"));break}case"callout-custom":t?.custom&&r.push(...Array.isArray(t.custom)?t.custom:[t.custom]);break;case"xy-threshold":{const e=i||0,s=o||0;if(void 0!==t?.x){const i=(t.x||0)-e;r.push((0,Ht.jsx)("line",{x1:i,y1:(t.y1||0)-s,x2:i,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else if(void 0!==t?.y){const i=(t.y||0)-s;r.push((0,Ht.jsx)("line",{x1:(t.x1||0)-e,y1:i,x2:(t.x2||0)-e,y2:i,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"))}else void 0!==t?.x1||void 0!==t?.x2?r.push((0,Ht.jsx)("line",{x1:(t.x1||0)-e,y1:0,x2:(t.x2||0)-e,y2:0,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line")):void 0===t?.y1&&void 0===t?.y2||r.push((0,Ht.jsx)("line",{x1:0,y1:(t.y1||0)-s,x2:0,y2:(t.y2||0)-s,stroke:n||"var(--semiotic-text-secondary, currentColor)",strokeDasharray:"5,5"},"threshold-line"));break}case"bracket":{const e=t?.type||"curly",i=t?.width??t?.height;void 0!==i&&r.push((0,Ht.jsx)("path",{d:_t(e,i,t?.depth||30,void 0===t?.width),fill:"none",stroke:n||"var(--semiotic-text-secondary, currentColor)"},"bracket-path"));break}}return(0,Ht.jsx)("g",{className:"annotation-subject",children:r})}function Vt(e,t,n,i,o,r){const s=[];let a=0,c=0;if("callout-circle"!==o&&"label"!==o||!r?.radius){if("callout-rect"===o&&r){const n=r.width||0,i=r.height||0;if(n>0||i>0){const o=n/2,r=i/2,s=e-o,l=t-r;if(0!==s||0!==l){const e=Math.abs(s),t=Math.abs(l),d=n/2,u=i/2,h=e*u>t*d?d/e:u/t;a=o+s*h,c=r+l*h}}}else if("bracket"===o&&r){const e=r.width,t=r.height,n=r.depth||30;void 0!==e?(a=e/2,c=n):void 0!==t&&(a=n,c=t/2)}}else{const n=(r.radius||0)+(r.radiusPadding||0);if(n>0&&(0!==e||0!==t)){const i=Math.atan2(t,e);a=Math.cos(i)*n,c=Math.sin(i)*n}}const l=Math.sqrt((e-a)**2+(t-c)**2);if(l>.5){const o=i||"var(--semiotic-text-secondary, currentColor)",r="curve"===n?.type;let d=Math.atan2(t-c,e-a);if(r){const i=(a+e)/2,r=(c+t)/2,u=-(t-c)/l,h=(e-a)/l,p=(n?.curve??.25)*l,m=i+u*p,f=r+h*p;s.push((0,Ht.jsx)("path",{className:"connector-curve",d:`M${a},${c}Q${m},${f} ${e},${t}`,fill:"none",stroke:o},"connector-line")),d=Math.atan2(f-c,m-a)}else s.push((0,Ht.jsx)("line",{x1:a,y1:c,x2:e,y2:t,stroke:o},"connector-line"));if("arrow"===n?.end){const e=10,t=16/180*Math.PI;s.push((0,Ht.jsx)("path",{d:`M${a},${c}L${a+e*Math.cos(d+t)},${c+e*Math.sin(d+t)}L${a+e*Math.cos(d-t)},${c+e*Math.sin(d-t)}Z`,fill:o,stroke:"none"},"connector-arrow"))}}return(0,Ht.jsx)("g",{className:"annotation-connector",children:s})}function Ut(e){const{x:t=0,y:n=0,dx:i,dy:o,nx:r,ny:s,note:a,connector:c,subject:l,type:d,color:u,className:h,disable:p,opacity:m,strokeDasharray:f,events:y={},"data-testid":g}=e,b=Array.isArray(t)?t[0]??0:t,x=Array.isArray(n)?n[0]??0:n,v=new Set(Array.isArray(p)?p:[]);let w=i||0,k=o||0;null!=r&&(w=r-b),null!=s&&(k=s-x);const M="string"==typeof d?d:"label";if("bracket"===M&&l&&0===w&&0===k)if(void 0!==l.width){w=l.width/2;const e=l.depth||30;k=e+(0>e?-5:5)}else if(void 0!==l.height){const e=l.depth||30;w=e+(0>e?-5:5),k=l.height/2}return(0,Ht.jsxs)("g",{className:("annotation "+(h||"")).trim(),transform:`translate(${b},${x})`,"data-testid":g,...null!=m&&{opacity:m},...f&&{strokeDasharray:f},...y,children:[!v.has("connector")&&Vt(w,k,c,u,M,l),!v.has("subject")&&Xt(M,l,u,b,x),!v.has("note")&&Gt(a,w,k,u)]})}function Kt(e){const{noteData:t}=e,{screenCoordinates:n}=t,i="string"==typeof t.type?t.type:"label",o=t.eventListeners||t.events||{};if(t.coordinates&&n){const e=t.nx||n[0][0]+(t.dx??0),o=t.ny||n[0][1]+(t.dy??0),r=n.map((n,r)=>{const s=Object.assign({},t,{note:0===r?t.note:{label:""},x:n[0],y:n[1],nx:e,ny:o});return(0,Ht.jsx)(Ut,{"data-testid":"semiotic-annotation",...s,type:i},"multi-annotation-"+r)});return(0,Ht.jsx)("g",{children:r})}const r=t.note||{title:"none",label:t.label},s=`${r.label}-${r.title}-${t.i}`;return(0,Ht.jsx)(Ut,{"data-testid":"semiotic-annotation",events:o,...t,type:i},s)}var Qt=require("d3-hierarchy"),Zt=require("d3-shape"),Jt=2;function en(e){const t=10**Jt;return Math.round(e*t)/t}function tn(e,t=2){const n=[],i=[],o=t+1;for(let t=0;o>t;t++){let r=0;for(const[n,i]of e)null!==i&&(r+=n**t*i);n.push(r);const s=[];for(let n=0;o>n;n++){let i=0;for(const[o,r]of e)null!==r&&(i+=o**(t+n));s.push(i)}i.push(s)}i.push(n);const r=function(e,t){const n=e,i=e.length-1,o=[t];for(let e=0;i>e;e++){let t=e;for(let o=e+1;i>o;o++)Math.abs(n[e][o])>Math.abs(n[e][t])&&(t=o);for(let o=e;i+1>o;o++){const i=n[o][e];n[o][e]=n[o][t],n[o][t]=i}for(let t=e+1;i>t;t++)for(let o=i;o>=e;o--)n[o][t]-=n[o][e]*n[e][t]/n[e][e]}for(let e=i-1;e>=0;e--){let t=0;for(let r=e+1;i>r;r++)t+=n[r][e]*o[r];o[e]=(n[i][e]-t)/n[e][e]}return o}(i,o).map(en);return{points:e.map(([e])=>[en(e),en(r.reduce((t,n,i)=>t+n*e**i,0))]),equation:[...r].reverse()}}function nn(e,t){const n=t.scales?.x??t.scales?.time;return n?null!=e.x?n(e.x):t.xAccessor&&null!=e[t.xAccessor]?n(e[t.xAccessor]):null:null}function on(e,t){const n=t.scales?.y??t.scales?.value;return n?null!=e.y?n(e.y):t.yAccessor&&null!=e[t.yAccessor]?n(e[t.yAccessor]):null:null}function rn(e){return null==e?null:e+""}function sn(e,t,n){return t.stickyPositionCache?.set(e,n),n}function an(e,t,n){const i=e.anchor||e.lifecycle?.anchor||"fixed";if("latest"===i){if(null!=e.pointId&&n.pointNodes&&n.pointNodes.length>0)for(let i=n.pointNodes.length-1;i>=0;i--){const o=n.pointNodes[i];if(o.pointId===e.pointId)return sn(t,n,{x:o.x,y:o.y})}const i=function(e){const t=e.data;if(!t||0===t.length)return null;const n=t[t.length-1],i=e.scales?.x??e.scales?.time,o=e.scales?.y??e.scales?.value;if(!i||!o)return null;const r=n[e.xAccessor||"x"],s=n[e.yAccessor||"y"];return null==r||null==s?null:{x:i(r),y:o(s)}}(n);return i?sn(t,n,i):null}if("semantic"===i){const i=function(e,t,n){const i=function(e){return rn(e.provenance?.stableId??e.stableId)}(e);if(!i)return null;const o=n.pointNodes?.find(e=>rn(e.pointId)===i);if(o)return sn(t,n,{x:o.x,y:o.y});const r=n.data?.find(e=>function(e){return rn(e.stableId??e.id??e.provenance?.stableId)}(e)===i);if(!r)return null;const s=nn(r,n),a=on(r,n);return null==s||null==a?null:sn(t,n,{x:s,y:a})}(e,t,n);if(i)return i}let o=null,r=null;if(null!=e.pointId&&n.pointNodes){const t=n.pointNodes.find(t=>t.pointId===e.pointId);t&&(o=t.x,r=t.y)}if(null!=o&&null!=r||(o=nn(e,n),r=on(e,n)),null!=o&&null!=r)return sn(t,n,{x:o,y:r});if("sticky"===i){const e=n.stickyPositionCache?.get(t);if(e)return e}return null}function cn(e,t,n,i=50){return!(-i>e||e>(n.width||0)+i||-i>t||t>(n.height||0)+i)}function ln(e){let t=1/0,n=-1/0;for(const i of e)t>i&&(t=i),i>n&&(n=i);return[t,n]}var dn=c(require("react")),[un,hn]=g(e=>({observations:[],maxObservations:100,version:0,pushObservation(t){e(e=>{const n=e.observations;return n.push(t),n.length>e.maxObservations&&n.shift(),{version:e.version+1}})},clearObservations(){e(()=>({observations:[],version:0}))}}));function pn(e,t={}){const n=function(e){const t=e.provenance,n=e.id??e.stableId??t?.stableId;return null==n||""===n?void 0:n+""}(e);return{"data-semiotic-annotation-widget":"",...n?{"data-semiotic-annotation-id":n}:{},onClickCapture(i){const o=function(e){const t=e.nativeEvent;return"touch"===t.pointerType?"touch":0===t.detail?"keyboard":"pointer"}(i);t.onAnnotationActivate?.({annotation:e,annotationId:n,chartId:t.chartId,inputType:o}),n&&t.onObservation&&t.onObservation({type:"annotation-activate",annotationId:n,inputType:o,timestamp:Date.now(),chartType:t.chartType??"unknown",chartId:t.chartId})}}}var mn=16,fn=20,yn=require("react/jsx-runtime"),gn="var(--semiotic-bg, #ffffff)",bn=.85;function xn(e){const{x:t,y:n,text:i,fill:o,fontSize:r=12,fontWeight:s,fontFamily:a,textAnchor:c="start",dominantBaseline:l,background:d,className:u}=e,h=function(e){return void 0===e||!0===e||"halo"===e?{type:"halo"}:!1===e||"none"===e?null:"box"===e?{type:"box"}:{type:e.type??"halo",...e}}(d),p=e=>(0,yn.jsx)("text",{x:t,y:n,textAnchor:c,dominantBaseline:l,fill:o,fontSize:r,fontWeight:s,fontFamily:a,className:u,...e?{stroke:e.stroke,strokeWidth:e.strokeWidth,paintOrder:"stroke"}:{},children:i});if(!h)return p();if("halo"===h.type)return p({stroke:h.fill??gn,strokeWidth:h.haloWidth??3});const m=h.padding??{x:6,y:3},f="number"==typeof m?m:m.x,y="number"==typeof m?m:m.y,g=function(e,t){return(e+"").length*t*.6}(i,r),b=r+2*y;let x,v;return x="middle"===c?t-g/2-f:"end"===c?t-g-f:t-f,v="middle"===l||"central"===l?n-b/2:"hanging"===l||"text-before-edge"===l?n-y:n-.8*r-y,(0,yn.jsxs)("g",{className:u,children:[(0,yn.jsx)("rect",{x:x,y:v,width:g+2*f,height:b,rx:h.radius??3,ry:h.radius??3,fill:h.fill??gn,fillOpacity:h.opacity??bn,stroke:h.stroke,strokeWidth:h.strokeWidth}),p()]})}var vn=require("react/jsx-runtime"),wn={linear:Zt.curveLinear,monotoneX:Zt.curveMonotoneX,monotoneY:Zt.curveMonotoneY,step:Zt.curveStep,stepAfter:Zt.curveStepAfter,stepBefore:Zt.curveStepBefore,basis:Zt.curveBasis,cardinal:Zt.curveCardinal,catmullRom:Zt.curveCatmullRom};var kn=new Set(["label","callout","callout-circle","callout-rect","text","widget"]);function Mn(e){return!!e&&"object"==typeof e&&kn.has(function(e){return"string"==typeof e?.type?e.type:""}(e))}new Set(["label","callout","callout-circle","callout-rect"]);var In=2e4,Sn=1;function jn(e){return"primary"===e?.emphasis||!0===e?.defensive}function An(e,t,n={}){return"number"==typeof n.maxAnnotations&&Number.isFinite(n.maxAnnotations)?Math.max(0,Math.floor(n.maxAnnotations)):e>0&&t>0?Math.max(1,Math.round(e*t/(n.areaPerAnnotation&&n.areaPerAnnotation>0?n.areaPerAnnotation:In))):1/0}function Cn(e){let t;const n=e?.emphasis;t="primary"===n?100:"secondary"===n?10:50;const i=e?.provenance?.confidence;switch("number"==typeof i&&Number.isFinite(i)&&(t+=15*Math.max(0,Math.min(1,i))),e?.lifecycle?.freshness){case"fresh":t+=8;break;case"aging":t+=4;break;case"stale":t+=1;break;case"expired":t-=200}return t}var Rn=32,$n=6,Pn=4,Bn=8,Dn=72,Tn=30,En=-30,On=8,Nn=480,Fn=3;var Wn={ai:"AI",agent:"agent",watcher:"watcher",system:"system",import:"imported",computed:"computed",user:"you"};function qn(e){if(!zn(e))return e;const t=("string"==typeof e.mobileText?e.mobileText:void 0)??("string"==typeof e.shortText?e.shortText:void 0);return!t||"string"!=typeof e.label&&null!=e.label?e:{...e,label:t}}function zn(e){return Mn(e)}function Ln(e,t){if(!e)return[];const n=Math.max(1,Math.floor(t/7)),i=e.split(/\s+/).filter(Boolean),o=[];let r="";for(const e of i)r&&r.length+e.length+1>n?(o.push(r),r=e):r=r?`${r} ${e}`:e;return r&&o.push(r),o}function Hn(e,t,n,i,o){const r=e+n,s=t+i;return Math.abs(n)>Math.abs(i)?{x:0>n?r-o.width-4:r+4,y:0>i?s-o.height:s,width:o.width,height:o.height}:{x:0>n?r-o.width:r,y:0>i?s-o.height-4:s+4,width:o.width,height:o.height}}function Yn(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function _n(e,t){return Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function Gn(e,t,n,i,o,r,s,a){const c=Yn(e,s);let l=.4*Math.hypot(t.dx,t.dy)+80*function(e,t,n,i){const o=Math.max(0,i-e.x),r=Math.max(0,i-e.y);return(o+Math.max(0,e.x+e.width-(t-i)))*e.height+(r+Math.max(0,e.y+e.height-(n-i)))*e.width}(c,o,r,a);for(const e of n)l+=12*_n(c,e);for(const e of i)l+=4*_n(c,e);return l}function Xn(e){const{annotations:t,context:n,defaultOffset:i=Rn,notePadding:o=$n,markPadding:r=Pn,edgePadding:s=Bn,preserveManualOffsets:a=!0,routeLongConnectors:c=!0,connectorThreshold:l=Dn,density:d,progressiveDisclosure:u=!1,redundantCues:h=!1,responsive:p,mobile:m,cohesion:f,audience:y}=e,g=n.width||0,b=n.height||0,x="object"==typeof m?m:{},v=x.breakpoint??Nn,w=!!m&&v>=g,k=w&&!1!==x.preferShortText?t.map(qn):t,M=w&&!d?{maxAnnotations:x.maxAnnotations??("callout-list"===x.strategy?1:2),minVisible:x.minVisible??1}:d,I=u||w&&(!1!==x.progressiveDisclosure||"callout-list"===x.strategy),S=w&&!p?x.responsive??{minWidth:v}:p,j=w&&!f?x.cohesion:f;if(0===k.length||0>=g||0>=b)return k.slice();const A=[],C=function(e,t){return(e.pointNodes||[]).map(e=>{const n=Math.max(1,e.r||1)+t;return{x:e.x-n,y:e.y-n,width:2*n,height:2*n}})}(n,r);let R=!1;const $=k.map((e,t)=>{if(!zn(e))return e;const r=function(e,t,n){if("widget"===e.type&&"number"==typeof e.px&&"number"==typeof e.py)return{x:e.px,y:e.py};const i=e.pointId??e.nodeId;if(null!=i&&n.pointNodes){const e=n.pointNodes.find(e=>e.pointId===i);if(e)return{x:e.x,y:e.y}}const o=e.coordinates,r=n.scales?.geoProjection;if(Array.isArray(o)&&o.length>=2&&r){const e=o[0],t=o[1];if("number"==typeof e&&"number"==typeof t){const n=r([e,t]);if(n&&"number"==typeof n[0]&&"number"==typeof n[1])return{x:n[0],y:n[1]}}}return n.scales||"number"!=typeof e.x||"number"!=typeof e.y?an(e,t,n):{x:e.x,y:e.y}}(e,t,n);if(!r)return e;const d=function(e){if("widget"===e.type)return{width:"number"==typeof e.width?e.width:32,height:"number"==typeof e.height?e.height:32};const t="number"==typeof e.wrap?e.wrap:120,n=[...Ln("string"==typeof e.title?e.title:void 0,t),...Ln("string"==typeof e.label?e.label:void 0,t)],i=n.reduce((e,t)=>Math.max(e,t.length),0);return{width:Math.max(24,Math.min(t,7*i)+10),height:Math.max(18,16*n.length+6)}}(e);if(a&&("number"==typeof(u=e).dx||"number"==typeof u.dy)){const t=function(e){return"text"===e.type||"widget"===e.type?{dx:0,dy:0}:{dx:Tn,dy:En}}(e);return A.push(Yn(Hn(r.x,r.y,"number"==typeof e.dx?e.dx:t.dx,"number"==typeof e.dy?e.dy:t.dy,d),o)),e}var u;let h=null,p=1/0;for(const e of function(e){const t=1.6*e;return[{dx:e,dy:-e},{dx:-e,dy:-e},{dx:e,dy:e},{dx:-e,dy:e},{dx:e,dy:0},{dx:-e,dy:0},{dx:0,dy:-e},{dx:0,dy:e},{dx:t,dy:-t},{dx:-t,dy:-t},{dx:t,dy:t},{dx:-t,dy:t}]}(i)){const t=Gn(Hn(r.x,r.y,e.dx,e.dy,d),e,A,C,g,b,o,s);p>t&&(h=e,p=t)}if(!h)return e;const m=Yn(Hn(r.x,r.y,h.dx,h.dy,d),o);A.push(m);const f=Math.hypot(h.dx,h.dy),y=c&&f>=l&&"text"!==e.type&&"widget"!==e.type?{...e.connector||{end:"arrow"},type:"curve"}:e.connector;return R=!0,{...e,dx:h.dx,dy:h.dy,...y?{connector:y}:{}}}),P=R?$:k.slice();let B=P;if(h){let e=!1;const t=P.map(t=>{const n=function(e){return"text"!==e.type||"string"!=typeof e.color||Math.hypot("number"==typeof e.dx?e.dx:0,"number"==typeof e.dy?e.dy:0)<On?e:{...e,_redundantConnector:!0}}(t);return n!==t&&(e=!0),n});B=e?t:P}{let e=!1;const t=B.map(t=>{if(!0!==t?.defensive)return t;const n=function(e){const t=e?.provenance;if(!t||"object"!=typeof t)return e;const n="string"==typeof t.source?Wn[t.source]??t.source:null,i="number"==typeof t.confidence&&Number.isFinite(t.confidence)?Math.round(100*Math.max(0,Math.min(1,t.confidence)))+"%":null;if(!n&&!i)return e;if(null!=e.label&&"string"!=typeof e.label)return e;const o=[n,i].filter(Boolean).join(" · "),r="string"==typeof e.label?e.label:"";return r.includes(`(${o})`)?e:{...e,label:r?`${r} (${o})`:`(${o})`}}(t);return n!==t&&(e=!0),n});B=e?t:B}const D=new Set;if(M){const e="object"==typeof M?M:{},t=function(e){if(!e)return 1;const t=function(e){const t=e?.familiarity;if(!t)return Fn;const n=Object.values(t).filter(e=>"number"==typeof e&&Number.isFinite(e));return 0===n.length?Fn:n.reduce((e,t)=>e+t,0)/n.length}(e);return t>2?4>t?1:.6:1.5}(y),n=1===t?e:{...e,maxAnnotations:Math.max(0,Math.round((e.maxAnnotations??An(g,b,e))*t))},{deferred:i}=function(e){const{annotations:t,width:n,height:i}=e,o=Math.max(0,e.minVisible??Sn),r=An(n,i,e),s=t.map((e,t)=>{return{annotation:e,index:t,note:(n=e,Mn(n))};var n}),a=s.filter(e=>e.note);if(0===a.length||r>=a.length)return{visible:t.slice(),deferred:[],budget:r};const c=a.filter(e=>jn(e.annotation)),l=a.filter(e=>!jn(e.annotation)).sort((e,t)=>Cn(t.annotation)-Cn(e.annotation)||e.index-t.index),d=Math.min(l.length,Math.max(Math.max(0,r-c.length),Math.max(0,o-c.length))),u=new Set([...c.map(e=>e.index),...l.slice(0,d).map(e=>e.index)]),h=[],p=[];for(const{annotation:e,index:t,note:n}of s)!n||u.has(t)?h.push(e):p.push(e);return{visible:h,deferred:p,budget:r}}({annotations:B,width:g,height:b,...n});for(const e of i)D.add(e)}if(S&&("object"==typeof S&&"number"==typeof S.minWidth?S.minWidth:Nn)>=g)for(const e of B)zn(e)&&"secondary"===e.emphasis&&D.add(e);if(D.size>0)for(const e of B)!0===e?.defensive&&D.delete(e);let T;return T=0===D.size?B:I?B.map(e=>D.has(e)?{...e,_annotationDeferred:!0}:e):B.filter(e=>!D.has(e)),j?function(e,t){let n=!1;const i=e.map(e=>zn(e)?"blended"===e.cohesion||"layer"===e.cohesion?e:(n=!0,{...e,cohesion:t}):e);return n?i:e}(T,j):T}var Vn=require("react/jsx-runtime");function Un(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Kn(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,Un(e))}))}function Qn(e){const{width:t,height:n,pointNodes:i=[],data:o}=e;return{scales:{x:(0,Je.scaleLinear)().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:(0,Je.scaleLinear)().domain([0,Math.max(1,n)]).range([0,Math.max(1,n)])},width:t,height:n,frameType:"network",pointNodes:i,data:o,xAccessor:"x",yAccessor:"y"}}function Zn(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}function Jn(e){const{width:t,height:n,totalWidth:i,totalHeight:o,margin:r,title:s,legend:a,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u,legendPosition:h="right",legendLayout:p,pointNodes:m=[],annotations:f,onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x,autoPlaceAnnotations:v,svgAnnotationRules:w,children:k}=e,M=function(e){const t=hn(e=>e.pushObservation),n=dn.useCallback(n=>{e.onObservation?.(n),t?.(n)},[e,t]);return dn.useMemo(()=>({...e,onObservation:n}),[n,e])}({onAnnotationActivate:y,onObservation:g,chartId:b,chartType:x}),I=Ze.useMemo(()=>Zn(f),[f]),S=Ze.useMemo(()=>Qn({width:t,height:n,pointNodes:m}),[n,m,t]),j=Ze.useMemo(()=>I&&v?Xn({annotations:I,context:S,..."object"==typeof v?v:{}}):I,[S,v,I]),A=Ze.useMemo(()=>function(e,t={}){return function(e,n,i){switch(e.type){case"label":case"callout":case"callout-circle":case"callout-rect":{const t=an(e,n,i);if(!t)return null;const{x:o,y:r}=t;if(!cn(o,r,i))return null;const s="callout"===e.type?"callout-circle":e.type,a="callout-circle"===s?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===s?{width:e.width,height:e.height}:void 0;return(0,vn.jsx)(Kt,{noteData:{x:o,y:r,dx:e.dx??30,dy:e.dy??-30,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:s,...a?{subject:a}:{},connector:e.connector||{end:"arrow"},color:e.color,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-"+n)}case"x-threshold":{const t=nn(null!=e.value?{...e,x:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"top";let s;s="bottom"===r?(i.height||0)-4:"center"===r?(i.height||0)/2:mn;const a=t>.6*(i.width||0),c=a?t-4:t+4,l=a?"end":"start";return(0,vn.jsxs)("g",{opacity:e.opacity,children:[(0,vn.jsx)("line",{x1:t,y1:0,x2:t,y2:i.height||0,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,vn.jsx)(xn,{x:c,y:s,text:e.label,textAnchor:l,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"y-threshold":{const t=on(null!=e.value?{...e,y:e.value}:e,i);if(null==t)return null;const o=e.color||"#f97316",r=e.labelPosition||"right";let a,c;"left"===r?(a=4,c="start"):"center"===r?(a=(i.width||0)/2,c="middle"):(a=(i.width||0)-4,c="end");const l=fn>(s=t)?Math.min((i.height||0)-4,s+mn):s-4;return(0,vn.jsxs)("g",{opacity:e.opacity,children:[(0,vn.jsx)("line",{x1:0,y1:t,x2:i.width||0,y2:t,stroke:o,strokeWidth:e.strokeWidth||1.5,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,vn.jsx)(xn,{x:a,y:l,text:e.label,textAnchor:c,fill:o,fontSize:12,fontWeight:"bold",background:e.labelBackground??"halo"})]},"ann-"+n)}case"enclose":{const t=(e.coordinates||[]).map(e=>({x:nn({...e,type:"point"},i),y:on({...e,type:"point"},i),r:1})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=(0,Qt.packEnclose)(t),r=e.padding||10;return(0,vn.jsxs)("g",{children:[(0,vn.jsx)("circle",{cx:o.x,cy:o.y,r:o.r+r,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,vn.jsx)(xn,{x:o.x,y:o.y-o.r-r-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"rect-enclose":{const t=(e.coordinates||[]).map(e=>({x:nn({...e,type:"point"},i),y:on({...e,type:"point"},i)})).filter(e=>null!=e.x&&null!=e.y);if(2>t.length)return null;const o=e.padding||10,r=t.map(e=>e.x),s=t.map(e=>e.y),[a,c]=ln(r),[l,d]=ln(s),u=a-o,h=c+o,p=l-o;return(0,vn.jsxs)("g",{children:[(0,vn.jsx)("rect",{x:u,y:p,width:h-u,height:d+o-p,fill:e.fill||"none",fillOpacity:e.fillOpacity||.1,stroke:e.color||"var(--semiotic-text-secondary, #666)",strokeWidth:1.5,strokeDasharray:"4,2"}),e.label&&(0,vn.jsx)(xn,{x:(u+h)/2,y:p-4,textAnchor:"middle",fill:e.color||"var(--semiotic-text-secondary, #666)",fontSize:12,text:e.label,background:e.labelBackground??"none"})]},"ann-"+n)}case"highlight":{const t=i.data||[],o="function"==typeof e.filter?t.filter(e.filter):e.field&&null!=e.value?t.filter(t=>t[e.field]===e.value):[],r={stroke:e.color||"#f97316",strokeWidth:2,fill:"none"};return(0,vn.jsx)("g",{children:o.map((t,n)=>{const o=nn(t,i),s=on(t,i);if(null==o||null==s)return null;const a="function"==typeof e.r?e.r(t):e.r||6,c="function"==typeof e.style?e.style(t):e.style||r;return(0,vn.jsx)("circle",{cx:o,cy:s,r:a,...c},"hl-"+n)})},"ann-"+n)}case"bracket":{const t=nn(e,i),o=on(e,i);return(0,vn.jsx)(Kt,{noteData:{x:t??0,y:o??0,dx:e.dx||0,dy:e.dy||0,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:"bracket",subject:{type:e.bracketType||"curly",width:e.width,height:e.height,depth:e.depth||30},color:e.color}},"ann-"+n)}case"trend":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s="ordinal"===i.frameType,a="horizontal"===i.projection,c=s?o:null,l=s?r:null;let d;const u=[],h=new Map;if(s&&c&&l){for(const e of t){const t=e[c];if(null==t)continue;const n=t+"";h.has(n)||(h.set(n,u.length),u.push(n))}d=t.map(e=>{const t=e[c],n=e[l];if(null==t||null==n)return null;const i=h.get(t+"");return null!=i?[i,+n]:null}).filter(e=>null!==e)}else d=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]);if(2>d.length)return null;const p=i.scales?.x??i.scales?.time,m=i.scales?.y??i.scales?.value;if(!p||!m)return null;const f=e=>t=>{const n=Math.max(0,Math.floor(t)),i=Math.min(u.length-1,n+1),o=t-n,r=e(u[n]);return r+(e(u[i])-r)*o},y=p,g=m;let b;if(s)if(a){const e=f(g);b=(t,n)=>[y(n),e(t)]}else{const e=f(y);b=(t,n)=>[e(t),g(n)]}else b=(e,t)=>[y(e),g(t)];const x=e.method||"linear";let v;if("loess"===x)v=function(e,t=.3){const n=e.length;if(2>n)return e.slice();const i=e.slice().sort((e,t)=>e[0]-t[0]),o=i.map(e=>e[0]),r=i.map(e=>e[1]),s=Math.max(2,Math.ceil(t*n)),a=[];for(let e=0;n>e;e++){const t=o[e],i=o.map(e=>Math.abs(e-t)),c=i.slice().sort((e,t)=>e-t)[Math.min(s-1,n-1)]||1,l=[];for(let e=0;n>e;e++){const t=0===c?0:i[e]/c;l[e]=1>t?Math.pow(1-Math.pow(t,3),3):0}let d=0,u=0,h=0,p=0,m=0;for(let e=0;n>e;e++){const t=l[e];0!==t&&(d+=t,u+=t*o[e],h+=t*r[e],p+=t*o[e]*o[e],m+=t*o[e]*r[e])}if(0===d){a.push([t,r[e]]);continue}const f=d*p-u*u;if(1e-12>Math.abs(f))a.push([t,h/d]);else{const e=(d*m-u*h)/f;a.push([t,(h-e*u)/d+e*t])}}return a}(d,e.bandwidth??.3);else{const t="polynomial"===x?tn(d,e.order||2):function(e){const t=[0,0,0,0];let n=0;for(const[i,o]of e)null!==o&&(n++,t[0]+=i,t[1]+=o,t[2]+=i*i,t[3]+=i*o);const i=n*t[2]-t[0]*t[0],o=0===i?0:en((n*t[3]-t[0]*t[1])/i),r=en(t[1]/n-o*t[0]/n);return{points:e.map(([e])=>[en(e),en(o*e+r)]),equation:[o,r]}}(d);v=t.points}const w=v.map(([e,t])=>{const[n,i]=b(e,t);return`${n},${i}`}).join(" "),k=e.color||"#6366f1",M=v[v.length-1],[I,S]=b(M[0],M[1]);return(0,vn.jsxs)("g",{children:[(0,vn.jsx)("polyline",{points:w,fill:"none",stroke:k,strokeWidth:e.strokeWidth||2,strokeDasharray:e.strokeDasharray||"6,3"}),e.label&&(0,vn.jsx)("text",{x:I+4,y:S-4,fill:k,fontSize:11,children:e.label})]},"ann-"+n)}case"band":{const t=i.scales?.y??i.scales?.value,s=t?.domain?.(),a=e.y0??s?.[0],c=e.y1??s?.[1],l=null!=a&&t?t(a):0,d=null!=c&&t?t(c):i.height||0,u=ce(e.fill,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,vn.jsxs)("g",{opacity:e.opacity,children:[u.def&&(0,vn.jsx)("defs",{children:u.def}),(0,vn.jsx)("rect",{x:0,y:Math.min(l,d),width:i.width||0,height:Math.abs(d-l),fill:u.fill,fillOpacity:e.fillOpacity||.1}),e.label&&(0,vn.jsx)(xn,{x:(i.width||0)-4,y:(o=l,r=d,Math.max(Math.min(o,r),0)+mn),textAnchor:"end",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"x-band":{const t=i.scales?.x??i.scales?.time,o=t?.domain?.(),r=e.x0??o?.[0],s=e.x1??o?.[1],a=null!=r&&t?t(r):null,c=null!=s&&t?t(s):null;if(null==a||null==c)return null;const l=ce(e.fill||e.color,"ann-"+n,"var(--semiotic-primary, #6366f1)");return(0,vn.jsxs)("g",{opacity:e.opacity,children:[l.def&&(0,vn.jsx)("defs",{children:l.def}),(0,vn.jsx)("rect",{x:Math.min(a,c),y:0,width:Math.abs(c-a),height:i.height||0,fill:l.fill,fillOpacity:e.fillOpacity??.1}),e.label&&(0,vn.jsx)(xn,{x:Math.min(a,c)+4,y:mn,textAnchor:"start",fill:e.color||"var(--semiotic-primary, #6366f1)",fontSize:11,fontWeight:"bold",text:e.label,background:e.labelBackground??"halo"})]},"ann-"+n)}case"envelope":{const t=i.data||[];if(2>t.length)return null;const o=i.xAccessor||"x",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=e.upperAccessor||"upperBounds",c=e.lowerAccessor||"lowerBounds",l=e.filter,d=t.filter(e=>null!=e[a]&&null!=e[c]&&!(l&&!l(e))).sort((e,t)=>e[o]-t[o]);if(2>d.length)return null;const u=wn[i.curve||"linear"]||Zt.curveLinear,h=(0,Zt.area)().x(e=>r(e[o])).y0(e=>s(e[c])).y1(e=>s(e[a])).curve(u)(d);if(!h)return null;const p=e.fill||"#6366f1";return(0,vn.jsxs)("g",{children:[(0,vn.jsx)("path",{d:h,fill:p,fillOpacity:e.fillOpacity??.15,stroke:"none"}),e.label&&d.length>0&&(0,vn.jsx)("text",{x:r(d[d.length-1][o])+4,y:s(d[d.length-1][a])-4,fill:p,fontSize:11,children:e.label})]},"ann-"+n)}case"anomaly-band":{const t=i.data||[];if(2>t.length)return null;const o=i.yAccessor||"y",r=i.scales?.x??i.scales?.time,s=i.scales?.y??i.scales?.value;if(!r||!s)return null;const a=t.map(e=>e[o]).filter(e=>null!=e&&isFinite(e));if(2>a.length)return null;const c=a.reduce((e,t)=>e+t,0)/a.length,l=a.reduce((e,t)=>e+(t-c)**2,0)/a.length,d=Math.sqrt(l),u=e.threshold??2,h=c-u*d,p=!1!==e.showBand,m=e.fill||"#6366f1",f=e.fillOpacity??.1,y=e.anomalyColor||"#ef4444",g=e.anomalyRadius??6,b=s(c+u*d),x=s(h),v=t.filter(e=>{const t=e[o];return null!=t&&Math.abs(t-c)>u*d});return(0,vn.jsxs)("g",{children:[p&&(0,vn.jsx)("rect",{x:0,y:Math.min(b,x),width:i.width||0,height:Math.abs(x-b),fill:m,fillOpacity:f}),v.map((e,t)=>{const n=nn(e,i),o=on(e,i);return null==n||null==o?null:(0,vn.jsx)("circle",{cx:n,cy:o,r:g,fill:y,fillOpacity:.7,stroke:y,strokeWidth:1.5},"anomaly-"+t)}),e.label&&(0,vn.jsx)("text",{x:(i.width||0)-4,y:Math.min(b,x)-4,textAnchor:"end",fill:m,fontSize:11,children:e.label})]},"ann-"+n)}case"forecast":{const t=i.data||[];if(3>t.length)return null;const o=i.xAccessor||"x",r=i.yAccessor||"y",s=i.scales?.x??i.scales?.time,a=i.scales?.y??i.scales?.value;if(!s||!a)return null;const c=t.map(e=>[e[o],e[r]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]);if(3>c.length)return null;let l;if("polynomial"===(e.method||"linear")){const t=tn(c,e.order||2).equation;l=e=>t.reduce((t,n,i)=>t+n*Math.pow(e,i),0)}else{const e=c.length;let t=0,n=0,i=0,o=0;for(const[e,r]of c)t+=e,n+=r,i+=e*e,o+=e*r;const r=e*i-t*t;if(1e-12>Math.abs(r))return null;const s=(e*o-t*n)/r,a=(n-s*t)/e;l=e=>a+s*e}const d=c.length,u=c.map(([e,t])=>t-l(e)),h=u.reduce((e,t)=>e+t*t,0),p=Math.sqrt(h/Math.max(d-2,1)),m=c.reduce((e,t)=>e+t[0],0)/d,f=c.reduce((e,t)=>e+(t[0]-m)**2,0),y=e.confidence??.95,g=.99>y?.95>y?.9>y?1:1.645:1.96:2.576,b=e.steps??5,x=c[d-1][0],v=(x-c[0][0])/Math.max(d-1,1),w=[];for(let e=1;b>=e;e++)w.push(x+e*v);const k=[];for(const e of w){const t=l(e),n=p*Math.sqrt(1+1/d+(f>0?(e-m)**2/f:0))*g;k.push({x:e,yCenter:t,yUpper:t+n,yLower:t-n})}const M=`M${k.map(e=>`${s(e.x)},${a(e.yUpper)}`).join(" L")} L${k.slice().reverse().map(e=>`${s(e.x)},${a(e.yLower)}`).join(" L")} Z`,I=k.map(e=>`${s(e.x)},${a(e.yCenter)}`).join(" "),S=`${s(x)},${a(l(x))}`,j=e.strokeColor||"#6366f1";return(0,vn.jsxs)("g",{children:[(0,vn.jsx)("path",{d:M,fill:e.fill||"#6366f1",fillOpacity:e.fillOpacity??.15,stroke:"none"}),(0,vn.jsx)("polyline",{points:`${S} ${I}`,fill:"none",stroke:j,strokeWidth:e.strokeWidth??2,strokeDasharray:e.strokeDasharray??"6,3"}),e.label&&k.length>0&&(0,vn.jsx)("text",{x:s(k[k.length-1].x)+4,y:a(k[k.length-1].yCenter)-4,fill:j,fontSize:11,children:e.label})]},"ann-"+n)}case"widget":{let o,r;if(null!=e.px&&null!=e.py)o=e.px,r=e.py;else{const t=an(e,n,i);if(!t)return null;o=t.x,r=t.y}if(!cn(o,r,i))return null;const s=e.dx??0,a=e.dy??0,c=e.width??32,l=e.height??32,d=e.content??(0,vn.jsx)("span",{style:{fontSize:18,cursor:"default"},title:e.label||"Info",children:"ℹ️"});return(0,vn.jsx)("foreignObject",{x:o+s-c/2,y:r+a-l/2,width:c,height:l,style:{overflow:"visible",pointerEvents:"auto"},children:(0,vn.jsx)("div",{...pn(e,t),style:{width:c,height:l,display:"flex",alignItems:"center",justifyContent:"center"},children:d})},"ann-"+n)}case"text":{const t=an(e,n,i);if(!t)return null;const{x:o,y:r}=t,s=o+(e.dx||0),a=r+(e.dy||0),c=e.color||"var(--semiotic-text, #333)",l=(0,vn.jsx)("text",{x:s,y:a,fill:c,fontSize:e.fontSize||11,opacity:e.opacity,strokeDasharray:e.strokeDasharray,dominantBaseline:"middle",style:{fontFamily:"inherit"},children:e.label});return!0!==e._redundantConnector?Lt.cloneElement(l,{key:"ann-text-"+n}):(0,vn.jsxs)("g",{opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:[(0,vn.jsx)("line",{x1:o,y1:r,x2:s,y2:a,stroke:c,strokeWidth:1,strokeOpacity:.5,style:{pointerEvents:"none"}}),Lt.cloneElement(l,{opacity:void 0,strokeDasharray:void 0})]},"ann-text-"+n)}case"category-highlight":{const t=e.category;if(null==t)return null;const o=e=>"function"==typeof e&&"function"==typeof e.bandwidth,r=i.scales?.o,s=i.scales?.x,a=i.scales?.y,c=o(r)?r:o(s)?s:o(a)?a:null;if(!c)return null;const l=c(t+"");if(null==l)return null;const d=c.bandwidth(),u=e.color||"var(--semiotic-primary, #4589ff)",h=e.opacity??.15,p=e.label;return(0,vn.jsxs)("g",(i.projection?"vertical"===i.projection:c===s)?{children:[(0,vn.jsx)("rect",{x:l,y:0,width:d,height:i.height||0,fill:u,fillOpacity:h}),p&&(0,vn.jsx)(xn,{x:l+d/2,y:mn,textAnchor:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]}:{children:[(0,vn.jsx)("rect",{x:0,y:l,width:i.width||0,height:d,fill:u,fillOpacity:h}),p&&(0,vn.jsx)(xn,{x:12,y:l+d/2,dominantBaseline:"middle",fill:u,fontSize:12,fontWeight:"bold",text:p,background:e.labelBackground??"none"})]},"ann-"+n)}default:return null}var o,r,s}}(0,M),[M]),C=j?function(e,t,n,i){const o=[];return e.forEach((e,r)=>{let s;if(n){const o=n(e,r,i);s=null!=o?o:t(e,r,i)}else s=t(e,r,i);s&&o.push({node:s,annotation:e})}),function(e){const t=e.map((e,t)=>{return{p:e,i:t,emphasis:(n=e.annotation,"primary"===n?.emphasis||"secondary"===n?.emphasis?n.emphasis:null),confidence:qt(e.annotation),readingOrder:null,rank:Rt};var n}),n=t.some(e=>null!=e.emphasis||null!=e.confidence),i=e.some(e=>Ft(e.annotation)),o=e.some(e=>null!=Wt(e.annotation)),r=e.some(e=>"layer"===Wt(e.annotation));if(!n&&!i&&!o)return e.map(e=>e.node);const s=t.filter(e=>null==e.emphasis&&null!=e.confidence).slice().sort((e,t)=>(t.confidence??0)-(e.confidence??0)||e.i-t.i);s.forEach((e,t)=>{e.readingOrder=t,e.rank=$t-t/Math.max(1,s.length)});for(const e of t)e.emphasis&&(e.rank=Ct[e.emphasis]);const a=t.sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>{const{p:t,i:n,emphasis:i,readingOrder:o}=e,r=Ft(t.annotation);let s=t.node;if("primary"===i||"secondary"===i||null!=o){const e=null==i&&null!=o;s=(0,At.jsx)("g",{className:e?"annotation-emphasis annotation-emphasis--inferred":"annotation-emphasis annotation-emphasis--"+i,..."secondary"===i?{opacity:Pt,fontSize:Bt}:{},...e?{opacity:zt(o),"data-annotation-reading-order":o}:{},children:t.node},"annotation-emphasis-"+n)}const a=Wt(t.annotation);return a&&(s=(0,At.jsx)("g",{className:"annotation-cohesion--"+a,children:s},"annotation-cohesion-"+n)),r&&(s=(0,At.jsx)("g",{className:"annotation-deferred","data-annotation-disclosure":"deferred",children:s},"annotation-deferred-"+n)),s});return i&&a.unshift((0,At.jsx)("style",{children:Ot},"annotation-disclosure-style")),r&&a.unshift((0,At.jsx)("style",{children:Nt},"annotation-cohesion-style")),a}(o)}(j,A,w,S):null,R=!0===j?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return(0,Vn.jsxs)(Vn.Fragment,{children:[R?(0,Vn.jsx)("style",{children:Ot},"physics-annotation-disclosure-style"):null,(0,Vn.jsxs)("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:i,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[(0,Vn.jsxs)("g",{transform:`translate(${r.left},${r.top})`,children:[C,k]}),s&&"string"==typeof s?(0,Vn.jsx)("text",{x:i/2,y:16,textAnchor:"middle",fontWeight:600,fill:"var(--semiotic-text, #333)",className:"semiotic-chart-title",style:{fontSize:"var(--semiotic-title-font-size, 14px)"},children:s}):s?(0,Vn.jsx)("foreignObject",{x:0,y:0,width:i,height:Math.max(r.top,28),children:s}):null,a?jt({legend:a,totalWidth:i,totalHeight:o,margin:r,legendPosition:h,legendLayout:p,title:s,legendHoverBehavior:c,legendClickBehavior:l,legendHighlightedCategory:d,legendIsolatedCategories:u}):null]})]})}var ei=2500;function ti(e){return"function"==typeof e}function ni(e){return void 0===e||!1===e||!ti(e.binAccessor)&&!ti(e.labelAccessor)&&!ti(e.valueAccessor)}function ii(e){if(void 0!==e){if(!1===e)return!1;if(!ni(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function oi(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function ri(e){return function(e){return!ti(e?.timeAccessor)}(e)}function si(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:n,sediment:i,...o}=e;return{...o,observation:oi(n),sediment:ii(i)}}var ai={};function ci(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var li=class{constructor(e=function(){const e="string"==typeof ai.url&&ai.url?new URL("./physicsWorker.js",ai.url):function(e){if("undefined"!=typeof __filename){const t=__filename.replace(/\\/g,"/"),n=t.startsWith("/")?t:"/"+t;return new URL("./"+e,"file:"+n)}throw Error("Cannot resolve module worker asset: "+e)}("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,n=this.pending.get(t.requestId);n&&(this.pending.delete(t.requestId),n.cleanup(),t.ok?n.resolve(t.payload):n.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(ci());const n=this.nextRequestId;this.nextRequestId+=1;const i={command:e,requestId:n};return new Promise((e,o)=>{const r=()=>{this.pending.delete(n),t?.removeEventListener("abort",r),o(ci())},s=()=>t?.removeEventListener("abort",r);this.pending.set(n,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(i)}catch(e){this.pending.delete(n),s(),o(e)}})}async init(e,t,n,i){if(!ri(n))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:si(e),initialSpawns:t,initialSpawnPacing:n},i);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const n=await this.request({type:"restore",snapshot:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame restore response");return n.frame}async initFromSnapshot(e,t,n){const i=await this.request({type:"init",config:si(e),snapshot:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame init response");return i.frame}async enqueue(e,t,n){if(!ri(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const i=await this.request({type:"enqueue",spawns:e,pacing:t},n);if("frame"!==i.type)throw Error("Physics worker returned a non-frame enqueue response");return i.frame}async tick(e,t){const n=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame tick response");return n.frame}async settle(e,t){const n=await this.request({type:"settle",maxSteps:e},t);if("frame"!==n.type)throw Error("Physics worker returned a non-frame settle response");return n.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const n=await this.request({type:"remove",ids:e},t);if("removed"!==n.type)throw Error("Physics worker returned a non-remove response");return{frame:n.frame,removed:n.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,n]of this.pending)this.pending.delete(t),n.cleanup(),n.reject(e)}};function di(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var ui={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},hi=1e-9,pi=.005;function mi(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function fi(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function yi(e,t,n){return Math.max(t,Math.min(n,e))}function gi(e){return 0>e?-1:1}function bi(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,n=e.shape.height/2;return{minX:e.x-t,minY:e.y-n,maxX:e.x+t,maxY:e.y+n}}function xi(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,n=t.height/2;return{minX:t.x-e,minY:t.y-n,maxX:t.x+e,maxY:t.y+n}}const n=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-n,minY:Math.min(t.y1,t.y2)-n,maxX:Math.max(t.x1,t.x2)+n,maxY:Math.max(t.y1,t.y2)+n}}function vi(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function wi(e,t,n,i,o,r,s,a){const c=o-e,l=(n+s)/2-Math.abs(c);if(0>=l)return null;const d=r-t,u=(i+a)/2-Math.abs(d);return u>0?u>l?{nx:gi(c),ny:0,penetration:l}:{nx:0,ny:gi(d),penetration:u}:null}function ki(e,t,n,i,o,r,s){const a=r/2,c=s/2;let l=e-yi(e,i-a,i+a),d=t-yi(t,o-c,o+c);const u=l*l+d*d;if(u>n*n)return null;if(hi>=u){const r=Math.abs(e-(i-a)),s=Math.abs(e-(i+a)),u=Math.abs(t-(o-c)),h=Math.abs(t-(o+c)),p=Math.min(r,s,u,h);return p===r?(l=-1,d=0,{nx:l,ny:d,penetration:n+r}):p===s?(l=1,d=0,{nx:l,ny:d,penetration:n+s}):p===u?(l=0,d=-1,{nx:l,ny:d,penetration:n+u}):(l=0,d=1,{nx:l,ny:d,penetration:n+h})}const h=Math.sqrt(u);return{nx:l/h,ny:d/h,penetration:n-h}}function Mi(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,n,i,o,r){const s=i-e,a=o-t,c=n+r,l=s*s+a*a;if(l>=c*c)return null;if(hi>=l)return{nx:1,ny:0,penetration:c};const d=Math.sqrt(l);return{nx:s/d,ny:a/d,penetration:c-d}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return wi(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const n=ki(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return n?{nx:-n.nx,ny:-n.ny,penetration:n.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?ki(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function Ii(e,t){const n=t.shape;return"aabb"===n.type?"circle"===e.shape.type?ki(e.x,e.y,e.shape.radius,n.x,n.y,n.width,n.height):wi(n.x,n.y,n.width,n.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,n,i,o,r,s,a=0){const c=r-i,l=s-o,d=c*c+l*l,u=d>hi?yi(((e-i)*c+(t-o)*l)/d,0,1):0,h=n+a/2,p=e-(i+c*u),m=t-(o+l*u),f=p*p+m*m;if(f>=h*h)return null;if(hi>=f){const e=Math.sqrt(d);return e>hi?{nx:-l/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const y=Math.sqrt(f);return{nx:p/y,ny:m/y,penetration:h-y}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,n.x1,n.y1,n.x2,n.y2,n.thickness??0)}function Si(e,t){return`${e}\0${t}`}function ji(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Ai(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:mi(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function Ci(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function Ri(e){return{id:e.id,shape:fi(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:Ci(e.bodyFilter),index:e.index}}function $i(e,t){return!!t?.some(t=>Object.is(e,t))}function Pi(e,t){const n=e.bodyFilter;if(!n)return!0;if("function"==typeof n)return n(t);const i=function(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(t,n.property);return!("equals"in n&&!Object.is(i,n.equals)||"notEquals"in n&&Object.is(i,n.notEquals)||n.oneOf&&!$i(i,n.oneOf)||n.notOneOf&&$i(i,n.notOneOf))}var Bi=class{constructor(e={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...ui,...e},this.random=di(this.options.seed)}init(e={}){this.options={...ui,...e},this.random=di(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(hi,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:mi(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))ji(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:fi(t.shape),bodyFilter:Ci(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,n){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=n/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const n=this.sortedBodies();for(const e of n)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of n)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const n=i/t;e.vx*=n,e.vy*=n}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(n),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(n,o,0===e),this.resolveColliders(n,r,0===e);this.updateSensors(n),this.updateSleeping(n,t)}settle(e=1200,t=this.options.fixedDt){let n=0;for(;e>n&&!this.allSleeping();)this.step(t),n+=1;return n}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:mi(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(ji)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(Ai),colliders:this.sortedColliders().map(Ri),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){this.options={...e.options,gravity:{...e.options.gravity}},this.random=di(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=Ai(t);this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=Ri(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const n=this.bodies.get(t.bodyId);if(!n||n.sleeping)continue;const i="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!i)continue;const o=i.x-n.x,r=i.y-n.y,s=Math.sqrt(o*o+r*r);if(hi>=s)continue;const a=o/s,c=r/s,l=(s-t.restLength)*t.stiffness+((("vx"in i?i.vx:0)-n.vx)*a+(("vy"in i?i.vy:0)-n.vy)*c)*t.damping;n.vx+=l*a*e/n.mass,n.vy+=l*c*e/n.mass}}resolveBodyPairs(e,t,n){for(const i of t){const[t,o]=i.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=Mi(r,s);a&&(this.resolveDynamicCollision(r,s,a),n&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),n=new Map;for(let i=0;e.length>i;i+=1){if(!1===e[i].bodyCollisions)continue;const o=bi(e[i]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=n.get(o);r?r.push(i):n.set(o,[i])}}const i=new Set;for(const t of Array.from(n.keys()).sort()){const o=n.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let n=t+1;o.length>n;n+=1){const r=o[t],s=o[n];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&vi(bi(e[r]),bi(e[s]))&&i.add(`${r}:${s}`)}}return Array.from(i).sort((e,t)=>{const[n,i]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return n===o?i-r:n-o})}resolveDynamicCollision(e,t,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const i=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=i+o;if(hi>=r)return;const s=Math.max(0,n.penetration-pi)/r;e.x-=n.nx*s*i,e.y-=n.ny*s*i,t.x+=n.nx*s*o,t.y+=n.ny*s*o;const a=(t.vx-e.vx)*n.nx+(t.vy-e.vy)*n.ny;if(a>0)return;const c=Math.abs(a),l=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*a/r,d=l*n.nx,u=l*n.ny;e.vx-=d*i,e.vy-=u*i,t.vx+=d*o,t.vy+=u*o,this.applyFriction(e,t,n,l,i,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,n,i,o,r){const s=-n.ny,a=n.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,l=o+r;if(hi>=Math.abs(c)||hi>=l)return;const d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),u=yi(-c/l,-i*d,i*d),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,n){for(const i of e)for(const e of t){if(!Pi(e,i))continue;if(!vi(bi(i),xi(e)))continue;const t=Ii(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),n&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,n){e.x+=n.nx*Math.max(0,n.penetration-pi),e.y+=n.ny*Math.max(0,n.penetration-pi);const i=e.vx*n.nx+e.vy*n.ny;if(0>i){const o=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+o)*i*n.nx,e.vy-=(1+o)*i*n.ny;const r=-n.ny,s=n.nx,a=e.vx*r+e.vy*s,c=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,n=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=bi(i);for(const o of n){if(!Pi(o,i))continue;if(!vi(e,xi(o)))continue;if(!Ii(i,o))continue;const n=Si(o.id,i.id);t.add(n),this.activeSensors.has(n)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:n,bodyId:i}=ji(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:n})}this.activeSensors=t}updateSleeping(e,t){const n=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e)Math.sqrt(i.vx*i.vx+i.vy*i.vy)>=this.options.sleepSpeed||Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY))>=this.options.sleepSpeed*t||n&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,i.sleeping||this.options.sleepAfter>i.sleepTime||(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}contactOpposesGravity(e,t){const{x:n,y:i}=this.options.gravity,o=Math.hypot(n,i);return 1e-9>=o||-.2>(e*n+t*i)/o}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},Di=class{constructor(e={}){this.id="builtin",this.capabilities={...(new Bi).capabilities,engine:"builtin"},this.world=new Bi(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function Ti(e={}){return new Di(e)}function Ei(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):Ti(t)}var Oi=["binId","targetBin","category","windowIndex","lane","group"];function Ni(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const n=t-e.mean;e.mean+=n/e.count,e.m2+=n*(t-e.mean)}function Fi(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Wi(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function qi(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function zi(e,t,n){return"function"==typeof e?e(t,n):"string"==typeof e?qi(t,e):void 0}function Li(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Hi(e){const t=Fi(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:Fi(e.x),y:Fi(e.y),value:t}}var Yi=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const n=Li(zi(this.config.binAccessor,e,t))??function(e){for(const t of Oi){const n=Li(qi(e,t));if(n)return n}return"sediment"}(e),i=Li(zi(this.config.labelAccessor,e,t))??n,o=function(e,t,n){if("number"==typeof e)return e;const i="function"==typeof e?e(t,n):"string"==typeof e?qi(t,e):1,o="number"==typeof i?i:Number(i);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(n);return s||(s={id:n,label:i,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(n,s)),s.label=i,s.lastBodyId=e.id,s.lastDatum=e.datum,Ni(s.x,e.x),Ni(s.y,e.y),Ni(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Hi(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Hi)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Wi(t.x),y:Wi(t.y),value:Wi(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function _i(e,t={}){const{baselineY:n=0,binWidth:i=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const l=Math.max(0,e[s]/c*r),d=a?.(e,t)??t*(i+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:d,y:n-l,width:i,height:l,meanX:e.x.mean,meanY:e.y.mean}})}function Gi(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function Xi(e){const t=Math.max(0,Math.floor(e.liveBodies)),n=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+n,o=Gi(e.bodyLimit),r=Gi(e.engineMaxBodiesHint),s=function(e,t,n){if(!1===n)return;const i=Gi(n?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>i?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:n,state:c,warnAt:s}}var Vi={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Ui={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Ki(e={},t=Ui){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function Qi(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function Zi(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function Ji(e,t){if(null!=e[t])return e[t];const n=e.datum;return n&&"object"==typeof n?n[t]:void 0}function eo(e){return{...Qi(e),sequence:e.sequence,spawnAt:e.spawnAt}}function to(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function no(e){return!1!==e&&{...e}}function io(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function oo(e){return{...e,gravity:{...e.gravity}}}function ro(e,t,n,i){if("circle"===e.shape.type){const o=e.x-t,r=e.y-n,s=e.shape.radius+i,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(n-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>i*i?null:s}function so(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ao(e,t={}){const{idPrefix:n="plot",includeFloor:i=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,l=[],d=e.x+e.width/2,u=e.y+e.height/2;return i&&l.push({id:n+"-floor",shape:{type:"aabb",x:d,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&l.push({id:n+"-ceiling",shape:{type:"aabb",x:d,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&l.push({id:n+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&l.push({id:n+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),l}function co(e){const{idPrefix:t="bin",count:n,domainStart:i,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:l=!0,includeInteriorWalls:d=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],f=s+(a-s)/2,y=Math.abs(a-s),g=l?n:n-1;if(d||l)for(let e=l?0:1;g>=e;e+=1){if(!d&&e>0&&n>e)continue;const s=r(i+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:f,width:c,height:y}})}if(null!=u)for(let e=0;n>e;e+=1){const n=i+e*o,s=n+o;if(s>=u)continue;const a=r(n),l=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,l)+c/2,y1:h,x2:Math.max(a,l)-c/2,y2:h,thickness:p}})}return m}var lo={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function uo(e,t){const n={...e};for(const e of t)n[lo[e]]++;return n}function ho(e,t,n){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:uo(n,i)}}var po=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=ho({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const n=ho(e,t,this.revisions);this.revisions=n.revisions,this.latest=n;for(const e of[...this.listeners])e();return n}},mo=require("d3-quadtree"),fo=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,n,i,o,r=0){const s=this.ensure(e,t);if(!s)return null;let a=null,c=1/0;const l=Math.max(0,r)+this.maxSearchRadius,d=i-l,u=i+l,h=o-l,p=o+l;return s.visit((e,t,s,l,m)=>{if(d>l||t>u||h>m||s>p)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e){const t=ro(e,i,o,Math.max(0,r));null!=t&&(c>t||t===c&&n.indexOf(e.id)>n.indexOf(a?.id??""))&&(a=e,c=t)}f=f.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const n=e.readState();return 0===n.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=n.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=(0,mo.quadtree)().x(e=>e.x).y(e=>e.y).addAll(n),this.revision=t,this.tree)}},yo=["data","scene-geometry","data-paint","accessibility","evidence"],go=["scene-geometry","data-paint","accessibility","evidence"],bo=["overlay","accessibility","evidence"],xo=(e,t)=>({retainedData:e,invalidations:t}),vo=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],wo=["scene-geometry","data-paint","accessibility","evidence"],ko=[],Mo={engine:xo("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:xo("preserve",wo),colliders:xo("preserve",wo),sediment:xo("preserve",wo),bodyBudget:xo("preserve",vo),bodyLimit:xo("preserve",vo),eviction:xo("preserve",vo),fixedDt:xo("preserve",ko),maxDeltaSeconds:xo("preserve",ko),maxSubsteps:xo("preserve",ko),settleStepLimit:xo("preserve",ko),timeScale:xo("preserve",ko),observation:xo("preserve",ko)},Io=xo("preserve",vo);function So(e){let t="preserve";const n=new Set;for(const i of e){const e=Mo[i]??Io;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)n.add(t)}return{retainedData:t,invalidations:n}}var jo=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function Ao(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&jo.every(n=>e[n]===t[n])}function Co(e,t,n,i){return e||!t?"paused":n||!i?"running":"settled"}var Ro=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,n){if(n>0)return void(this.seconds=0);const i=e.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,t):0}},$o=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new fo,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new po,this.simulationState="settled",this.visible=!0,this.quiescence=new Ro;const{bodyBudget:t,colliders:n,engine:i,kernel:o,observation:r,sediment:s,...a}=e;this.config={...Vi,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=Ki(r),this.sediment=new Yi(s??!1),this.world=Ei(i,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),n&&this.world.setColliders(to(n))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(n=>"kernel"===n?!Ao(e.kernel,t.kernel):e[n]!==t[n])}(e,this.configInput),{colliders:n,bodyBudget:i,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=Ei(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!Ao(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=Ki(s,this.observation)),this.sediment.updateConfig(a),n&&(this.world.setColliders(to(n)),this.revision+=1),this.configInput={...this.configInput,...e};const l=So(t);this.updateResults.record({kind:"config",keys:t},l.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(to(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},So(["colliders"]).invalidations)}enqueue(e,t){const n=Array.isArray(e)?e:[e],i=t?function(e,t={}){const n=Zi(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,n)=>function(e,t,n){return"function"==typeof n?Zi(n(e,t)):"string"==typeof n?Zi(Ji(e,n)):Zi(e.spawnAt)??Zi(Ji(e,"arrivalTime"))??Zi(Ji(e,"timestamp"))??Zi(Ji(e,"time"))??Zi(Ji(e,"eventTime"))}(e,n,t.timeAccessor)),o=i.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=Zi(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=i[t],s=null==o?0:Math.max(0,o-r);return{...Qi(e),spawnAt:n+s/a}})}if("object"==typeof i){const t=Zi(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...Qi(e),spawnAt:n+i/t}))}return e.map(e=>({...Qi(e),spawnAt:n}))}(n,{...t,startAt:t.startAt??this.elapsedSeconds}):n;for(const e of i)this.queue.push({...Qi(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(io),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?yo:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Qi(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},yo)}materializeDueSpawns(){const e=this.revision,t=[],n=[];return this.spawnDue(t,n),0===t.length||(this.observeBodyBudget(n),this.evictOverflow(n),this.syncSimulationState(n),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?yo:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},yo)}tick(e){const t=this.revision,n=[],i=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,n,i,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(n,s);const c=this.observeBodyBudget(s),l=this.evictOverflow(s);i.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(s),this.accumulator+=a;let d=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>d;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,d+=1}d===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,n.length),(d>0||n.length>0||i.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(d,n,i,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:d},this.revision!==t?n.length||i.length||o.length?yo:go:[]),u}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t){const n=this.revision,i=[],o=[],r=[],s=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,o,r,s,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const c=this.observeBodyBudget(a),l=this.evictOverflow(a);o.push(...l.evicted),r.push(...l.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const d=t?{spawned:i,evicted:o,sedimented:r,events:s,observations:a}:{spawned:i},{steps:u,budget:h}=function(e,t,n){let i,o=0;for(;t>o&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,n.observations),t.length>0){n.spawned.push(...t),i=e.observeBodyBudget(n.observations);const o=e.evictOverflow(n.observations);n.evicted?.push(...o.evicted),n.sedimented?.push(...o.sedimented)}e.step(e.fixedDt);const r=e.drainEvents();n.events&&(n.events.push(...r),e.observeKernelEvents(r,n.observations),e.observeSensorTransitions(n.observations)),o+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:o,budget:i}}(this.settleHost(),e,d),p=i.length+o.length+r.length>0;(u>0||p||s.length>0)&&(this.revision+=1);const m=this.result(u,i,o,r,s,a??[],void 0,h??c);return this.updateResults.record({kind:"settle",count:u},this.revision===n?[]:p?yo:go),m}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return _i(this.readSediment(),e)}hitTest(e,t,n=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:n,chartId:i,...o}=e,r={...o,timestamp:t??this.elapsedSeconds,chartType:n??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?bo:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?bo:[])}remove(e){const t=new Set(e),n=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>n.has(e)||i.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?yo:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},go),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},go)}applyImpulse(e,t,n){this.world.applyImpulse(e,t,n),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},go)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,n,i)=>e.applyImpulse(t,n,i),clear:()=>e.clear(),hitTest:(t,n,i)=>e.hitTest(t,n,i),pause:()=>e.setPaused(!0),push:(t,n)=>e.enqueue(t,n),pushMany:(t,n)=>e.enqueue(t,n),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:no(this.bodyBudget),config:{...this.config,kernel:oo(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(eo),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:no(e.bodyBudget??{}),kernel:oo(e.world.options)},this.bodyBudget=no(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(eo).sort(io),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Co(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},yo)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const n=this.queue.shift();if(!n)return;this.spawnOne(n,t),e.push(n.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const n=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:n?.datum??e.datum,x:n?.x??e.x,y:n?.y??e.y},t)}result(e,t,n,i,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:n,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,n){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);n.emit({type:"physics-settle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,n){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:i,bodyId:r}=so(t),s=n.observation.sensors[i],a=o.get(r);n.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:s?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())i.has(e)||r("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const n of e)t.has(so(n).bodyId)&&e.delete(n)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return Xi({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const n=`${t.state}:${t.action}`;return n===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=n,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=Co(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const n=this.simulationState;this.simulationState=t,function(e,t,n){n.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||n.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,simulationState:t,previousSimulationState:e})}(n,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:n,liveBodyOrder:i}=function(e,t,n,i,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===n)return s;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const l=function(e,t,n){if("sleeping-first"!==t)return n.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),o=[],r=[];for(const e of n)i.get(e)?o.push(e):r.push(e);return[...o,...r]}(e,n,o),d=l.slice(0,c);if(0===d.length)return s;const u=function(e,t,n,i){const o=new Map(e.readState().map(e=>[e.id,e])),r=[];for(const e of n){const n=o.get(e);if(!n)continue;const s=t.add(n);s&&(r.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:n.datum,x:n.x,y:n.y,binId:s.id,count:s.count,total:s.total}))}return r}(e,t,d,r);e.remove(d);const h=new Set(d);return{evicted:d,sedimented:u,liveBodyOrder:o.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:n}}};function Po(e,t,n){const i=new $o(e);return t?.length&&(i.enqueue(t,n),i.materializeDueSpawns()),i}function Bo(){return"undefined"!=typeof performance?performance.now():Date.now()}var Do=c(require("react-dom/server"));function To(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Eo={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Oo(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function No(e,t){const n="function"==typeof t?t(e):t;return{...Eo,...n??{}}}function Fo(e,t={}){const n=e.settle(t.maxSteps),i=e.readBodies(),o=e.snapshot(),r=function(e,t={}){return e.map(e=>function(e,t={}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),i={label:t.getBodyLabel?.(e)??Oo(e)},o={style:No(e,t.bodyStyle),datum:n,accessibleDatum:n,accessibility:i,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...o}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...o}}(e,t))}(i,t),s=function(e,t={}){const n=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),i=n.filter(e=>e.sleeping).length,o=e.queue.length,r=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===o&&i===n.length,a=[];o>0&&a.push("PHYSICS_QUEUE_UNDRAINED");const c=null!=t.charge&&Number.isFinite(t.charge)?function(e,t,n,i){const o=e-(t+n+i);return{charge:e,live:t,queued:n,sedimented:i,unaccounted:o,balanced:0===o}}(t.charge,n.length,o,r):void 0;return c&&!c.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:n.length,sleepingCount:i,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:To(t.projectionRows),queuedCount:o,sedimentedCount:r,...c?{ledger:c}:{},warnings:a}}(o,{bodies:i,projectionRows:t.projectionRows,stepsRun:n,charge:t.charge});return{snapshot:o,bodies:i,sceneNodes:r,evidence:s,stepsRun:n}}var Wo=require("react/jsx-runtime"),qo={top:0,right:0,bottom:0,left:0};function zo(e,t,n){return"function"==typeof e?e({size:t,margin:n}):e}function Lo(e,t){if("function"==typeof t){const n=t(e);return Number.isFinite(n)&&n>0?Number(n):1}const n=e.datum;if(t&&n&&"object"==typeof n){const e=Number(n[t]);if(Number.isFinite(e)&&e>0)return e}const i=Number(n?.work??n?.reviewWork??n?.value);return Number.isFinite(i)&&i>0?i:1}function Ho(e,t){if("function"==typeof t){const n=t(e);if(null!=n&&(n+"").length>0)return n+""}else if(t){const n=_o(e.datum,t),i=_o(e,t),o=n??i;if(null!=o&&(o+"").length>0)return o+""}return e.id}function Yo(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const n=Math.max(0,Math.min(1,t))*(e.length-1),i=Math.floor(n);return e[i]+(e[Math.ceil(n)]-e[i])*(n-i)}function _o(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Go(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=_o(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Xo(e){const t=e.regionId,n=Math.max(0,e.unitsPerSecond),i=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),l=e.releaseImpulse??{x:90,y:0},d=new Map,u=new Map,h=new Map,p=new Map,m=new Map,f=new Map,y=new Map,g=[];let b=0,x=new Map,v=new Map,w=0,k=0,M=0,I=null,S=0,j=0,A=0,C=0,R=0,$=0,P=0,B=0,D=0,T=0,E=0,O=0,N=-1,F=!1;function W(e,n){const i=n(e);return!!i&&i.activeRegionIds.includes(t)}function q(){O+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function L(n,i,o,r){const s={bodyId:n.id,jobId:i.jobId,visitId:i.visitId,visit:i.visit,remaining:i.work,total:i.work,queuedAt:i.queuedAt,sequence:r};return d.set(i.jobId,s),y.delete(n.id),f.set(n.id,i.jobId),j+=1,A+=i.work,q(),function(n,i,o){const r=z(i);e.onQueued?.(n,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:n.id,datum:n.datum,x:n.x,y:n.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,queueDepth:d.size})}(n,s,o),s}function H(e){if(d.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const n of t){if(d.size>=s)break;const t=m.get(n.jobId);t&&h.has(n.jobId)?(u.delete(n.jobId),y.delete(n.bodyId),L(t,n,e,n.sequence)):u.delete(n.jobId)}}function Y(){let e=0;for(const t of d.values())e+=t.remaining;return e}function _(){D=Math.max(D,d.size),T=Math.max(T,Y())}function G(){const e=M-a,t=Math.max(0,Math.min(a,M-(I??M)));let i=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;i+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const n=t.end-t.start;c+=n>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/n):t.processedWork}const l=t>0?o/t:0;return{seconds:t,arrivals:i,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?i/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&n>0?Math.max(0,Math.min(1,c/(n*t))):0,pressure:n>0?l/n:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:i=>{const o=i.controls.readBodies(),r=new Map,j=new Map;for(const t of o){if(r.set(t.id,t),!W(t.id,i.getRegionState))continue;if(!Go(t,e.bodyFilter))continue;const n=Ho(t,e.jobKey),o=j.get(n)??[];o.push(t),j.set(n,o)}const A=Number.isFinite(i.dt)?Math.max(0,i.dt):0;if(!F){const e=Number.isFinite(i.elapsed)?Math.max(0,i.elapsed):A;M=Math.max(0,e-A),F=!0}const D=M,T=D+A;M=T,I=null==I?D:Math.min(I,D);const O={start:D,end:T,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},Y=new Map;for(const[e,t]of j){const n=h.get(e)?.bodyId,i=t.find(e=>e.id===n)??t[0];Y.set(e,i),m.set(e,i)}for(const[n,o]of h){if(Y.has(n))continue;const s=d.get(n),a=r.get(o.bodyId)??m.get(n);if(s){d.delete(n),f.delete(s.bodyId),P+=1,B+=s.remaining,q();const r={...z(s),abandonedAt:M,remainingWork:s.remaining,queueSeconds:Math.max(0,M-s.queuedAt)};a&&e.onAbandoned?.(a,r),i.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:n,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:M,queueSeconds:r.queueSeconds,queueDepth:d.size})}u.delete(n),y.delete(o.bodyId),h.delete(n),m.delete(n)}for(const[n,o]of Y){if(h.has(n))continue;const r=(p.get(n)??0)+1;p.set(n,r);const a=Lo(o,e.unitAccessor),c={bodyId:o.id,jobId:n,visitId:`${t}:${n}:${r}`,visit:r,regionId:t,work:a,queuedAt:M};h.set(n,c),S+=1,O.arrivals+=1,O.arrivalWork+=a;const l=b++;if(s>d.size)L(o,c,i,l);else{const s={...c,blockedAt:M,sequence:l};u.set(n,s),y.set(o.id,n),$+=1,q(),e.onBlocked?.(o,s),i.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:n,visitId:c.visitId,visit:r,queuedAt:M,blockedAt:M,queueDepth:d.size,blockedDepth:u.size})}}H(i),_();const G=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);let X=n*A;for(const n of G){if(0>=X)break;const o=Math.min(n.remaining,X);if(n.remaining-=o,X-=o,C+=o,O.processedWork+=o,n.remaining>1e-6)continue;d.delete(n.jobId),f.delete(n.bodyId),k+=1,R+=n.total,O.completions+=1,O.completedWork+=n.total;const s=Math.max(0,M-n.queuedAt);E+=s,q();const a=r.get(n.bodyId);if(!a)continue;i.controls.applyImpulse(n.bodyId,l.x??0,l.y??0);const c={...z(n),completedAt:M,queueSeconds:s};e.onProcessed?.(a,c),i.controls.recordObservation({type:"physics-capacity-processed",bodyId:n.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,completedAt:M,queueSeconds:s,queueDepth:d.size})}H(i),_(),function(){const e=Array.from(d.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=M-a;for(;g.length>0&&t>g[0].end;)g.shift()}(O);const V=Math.floor(M/c);V!==N&&(N=V,q())},getSnapshot:()=>{const e=Y(),i=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=d.size,r=Array.from(d.values()).map(e=>Math.max(0,M-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:k,unitsPerSecond:n,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+i,blockedDepth:u.size,blockedWork:i,arrivalCount:S,admittedCount:j,admittedWork:A,processedWork:C,completedWork:R,blockedCount:$,abandonedCount:P,abandonedWork:B,peakQueueDepth:D,peakRemainingWork:T,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:Yo(r,.5),p95Seconds:Yo(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:k>0?E/k:0,window:G(),simulatedAt:M,metricRevision:O}},bodyForce:e=>{if("none"===i)return null;const n=f.get(e.body.id),s=y.get(e.body.id),a=n?d.get(n):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const l=a?x.get(e.body.id):v.get(e.body.id);if(null==l)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-l*(.15*o))-e.body.x)*r,y:(h.y-(l-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*r*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function Vo(e,t){if(!t)return;let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}function Uo(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const n=Vo(e,t.property);return!("equals"in t&&!Object.is(n,t.equals)||"notEquals"in t&&Object.is(n,t.notEquals)||t.oneOf&&!t.oneOf.some(e=>Object.is(n,e))||t.notOneOf&&t.notOneOf.some(e=>Object.is(n,e)))}function Ko(e){const t=e.resources.map(e=>({...e,bodyId:e.bodyId??e.id})),n=new Map(t.map(e=>[e.bodyId,e])),i=new Map,o=new Map,r=e.assignmentForce??.45,s=e.returnForce??.35,a=e.caseAttraction??.08,c=e.assignmentOffset??{x:0,y:0};let l=new Map,d=0,u=0;return{id:e.id??"service-resource-pool",continuous:!0,assign:e=>{const n=i.get(e);if(n)return n;const r=t.find(e=>!o.has(e.id));if(!r)return null;const s={resourceId:r.id,resourceBodyId:r.bodyId,caseBodyId:e,assignedAt:d};return i.set(e,s),o.set(r.id,s),u+=1,s},release:e=>{const t=i.get(e);return!!t&&(i.delete(e),o.delete(t.resourceId),u+=1,!0)},getAssignment:e=>i.get(e),tick:e=>{d=Math.max(d,e.elapsed),l=new Map(e.controls.readBodies().map(e=>[e.id,e]));for(const[e,t]of i)l.has(e)&&l.has(t.resourceBodyId)||(i.delete(e),o.delete(t.resourceId),u+=1)},getSnapshot:()=>({total:t.length,available:t.length-o.size,assigned:o.size,assignments:Array.from(i.values()),simulatedAt:d,metricRevision:u}),bodyForce:e=>{const t=n.get(e.body.id);if(t){const n=o.get(t.id),i=n?l.get(n.caseBodyId):void 0,a=n?r:s;return{x:((i?i.x+(c.x??0):t.home.x)-e.body.x)*a,y:((i?i.y+(c.y??0):t.home.y)-e.body.y)*a}}const d=i.get(e.body.id);if(!d||0>=a)return null;const u=l.get(d.resourceBodyId);return u?{x:(u.x-e.body.x)*a,y:(u.y-e.body.y)*a}:null}}}function Qo(e,t){const n="function"==typeof t.deadlineAccessor?t.deadlineAccessor(e):Vo(e.datum,t.deadlineAccessor)??Vo(e,t.deadlineAccessor);return Number.isFinite(Number(n))?Math.max(0,Number(n)):0}function Zo(e){const t=new Map;let n=0,i=0;function o(n){t.set(n.bodyId,n),i+=1,e.onStateChange?.({...n})}function r(e){const i=t.get(e);return!(!i||null!=i.completedAt||(o({...i,completedAt:n,state:"unhappy"===i.state?"resolved-unhappy":"resolved"}),0))}return{id:e.id??"service-level",continuous:!0,protect:e=>{const i=t.get(e);return!(!i||null!=i.completedAt||"unhappy"===i.state||(o({...i,state:"protected",protectedAt:n}),0))},complete:r,getCase:e=>t.get(e),tick:i=>{n=Math.max(n,i.elapsed);for(const s of i.controls.readBodies()){if(!Uo(s,e.bodyFilter))continue;if(!t.has(s.id)){const t=Qo(s,e);o({bodyId:s.id,openedAt:n,deadlineAt:n+t,state:"waiting"})}const a=t.get(s.id);a&&null==a.completedAt&&(e.completionRegionId&&i.getRegionState(s.id)?.activeRegionIds.includes(e.completionRegionId)?r(s.id):"waiting"!==a.state||a.deadlineAt>n||o({...a,state:"unhappy"}))}},getSnapshot:()=>{const e=Array.from(t.values()),o=t=>e.filter(e=>e.state===t).length;return{total:e.length,waiting:o("waiting"),protected:o("protected"),unhappy:o("unhappy"),resolved:o("resolved"),resolvedUnhappy:o("resolved-unhappy"),simulatedAt:n,metricRevision:i}}}}function Jo(e){const t=new Set;let n=0,i=0,o=0,r=!1;return{id:e.id??"dependency-gate:"+e.regionId,continuous:!0,tick:s=>{n=Math.max(n,s.elapsed);const a=r;var c;c=n,r=e.isOpen?e.isOpen(c):null!=e.opensAt&&c>=e.opensAt;const l=s.controls.readBodies(),d=new Map(l.map(e=>[e.id,e]));for(const n of l){const i=s.getRegionState(n.id)?.activeRegionIds.includes(e.regionId);i&&Uo(n,e.bodyFilter)&&(r||t.has(n.id)||(t.add(n.id),o+=1,e.onHeld?.(n)))}if(r&&!a){for(const n of t){const t=d.get(n);t&&(s.controls.applyImpulse(n,e.releaseImpulse?.x??86,e.releaseImpulse?.y??0),i+=1,e.onReleased?.(t))}t.clear(),o+=1}for(const e of t)d.has(e)||(t.delete(e),o+=1)},getSnapshot:()=>({regionId:e.regionId,isOpen:r,blocked:t.size,released:i,simulatedAt:n,metricRevision:o}),bodyForce:n=>{if(r||!t.has(n.body.id))return null;const i=n.regions?.find(t=>t.id===e.regionId),o=i?.shape;if(!o||"aabb"!==o.type)return{x:.8*-n.body.vx,y:.8*-n.body.vy};const s=e.holdForce??.4;return{x:(o.x-n.body.x)*s-.45*n.body.vx,y:(o.y-n.body.y)*s-.45*n.body.vy}}}}function er(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function tr(e){if(!e?.length)return null;const t=e.slice(),n=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:n,onTick:(e,n,i)=>{const o={result:e,controls:n,dt:i.dt,elapsed:i.elapsed,getRegionState:i.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let n=null;for(const i of t)i.bodyForce&&(n=er(n,i.bodyForce(e)));return n}}}function nr(e){const t=new Set,n=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:i=>{const o=i.controls.readBodies();for(const r of o){const o=i.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),i.controls.applyImpulse(r.id,n.x??0,n.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}var ir=require("react");function or(){return"undefined"==typeof document||!document.hidden}var rr=require("react/jsx-runtime"),sr="var(--semiotic-focus, #005fcc)";function ar({active:e,hoverPoint:t,margin:n,size:i,shape:o="circle",width:r,height:s,pathData:a}){if(!e||!t)return null;const c=t.x+n.left,l=t.y+n.top;let d;if("geoarea"!==o&&"path"!==o||!a)if("rect"===o&&null!=r&&null!=s){const e=Math.max(r,4),t=Math.max(s,4);d=(0,rr.jsx)("rect",{x:c-e/2-3,y:l-t/2-3,width:e+6,height:t+6,rx:3,fill:"none",stroke:sr,strokeWidth:2,strokeDasharray:"4,2"})}else d=(0,rr.jsx)("circle","wedge"===o?{cx:c,cy:l,r:12,fill:"none",stroke:sr,strokeWidth:2.5,strokeDasharray:"6,3"}:{cx:c,cy:l,r:8,fill:"none",stroke:sr,strokeWidth:2,strokeDasharray:"4,2"});else d=(0,rr.jsx)("g",{transform:`translate(${n.left},${n.top})`,children:(0,rr.jsx)("path",{d:a,fill:"none",stroke:sr,strokeWidth:2.5,strokeDasharray:"6,3"})});return(0,rr.jsx)("svg",{style:{position:"absolute",left:0,top:0,width:i[0],height:i[1],pointerEvents:"none",zIndex:2},"aria-hidden":"true",children:d})}var cr=require("react"),lr={sceneGeometry:0,layout:0,domain:0};function dr(e){const{domain:t,layout:n,sceneGeometry:i}=e.revisions;return{domain:t,layout:n,sceneGeometry:i}}function ur(e,t){return{sceneGeometry:Math.max(e.sceneGeometry,t.sceneGeometry),layout:Math.max(e.layout,t.layout),domain:Math.max(e.domain,t.domain)}}var hr="production"!==process.env.NODE_ENV,pr={revisions:lr,signature:"",sawSignals:!1,wasUnconsumed:!1,warnUnconsumed:!1},mr=class{constructor(e="scene host"){this.hostName=e,this.lastConsumed=lr,this.lastObserved=lr,this.lastDuplicateWarning="",this.lastUnconsumedWarning=""}observeUpdateResult(e){hr&&(this.lastObserved=ur(this.lastObserved,dr(e)))}beforeCompute(e,t){if(!hr)return pr;const n=ur(dr(e),this.lastObserved),i=function(e){return`${e.sceneGeometry}|${e.layout}|${e.domain}`}(n),o=!((r=n).sceneGeometry===(s=this.lastConsumed).sceneGeometry&&r.layout===s.layout&&r.domain===s.domain);var r,s;return{revisions:n,signature:i,sawSignals:e.changed.has("scene-geometry")||e.changed.has("layout")||e.changed.has("domain"),wasUnconsumed:o,warnUnconsumed:!t&&o&&this.lastUnconsumedWarning!==i}}afterCompute(e,t,n){if(hr){if(t&&e.wasUnconsumed&&(this.lastConsumed=e.revisions),e.warnUnconsumed&&!t)return console.warn(`[semiotic] ${this.hostName} observed scene-affecting revisions without a scene rebuild: ${e.signature}.`),void(this.lastUnconsumedWarning=e.signature);t&&e.sawSignals&&!e.wasUnconsumed&&!n&&this.lastDuplicateWarning!==e.signature?(console.warn(`[semiotic] ${this.hostName} performed scene rebuild with unchanged scene revisions: ${e.signature}.`),this.lastDuplicateWarning=e.signature):t&&!e.sawSignals&&(this.lastDuplicateWarning="")}}},fr=(0,cr.memo)(function({store:e,diagnostics:t}){return(0,cr.useEffect)(()=>{const n=()=>t.observeUpdateResult(e.getUpdateSnapshot());return n(),e.subscribeUpdateResult(n)},[t,e]),null}),yr=(c(require("react")),c(require("react"))),gr=(require("react/jsx-runtime"),yr.createContext(null)),br=require("react/jsx-runtime"),xr={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0};function vr({hoverPoint:e}){let t="";if(e){const n=e.data||e;t="object"==typeof n?"Data point: "+Object.entries(n).filter(([,e])=>"object"!=typeof e&&"function"!=typeof e).map(([e,t])=>`${e}: ${t}`).join(", "):"Data point: "+n}return(0,br.jsx)("div",{"aria-live":"polite","aria-atomic":"true",style:xr,children:t})}var wr=require("react/jsx-runtime");function kr({summary:e}){return e?(0,wr.jsx)("div",{role:"note",style:xr,children:e}):null}function Mr({tableId:e}){return(0,wr.jsx)("a",{href:"#"+e,style:xr,onClick:t=>{t.preventDefault();const n=document.getElementById(e);n&&requestAnimationFrame(()=>n.focus())},onFocus:e=>{Object.assign(e.currentTarget.style,{position:"absolute",width:"auto",height:"auto",overflow:"visible",clip:"auto",whiteSpace:"normal",padding:"4px 8px",background:"var(--semiotic-bg, #fff)",color:"var(--semiotic-text, #000)",border:"2px solid var(--semiotic-focus, #005fcc)",borderRadius:"4px",zIndex:"10",fontSize:"12px",top:"4px",left:"4px"})},onBlur:e=>{const t=e.currentTarget;t.removeAttribute("style"),Object.assign(t.style,xr)},children:"Skip to data table"})}function Ir(e,t,n){const i=function(e,t){if(null==t)return;const n=ue(e,t,"");return""===n?void 0:n}(e,n.fill)??"#4e79a7",o=n.stroke,r=n.strokeWidth??0,s=n.opacity??1,a=n.fillOpacity??1,c=function(e,t){const n=t.mark;if(n)return n;const i=e.datum,o=i?.__physicsMark??i?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}(t,n),l="circle"===t.shape.type?n.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=s,e.beginPath(),"pill"===c||"square"===c||"aabb"===t.shape.type){const n="pill"===c?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,i="pill"===c?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,o=t.x-n/2,r=t.y-i/2,s="pill"===c?i/2:Math.min(4,n/4);e.moveTo(o+s,r),e.arcTo(o+n,r,o+n,r+i,s),e.arcTo(o+n,r+i,o,r+i,s),e.arcTo(o,r+i,o,r,s),e.arcTo(o,r,o+n,r,s),e.closePath()}else if("diamond"===c)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===c){const n=6;for(let i=0;n>i;i+=1){const o=2*Math.PI*i/n-Math.PI/2,r=t.x+Math.cos(o)*l,s=t.y+Math.sin(o)*l;0===i?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);i&&(e.save(),e.globalAlpha*=a,e.fillStyle=i,e.fill(),e.restore()),"halo"===c&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=o??i,e.lineWidth=Math.max(1.5,r||1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),o&&r>0&&(e.strokeStyle=o,e.lineWidth=r,n.strokeDasharray&&e.setLineDash(n.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function Sr(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function jr(e){return e.sensorId??"stream-region-"+e.id}function Ar(e){const t=jr(e),n={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const i=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...n,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:i}},{...n,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:i}},{...n,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:i}},{...n,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:i}}]}return e.collider?[{...n,id:t+"-collider",shape:e.shape}]:[]}function Cr(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function Rr(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}function $r(e){if(!1===e.semanticItem)return null;const t=e.shape,n=e.semanticItem??{},i="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...i,...n,id:n.id??i.id}}function Pr(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function Br(e,t){const n="function"==typeof e?e(t):e;if(!n)return null;const i=Number(n.x??0),o=Number(n.y??0);return Number.isFinite(i)||Number.isFinite(o)?{x:Number.isFinite(i)?i:0,y:Number.isFinite(o)?o:0}:null}var Dr=[];function Tr(e){const t=e.store.controls(),n=e.store.snapshot(),i=Math.max(0,e.result.steps*(n.config.fixedDt||1/60)),o=function(e,t,n,i){const o=Number.isFinite(i)?Math.max(0,i):0;if(0>=o||!Pr(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const i=n.get(t.id);if(!i||!i.activeRegionIds.size)continue;const s=Cr(i);if(s)for(const n of i.activeRegionIds){const i=r.get(n);if(!i)continue;const c=Rr(i.force,{body:t,region:i,regionState:s}),l=Number(i.damping??0),d=(c?.x??0)*o-(Number.isFinite(l)?t.vx*l*o:0),u=(c?.y??0)*o-(Number.isFinite(l)?t.vy*l*o:0);(d||u)&&(e.applyImpulse(t.id,d,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,i),r=function(e,t,n,i,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(n.map(e=>[e.id,e])),c=e.readBodies();let l=!1;for(let n=0;c.length>n;n+=1){const r=c[n],d=i.get(r.id),u=Cr(d);let h=Dr;if(d&&d.activeRegionIds.size>0){const e=[];for(const t of d.activeRegionIds){const n=a.get(t);n&&e.push(n)}h=e}const p=Br(t,{body:r,bodies:c,index:n,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,f=(p.y??0)*s;(m||f)&&(e.applyImpulse(r.id,m,f),l=!0)}return l}(t,e.bodyForces,e.regionEffects,e.regionState,n.simulationState,i);return e.composed&&e.composed.onTick(e.result,t,{dt:i,elapsed:e.result.elapsedSeconds,getRegionState:t=>Cr(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:n}}function Er(e,t,n,i,o,r,s,a,c,l){const d=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:d,simulationState:t,regionState:r,regions:s},h="function"==typeof n?n(e,u):n,p=s.reduce((t,n)=>n.bodyStyle?{...t,..."function"==typeof n.bodyStyle?n.bodyStyle(e,u):n.bodyStyle}:t,{}),m=d?"function"==typeof i?i(e,u):i:void 0;return{fill:l?.color??a,stroke:l?.stroke??c,strokeWidth:l?.strokeWidth??1,opacity:l?.opacity??.9,...h,...p,...m}}var Or=require("react");function Nr(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Fr(e,t){const n="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,Nr(e.thickness)??Nr(n)??Nr(t.thickness)??4)}var Wr=c(require("react")),qr=require("react/jsx-runtime"),zr={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Lr="semiotic-accessible-data-table",Hr=Lr+" semiotic-accessible-data-table-hidden",Yr=Lr+" semiotic-accessible-data-table-visible",_r={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},Gr={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Xr={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},Vr={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},Ur={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},Kr={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},Qr={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},Zr={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function Jr(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function es(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function ts(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function ns(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function is(e){const t=os(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function os(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const n=Jr(t);return null==n?null:[e,n]}).filter(e=>null!=e).slice(0,8):[]}function rs({hover:e}){const t=os(e.data);return(0,qr.jsxs)("div",{className:"semiotic-tooltip",style:De,children:[(0,qr.jsx)("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>(0,qr.jsxs)("div",{children:[(0,qr.jsxs)("span",{style:{opacity:.72},children:[e,": "]}),(0,qr.jsx)("span",{children:t})]},e))]})}function ss(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const n=Jr(t);return null==n?null:`${e}: ${n}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function as(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],n=new Map;for(const t of e)t.group&&n.set(t.group,(n.get(t.group)??0)+1);return n.size&&t.push(Array.from(n).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function cs(e){const{chartTitle:t,items:n,tableId:i}=e,[o,r]=Wr.useState(!1),[s,a]=Wr.useState(5),c=yr.useContext(gr),l=c?.visible??!1,d=o||l,u=Wr.useRef(null),h="Data summary for "+(t??"physics chart");Wr.useEffect(()=>{d||a(5)},[d]);const p=Wr.useCallback(e=>{e.target===e.currentTarget&&(o||l||r(!0))},[o,l]),m=Wr.useCallback(e=>{l||u.current?.contains(e.relatedTarget)||r(!1)},[l]);if(!n.length)return(0,qr.jsx)("span",{id:i,tabIndex:-1,style:zr});if(!d)return(0,qr.jsx)("div",{id:i,className:Hr,role:"region","aria-label":h,tabIndex:-1,style:zr,onFocus:p,children:(0,qr.jsxs)("button",{type:"button",onClick:()=>r(!0),children:["View data summary (",n.length," semantic items)"]})});const f=Math.min(s,n.length),y=n.slice(0,f),g=n.length-f;return(0,qr.jsxs)("div",{ref:u,id:i,className:Yr,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:_r,children:[(0,qr.jsx)("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{l&&c&&c.setVisible(!1),r(!1)},style:Xr,children:"×"}),(0,qr.jsx)("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Gr,children:as(n)}),(0,qr.jsxs)("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:Vr,children:[(0,qr.jsx)("caption",{className:"semiotic-accessible-data-table-caption",style:Qr,children:g>0?`First ${f} of ${n.length} semantic items`:`All ${n.length} semantic items`}),(0,qr.jsx)("thead",{children:(0,qr.jsxs)("tr",{children:[(0,qr.jsx)("th",{scope:"col",style:Ur,children:"Item"}),(0,qr.jsx)("th",{scope:"col",style:Ur,children:"Description"}),(0,qr.jsx)("th",{scope:"col",style:Ur,children:"Group"}),(0,qr.jsx)("th",{scope:"col",style:Ur,children:"Position"}),(0,qr.jsx)("th",{scope:"col",style:Ur,children:"Data"})]})}),(0,qr.jsx)("tbody",{children:y.map((e,t)=>(0,qr.jsxs)("tr",{children:[(0,qr.jsx)("th",{scope:"row",style:Kr,children:e.label}),(0,qr.jsx)("td",{style:Kr,children:e.description??e.label}),(0,qr.jsx)("td",{style:Kr,children:e.group??""}),(0,qr.jsxs)("td",{style:Kr,children:[Math.round(e.x),", ",Math.round(e.y)]}),(0,qr.jsx)("td",{style:Kr,children:ss(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?(0,qr.jsxs)("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:Zr,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}rs.ownsChrome=!0;var ls=require("react/jsx-runtime"),ds=[640,360],us={top:0,right:0,bottom:0,left:0},hs=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]),ps="StreamPhysicsFrame",ms=(0,h.memo)((0,h.forwardRef)(function(e,t){const{accessibleTable:n=!0,annotations:i,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:a,bodySemanticItemLimit:c=200,bodySemanticItems:l=!1,bodySemanticUpdateMs:d=200,bodyForces:f,bodyStyle:y,chartId:g,className:b,frameScheduler:x,clock:v,random:w,seed:k,color:M,config:I,controllers:S,continuous:A=!1,description:R,emphasis:P,chartMode:D,enableHover:T=!0,foregroundGraphics:E,hoverRadius:O=16,initialSpawns:N,initialSpawnPacing:F,legend:_,legendClickBehavior:G,legendHighlightedCategory:X,legendHoverBehavior:K,legendIsolatedCategories:Z,legendLayout:J,legendPosition:ee,margin:te,onClick:ne,onObservation:ie,onRegionEvent:oe,onSimulationExecutionChange:re,onBodyHover:se,onBodyPointerDown:ae,onSemanticItemActivate:ce,onSemanticItemFocus:le,onTick:de,opacity:ue,paused:he=!1,regionEffects:pe=[],responsiveHeight:me,responsiveWidth:fe,selectedBodyStyle:ye={stroke:"#111827",strokeWidth:2,opacity:1},selection:ge,semanticItems:be=[],simulationExecution:xe="auto",size:ve=ds,stroke:we,strokeWidth:ke,summary:Me,suspendWhenHidden:je=!0,svgAnnotationRules:Ae,title:Ce,tooltipContent:Re,workerBodyThreshold:$e=ei,renderBody:Pe,beforePaint:Be,afterPaint:De}=e,Te=u.useMemo(()=>({color:M,stroke:we,strokeWidth:ke,opacity:ue}),[M,ue,we,ke]),Ee=(0,h.useRef)(ie);Ee.current=ie;const Oe=(0,h.useRef)(g);Oe.current=g;const Ne=(0,h.useRef)(new Map),Fe=(0,h.useRef)(pe);Fe.current=pe;const Ze=(0,h.useRef)(f);Ze.current=f;const Je=(0,h.useRef)(de);Je.current=de;const et=u.useMemo(()=>tr(S),[S]),tt=(0,h.useRef)(et);tt.current=et;const nt=A||!!et?.continuous,it=(0,h.useRef)(nt);it.current=nt;const ot=u.useMemo(()=>{if(!f&&!et?.bodyForce)return f;if(!et?.bodyForce)return f;if(!f)return et.bodyForce;const e=et.bodyForce;return t=>{const n="function"==typeof f?f(t):f,i="function"==typeof e?e(t):e;return n||i?{x:(n?.x??0)+(i?.x??0),y:(n?.y??0)+(i?.y??0)}:null}},[f,et]);Ze.current=ot;const rt=u.useMemo(()=>new Map(pe.map(e=>[jr(e),e])),[pe]),st=u.useMemo(()=>new Map(pe.map(e=>[e.id,e])),[pe]),at=u.useMemo(()=>pe.map($r).filter(e=>null!=e),[pe]),[ct,lt]=u.useState([]),dt=u.useMemo(()=>ct.length||at.length?[...be,...ct,...at]:be,[ct,at,be]),ut=u.useMemo(()=>Pr(pe),[pe]),ht=!!ot,pt=(0,h.useRef)(null),mt=(0,h.useRef)(v??Bo);mt.current=v??Bo;const ft=(0,h.useCallback)((e,t,n)=>{const i=pt.current;if(!i||!n)return!1;const o=i.readBodies().find(t=>t.id===e),r=Cr(Ne.current.get(e));if(!o||!r)return!1;const s=Rr(n,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(i.applyImpulse(e,s.x??0,s.y??0),0))},[]),yt=(0,h.useCallback)((e,t,n)=>{if(!n.bodyId)return;const i=Cr(Ne.current.get(n.bodyId));if(!i)return;const o={bodyId:n.bodyId,datum:n.datum,observation:n,region:t,regionState:i,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),oe?.(o)},[oe]),gt=(0,h.useCallback)(e=>{const t=e.sensorId?rt.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const n=function(e,t){let n=e.get(t);return n||(n={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,n)),n}(Ne.current,e.bodyId),i=pt.current?.readBodies().find(t=>t.id===e.bodyId),o=Cr(n),r=i&&o?{body:i,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(n.activeRegionIds.add(t.id),n.regionIds.add(t.id),n.energy+=t.energyDelta??0,r){!function(e,t,n){const i="function"==typeof e.attributes?e.attributes(t):e.attributes;i&&(n.attributes={...n.attributes,...i})}(t,r,n);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(n.charges[t.id]=e)}ft(e.bodyId,t,t.impulseOnEnter),yt("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(n.activeRegionIds.delete(t.id),ft(e.bodyId,t,t.impulseOnExit),yt("region-exit",t,e))},[ft,yt,rt]),bt=u.useMemo(()=>function({annotations:e,chartId:t,chartType:n,config:i,onRegionObservation:o,regionEffects:r,seed:s,size:a}){const c=function(e=[],t={}){const n=t.idPrefix?t.idPrefix+"-":"",i=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=Fr(o,t),s=o.colliderId??`${n}${o.id}`;let a;if("x"===e){const e=Nr(o.x),n=Nr(o.y1)??Nr(t.plotBounds?.y)??Nr(o.y),i=Nr(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??Nr(o.y);if(null==e||null==n||null==i)continue;a={type:"segment",x1:e,y1:n,x2:e,y2:i,thickness:r}}else{const e=Nr(o.y),n=Nr(o.x1)??Nr(t.plotBounds?.x)??Nr(o.x),i=Nr(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??Nr(o.x);if(null==e||null==n||null==i)continue;a={type:"segment",x1:n,y1:e,x2:i,y2:e,thickness:r}}i.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:Nr(o.restitution)??Nr(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:Nr(o.friction)??Nr(t.barrierFriction)}})}return i}((e??[]).filter(e=>"barrier"===e.physics||"sensor"===e.physics),{idPrefix:t?t+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:a[0],height:a[1]}}),l=void 0===s||void 0!==i?.kernel?.seed?i:{...i,kernel:{...i?.kernel,seed:s}},d=r.flatMap(e=>[{id:jr(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...Ar(e)]),u=Object.fromEntries(r.map(e=>[jr(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),h=l?.observation,p=r.length>0;return p||d.length>0||c.length>0||null!=t||h?{...l,colliders:[...l?.colliders??[],...d,...c],observation:{...h,chartId:t??h?.chartId,chartType:h?.chartType??n,sensors:{...h?.sensors??{},...u},onObservation:e=>{p&&o(e),h?.onObservation?.(e)}}}:l}({annotations:i,chartId:g,chartType:ps,config:I,onRegionObservation:gt,regionEffects:pe,seed:k,size:ve}),[i,g,I,gt,pe,k,ve]);if(!pt.current){const e=Po(bt,N,F);e.setPaused(he),je&&e.setVisible(or()),pt.current=e}const xt=(0,h.useRef)(-1),vt=(0,h.useRef)(null),wt=(0,h.useRef)(!0),kt=(0,cr.useRef)(new mr("StreamPhysicsFrame")),Mt=(0,h.useRef)(""),It=(0,h.useId)().replace(/:/g,""),St=(0,h.useRef)(!1),jt=(0,h.useRef)(!1),At=(0,h.useRef)(0),Ct=(0,h.useRef)(!1),Rt=(0,h.useRef)(!1),$t=(0,h.useRef)(null),Pt=(0,h.useRef)(!1),Bt=function(e){const t=C(),n=(0,m.useRef)(t);n.current=t;const[i,o]=$(e.sizeProp,e.responsiveWidth,e.responsiveHeight),r=!!e.title,s=!!e.legend&&"top"===e.legendPosition,a=(0,m.useMemo)(()=>function(e,t,n=!1){const i=n?t?58:34:t?36:0;return i>e.top?{...e,top:i}:e}({...e.marginDefault,...e.userMargin},r,s),[e.marginDefault,e.userMargin,r,s]),c=o[0]-a.left-a.right,l=o[1]-a.top-a.bottom,d=L(e.foregroundGraphics,o,a),u=L(e.backgroundGraphics,o,a),h=j(e=>e.theme),{transition:f,introEnabled:y}=function(e,t){if(!1===e)return{transition:void 0,introEnabled:!1};const n="undefined"!=typeof window&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return{transition:e?!0===e?{duration:300}:{duration:e.duration??300,easing:"linear"===e.easing?"linear":"ease-out"}:t,introEnabled:!(n||!e||!0!==e&&!1===e.intro)}}(e.animate,e.transitionProp),g="semiotic-table-"+p.useId(),b=(0,m.useRef)(null);if(!b.current){const t=!e.suspendWhenHidden||"undefined"==typeof document||!document.hidden;b.current=new W({clock:e.clock,random:e.random,seed:e.seed,paused:e.paused,visible:t})}const x=b.current;x.configure({clock:e.clock,random:e.random,seed:e.seed});const v=(0,m.useRef)(null),w=(0,m.useRef)(e.frameScheduler??z);w.current=e.frameScheduler??z;const k=(0,m.useRef)(null),M=(0,m.useRef)(!1),I=(0,m.useRef)(()=>{}),S=(0,m.useCallback)(()=>{if(null!==v.current||M.current)return;const e=w.current;let t=!1,n=!1;const i=e.requestAnimationFrame(()=>{t=!0;const e=!n;e&&(M.current=!0),v.current=null,k.current=null;try{I.current()}finally{e&&(M.current=!1)}});n=!0,t||(v.current=i,k.current=e)},[]),A=(0,m.useCallback)(()=>{null!==v.current&&((k.current??w.current).cancelAnimationFrame(v.current),v.current=null,k.current=null)},[]);q(()=>{x.setPaused(!0===e.paused)},[x,e.paused]),(0,m.useEffect)(()=>{if(!e.suspendWhenHidden||"undefined"==typeof document)return void x.setVisible(!0);const t=()=>x.setVisible(!document.hidden);return t(),document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[x,e.suspendWhenHidden]),(0,m.useEffect)(()=>()=>{A()},[A]);const R=(0,m.useRef)(()=>{}),P=(0,m.useRef)(()=>{}),D=(0,m.useRef)(null),T=(0,m.useRef)(null),E=(0,m.useRef)(null),O=(0,m.useCallback)(()=>{const e=D.current;D.current=null,e&&R.current(e)},[]),N=(0,m.useCallback)(e=>{if(D.current={clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType},null===T.current){const e=w.current;let t=!1;const n=e.requestAnimationFrame(()=>{t=!0,T.current=null,E.current=null,O()});t||(T.current=n,E.current=e)}},[O]),F=(0,m.useCallback)(()=>{D.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null),P.current()},[]);(0,m.useEffect)(()=>()=>{D.current=null,null!==T.current&&((E.current??w.current).cancelAnimationFrame(T.current),T.current=null,E.current=null)},[]);const H=e.themeDirtyRef;return q(()=>{H&&(B++,H.current=!0,S())},[h,S,H]),{reducedMotion:t,reducedMotionRef:n,responsiveRef:i,size:o,margin:a,adjustedWidth:c,adjustedHeight:l,resolvedForeground:d,resolvedBackground:u,currentTheme:h,transition:f,introEnabled:y,tableId:g,frameRuntime:x,rafRef:v,renderFnRef:I,scheduleRender:S,cancelRender:A,hoverHandlerRef:R,hoverLeaveRef:P,onPointerMove:N,onPointerLeave:F}}({sizeProp:ve,responsiveWidth:fe,responsiveHeight:me,userMargin:te,marginDefault:us,foregroundGraphics:E,backgroundGraphics:a,frameScheduler:x,clock:v,random:w,seed:k,paused:he,suspendWhenHidden:je}),{margin:Dt,rafRef:Tt,reducedMotion:Et,reducedMotionRef:Ot,renderFnRef:Nt,cancelRender:Ft,resolvedBackground:Wt,resolvedForeground:qt,responsiveRef:zt,scheduleRender:Lt,size:Ht,frameRuntime:Yt}=Bt,_t=(0,h.useRef)(Yt.now);_t.current=Yt.now;const Gt=function(){const[e,t]=(0,H.useState)(!1);return Y(()=>{t(!0)},[]),e}(),Xt=V(),[Vt,Ut]=u.useState(null),[Kt,Qt]=u.useState(null),Zt=(0,h.useRef)(null),Jt=(0,h.useRef)(0),en=(0,h.useRef)(new Map),tn=It+"-physics-live",nn=(0,h.useCallback)((e,t,n=!1)=>{if(!l)return void lt(e=>e.length?[]:e);const i=_t.current();if(!n&&d>0&&d>i-Jt.current)return;Jt.current=i;const o=function(e,t,n,i){if(!n)return[];const o=Math.max(0,Math.floor(i));if(!o)return[];const r=[];for(let i=0;e.length>i&&o>r.length;i+=1){const o=e[i],s="function"==typeof n?n(o,{index:i,simulationState:t}):void 0;if(!1===s)continue;const a=ts(o);r.push({datum:o.datum??o,description:is(o),group:"body",label:ns(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(e,t,l,c);lt(e=>function(e,t){if(e.length!==t.length)return!0;for(let n=0;e.length>n;n+=1){const i=e[n],o=t[n];if(i.id!==o.id||i.label!==o.label||i.description!==o.description||i.group!==o.group||i.bodyId!==o.bodyId||Math.round(i.x)!==Math.round(o.x)||Math.round(i.y)!==Math.round(o.y))return!0}return!1}(e,o)?o:e)},[c,l,d]),on=(0,h.useCallback)(e=>{if(!dt.length)return;const t=Math.max(0,Math.min(e,dt.length-1));xt.current=t;const n=dt[t];if(Zt.current=n.bodyId??null,Ut(n),le?.(n),n.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=es(e);Qt(t),se?.(e,t)}}},[dt,se,le]),rn=(0,h.useCallback)(()=>{xt.current=-1,Zt.current=null,Ut(null),le?.(null)},[le]),sn=function({onObservationRef:e,chartIdRef:t,wallClockRef:n}){return(0,Or.useCallback)((i,o)=>{const r=e.current;if(!r)return;const s={timestamp:n.current(),chartType:"StreamPhysicsFrame",chartId:t.current};r("hover"===i||"click"===i?{...s,type:i,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===i?{...s,type:i,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===i?{...s,type:i,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:i})},[t,e,n])}({onObservationRef:Ee,chartIdRef:Oe,wallClockRef:mt}),an=(0,h.useCallback)(()=>{Qt(e=>e?(se?.(null,null),sn("hover-end"),null):e)},[sn,se]),cn=(0,h.useCallback)(e=>{if(!T||!pt.current)return;const t=e.currentTarget.getBoundingClientRect(),n=pt.current.hitTest(e.clientX-t.left,e.clientY-t.top,O);if(!n)return void an();const i=es(n);Qt(e=>e&&e.id===i.id&&e.x===i.x&&e.y===i.y?e:(se?.(n,i),sn("hover",{datum:n.datum,x:n.x,y:n.y}),i))},[an,sn,T,O,se]),ln=(0,h.useCallback)(e=>{rn();const t=pt.current,n=e.currentTarget.getBoundingClientRect(),i=e.clientX-n.left,o=e.clientY-n.top,r=t?t.hitTest(i,o,Math.max(16,O)):null;ae?.(r,e),r?(sn("click",{datum:r.datum,x:r.x,y:r.y}),sn("activate",{datum:r.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),ne?.(r.datum??null,{x:r.x,y:r.y,body:r})):(sn("click-end"),ne?.(null,{x:i,y:o,body:null}),an())},[an,rn,sn,O,ae,ne]);(0,h.useEffect)(()=>{if(!dt.length)return void rn();const e=xt.current;if(dt.length>e){if(e>=0){const t=dt[e];if(Zt.current=t.bodyId??null,Ut(e=>null!=e&&e.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t),t.bodyId&&pt.current){const e=pt.current.readBodies().find(e=>e.id===t.bodyId);if(e){const t=es(e);Qt(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else on(dt.length-1)},[dt,rn,on]),(0,h.useEffect)(()=>{T||an()},[an,T]);const dn=(0,h.useCallback)(e=>{if(function(e){const t=e.target;return t instanceof Element&&t!==e.currentTarget&&null!=t.closest("button, a[href], input, select, textarea, summary, [contenteditable='true'], [role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch']")}(e))return;if(!dt.length)return;if("Escape"===e.key)return e.preventDefault(),void rn();if(("Enter"===e.key||" "===e.key)&&xt.current>=0){e.preventDefault();const t=dt[xt.current];return sn("activate",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"}),void ce?.(t)}if(!hs.has(e.key))return;e.preventDefault();const t=xt.current;if(0>t){on(0);const e=dt[0];return void sn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*dt.length));let i=t;if("Home"===e.key?i=0:"End"===e.key?i=dt.length-1:"PageDown"===e.key?i=Math.min(dt.length-1,t+n):"PageUp"===e.key?i=Math.max(0,t-n):"ArrowRight"===e.key||"ArrowDown"===e.key?i=Math.min(dt.length-1,t+1):"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(i=Math.max(0,t-1)),on(i),i!==t){const e=dt[i];sn("focus",{datum:e.datum??{id:e.id,label:e.label},inputType:"keyboard"})}},[rn,sn,on,ce,dt]),[un,hn]=u.useState([]),pn=(0,h.useRef)(0),mn=!!i?.length&&i.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:fn}=function(e,t){return function(e){const{cancelRender:t,dirtyRef:n,frameRuntime:i,manageFrameRuntime:o,scheduleRender:r}=e,s=(0,U.useRef)(null),a=(0,U.useRef)(null),c=(0,U.useRef)(!1);return function(e){const{hydrated:t,wasHydratingFromSSR:n,storeRef:i,dirtyRef:o,renderFnRef:r,cancelRender:s,cleanup:a}=e;Y(()=>{const e=i.current;t&&n&&e?.cancelIntroAnimation?.(),!n&&e?.sceneNodes&&e.sceneNodes.length>0&&e?.markStylePaintPending?e.markStylePaintPending():o.current=!0,s?.(),r.current()},[t,n]);const c=(0,H.useRef)(a);c.current=a,(0,H.useEffect)(()=>()=>c.current?.(),[])}({hydrated:e.hydrated,wasHydratingFromSSR:e.wasHydratingFromSSR,storeRef:e.storeRef,dirtyRef:e.dirtyRef,renderFnRef:e.renderFnRef,cancelRender:e.cancelRender,cleanup:e.cleanup}),(0,U.useEffect)(()=>{if(!1!==o)return i.subscribe(()=>{i.isActive?(n.current=!0,r()):t()})},[t,n,i,o,r]),(0,U.useEffect)(()=>{!c.current&&(c.current=!0,e.skipInitialCanvasPaintInvalidation)||(e.dirtyRef.current=!0,e.scheduleRender())},e.canvasPaintDependencies),{canvasRef:s,interactionCanvasRef:a}}({...t,renderFnRef:e.renderFnRef,scheduleRender:e.scheduleRender,cancelRender:e.cancelRender,frameRuntime:e.frameRuntime})}(Bt,{hydrated:Gt,wasHydratingFromSSR:Xt,storeRef:pt,dirtyRef:wt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,canvasPaintDependencies:[s,a,Lt]}),yn=(0,h.useCallback)(()=>{const e=fn.current,t=pt.current;if(!e||!t)return;const n=kt.current.beforeCompute(t.getLastUpdateResult(),!1),i=function(){if("undefined"==typeof window)return 1;const e=window.devicePixelRatio||1,t=function(){if("undefined"==typeof window)return!1;const e="function"==typeof window.matchMedia&&window.matchMedia("(pointer: coarse)").matches,t=768>Math.min(window.innerWidth||1/0,window.innerHeight||1/0);return e||t}()?2:3;return Math.max(1,Math.min(e,t))}(),o=function(e,t,n,i){const o=e.getContext("2d");if(!o)return null;const r=Math.round(t[0]*i),s=Math.round(t[1]*i),a=r/t[0],c=s/t[1],l=t[0]+"px",d=t[1]+"px";return e.style.width!==l&&(e.style.width=l),e.style.height!==d&&(e.style.height=d),e.width===r&&e.height===s||(e.width=r,e.height=s),o.setTransform(a,0,0,c,0,0),o.translate(n.left,n.top),o}(e,Ht,Dt,i);if(!o)return void kt.current.afterCompute(n,!1,!1);const r=function(e){const t=Ke(e,_e),n=Ke(e,Le),i=Ke(e,Ue),o=Ke(e,Ge),r=Ke(e,ze),s=Ke(e,qe),a=Ke(e,Xe),c=Ke(e,Ve),l=Ke(e,He),d=Ke(e,Ye);return{annotationBackground:Qe(s,.94),annotationStroke:r,annotationText:a,background:s,border:r,closedWindowFill:Qe(n,.08),closedWindowStroke:Qe(n,.55),danger:n,focus:l,grid:d,gutterFill:Qe(c,.14),lateFill:i,openWindowFill:Qe(t,.07),openWindowStroke:Qe(t,.3),primary:t,selectedFill:i,selectedStroke:l,success:o,text:a,textSecondary:c,warning:i}}(o);o.clearRect(-Dt.left,-Dt.top,Ht[0],Ht[1]),a||"transparent"===s||(o.fillStyle=s??r.background,o.fillRect(-Dt.left,-Dt.top,Ht[0],Ht[1]));const c=t.snapshot(),l=t.readBodies();if(nn(l,c.simulationState),mn){const e=_t.current();if(e-pn.current>=100){pn.current=e;const t=Kn(l);hn(e=>e.length===t.length&&e.every((e,n)=>e.pointId===t[n].pointId&&Math.round(e.x)===Math.round(t[n].x)&&Math.round(e.y)===Math.round(t[n].y))?e:t)}}Be&&(o.save(),Be(o,l),o.restore());for(const e of l){const t=Ne.current.get(e.id),n=t?Array.from(t.activeRegionIds).map(e=>st.get(e)).filter(e=>null!=e):[],i=Er(e,c.simulationState,y,ye,ge,Cr(t),n,r.primary,r.text,Te);Pe?(o.save(),Pe(o,e,i),o.restore()):Ir(o,e,i)}De&&(o.save(),De(o,l),o.restore()),function(e,t,n){let i=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(n-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}i=!0;const a=1-Math.pow(1-s,3),{body:c}=r,l=r.scale>0?r.scale:1,d=(r.radius+28*a)*l,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*l),e.beginPath(),e.arc(c.x,c.y,d,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*d,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.lineWidth=Math.max(.5,1.8*l);for(let t=0;8>t;t+=1){const n=t*(Math.PI/4)+1.4*s,i=(r.radius+5+12*a)*l,o=(r.radius+12+34*a)*l;e.beginPath(),e.moveTo(c.x+Math.cos(n)*i,c.y+Math.sin(n)*i),e.lineTo(c.x+Math.cos(n)*o,c.y+Math.sin(n)*o),e.stroke()}e.restore()}}(o,en.current,_t.current()),kt.current.afterCompute(n,!0,!1),wt.current=!1},[fn,kt,Ht,Dt,a,s,nn,mn,Be,De,y,ye,ge,Te,Pe,st]),gn=(0,h.useCallback)((e,t)=>{const n=pt.current,i=`${xe}:${e}:${t??""}`;Mt.current!==i&&(Mt.current=i,re?.({execution:e,liveBodies:n?.liveBodyCount()??0,queuedBodies:n?.queueSize()??0,reason:t,requested:xe}))},[re,xe]),bn=(0,h.useCallback)((e,t=!0)=>{At.current+=1,St.current=!1,Ct.current=!1,Rt.current=!1,Pt.current=!1,$t.current?.terminate(),$t.current=null,t&&gn("sync",e)},[gn]),xn=(0,h.useCallback)(()=>Gt?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":ut?"runtime region effects require sync":ht?"body forces require sync":et?"physics controllers require sync":function(e){return!e||!e.engine&&ni(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(bt??{})?ri(F)?jt.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[bt,et,ht,ut,Gt,F]),vn=(0,h.useCallback)(()=>{const e=pt.current,t=xn();if(!e||t)return{reason:t,useWorker:!1};const n=e.liveBodyCount(),i=e.queueSize(),o=function(e,t,n=0,i=ei){return"sync"!==e&&("worker"===e||t+n>=i)}(xe,n,i,$e);return{reason:o?"worker"===xe?"forced worker":"body threshold":"below threshold",useWorker:o}},[xe,$e,xn]),wn=(0,h.useCallback)(e=>{const t=pt.current;return t&&e.snapshot?(t.restore(e.snapshot),wt.current=!0,t):t},[]),kn=(0,h.useCallback)((e,t=!0)=>{const n=wn(e);if(!n)return;t&&de?.(e.result,n.controls()),yn();const i=n.snapshot();!e.result.shouldContinue&&en.current.size<=0||i.paused||!i.visible||Ot.current||Lt()},[wn,de,yn,Ot,Lt]),Mn=(0,h.useCallback)(e=>{jt.current=!0,bn("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[bn]),In=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return!1;const t=vn();if(!t.useWorker)return St.current||Pt.current?bn(t.reason??"sync fallback"):gn("sync",t.reason??"sync"),!1;if(St.current||Pt.current)return!0;const n=$t.current??new li;$t.current=n,Pt.current=!0;const i=At.current+1;return At.current=i,n.initFromSnapshot(bt??{},e.snapshot()).then(e=>{if(At.current!==i)return;Pt.current=!1,St.current=!0,jt.current=!1,wn(e),gn("worker",t.reason??"worker"),yn();const n=pt.current?.snapshot();e.result.shouldContinue&&n&&!n.paused&&n.visible&&!Ot.current&&(vt.current=null,Lt())}).catch(e=>{At.current===i&&Mn(e)}),!0},[wn,bt,Mn,yn,Ot,gn,Lt,bn,vn]),Sn=(0,h.useCallback)(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),jn=(0,h.useCallback)((e,t=!0)=>{const n=$t.current;if(!n||!St.current)return;const i=At.current;n.request(e).then(e=>{if(At.current!==i)return;const n=Sn(e);n&&kn(n,t)}).catch(Mn)},[kn,Sn,Mn]),An=(0,h.useCallback)(()=>{const e=pt.current;if(!e)return;const t=In(),n=e.snapshot(),i=nt||ht||ut||!!et;n.paused||!n.visible||!e.hasPendingWork()&&!i||Ot.current?Nt.current():t&&Pt.current||Lt()},[et,nt,ht,ut,Ot,Nt,Lt,In]),Cn=(0,h.useCallback)(()=>{Ft(),Tt.current=null;const e=pt.current;if(!e)return;const t=Ot.current;if(t&&(vt.current=null),St.current&&$t.current){if(Ct.current)return void(Rt.current=!0);let n=0;if(!t){const e=_t.current();n=null!==vt.current?(e-vt.current)/1e3:0,vt.current=e}const i=$t.current,o=At.current;return Ct.current=!0,void(t?i.settle():i.tick(n)).then(e=>{Ct.current=!1;const t=Rt.current;Rt.current=!1,At.current===o&&(kn(e),t&&An())}).catch(i=>{Ct.current=!1;const r=Rt.current;if(Rt.current=!1,At.current!==o)return;Mn(i);const s=t?e.settleWithObservations():e.tick(n);Tr({store:e,result:s,regionEffects:Fe.current,regionState:Ne.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),yn(),r&&An()})}const n=tt.current,i=t=>Tr({store:e,result:t,composed:n,regionEffects:Fe.current,regionState:Ne.current,bodyForces:Ze.current,onTick:Je.current});let o;if(t)o=function(e,t,n=4){let i,o=!1,r=!1,s=0;do{const n=e.settleWithObservations(),a=t(n);o=o||a.regionEffectsApplied,r=r||a.bodyForcesApplied,i={...a,regionEffectsApplied:o,bodyForcesApplied:r,result:n},s+=1}while(n>s&&e.hasPendingWork());return i}(e,i);else{const t=_t.current(),n=vt.current;vt.current=t;const r=e.tick(null===n?0:(t-n)/1e3);o={...i(r),result:r}}const{result:r,regionEffectsApplied:s,bodyForcesApplied:a,snapshot:c}=o;yn(),(it.current||r.shouldContinue||s||a||n||en.current.size>0)&&!c.paused&&c.visible&&!Ot.current&&Lt()},[kn,Mn,yn,Ft,An,Lt,Ot,Tt]);Nt.current=Cn,(0,h.useEffect)(()=>{jt.current=!1,(St.current||Pt.current)&&bn("config changed",!1),pt.current?.updateConfig(bt??{}),An()},[bt,bn]),(0,h.useEffect)(()=>{jt.current=!1,An()},[Gt,xe,$e]),(0,h.useEffect)(()=>{An()},[Et,An]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:n,paused:i,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=(0,ir.useRef)(o);c.current=o;const l=(0,ir.useRef)(r);l.current=r,(0,ir.useEffect)(()=>{const o=s.current;o&&(t.setPaused(i),o.setPaused(i),i&&(n.current=null,e()),c.current({type:"setPaused",paused:i},!1),l.current())},[e,t,i]),(0,ir.useEffect)(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),l.current()))}if("undefined"==typeof document)return;const i=()=>{const i=s.current;if(!i)return;const o=or();t.setVisible(o),i.setVisible(o),o||(n.current=null,e()),c.current({type:"setVisible",visible:o},!1),l.current()};return i(),document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[e,t,a])}({cancelRender:Ft,frameRuntime:Yt,lastFrameTimeRef:vt,paused:he,postWorkerCommand:jn,requestRender:An,storeRef:pt,suspendWhenHidden:je}),(0,h.useEffect)(()=>()=>bn("unmount",!1),[bn]),(0,h.useEffect)(()=>{yn()},[yn]),(0,h.useImperativeHandle)(t,()=>({...pt.current.controls(),applyImpulse:(e,t,n)=>{pt.current.applyImpulse(e,t,n),jn({type:"applyImpulse",id:e,ix:t,iy:n}),An()},clear:()=>{pt.current.clear(),Ne.current.clear(),en.current.clear(),jn({type:"clear"}),An()},clearRegionState:e=>{e?Ne.current.delete(e):Ne.current.clear(),An()},getData:()=>pt.current.readBodies(),getRegionState:e=>e?Cr(Ne.current.get(e)):function(e){const t={};return e.forEach((e,n)=>{const i=Cr(e);i&&(t[n]=i)}),t}(Ne.current),getStore:()=>pt.current,pause:()=>{Yt.setPaused(!0),vt.current=null,Ft(),pt.current.setPaused(!0),jn({type:"setPaused",paused:!0},!1),An()},push:(e,t)=>{pt.current.enqueue(e,t),ri(t)?jn({type:"enqueue",spawns:[e],pacing:t}):(St.current||Pt.current)&&bn("spawn pacing is not worker-cloneable"),An()},pushMany:(e,t)=>{pt.current.enqueue(e,t),ri(t)?jn({type:"enqueue",spawns:e,pacing:t}):(St.current||Pt.current)&&bn("spawn pacing is not worker-cloneable"),An()},popBodies:(e,t={})=>{const n=pt.current,i=new Map(n.readBodies().map(e=>[e.id,e])),o=n.remove(e),r=_t.current();for(const e of o){const n=i.get(e);n&&(Ne.current.delete(e),en.current.set(e,{body:n,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??Sr(n),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:r}),Zt.current===e&&(Zt.current=null,Ut(null)),Qt(t=>t?.id===e?null:t))}return o.length&&(jn({type:"remove",ids:o}),An()),o},remove:e=>{const t=pt.current.remove(e);for(const t of e)Ne.current.delete(t);return jn({type:"remove",ids:e}),An(),t},restore:e=>{pt.current.restore(e),Ne.current.clear(),en.current.clear(),jn({type:"restore",snapshot:e},!1),An()},resume:()=>{Yt.setPaused(!1),vt.current=null,pt.current.setPaused(!1),jn({type:"setPaused",paused:!1},!1),An()},settle:e=>{const t=pt.current.settle(e);return jn({type:"settle",maxSteps:e}),An(),t},settleWithObservations:e=>{const t=pt.current.settleWithObservations(e);return jn({type:"settle",maxSteps:e}),An(),t},step:e=>{const t=pt.current,n=t.tick(e);return Tr({store:t,result:n,regionEffects:Fe.current,regionState:Ne.current,bodyForces:Ze.current,composed:tt.current,onTick:Je.current}),jn({type:"tick",deltaSeconds:e}),yn(),n}}),[Ft,Yt,yn,jn,An,bn]);const Rn=Se||!Gt&&Xt,$n=["stream-physics-frame",D?"stream-physics-frame--mode-"+D:null,P?"stream-physics-frame--emphasis-"+P:null,b].filter(Boolean).join(" "),Pn=R??("string"==typeof Ce?Ce:void 0)??"Physics chart",Bn=It+"-physics-table",Dn=Math.max(1,Ht[0]-Dt.left-Dt.right),Tn=Math.max(1,Ht[1]-Dt.top-Dt.bottom),En=T&&Kt?Re?Re(Kt):(0,ls.jsx)(rs,{hover:Kt}):null,On=En&&Kt?(0,ls.jsx)(We,{x:Kt.x-Dt.left,y:Kt.y-Dt.top,containerWidth:Math.max(1,Ht[0]-Dt.left-Dt.right),containerHeight:Math.max(1,Ht[1]-Dt.top-Dt.bottom),margin:Dt,className:"stream-physics-tooltip",children:En}):null;if(Rn){const e=pt.current??Po(bt,N,F),t="string"==typeof Ce?Ce:void 0,{svg:n}=function(e,t={}){const{width:n=640,height:i=360,title:o,description:r,background:s,backgroundGraphics:a,className:c,foregroundGraphics:l,idPrefix:d="physics",margin:u,renderBodySVG:h,...p}=t,m=Fo(e,p),f={...qo,...u},y=[n,i],g=zo(a,y,f),b=zo(l,y,f),x=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(d),v=o?x+"-title":void 0,w=r?x+"-desc":void 0,k=[v,w].filter(Boolean).join(" ")||void 0;return{svg:Do.renderToStaticMarkup((0,Wo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:c??"stream-physics-frame",width:n,height:i,viewBox:`0 0 ${n} ${i}`,role:"img","aria-labelledby":k,children:[o&&(0,Wo.jsx)("title",{id:v,children:o}),r&&(0,Wo.jsx)("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?(0,Wo.jsx)("rect",{x:0,y:0,width:n,height:i,fill:s}):null,g,(0,Wo.jsx)("g",{id:x+"-data-area",children:m.sceneNodes.map((e,t)=>{const n=m.bodies[t];return(n&&h?h(n,e.style??{},t,x):void 0)??Ie(e,t,x)})}),b]})),scene:m,evidence:m.evidence}}(e,{width:Ht[0],height:Ht[1],title:t,description:R,background:a||"transparent"===s?void 0:s,backgroundGraphics:Wt,className:"stream-physics-frame__svg",foregroundGraphics:qt,idPrefix:"physics-"+It,margin:Dt});return(0,ls.jsxs)("div",{ref:zt,className:$n,"data-semiotic-mode":D,role:"img","aria-label":Pn,style:{width:Ht[0],height:Ht[1]},children:[(0,ls.jsx)(kr,{summary:Me}),(0,ls.jsx)("div",{dangerouslySetInnerHTML:{__html:n}})]})}return(0,ls.jsxs)("div",{ref:zt,className:$n,"data-semiotic-mode":D,role:"group","aria-label":Pn,"aria-describedby":Vt?tn:void 0,tabIndex:0,style:{position:"relative",width:Ht[0],height:Ht[1]},onKeyDown:dn,children:["production"!==process.env.NODE_ENV&&pt.current&&(0,ls.jsx)(fr,{store:pt.current,diagnostics:kt.current}),n?(0,ls.jsx)(Mr,{tableId:Bn}):null,n?(0,ls.jsx)(cs,{chartTitle:"string"==typeof Ce?Ce:Pn,items:dt,tableId:Bn}):null,(0,ls.jsx)(kr,{summary:Me}),(0,ls.jsx)(vr,{hoverPoint:Kt}),(0,ls.jsx)("div",{id:tn,"aria-live":"polite","aria-atomic":"true",style:zr,children:Vt?Vt.description??Vt.label:""}),(0,ls.jsxs)("div",{role:"img","aria-label":Pn,style:{position:"relative",width:"100%",height:"100%"},children:[(0,ls.jsx)(Q,{size:Ht,margin:Dt,children:Wt}),(0,ls.jsx)("canvas",{ref:fn,width:Ht[0],height:Ht[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:ln,onPointerMove:T?cn:void 0,onPointerLeave:T?an:void 0}),qt,(0,ls.jsx)(Jn,{width:Dn,height:Tn,totalWidth:Ht[0],totalHeight:Ht[1],margin:Dt,title:Ce,legend:_,legendPosition:ee,legendLayout:J,legendHoverBehavior:K,legendClickBehavior:G,legendHighlightedCategory:X,legendIsolatedCategories:Z,pointNodes:un,annotations:i,onAnnotationActivate:o,onObservation:ie,chartId:g,chartType:ps,autoPlaceAnnotations:r,svgAnnotationRules:Ae}),(0,ls.jsx)(ar,{active:null!=Vt,hoverPoint:Vt?{x:Vt.x,y:Vt.y}:null,margin:Dt,size:Ht,shape:Vt?.shape,width:Vt?.width,height:Vt?.height,pathData:Vt?.pathData}),On]})]})}));ms.displayName="StreamPhysicsFrame";var fs=ms;function ys(e){if(null==e)return()=>{};const t="function"==typeof e?e:t=>t[e];return e=>gs(t(e))}function gs(e){if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}}function bs(e,t,n){const i=null!=e.axis?n[e.axis]:null!=e.field?t[e.field]:n.value;if(void 0!==e.eq&&i!==e.eq)return!1;if(void 0!==e.ne&&i===e.ne)return!1;if(void 0!==e.in&&!e.in.includes(i))return!1;if(void 0===e.gt&&void 0===e.gte&&void 0===e.lt&&void 0===e.lte&&void 0===e.within&&void 0===e.outside)return!0;const o=gs(i);if(void 0===o)return!1;if(void 0!==e.gt&&e.gt>=o)return!1;if(void 0!==e.gte&&e.gte>o)return!1;if(void 0!==e.lt&&o>=e.lt)return!1;if(void 0!==e.lte&&o>e.lte)return!1;if(void 0!==e.within){const[t,n]=e.within;if(t>o||o>n)return!1}if(void 0!==e.outside){const[t,n]=e.outside;if(o>=t&&n>=o)return!1}return!0}function xs(e,t,n){const i=e.when;return void 0===i||!0===i||!1!==i&&("function"==typeof i?i(t,n):bs(i,t,n))}function vs(e,t,n){if(!t||0===t.length)return{};let i={};for(const o of t){if(!xs(o,e,n))continue;const t="function"==typeof o.style?o.style(e,n):o.style;t&&(i={...i,...t})}return i}function ws(e,t,n,i=e=>e){const o=e??(()=>({}));return t&&0!==t.length?(e,r)=>{const s=i(e),a={...o(e,r)};return Object.assign(a,vs(s,t,n(s,r))),a}:o}function ks(e){const[t,n]=e,i=160>t||116>n,o=i?Math.min(12,Math.max(2,.08*t)):32,r=i?Math.min(8,Math.max(2,.12*n)):24,s=i?r:34;return{width:t,height:n,plot:{x:o,y:r,width:Math.max(1,t-2*o),height:Math.max(1,n-r-s)}}}function Ms(e){const t=(e??"")+"";if(!t)return"#4e79a7";const n=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let i=0;for(let e=0;t.length>e;e+=1)i=31*i+t.charCodeAt(e)>>>0;return n[i%n.length]}function Is(e,t="#4e79a7",n){const i=n?.styleRules,o=!!i&&i.length>0,r=o?ys(n?.valueAccessor):void 0;return n=>{const s=n.datum,a=s&&e?"function"==typeof e?e(s,0):s[e]:void 0,c={fill:null==a?t:Ms(a),stroke:"#111827",strokeWidth:1,opacity:.9};return o&&s&&Object.assign(c,vs(s,i,{value:r?r(s):void 0,category:null==a?void 0:a+""})),c}}function Ss(e,t,n,i){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:n},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...i}}}function js(e,t,n){if(!e.length)return[];const i=ks(t),o=i.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*i.plot.height,a=i.plot.y+i.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),l=`${n} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${n}-${e.label}`,label:l,description:l,datum:e,x:i.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:n}})}function As(e,t,n){return"function"==typeof n?n(e,t):e[n]}function Cs(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Rs(e,t,n){return Math.max(t,Math.min(n,e))}function $s(e,t){const n=Cs(e);return null!=n&&n>0?n:t}function Ps(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Bs(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}var Ds=require("d3-scale");function Ts(e){const{data:t,valueAccessor:n,bins:i,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=ks(s),l=t.map((e,t)=>Cs(As(e,t,n))).filter(e=>null!=e),d=function(e){if(!e)return;const t=Cs(e[0]),n=Cs(e[1]);return null!=t&&null!=n?t>n?[n,t]:[t,n]:void 0}(a),u=d?.[0]??(l.length?Math.min(...l):0),h=d?.[1]??(l.length?Math.max(...l):1),p=h===u?1:h-u,m=(0,Ds.scaleLinear)().domain([0,i]).range([c.plot.x,c.plot.x+c.plot.width]),f=Array.from({length:i},()=>0),y=[];t.forEach((e,t)=>{const r=Cs(As(e,t,n));if(null==r)return;const s=Math.max(0,Math.min(i-1,Math.floor((r-u)/p*i)));f[s]+=1,y.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:Ss(r,[...ao({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...co({idPrefix:"galton-bin",count:i,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:y,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:f.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:i,plot:c.plot,valueExtent:[u,h]}}}var Es=require("d3-scale");function Os(e){const{count:t,idPrefix:n,wallThickness:i,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),l=Math.max(1,r-c);return{id:`${n}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+l/2,width:i,height:l}}})}function Ns(e){const{data:t,timeAccessor:n,arrivalAccessor:i,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:l,timeScale:d=1}=e,u=ks(c),h=t.map((e,t)=>Cs(As(e,t,n))).filter(e=>null!=e),p=Cs(l?.[0]),m=Cs(l?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+o.size,g=Math.min(p??f,f),b=Math.max(m??y,y),x=Math.floor(g/o.size)*o.size,v=Math.max(1,Math.ceil((b-x+o.size)/o.size)),w=h.length?Math.max(...h):0,k="function"==typeof r?r(w):Cs(r?.value)??w-(r?.delay??o.size),M=Math.max(0,Math.min(v,Array.from({length:v},(e,t)=>t).reduce((e,t)=>x+(t+1)*o.size>k?e:e+1,0))),I=function(e,t){const n=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:n,height:e.plot.height},windowPlot:{x:e.plot.x+n,y:e.plot.y,width:Math.max(40,e.plot.width-n),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),S=x+v*o.size,j=(0,Es.scaleLinear)().domain([x,S]).range([I.windowPlot.x,I.windowPlot.x+I.windowPlot.width]),A=Array.from({length:v},()=>({value:0,secondary:0})),C=[];t.forEach((e,t)=>{const r=Cs(As(e,t,n));if(null==r)return;const a=Cs(As(e,t,i))??r,c=Math.max(0,Math.min(v-1,Math.floor((r-x)/o.size))),l=k>=x+(c+1)*o.size;A[c].value+=l?0:1,A[c].secondary+=l?1:0,C.push({id:(e.id??"event-"+t)+"",x:Math.max(I.windowPlot.x+s,Math.min(I.windowPlot.x+I.windowPlot.width-s,j(r))),y:u.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:c,late:l}})});const R=u.plot.y+u.plot.height,$=function(e,t){const n=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!n)return[];const i=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=(0,Es.scaleLinear)().domain([i,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+n*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),l=e=>s===a?t:c+(e-a)/(s-a)*(t-c),d=[];for(let t=0;n>t;t+=1){const n=e.windowStart+t*e.windowSize,i=n+e.windowSize,o=r(n),s=r(i);d.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:l(o),x2:s,y2:l(s)})}return d}({closedWindowCount:M,gutter:I.gutter,plot:u.plot,windowCount:v,windowPlot:I.windowPlot,windowSize:o.size,windowStart:x},u.plot.y+.28*u.plot.height);return{config:Ss(a,[...ao({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...Os({idPrefix:"eventdrop-window",count:v,xScale:e=>j(x+e*o.size),yTop:I.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>M)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?I.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...$.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:C,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:d},projectionRows:A.map((e,t)=>({label:`${x+t*o.size}-${x+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:M,gutter:I.gutter,lidSegments:$,lateCount:A.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:I.windowPlot,watermarkValue:k,windowCount:v,windowSize:o.size,windowStart:x}}}function Fs(e,t,n){const i=e.width/Math.max(1,t),o=Math.max(2,2*n),r=Math.min(.7*i,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:i,tubeWidth:r,ballDiameter:o,perRow:s,centerX:t=>e.x+(t+.5)*i,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function Ws(e){const{data:t,categoryAccessor:n,valueAccessor:i,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=$s(o,1),l=ks(a),d=[],u=new Map,h=new Map,p=[];function m(e){let t=u.get(e);return null==t&&(t=d.length,d.push(e),u.set(e,t)),t}t.forEach((e,t)=>{m((As(e,t,n)??"unknown")+"")});const f=Math.max(1,d.length),y=Fs(l.plot,f,r),g=Math.max(0,y.tubeWidth/2-r-1),b=d.map(()=>[]);t.forEach((e,t)=>{const o=(As(e,t,n)??"unknown")+"",s=m(o),a=i?Cs(As(e,t,i)):1,d=Math.max(0,Math.round((a??0)/c)),u=y.centerX(s);for(let n=0;d>n;n+=1){const i=h.get(o)??0,a=y.perRow>1?((y.perRow>1?i%y.perRow:0)/(y.perRow-1)*2-1)*g:0;h.set(o,i+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${n}`,x:u+a,y:l.plot.y+r+2,vx:(n%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:n}})}});const x=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;x>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const v=l.plot.y+l.plot.height,w=[...ao({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=l.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const n of[-1,1])w.push({id:`pile-tube-${e}-${0>n?"l":"r"}`,shape:{type:"aabb",x:t+n*y.tubeWidth/2,y:(k+v)/2,width:6,height:v-k}})}return{config:Ss(s,w,"UnitPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:d.map(e=>({label:e,value:h.get(e)??0}))}}var qs=require("d3-scale");function zs(e){const{data:t,xAccessor:n,groupAccessor:i,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:l,settle:d}=e,u=ks(a),h=Bs(s),p=[],m=[],f=new Map;t.forEach((e,t)=>{const s=Cs(As(e,t,n));if(null==s)return;const a=i?(As(e,t,i)??"All")+"":"All",c=o?Cs(As(e,t,o)):null,l=Rs(null!=c&&c>0?c:r,2,18);!function(e){let t=f.get(e);null==t&&(t=m.length,m.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:l})});const y=p.map(e=>e.value),g=c?Cs(c[0]):null,b=c?Cs(c[1]):null,x=y.length?Math.min(...y):0,v=y.length?Math.max(...y):1;let w=g??x,k=b??v;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const M=Math.max(r,...p.map(e=>e.radius)),I=u.plot.x+M+8,S=u.plot.x+u.plot.width-M-8,j=(0,qs.scaleLinear)().domain([w,k]).range([I,S]),A=Math.max(1,m.length),C=Math.min(Math.max(28,3*M),u.plot.height/4),R=u.plot.y+C,$=Math.max(0,u.plot.y+u.plot.height-C-R),P=e=>{const t=f.get(e)??0;return 1===A?u.plot.y+.54*u.plot.height:R+t/(A-1)*$},B=new Map,D=p.map((e,t)=>{B.set(e.group,(B.get(e.group)??0)+1);const n=j(e.value),i=P(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:d?n+o:Rs(n+(t%9-4)*e.radius*2.5,I,S),y:d?i+r:u.plot.y-18-t%12*e.radius,vx:d?0:22*(h()-.5),vy:d?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:n,targetY:i},springs:[{target:{type:"point",x:n,y:i},restLength:0,stiffness:34,damping:5.5}]}});return{config:Ss(s,ao({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*M),collisionIterations:Math.max(1,Math.round(l??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:D,projectionRows:m.map(e=>({label:e,value:B.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[I,S],groups:m.map(e=>({label:e,y:P(e),count:B.get(e)??0})),plot:u.plot}}}function Ls(e){if(Array.isArray(e)&&e.length>=2){const t=Cs(e[0]),n=Cs(e[1]);return null!=t&&null!=n?{x:t,y:n}:null}if(e&&"object"==typeof e){const t=e,n=Cs(t.x),i=Cs(t.y);return null!=n&&null!=i?{x:n,y:i}:null}return null}function Hs(e){return Array.isArray(e)?e.map(Ls).filter(e=>null!=e):[]}function Ys(e,t,n){return"normalized"===n?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:Rs(e.x,t.plot.x,t.plot.x+t.plot.width),y:Rs(e.y,t.plot.y,t.plot.y+t.plot.height)}}function _s(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}function Gs(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const n=Rs(t,0,1)*_s(e);let i=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(i+s>=n){const e=(n-i)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}i+=s}}return{...e[e.length-1]}}function Xs(e,t){const n=Gs(e,Math.max(0,t-.02)),i=Gs(e,Math.min(1,t+.02)),o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function Vs(e){const{coordinateMode:t,flowSpeed:n,links:i,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:l,particleRate:d,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:f,sourceAccessor:y,targetAccessor:g,throughputAccessor:b}=e,x=ks(f),v=Bs(m),w=new Map,k=new Map,M=[];function I(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}c.forEach((e,t)=>{const n=(As(e,t,r)??e.id??t)+"",i=Cs(As(e,t,s)),o=Cs(As(e,t,a));if(null!=i&&null!=o){const e={x:i,y:o};w.set(n,e),M.push(e)}k.set(n,(e.label??e.name??n)+"")});const S=[];i.forEach((e,t)=>{const n=I(As(e,t,y)),i=I(As(e,t,g)),o=Math.max(0,Cs(As(e,t,b))??0),r=Hs(u?As(e,t,u):void 0),s=r.length?r:Hs(e.path??e.points??e.route);s.forEach(e=>M.push(e)),S.push({id:(e.id??`physical-flow-${n}-${i}-${t}`)+"",link:e,index:t,source:n,target:i,throughput:o,rawPath:s})});const j=(C=M,"normalized"===(A=t)||"pixels"===A?A:C.length>0&&C.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var A,C;const R=new Map;for(const[e,t]of w)R.set(e,Ys(t,x,j));const $=[];for(const e of S){let t=e.rawPath.map(e=>Ys(e,x,j));if(2>t.length){const n=R.get(e.source),i=R.get(e.target);n&&i&&(t=[n,i])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),$.push({...e,path:t,packetCount:0}))}const P=$s(d,.12),B=Math.max(1,Math.round(o)),D=$.map(e=>Math.max(1,Math.round(e.throughput*P))),T=D.reduce((e,t)=>e+t,0),E=T>B?B/T:1;$.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(D[t]*E))});let O=$.reduce((e,t)=>e+t.packetCount,0);for(;O>B;){const e=$.reduce((e,t,n)=>t.packetCount>1&&(-1===e||t.packetCount>$[e].packetCount)?n:e,-1);if(-1===e)break;$[e].packetCount-=1,O-=1}const N=new Map,F=new Map,W=[],q=$s(n,90),z=$s(l,4);$.forEach((e,t)=>{N.set(e.target,(N.get(e.target)??0)+e.throughput),F.set(e.source,(F.get(e.source)??0)+e.throughput);const n=_s(e.path);for(let i=0;e.packetCount>i;i+=1){const o=(i+.5)/e.packetCount,r=p?o:Rs(.12+.84*o+.04*(v()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*v())),a=Gs(e.path,s),c=Gs(e.path,r),l=Xs(e.path,s),d={x:-l.y,y:l.x},u=(v()-.5)*z*1.5;W.push({id:`${e.id}-packet-${i}`,x:a.x+d.x*u,y:a.y+d.y*u,vx:p?0:l.x*q+10*(v()-.5),vy:p?0:l.y*q+10*(v()-.5),mass:.8,spawnAt:p?0:.04*t+i/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:i,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:n,flowRouteId:e.id,flowSpeed:q,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const L=Math.max(18,5*z),H=Array.from(R,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+Ps(e),point:t})),Y=H.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:L,height:L}})),_=Object.fromEntries(H.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),G=Ss(m,[...ao({x:x.plot.x,y:x.plot.y,width:x.plot.width,height:x.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...Y],"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});G.bodyLimit=B,G.eviction="oldest",G.observation={...G.observation,sensors:_};const X=Array.from(R,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+Ps(e),incoming:N.get(e)??0,outgoing:F.get(e)??0})),V=$.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:G,initialSpawns:W,projectionRows:X.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:j,particleCount:W.length,totalThroughput:$.reduce((e,t)=>e+t.throughput,0),plot:x.plot,nodes:X,links:V}}}function Us(e,t){if("region-enter"!==t.type)return e;const n=t.region.id,i=e[n]??{id:n,label:t.region.label??n,count:0,bodyIds:[]};if(i.bodyIds.includes(t.bodyId))return e;const o=[...i.bodyIds,t.bodyId];return{...e,[n]:{...i,count:o.length,bodyIds:o}}}function Ks(e,t){return(t??Object.keys(e)).map(t=>e[t]).filter(e=>null!=e).map(e=>({label:e.label??e.id,value:e.count}))}function Qs(e,t){const n=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],i=t.filter(e=>!n.has(e)),o=t.length-i.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?.[e];return Number.isFinite(t)&&Number(t)>=0?Number(t):1},c=t.reduce((e,t)=>e+a(t),0),l=t.reduce((e,t)=>e+(n.has(t)?a(t):0),0),d=e.completion?.threshold,u="threshold"===r?Number.isFinite(d)&&Number(d)>=0?Number(d):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?l>=(u??c):0===i.length),absorbed:o,total:t.length,absorbedValue:l,totalValue:c,threshold:u,missing:i}})}function Zs(e,t,n){return Math.max(t,Math.min(n,e))}function Js(e,t,n={}){const i=n.random??Math.random,o=e.stages.find(e=>e.id===t)??e.stages[e.stages.length-1],r=Zs(n.along??.5,.05,.95),s=n.jitterX??0,a=n.padY??20,c=o.x0+(o.x1-o.x0)*r+(2*i()-1)*s,l=Math.min(1,o.width/2),d=Zs(c,o.x0+l,o.x1-l),u=e.boundaryY(d,"top")+a,h=e.boundaryY(d,"bottom")-a;return{x:d,y:h>u?u+i()*Math.max(1,h-u):e.midY}}function ea(e){return"bowtie"===e.shape?[{id:"incoming",role:"incoming",points:[[e.left,e.topY],[e.centerLeft,e.pinchTop],[e.centerLeft,e.pinchBottom],[e.left,e.bottomY]]},{id:"center",role:"center",points:[[e.centerLeft,e.pinchTop],[e.centerRight,e.pinchTop],[e.centerRight,e.pinchBottom],[e.centerLeft,e.pinchBottom]]},{id:"outgoing",role:"outgoing",points:[[e.centerRight,e.pinchTop],[e.right,e.topY],[e.right,e.bottomY],[e.centerRight,e.pinchBottom]]}]:[{id:"volume",role:"volume",points:[[e.left,e.topY],[e.right,"funnel"===e.shape?e.pinchTop:e.topY],[e.right,"funnel"===e.shape?e.pinchBottom:e.bottomY],[e.left,e.bottomY]]}]}function ta(e,t,n){return Math.max(t,Math.min(n,e))}function na(e,t,n,i,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:n,x2:i,y2:o,thickness:r.thickness??8}}}function ia(e){const t=e.shape??"lane",n=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=n-o,c=r,l=i-Math.max(24,Math.round(.45*r)),d=(c+l)/2,u=Math.max(1,l-c),h=ta(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,f=ta(u*h+m,.06*u,.5*u),y=f/2,g=d-y,b=d+y,x=e.idPrefix??"process",v=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,M=e.stages;if(!M.length)throw Error("processStageLayout requires at least one stage");const I=ta(e.centerStageIndex??Math.floor(M.length/2),0,M.length-1),S=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(M),j=a-s;let A=s;const C=M.map((e,t)=>{const n=A,i=t===M.length-1?a:A+(e.share??1)/S*j;return A=i,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:n,x1:i,x:(n+i)/2,width:i-n,y:d,height:u}}),R=C[I],$=R.x0,P=R.x1,B=(e,n)=>{if("lane"===t)return"top"===n?c:l;if("funnel"===t){const t=ta((e-s)/Math.max(1,a-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if($>=e){const t=ta((e-s)/Math.max(1,$-s),0,1);return"top"===n?c+(g-c)*t:l+(b-l)*t}if(P>=e)return"top"===n?g:b;const i=ta((e-P)/Math.max(1,a-P),0,1);return"top"===n?g+(c-g)*i:b+(l-b)*i},D=C.map(e=>{const t=Math.min(B(e.x0,"top"),B(e.x1,"top")),n=Math.max(B(e.x0,"bottom"),B(e.x1,"bottom"));return{...e,y:(t+n)/2,height:Math.max(1,n-t)}}),T={thickness:k,friction:v,restitution:w},E=[];"lane"===t?E.push(na(x+"-top",s,c,a,c,T),na(x+"-bottom",s,l,a,l,T),na(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),na(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)})):"funnel"===t?E.push(na(x+"-top",s,c,a,g,T),na(x+"-bottom",s,l,a,b,T),na(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),na(x+"-right",a,g,a,b,{...T,thickness:Math.max(6,k)})):E.push(na(x+"-left-top",s,c,$,g,T),na(x+"-left-bottom",s,l,$,b,T),na(x+"-center-top",$,g,P,g,T),na(x+"-center-bottom",$,b,P,b,T),na(x+"-right-top",P,g,a,c,T),na(x+"-right-bottom",P,b,a,l,T),na(x+"-left",s,c,s,l,{...T,thickness:Math.max(6,k-2)}),na(x+"-right",a,c,a,l,{...T,thickness:Math.max(6,k)}));const O=e.membraneDampingScale??.5,N=s,F=Math.max(1,("bowtie"===t?$:a)-N),W=(e.membranes??[]).map(e=>{const t=N+ta(e.offset,0,1)*F,n=e.width??18+18*e.cost,i=u-16,o=d+.25*(e.wobble??0);return{...e,x:t,y:o,width:n,height:i}}),q=!1===e.includeMembraneRegions?[]:W.map(e=>sa({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??O,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:n,height:i,padX:o,padY:r,left:s,right:a,topY:c,bottomY:l,midY:d,centerLeft:$,centerRight:P,pinchHeight:f,pinchTop:g,pinchBottom:b,stages:D,membranes:W,colliders:E,regionEffects:q,boundaryY:B}}function oa(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,n=e.y,i=e.width,o=e.height,{type:"aabb",x:t,y:n,width:i,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,n,i,o}function ra(e,t={}){const n=t.idPrefix??"stage",i=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...oa({id:n?`${n}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*i),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function sa(e){const t=e.dampingScale??.5,n=e.energyScale??1,i=ta(e.cost,0,2);return{...oa({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:i,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i*t,energyDelta:-i*n}}function aa(e){return{...oa({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function ca(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...oa({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function la(e){const t=e.pressure??e.occupancy??0,n=e.baseDamping??.08,i=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...oa({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n+t*i,energyDelta:o?-t*o:void 0,force:e.force}}function da(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...oa({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function ua(e){return{...oa({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function ha(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...oa({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function pa(e){return{...oa({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function ma(e){const t=e.x??e.anchor?.x??0,n=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:n,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:n},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function fa(e){const t=e.idPrefix??"lane",n={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},i=[na(t+"-top",e.left,e.top,e.right,e.top,n),na(t+"-bottom",e.left,e.bottom,e.right,e.bottom,n)];return e.openEnds||i.push(na(t+"-left",e.left,e.top,e.left,e.bottom,n),na(t+"-right",e.right,e.top,e.right,e.bottom,n)),i}function ya(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}function ga(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const n=e.size,i=ks(n),o=Rs(e.ballRadius??6,2,18),r=e.seed??1,s=Bs(r),a=e.idAccessor,c=e.stageAccessor??"stage",l=e.groupBy,d=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(l?"allAbsorbed":"none"),m=e.springStiffness??.28,f=e.springDamping??.72,y=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=ia({width:n[0],height:n[1],shape:"lane",padX:Math.max(28,i.plot.x),padY:Math.max(36,i.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),x=new Map(b.stages.map((e,t)=>[e.id,t])),v=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,k=b.stages[0],M=new Set(t.filter(e=>e.absorb).map(e=>e.id)),I=t.map(e=>{const t=v.get(e.id)??k;return function(e,t){const n={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return ha({...n,kind:e.kind??"sink",force:ya(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...n.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return ua({...n,kind:e.kind??"force-field",force:ya(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...n.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return da({...n,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:ya(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...n.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return la({...n,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:ya(e.force,8),attributes:{...n.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?ca({...n,kind:e.kind??"force-field",force:ya(e.force,14),damping:e.damping??.02,attributes:{...n.attributes,primitive:"routeSurface"}}):pa({...n,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...n.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});I.unshift(ca({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(b.left+b.right)/2,y:b.midY,width:b.right-b.left,height:b.bottomY-b.topY-12,force:8,damping:.012,semanticItem:!1}));const S=new Map;for(const e of b.stages)S.set(e.id,0);const j=[];e.data.forEach((e,t)=>{const n=(a?As(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",i=(As(e,t,c)??w)+"",r=x.has(i)?i:w;S.set(r,(S.get(r)??0)+1);const s=l?(As(e,t,l)??"")+"":void 0,p=s&&d?(As(e,t,d)??s)+"":s,m=u?Cs(As(e,t,u))??1:1,f=h?Cs(As(e,t,h)):null,y=Rs(null!=f&&f>0?f:o,2,18);j.push({datum:e,id:n,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:y,index:t})});const A=new Map,C=new Map;for(const e of j){if(!e.groupId)continue;const t=A.get(e.groupId)??[];t.push(e.id),A.set(e.groupId,t),e.groupLabel&&C.set(e.groupId,e.groupLabel)}const R=Rs(e.groupAnchorAlong??.55,.15,.9),$=b.left+(b.right-b.left)*R,P=Array.from(A.keys()),B=P.map((e,n)=>{const i=A.get(e)??[],o=P.length>1?b.topY+28+n/Math.max(1,P.length-1)*(b.bottomY-b.topY-56):b.midY;return ma({id:e,label:C.get(e)??e,bodyIds:i,anchor:{x:$,y:o},x:$,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),D=Qs(B,j.filter(e=>M.has(e.stageId)).map(e=>e.id)),T=new Map(B.map(e=>[e.id,e])),E=j.map((e,t)=>{const n=v.get(e.stageId)??k,i=n.x+(s()-.5)*Math.min(24,.2*n.width),o=b.boundaryY(i,"top")+e.radius+10,r=b.boundaryY(i,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=y?i:b.left+18+t%7*4,l=y?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,d=[{target:{type:"point",x:i,y:a},restLength:.45*e.radius,stiffness:m,damping:f}];if(e.groupId){const t=T.get(e.groupId);t?.anchor&&!M.has(e.stageId)&&d.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:c,y:l,vx:y?0:40+40*s(),vy:y?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:y?0:.03*t,springs:d,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),O={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:b.colliders,fixedDt:1/60,maxSubsteps:8},N=b.stages.map(e=>({label:e.label??e.id,value:S.get(e.id)??0})),F=t.map(e=>{const t=v.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:S.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:O,initialSpawns:E,initialSpawnPacing:y?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:N,metadata:{kind:"process-flow",plot:i.plot,volume:b,stages:F,groups:B,groupCompletion:D,regionEffects:I}}}var ba=require("react");function xa(e,t){if(!t?.length)return[e];const n=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const n=t.datum;return!(!n||"object"!=typeof n||null==n.id)&&n.id+""===e}).map(e=>e.id);return n.length?n:[e]}function va(e,t,n){if("function"==typeof n)return n(e,t)+"";if("string"==typeof n){const t=e[n];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function wa(e,t){const n=e?.getData().find(e=>e.id===t),i=n?.datum;if(i&&"object"==typeof i)return i}function ka(e,t){const{frameRef:n,spawnDatum:i,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=(0,ba.useRef)(new Map),l=(0,ba.useRef)(new Map),d=(0,ba.useRef)(""),u=o?o.map((e,t)=>va(e,t,r)).join("\0"):"";if(u!==d.current&&(d.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],n=va(t,e,r);c.current.set(n,t),l.current.set(n,s?.(t,n,e)??xa(n,a))}(0,ba.useImperativeHandle)(e,()=>{const e=c.current,t=l.current;function o(e,t){const n=i(e,t);return{datumId:n.datumId||va(e,t,r),spawns:n.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(i){const o=[];for(const{datum:n,result:r}of i)e.set(r.datumId,n),t.set(r.datumId,r.spawns.map(e=>e.id)),o.push(...r.spawns);if(!o.length)return;const r=n.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(i){const o=e.get(i);if(o)return o;const r=t.get(i)??[i];for(const o of r){const r=wa(n.current,o);if(r)return e.set(i,r),t.has(i)||t.set(i,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const n=e.size;s(t.map((e,t)=>({datum:e,result:o(e,n+t)})))},remove:i=>{const o=Array.isArray(i)?i:[i],r=[],s=[];for(const n of o){const i=a(n);i&&r.push(i),e.delete(n),s.push(...t.get(n)??[n]),t.delete(n)}return s.length&&n.current?.remove(s),r},update:(i,r)=>{const c=Array.isArray(i)?i:[i],l=[];for(const i of c){const c=a(i);if(!c)continue;l.push(c);const d=t.get(i)??[i];n.current?.remove(d),e.delete(i),t.delete(i);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return l},clear:()=>{e.clear(),t.clear(),d.current="",n.current?.clear()},getData:()=>{const t=n.current;if(!t)return Array.from(e.values());const i=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return i.length?i:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>n.current?.snapshot()??null,popBodies:(e,t)=>n.current?.popBodies(e,t)??[]}},[n,r,i])}var Ma=require("react"),Ia=c(require("react")),Sa=require("react/jsx-runtime");function ja({componentName:e,message:t,diagnosticHint:n,width:i,height:o}){return(0,Sa.jsx)("div",{role:"alert",style:{width:i,height:Math.max(o,120),display:"flex",alignItems:"center",justifyContent:"center",border:"1px dashed rgba(128, 128, 128, 0.4)",borderRadius:8,background:"rgba(128, 128, 128, 0.04)",padding:24,boxSizing:"border-box"},children:(0,Sa.jsxs)("div",{style:{textAlign:"center",maxWidth:400},children:[(0,Sa.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"rgba(128, 128, 128, 0.7)",marginBottom:6,fontFamily:"monospace"},children:e}),(0,Sa.jsx)("div",{style:{fontSize:14,color:"rgba(128, 128, 128, 0.9)",lineHeight:1.5},children:t}),n&&(0,Sa.jsx)("div",{"data-testid":"semiotic-diagnostic-hint",style:{marginTop:10,padding:"8px 12px",background:"rgba(128, 128, 128, 0.06)",borderRadius:4,fontSize:12,color:"rgba(128, 128, 128, 0.8)",fontFamily:"monospace",textAlign:"left",whiteSpace:"pre-wrap",lineHeight:1.6},children:n})]})})}var Aa=require("react/jsx-runtime"),Ca=class extends Ia.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}render(){if(this.state.error){const{fallback:e}=this.props,t=this.state.error;return"function"==typeof e?e(t):void 0!==e?e:(0,Aa.jsx)(ja,{componentName:"ChartErrorBoundary",message:t.message||"An unexpected error occurred while rendering this chart.",width:600,height:400})}return this.props.children}},Ra=require("react/jsx-runtime");function $a({componentName:e,width:t,height:n,children:i}){return(0,Ra.jsx)(Ca,{fallback:i=>(0,Ra.jsx)(ja,{componentName:e,message:i.message,width:t,height:n}),children:i})}"undefined"!=typeof process&&process;var Pa={display:"flex",alignItems:"center",justifyContent:"center",color:"var(--semiotic-text-secondary, #666)",fontSize:13,fontFamily:"inherit",border:"1px dashed var(--semiotic-border, #ddd)",borderRadius:4,boxSizing:"border-box"},Ba={background:"var(--semiotic-border, #e0e0e0)",borderRadius:2},Da=require("react");function Ta(e){return[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)]}function Ea(e,t,n){const i=e=>e.toString(16).padStart(2,"0");return`#${i(e)}${i(t)}${i(n)}`}function Oa(e){const t=e.map(Ta),n=t.length-1;return e=>{if(0>=e){const[e,n,i]=t[0];return Ea(e,n,i)}if(e>=1){const[e,i,o]=t[n];return Ea(e,i,o)}const i=e*n,o=Math.floor(i),r=i-o,[s,a,c]=t[o],[l,d,u]=t[o+1];return Ea(Math.round(s+(l-s)*r),Math.round(a+(d-a)*r),Math.round(c+(u-c)*r))}}require("d3-scale");var Na=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Fa=Oa(["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]),Wa=Oa(["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]),qa=Oa(["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"]),za=Oa(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]),La=Oa(["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]),Ha=Oa(["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]),Ya={blues:Fa,reds:Wa,greens:qa,viridis:Oa(["#440154","#482878","#3e4989","#31688e","#26828e","#1f9e89","#35b779","#6ece58","#b5de2b","#fde725"]),oranges:za,purples:La,greys:Ha,plasma:Oa(["#0d0887","#41049d","#6a00a8","#8f0da4","#b12a90","#cb4679","#e16462","#f1844b","#fca636","#fcce25","#f0f921"]),inferno:Oa(["#000004","#160b39","#420a68","#6a176e","#932667","#bc3754","#dd513a","#f3771a","#fca50a","#f6d746","#fcffa4"]),magma:Oa(["#000004","#140e36","#3b0f70","#641a80","#8c2981","#b73779","#de4968","#f7705c","#fe9f6d","#fecf92","#fcfdbf"]),cividis:Oa(["#00224e","#123570","#3b496c","#575d6d","#707173","#8a8678","#a59c74","#c3b369","#e1cc55","#fee838","#ffea46"]),turbo:Oa(["#23171b","#4a58dd","#3f9ee9","#46c7af","#7eed5a","#cdf134","#fbb91f","#f56918","#c52f06","#7a0403"])},_a=(Oa(["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"]),Oa(["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"]),Oa(["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"]),Oa(["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"]),Oa(["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"]),Oa(["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]),Oa(["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"]),{category10:Na,tableau10:["#4e79a7","#f28e2c","#e15759","#76b7b2","#59a14f","#edc949","#af7aa1","#ff9da7","#9c755f","#bab0ab"],set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],...Ya}),Ga=Na;function Xa(e,t){if(null==t||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];return"string"==typeof n&&n.length>0?n:void 0}var Va=require("react");function Ua(e){const t=[];for(const[n,i]of Object.entries(e.fields))if("point"===i.type)t.push(e=>i.values.has(e[n]));else{const[e,o]=i.range;t.push(t=>{const i=t[n];return i>=e&&o>=i})}return e=>t.every(t=>t(e))}function Ka(e,t){let n=e.get(t);return n||(n={name:t,resolution:"union",clauses:new Map},e.set(t,n)),n}function Qa(e,t){if(e.type!==t.type)return!1;if("interval"===e.type&&"interval"===t.type)return e.range[0]===t.range[0]&&e.range[1]===t.range[1];if("point"===e.type&&"point"===t.type){if(e.values.size!==t.values.size)return!1;for(const n of e.values)if(!t.values.has(n))return!1;return!0}return!1}var[Za,Ja]=g(e=>({selections:new Map,setClause(t,n){e(e=>{const i=e.selections.get(t),o=i?.clauses.get(n.clientId);if(o&&function(e,t){if(e.clientId!==t.clientId||e.type!==t.type)return!1;const n=Object.entries(e.fields);if(n.length!==function(e){let t=0;for(const n in e)t++;return t}(t.fields))return!1;for(const[e,i]of n){const n=t.fields[e];if(!n||!Qa(i,n))return!1}return!0}(o,n))return{};const r=new Map(e.selections),s=Ka(r,t),a=new Map(s.clauses);return a.set(n.clientId,n),r.set(t,{...s,clauses:a}),{selections:r}})},clearClause(t,n){e(e=>{const i=e.selections.get(t);if(!i||!i.clauses.has(n))return{};const o=new Map(e.selections),r=new Map(i.clauses);return r.delete(n),o.set(t,{...i,clauses:r}),{selections:o}})},setResolution(t,n){e(e=>{const i=e.selections.get(t);if(i?.resolution===n)return{};const o=new Map(e.selections),r=Ka(o,t);return o.set(t,{...r,resolution:n}),{selections:o}})},clearSelection(t){e(e=>{const n=e.selections.get(t);if(!n||0===n.clauses.size)return{};const i=new Map(e.selections);return i.set(t,{...n,clauses:new Map}),{selections:i}})}})),ec=(require("react"),{positions:new Map}),tc=new Set;function nc(){for(const e of tc)e()}function ic(e,t){const n=ec.positions.get(e);if(n?.locked)return;if(!n||n.sourceId!==t)return;const i=new Map(ec.positions);i.delete(e),ec={positions:i},nc()}function oc(e,t){const n=ec.positions.get(e);if(!n?.locked)return;if(t&&n.sourceId!==t)return;const i=new Map(ec.positions);i.delete(e),ec={positions:i},nc()}function rc(e){const t=(0,Va.useId)(),n=e.clientId||t,{name:i}=e,o=Ja(e=>e.selections.get(i)),r=Ja(e=>e.setClause),s=Ja(e=>e.clearClause),a=(0,Va.useMemo)(()=>!!o&&o.clauses.size>0,[o]);return{predicate:(0,Va.useMemo)(()=>o&&0!==o.clauses.size?function(e,t){const n=[];for(const[i,o]of e.clauses)"crossfilter"===e.resolution&&i===t||n.push(Ua(o));return 0===n.length?()=>!0:"intersect"===e.resolution?e=>n.every(t=>t(e)):e=>n.some(t=>t(e))}(o,n):()=>!0,[o,n]),isActive:a,selectPoints:(0,Va.useCallback)(e=>{const t={};let o=!1;for(const[n,i]of Object.entries(e))t[n]={type:"point",values:new Set(i)},o=!0;o&&r(i,{clientId:n,type:"point",fields:t})},[n,i,r]),selectInterval:(0,Va.useCallback)(e=>{const t={};let o=!1;for(const[n,i]of Object.entries(e))t[n]={type:"interval",range:i},o=!0;o&&r(i,{clientId:n,type:"interval",fields:t})},[n,i,r]),clear:(0,Va.useCallback)(()=>{s(i,n)},[s,i,n]),clientId:n}}function sc(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var ac={enabled:!0,tapToSelect:!0,tapToLockTooltip:!0,clearSelection:"backgroundTap",targetSize:44,snap:"nearestDatum",brushHandleSize:44,standardControls:!1,enabled:!1,tapToSelect:!1,tapToLockTooltip:!1};function cc(e,t={}){const n=t.mobileSemantics?.interaction,i="number"==typeof n?.targetSize?n.targetSize:"number"==typeof t.mobileSemantics?.minimumHitTarget?t.mobileSemantics.minimumHitTarget:void 0,o="mobile"===t.mode||"number"==typeof t.width&&480>=t.width,r=!!n||void 0!==i,s=e&&"object"==typeof e?e:void 0;if(!1===e||!1===s?.enabled||void 0===e&&!o&&!r)return ac;const a=s??{};return{enabled:!0,tapToSelect:a.tapToSelect??!0,tapToLockTooltip:a.tapToLockTooltip??!0,clearSelection:a.clearSelection??"backgroundTap",targetSize:a.targetSize??i??44,snap:a.snap??"nearestDatum",brushHandleSize:a.brushHandleSize??44,standardControls:a.standardControls??!1}}var lc={primary:{width:600,height:400,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:void 0,showLabels:void 0,marginDefaults:{top:50,bottom:60,left:70,right:40}},context:{width:400,height:250,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:10,bottom:10,left:10,right:10}},sparkline:{width:120,height:24,showAxes:!1,showGrid:!1,enableHover:!1,showLegend:!1,showLabels:!1,marginDefaults:{top:2,bottom:2,left:0,right:0}},mobile:{width:390,height:300,showAxes:!0,showGrid:!1,enableHover:!0,showLegend:!1,showLabels:!0,marginDefaults:{top:28,bottom:42,left:44,right:16}}};function dc(e,t,n){if(!1!==t)return e;const i={...e};return"horizontal"===n?i.left=Math.min(i.left,15):i.bottom=Math.min(i.bottom,15),i}function uc(e,t,n){const i=e.xValue??t?.[n];if(null==i)return null;const o=Number(i);return Number.isFinite(o)?o:null}function hc(e){let t=e.data||e.datum||e;return Array.isArray(t)&&(t=t[0]),null!=e.xValue&&t&&"object"==typeof t&&!Array.isArray(t)&&null==t.xValue?{...t,xValue:e.xValue}:t||{}}var pc=[];function mc({selection:e,linkedHover:t,fallbackFields:n=pc,unwrapData:i=!1,onObservation:o,chartType:r,chartId:s,onClick:a,hoverHighlight:c,colorByField:l,mobileInteraction:d}){const u=(0,Da.useId)(),h=(0,Da.useMemo)(()=>function(e,t){return e?!0===e?{name:"hover",fields:t||[]}:"string"==typeof e?{name:e,fields:t||[]}:{name:e.name||"hover",fields:e.fields||t||[],mode:e.mode,xField:e.xField,seriesField:e.seriesField}:null}(t,n),[t,n]),p=(0,Da.useMemo)(()=>"series"===h?.mode?[h.seriesField||l||n[0]].filter(e=>!!e):h?.fields||n,[h,l,n]),m=rc({name:e?.name||"__unused__",fields:p}),f=function(e){const t=e.name||"hover",{fields:n}=e,{predicate:i,isActive:o,selectPoints:r,clear:s}=rc({name:t,fields:n});return{onHover:(0,Va.useCallback)(e=>{if(!e)return void s();const t={};for(const i of n){const n=e[i];void 0!==n&&(t[i]=[n])}(function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1})(t)&&r(t)},[n,r,s]),predicate:i,isActive:o}}({name:h?.name||"hover",fields:p}),y=hn(e=>e.pushObservation),g=(0,Da.useCallback)(e=>{o?.(e),y?.(e)},[o,y]),b=e?{isActive:m.isActive,predicate:m.predicate}:null,[x,v]=(0,Da.useState)(null),w=(0,Da.useRef)(!1),k=l||n[0],M=(0,Da.useMemo)(()=>{if(!c||null==x||!k)return null;const e=x,t=k;return{isActive:!0,predicate:n=>("string"==typeof n[t]?n[t]:(n[t]??"")+"")===e}},[c,x,k]),I=(0,Da.useCallback)((e,n)=>{const i=!e&&w.current&&!!d?.enabled&&d.tapToLockTooltip;if(t)if(e){let t=e.data||e.datum||e;if(Array.isArray(t)&&(t=t[0]),"x-position"===h?.mode&&h.xField){const n=uc(e,t,h.xField);null!=n&&function(e,t,n){const i=ec.positions.get(e);i?.locked||i&&i.xValue===t&&i.sourceId===n||(ec={positions:new Map(ec.positions).set(e,{xValue:t,sourceId:n})},nc())}(h.name||"hover",n,u)}"x-position"!==h?.mode&&f.onHover(t)}else"x-position"!==h?.mode||i||ic(h.name||"hover",u),"x-position"===h?.mode||i||f.onHover(null);if(c&&k)if(e){let t=e.data||e.datum||e;Array.isArray(t)&&(t=t[0]);const n=t?.[k];v(null!=n?n+"":null)}else i||v(null);(o||y)&&function(e){const{onObservation:t,datum:n,x:i=0,y:o=0,chartType:r,chartId:s,context:a,timestamp:c=Date.now()}=e;t&&(n?(t({type:"hover",datum:n,x:i,y:o,timestamp:c,chartType:r,chartId:s}),"focus"===a?.type&&t({type:"focus",datum:n,inputType:"touch"===a.inputType?"pointer":a.inputType,timestamp:c,chartType:r,chartId:s})):t({type:"hover-end",timestamp:c,chartType:r,chartId:s}))}({onObservation:g,datum:e?hc(e):null,x:e?.x,y:e?.y,chartType:r||"unknown",chartId:s,context:n})},[t,f,h,u,o,r,s,y,g,c,k,d]),S=(0,Da.useCallback)((n=!0)=>{w.current=!1,t&&"x-position"!==h?.mode&&f.onHover(null),e&&d?.tapToSelect&&m.clear(),n&&c&&v(null),"x-position"===h?.mode&&(oc(h.name||"hover",u),ic(h.name||"hover",u))},[t,h,f,e,d,m,c,u]),j=(0,Da.useCallback)((n,i)=>{const l=!!d?.enabled&&(d.tapToLockTooltip||d.tapToSelect),b=!!d?.enabled&&"backgroundTap"===d.clearSelection;if("x-position"===h?.mode&&h.xField&&n){let e=n.data||n.datum||n;Array.isArray(e)&&(e=e[0]);const t=uc(n,e,h.xField);null!=t&&function(e,t,n){const i=ec.positions.get(e);if(i?.locked){const t=new Map(ec.positions);return t.delete(e),ec={positions:t},nc(),!1}ec={positions:new Map(ec.positions).set(e,{xValue:t,sourceId:n,locked:!0})},nc()}(h.name||"hover",t,u)}if(l)if(n){w.current=!0;const i=hc(n);if(t&&"x-position"!==h?.mode&&f.onHover(i),e&&d?.tapToSelect&&p.length>0){const e={};for(const t of p){const n=i[t];void 0!==n&&(e[t]=[n])}(function(e){if(!e)return!1;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1})(e)&&m.selectPoints(e)}if(c&&k){const e=i?.[k];v(null!=e?e+"":null)}}else b&&S();if(n||b){if(n&&a){let e=n.data||n.datum||n;Array.isArray(e)&&(e=e[0]),a(e,{x:n.x??0,y:n.y??0})}(o||y)&&function(e){const{onObservation:t,datum:n,x:i=0,y:o=0,chartType:r,chartId:s,context:a,timestamp:c=Date.now()}=e;t&&(n?(t({type:"click",datum:n,x:i,y:o,timestamp:c,chartType:r,chartId:s}),"activate"===a?.type&&t({type:"activate",datum:n,inputType:a.inputType,timestamp:c,chartType:r,chartId:s})):t({type:"click-end",timestamp:c,chartType:r,chartId:s}))}({onObservation:g,datum:n?hc(n):null,x:n?.x,y:n?.y,chartType:r||"unknown",chartId:s,context:i})}},[a,o,y,g,r,s,h,u,d,t,f,e,m,p,c,k,S]);return(0,Da.useEffect)(()=>{if(!d?.enabled||"undefined"==typeof document)return;const e=e=>{"Escape"===e.key&&w.current&&S()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[d?.enabled,S]),(0,Da.useEffect)(()=>()=>{w.current&&S(!1)},[S]),(0,Da.useEffect)(()=>{if("x-position"!==h?.mode)return;const e=h.name||"hover";return()=>{oc(e,u),ic(e,u)}},[h?.mode,h?.name,u]),{activeSelectionHook:b,hoverSelectionHook:M,customHoverBehavior:I,customClickBehavior:j,crosshairSourceId:u}}function fc(e,t,n){return function(e,t,n){const i=lc[e||"primary"],o=e&&"primary"!==e||!n?.width?i.width:n.width,r=e&&"primary"!==e||!n?.height?i.height:n.height,s=function(e,t,n=e.responsiveRules){if(!Array.isArray(n)||0===n.length)return{props:e,matches:[]};const i=n.map((e,t)=>({rule:e,index:t})).filter(e=>function(e,t){const{when:n}=e,i=t.width,o=t.height,r=function(e){if("number"==typeof e.height&&e.height>0)return e.width/e.height}(t),s=function(e){if("number"==typeof e.height&&e.height>0)return e.height>e.width?"portrait":"landscape"}(t);return!("number"==typeof n.minWidth&&n.minWidth>i||"number"==typeof n.maxWidth&&i>n.maxWidth||"number"==typeof n.minHeight&&("number"!=typeof o||n.minHeight>o)||"number"==typeof n.maxHeight&&("number"!=typeof o||o>n.maxHeight)||"number"==typeof n.minAspectRatio&&("number"!=typeof r||n.minAspectRatio>r)||"number"==typeof n.maxAspectRatio&&("number"!=typeof r||r>n.maxAspectRatio)||n.orientation&&s!==n.orientation)}(e.rule,t)).sort((e,t)=>("number"==typeof e.rule.priority?e.rule.priority:e.index)-("number"==typeof t.rule.priority?t.rule.priority:t.index));return{props:i.reduce((e,t)=>function(e,t){const n={...e,...t};for(const i of["margin","frameProps","mobileSemantics","style"])sc(e[i])&&sc(t[i])&&(n[i]={...e[i],...t[i]});return"string"==typeof e.className&&"string"==typeof t.className&&(n.className=`${e.className} ${t.className}`),n}(e,t.rule.transform),e),matches:i}}({...t,mode:e},{width:t.width??o,height:t.height??r}).props,a=s.mode||e||"primary",c=lc[a],l="context"===a||"sparkline"===a,d="primary"===a&&n?.width?n.width:c.width;return{mode:a,width:s.width??d,height:s.height??("primary"===a&&n?.height?n.height:c.height),showAxes:s.showAxes??c.showAxes,showGrid:s.showGrid??c.showGrid,enableHover:s.enableHover??(!!s.linkedHover||c.enableHover),showLegend:s.showLegend??c.showLegend,showLabels:s.showLabels??c.showLabels,title:l?void 0:s.title,description:s.description,summary:s.summary,accessibleTable:s.accessibleTable,xLabel:l?void 0:s.xLabel,yLabel:l?void 0:s.yLabel,categoryLabel:l?void 0:s.categoryLabel,valueLabel:l?void 0:s.valueLabel,marginDefaults:dc(c.marginDefaults,s.showCategoryTicks,s.orientation),compactMode:l,mobileInteraction:cc(s.mobileInteraction,{mode:a,width:s.width??d,mobileSemantics:s.mobileSemantics}),mobileSemantics:s.mobileSemantics}}(e,t,n)}var yc=require("react/jsx-runtime");function gc(e){return!!e&&"string"==typeof e.name}function bc(e,t=!1){if(!e?.datum)return null;const n=e.datum,i=n.sourceDatum;return t&&i&&"object"==typeof i?i:n}function xc(e){const{selection:t,linkedHover:n,colorBy:i,chartType:o,chartId:r,onBodyHover:s,fallbackFields:a,unwrapSourceDatum:c}=e,l="string"==typeof i?i:void 0,d=gc(t)?t:void 0,{activeSelectionHook:u,customHoverBehavior:h}=mc({selection:d,linkedHover:n,fallbackFields:l?[l]:a,onObservation:e.onObservation,onClick:e.onClick,chartType:o,chartId:r,colorByField:l}),p=gc(t)?null:t??null,m=(0,Ma.useMemo)(()=>{if(p)return p;if(!u?.isActive)return null;const e=u.predicate;return{isActive:!0,predicate:t=>{const n=bc(t,c);return null!=n&&e(n)}}},[u?.isActive,u?.predicate,p,c]),f=(0,Ma.useMemo)(()=>{if(n||s)return(e,t)=>{if(s?.(e,t),!n)return;const i=bc(e,c);h(i&&t?{...t,data:i}:null)}},[h,s,n,c]);return(0,Ma.useMemo)(()=>({selection:m,onBodyHover:f}),[f,m])}var vc=new Set(["sample","mechanical"]);function wc(e,t,n,i){const[o,r]=(0,Ma.useState)(0),s=(0,Ma.useRef)(null),a=(0,Ma.useRef)(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),l=(0,Ma.useRef)(c),d=(0,Ma.useRef)(!!n),u=(0,Ma.useRef)(i);l.current=c,d.current=!!n,u.current=i;const h=(0,Ma.useCallback)(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=(0,Ma.useCallback)(()=>{h();const e=l.current;null!=e&&!d.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(e=>e+1)},e))},[h]);(0,Ma.useEffect)(()=>{null==c||n?h():a.current&&p()},[h,c,n,p]),(0,Ma.useEffect)(()=>h,[h]);const m=e?.observation?.onSimulationStateChange,f=(0,Ma.useCallback)((e,t)=>{if(m?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,m,p]);return{config:(0,Ma.useMemo)(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:f}},[e,c,f]),rerunKey:o}}function kc(e,t,n){const i=n?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&vc.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=fc(i.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],l=(0,Ma.useMemo)(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),d=o.compactMode?"sparkline"===i.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const u=e.showProjection??!o.compactMode,h=e.showChrome??!o.compactMode,p=jc(e.tooltip,void 0),m=void 0!==p.enableHover?p.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??e.title,y=[e.className,i.chartMode&&"primary"!==i.chartMode?"semiotic-physics--"+i.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:i.chartMode,simulationMode:i.simulationMode,resolved:o,chartSize:l,margin:d,showProjection:u,showChrome:h,enableHover:m,title:f,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:y,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function Mc(e){const[t,n]=e.size,i=function(e,t,n,i){if(!e)return null;if(!1===i)return null;if(null!=i)return(0,Ra.jsx)("div",{style:{width:t,height:n,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:i});const o=Math.min(5,Math.floor(n/40)),r=Math.max(8,Math.floor(n/(3*o))),s=Math.max(6,Math.floor(n/(2.5*o))),a=Math.floor((n-(o*(r+s)-s))/2);return(0,Ra.jsx)("div",{style:{width:t,height:n,position:"relative",overflow:"hidden",border:"1px solid var(--semiotic-border, #e0e0e0)",borderRadius:4,boxSizing:"border-box"},children:Array.from({length:o},(e,n)=>(0,Ra.jsx)("div",{className:"semiotic-loading-bar",style:{...Ba,position:"absolute",top:a+n*(r+s),left:Math.floor(.1*t),width:30+(37*n+13)%50+"%",height:r,opacity:.5+n%2*.2}},n))})}(e.loading,t,n,e.loadingContent);return i||function(e,t,n,i){return!1===i||null==e||Array.isArray(e)&&e.length>0?null:Array.isArray(e)?(0,Ra.jsx)("div",{style:{...Pa,width:t,height:n},children:i||"No data available"}):null}(e.data,t,n,e.emptyContent)}function Ic(e,t,n){return(0,yc.jsx)($a,{componentName:e,width:t[0],height:t[1],children:n})}function Sc(e,t){return e?t?n=>(0,yc.jsxs)(yc.Fragment,{children:["function"==typeof e?e(n):e,"function"==typeof t?t(n):t]}):e:t}function jc(e,t){return!1===e?{enableHover:!1}:{enableHover:t?.enableHover,tooltipContent:Ne(e)||t?.tooltipContent}}function Ac(e,t,n,i){return{accessibleTable:i?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:i?.chartMode??t?.chartMode,className:i?.className??e.className??t?.className,color:e.color??t?.color,description:i?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:i?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:i?.margin??t?.margin,onClick:null!=e.onClick?(t,n)=>{t&&e.onClick?.(t,{x:n.x,y:n.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,selection:i?.selection??t?.selection,semanticItems:t?.semanticItems??n,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:i?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:i?.title??e.title??t?.title}}var Cc=require("react/jsx-runtime"),Rc=(0,d.forwardRef)(function(e,t){const{data:n,valueAccessor:i="value",styleRules:o,bins:r=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:l,frameProps:u,loading:h,loadingContent:p,mechanicalCount:m,paused:f,pegRows:y,referenceLines:g,rerunMS:b,responsiveHeight:x,responsiveWidth:v,seed:w=1,valueExtent:k}=e,M=kc(e,[700,420],{hasSimulationMode:!0}),{chartSize:I,simulationMode:S,showProjection:j,className:A,title:C,chartMode:R,margin:$,enableHover:P,description:B,summary:D,accessibleTable:T}=M,E=s??("sparkline"===R?1.5:"context"===R?4:6),O=(0,d.useRef)(null),N=Math.max(1,Math.round(y??r-1)),F=(0,d.useMemo)(()=>"mechanical"===S?[0,N]:function(e){if(!e)return;const t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?t>n?[n,t]:[t,n]:void 0}(k),[N,S,k]),W=(0,d.useMemo)(()=>"mechanical"===S?function(e){const t=Math.max(2,Math.round(e.bins)),n=Math.max(1,Math.round(e.pegRows??t-1)),i=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=Rs(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Bs(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:i},(e,t)=>{let i=0;for(let e=0;n>e;e+=1)r()<o&&(i+=1);const a=n/2;return{id:`${s}-${t}`,value:i,mechanical:!0,pegRows:n,branchProbability:o,pathRights:i,side:a>i?"left":i>a?"right":"center"}})}({bins:r,branchProbability:c,count:m,pegRows:N,seed:w}):n??[],[r,c,n,m,N,w,S]),q=(0,d.useMemo)(()=>Ts({data:W,valueAccessor:i,bins:r,ballRadius:E,seed:w,size:I,valueExtent:F}),[r,W,I,E,F,w,i]),z=wc(q.config,b,f);ka(t,{frameRef:O,spawnDatum:(0,d.useCallback)((e,t)=>{const n=Ts({data:[e],valueAccessor:i,bins:r,ballRadius:E,seed:w+t+1,size:I,valueExtent:F}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:ks(I).plot.x,y:ks(I).plot.y,mass:1,shape:{type:"circle",radius:E},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[r,I,E,F,w,i]),seedRows:W,seedSpawns:q.initialSpawns});const L="mechanical"===S&&null==a?"side":a,H=(0,d.useMemo)(()=>Is(L,"#4e79a7",{styleRules:o,valueAccessor:i}),[L,o,i]),Y=(0,d.useMemo)(()=>js(q.projectionRows,I,"bin"),[I,q.projectionRows]),{selection:_,onBodyHover:G}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:a,chartType:"GaltonBoardChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:u?.onBodyHover,fallbackFields:"string"==typeof i?[i]:void 0}),X=Mc({data:"mechanical"===S?W:n,emptyContent:l,loading:h,loadingContent:p,size:I});if(X)return X;const V=function(e,t,n,i,o){const r=Array.isArray(o)?o:o?[o]:[];if(!1!==n||0!==r.length)return({size:o})=>{const s=[Number(o[0])||700,Number(o[1])||420],a=ks(s),c=Math.max(2,Math.round(t)),l=a.plot.width/c,d=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==n,[p,m]=i?.valueExtent??[0,c],f=m===p?1:m-p,y=e.map((e,t)=>{const n=d-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*l).toFixed(1)} ${n.toFixed(1)}`}).join(" ");return(0,Cc.jsxs)("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?(0,Cc.jsxs)(Cc.Fragment,{children:[Array.from({length:c+1},(e,t)=>{const n=a.plot.x+t*l;return(0,Cc.jsx)("line",{"data-testid":"galton-board-bin-wall",x1:n,x2:n,y1:a.plot.y,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),(0,Cc.jsx)("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,Cc.jsx)("path",{d:y,fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?(0,Cc.jsx)("text",{x:a.plot.x+(t+.5)*l,y:Math.max(a.plot.y+10,d-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,r.map((e,t)=>{const n=Number(e.value);if(!Number.isFinite(n))return null;const i=a.plot.x+Math.max(0,Math.min(1,(n-p)/f))*a.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===e.labelPosition?Math.min(s[1]-8,d+16):a.plot.y+16;return(0,Cc.jsxs)("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[(0,Cc.jsx)("line",{x1:i,x2:i,y1:a.plot.y+8,y2:d-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:(0,Cc.jsx)("text",{x:Math.min(a.plot.x+a.plot.width-4,i+6),y:r,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${n}`)})]})}}(q.projectionRows,r,j,q.metadata,g),U=jc(e.tooltip,u),K=Ac(e,u,Y,{selection:_,chartMode:R,className:A,title:C,description:B,summary:D,accessibleTable:T,enableHover:P,margin:$});return Ic("GaltonBoardChart",I,(0,Cc.jsx)(fs,{...u,...U,...K,ref:O,onBodyHover:G,config:z.config,foregroundGraphics:Sc(V,u?.foregroundGraphics),initialSpawns:q.initialSpawns,initialSpawnPacing:q.initialSpawnPacing,paused:f,responsiveHeight:x,responsiveWidth:v,size:I,bodyStyle:H},z.rerunKey))}),$c=require("react"),Pc=require("react/jsx-runtime"),Bc=require("react"),Dc=(0,$c.forwardRef)(function(e,t){const{arrivalAccessor:n="arrivalTime",ballRadius:i=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:l,loadingContent:d,paused:u,rerunMS:h,responsiveHeight:p,responsiveWidth:m,seed:f=1,timeAccessor:y="time",timeExtent:g,timeScale:b=1,watermark:x,windows:v={size:10}}=e,w=kc(e,[760,360]),{chartSize:k,showProjection:M,className:I,title:S,chartMode:j,margin:A,enableHover:C,description:R,summary:$,accessibleTable:P}=w,B=(0,$c.useRef)(null),D=(0,$c.useMemo)(()=>s??[],[s]),T=(0,$c.useMemo)(()=>Ns({data:D,timeAccessor:y,arrivalAccessor:n,windows:v,watermark:x,ballRadius:i,seed:f,size:k,timeExtent:g,timeScale:b}),[n,i,k,D,f,y,g,b,x,v]),E=wc(T.config,h,u),O=T.metadata;ka(t,{frameRef:B,spawnDatum:(0,$c.useCallback)((e,t)=>{const o=O?function(e,t,n,i){const o=Cs(As(e,t,i.timeAccessor));if(null==o)return null;const r=Cs(As(e,t,i.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:l,watermarkValue:d}=n,u=a+c*l,h=(0,Es.scaleLinear)().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/l))),m=d>=a+(p+1)*l,{ballRadius:f}=i;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+f,Math.min(s.x+s.width-f,h(o))),y:s.y+f+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:f},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(e,t,O,{timeAccessor:y,arrivalAccessor:n,ballRadius:i}):null,r=o??{id:(e.id??"event-push-"+t)+"",x:ks(k).plot.x,y:ks(k).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??r.id)+"",spawns:[r]}},[n,i,k,O,y]),seedRows:D,seedSpawns:T.initialSpawns});const N=(0,$c.useMemo)(()=>Is(o,"#4e79a7",{styleRules:r,valueAccessor:y}),[o,r,y]),F=(0,$c.useMemo)(()=>function(e,t,n){if(!t)return js(e,n,"window");const i=t.windowPlot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),r=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,n)=>{const a=Math.max(8,(e.value+(e.secondary??0))/o*r),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(n+.5)*i,y:s-a/2,shape:"rect",width:Math.max(12,.58*i),height:a,group:"window"}})}(T.projectionRows,O,k),[k,T.projectionRows,O]),{selection:W,onBodyHover:q}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"EventDropChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof y?[y]:void 0}),z=Mc({data:s,emptyContent:a,loading:l,loadingContent:d,size:k});if(z)return z;const L=function(e,t,n){if(!1!==n&&t)return({size:n})=>{const i=[Number(n[0])||760,Number(n[1])||360],o=ks(i),r=Math.max(1,t.windowCount),s=t.plot??o.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,l=c.width/r,d=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,m=t.windowStart+r*t.windowSize,f=c.x+Math.max(0,Math.min(1,m===p?0:(t.watermarkValue-p)/(m-p)))*c.width;return(0,Pc.jsxs)("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,Pc.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?(0,Pc.jsxs)("g",{children:[(0,Pc.jsx)("rect",{x:a.x,y:h,width:a.width,height:d-h,fill:"var(--semiotic-danger, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),(0,Pc.jsx)("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:r},(n,o)=>{const r=e[o],s=c.x+o*l,a=t.closedWindowCount>o,h=r?.secondary??0;return(0,Pc.jsxs)("g",{children:[(0,Pc.jsx)("rect",{x:s,y:u,width:l,height:d-u,fill:a?"var(--semiotic-danger, #e15759)":"var(--semiotic-primary, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===o).map(e=>(0,Pc.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,(0,Pc.jsxs)("text",{x:s+l/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),(0,Pc.jsx)("text",{x:s+l/2,y:Math.min(i[1]-8,d+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>(0,Pc.jsx)("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),(0,Pc.jsx)("line",{x1:s.x,x2:s.x+s.width,y1:d,y2:d,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),(0,Pc.jsx)("line",{"data-testid":"event-drop-watermark",x1:f,x2:f,y1:s.y+8,y2:d,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),(0,Pc.jsxs)("text",{x:Math.min(s.x+s.width-4,f+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?(0,Pc.jsxs)("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(T.projectionRows,T.metadata,M),H=jc(e.tooltip,c),Y=Ac(e,c,F,{selection:W,chartMode:j,className:I,title:S,description:R,summary:$,accessibleTable:P,enableHover:C,margin:A});return Ic("EventDropChart",k,(0,Bc.createElement)(fs,{...c,...H,...Y,ref:B,onBodyHover:q,key:E.rerunKey,config:E.config,foregroundGraphics:Sc(L,c?.foregroundGraphics),initialSpawns:T.initialSpawns,initialSpawnPacing:T.initialSpawnPacing,paused:u,responsiveHeight:p,responsiveWidth:m,size:k,bodyStyle:N}))}),Tc=require("react"),Ec=require("react/jsx-runtime"),Oc=require("react"),Nc=(0,Tc.forwardRef)(function(e,t){const{ballRadius:n=8,categoryAccessor:i="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:l,mechanicalCategories:d,mechanicalCount:u,paused:h,rerunMS:p,responsiveHeight:m,responsiveWidth:f,seed:y=1,unitValue:g=1,valueAccessor:b,styleRules:x}=e,v=kc(e,[700,380],{hasSimulationMode:!0}),{chartSize:w,simulationMode:k,showProjection:M,className:I,title:S,chartMode:j,margin:A,enableHover:C,description:R,summary:$,accessibleTable:P}=v,B=(0,Tc.useRef)(null),D="mechanical"===k&&null==b?"value":b,T=(0,Tc.useMemo)(()=>"mechanical"===k?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),n=t.length?t:["Intake"],i=Math.max(n.length,Math.round(e.count??Math.max(48,12*n.length))),o=$s(e.unitValue,1),r=Bs(e.seed??1),s=e.idPrefix??"mechanical-pile",a=n.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,l=i-n.length,d=a.map(e=>e/c*l),u=d.map(e=>1+Math.floor(e));let h=i-u.reduce((e,t)=>e+t,0);const p=d.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)u[p[e].index]+=1,h-=1;return n.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/i}))}({categories:d,count:u,seed:y,unitValue:g}):r??[],[r,d,u,y,k,g]),E=(0,Tc.useMemo)(()=>Ws({data:T,categoryAccessor:i,valueAccessor:D,unitValue:g,ballRadius:n,seed:y,size:w}),[n,i,w,T,D,y,g]),O=wc(E.config,p,h);ka(t,{frameRef:B,spawnDatum:(0,Tc.useCallback)((e,t)=>{const o=Ws({data:[e],categoryAccessor:i,valueAccessor:D,unitValue:g,ballRadius:n,seed:y+t+1,size:w}),r={id:(e.id??"pile-push-"+t)+"",x:ks(w).plot.x,y:ks(w).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(e.id??s[0].id)+"",spawns:s}},[n,i,w,D,y,g]),seedRows:T,seedSpawns:E.initialSpawns});const N="mechanical"===k&&null==o?"category":o,F=(0,Tc.useMemo)(()=>Is(N,"#4e79a7",{styleRules:x,valueAccessor:b}),[N,x,b]),W=(0,Tc.useMemo)(()=>js(E.projectionRows,w,"category"),[w,E.projectionRows]),{selection:q,onBodyHover:z}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"UnitPileChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof i?[i]:void 0}),L=Mc({data:"mechanical"===k?T:r,emptyContent:s,loading:c,loadingContent:l,size:w});if(L)return L;const H=function(e,t,n){if(!1!==n&&0!==e.length)return({size:n})=>{const i=[Number(n[0])||700,Number(n[1])||380],o=ks(i),r=Fs(o.plot,e.length,t),s=o.plot.y+o.plot.height;return(0,Ec.jsxs)("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,Ec.jsx)("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const n=Math.min(o.plot.height,r.pileHeight(e.value)),a=r.tubeWidth,c=r.centerX(t),l=s-n;return(0,Ec.jsxs)("g",{children:[(0,Ec.jsx)("rect",{x:c-a/2,y:l,width:a,height:n,rx:3,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),(0,Ec.jsx)("text",{x:c,y:Math.max(o.plot.y+12,l-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),(0,Ec.jsx)("text",{x:c,y:Math.min(i[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(E.projectionRows,n,M),Y=jc(e.tooltip,a),_=Ac(e,a,W,{selection:q,chartMode:j,className:I,title:S,description:R,summary:$,accessibleTable:P,enableHover:C,margin:A});return Ic("UnitPileChart",w,(0,Oc.createElement)(fs,{...a,...Y,..._,ref:B,onBodyHover:z,key:O.rerunKey,config:O.config,foregroundGraphics:Sc(H,a?.foregroundGraphics),initialSpawns:E.initialSpawns,initialSpawnPacing:E.initialSpawnPacing,paused:h,responsiveHeight:m,responsiveWidth:f,size:w,bodyStyle:F}))}),Fc=Nc,Wc=require("react"),qc=Object.freeze([]);function zc(e){if(!e)return qc;let t=!1;for(let n=0;e.length>n;n++){const i=e[n];if(null==i||"object"!=typeof i){t=!0;break}}if(!t)return e;const n=[];for(const t of e)null!=t&&"object"==typeof t&&n.push(t);return n}var Lc=require("d3-scale");function Hc(e,t){const n=t&&"object"==typeof t&&!Array.isArray(t)?t:void 0;return 0===e.length?e=>n&&Xa(n,e)||"#4e79a7":t=>{if(n){const e=Xa(n,t);if(e)return e}let i=0;for(let e=0;t.length>e;e++)i=31*i+t.charCodeAt(e)|0;return e[Math.abs(i)%e.length]??"#4e79a7"}}function Yc(e,t){const n=t.config??{},i=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...i],r=[...e.colliders??[],...n.colliders??[],...o];return{...e,...n,observation:{...e.observation,...n.observation},...r.length>0&&{colliders:r}}}function _c(e){const t=function(e,t,n){const i=e?.observation;return{...e,observation:{...i,chartId:t??i?.chartId??"physics-custom",chartType:i?.chartType??"PhysicsCustomChart",onObservation:n??i?.onObservation}}}(e.config,e.chartId,e.onObservation),n=function(e,t,n=Ga){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=Object.values(e).filter(e=>"string"==typeof e&&e.length>0);if(t.length>0)return t}if(Array.isArray(e)&&e.length>0)return e;if("string"==typeof e){const t=_a[e];if(Array.isArray(t)&&t.length>0)return t}return t&&t.length>0?t:n}(e.colorScheme,e.themeCategorical,Na),i=ks(e.size),o={data:e.data,scales:{x:(0,Lc.scaleLinear)().domain(e.xExtent??[0,1]).range([i.plot.x,i.plot.x+i.plot.width]),y:(0,Lc.scaleLinear)().domain(e.yExtent??[0,1]).range([i.plot.y+i.plot.height,i.plot.y])},dimensions:i,theme:{semantic:e.semantic,categorical:[...n]},resolveColor:Hc(n,e.colorScheme),config:e.layoutConfig??{},world:new $o(t)},r=e.skipLayout?{}:e.layout(o)??{},s=function(e,t){if(!t?.length)return e;const n=new Map;for(const e of t){const{bodyId:t,...i}=e,o=n.get(t)??[];o.push(i),n.set(t,o)}return e.map(e=>{const t=n.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...r.initialSpawns??r.bodies??[]],r.constraints);return{config:Yc(t,r),context:o,initialSpawnPacing:r.initialSpawnPacing,initialSpawns:s,result:r}}var Gc=require("react/jsx-runtime"),Xc=(0,Wc.forwardRef)(function(e,t){const{chartId:n,color:i,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:l,frameProps:d={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:f,opacity:y,paused:g,spawnDatum:b,stroke:x,strokeWidth:v,title:k,xExtent:M,yExtent:I}=e,S=kc(e,[700,380]),{chartSize:A,className:C,title:R,chartMode:$,margin:P,enableHover:B,description:D,summary:T,accessibleTable:E}=S,O=(0,Wc.useRef)(null),N=(0,Wc.useRef)(null),F=(0,Wc.useRef)(""),{selection:W,onBodyHover:q}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"PhysicsCustomChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:d?.onBodyHover}),z=Mc({data:c,emptyContent:l,loading:p,loadingContent:m,size:A}),L=null!=z,H=(0,Wc.useMemo)(()=>zc(c??[]),[c]),Y=j(e=>e.theme),_=(0,Wc.useMemo)(()=>function(e){if(!e?.colors)return;const t=e.colors;return{primary:t.primary,secondary:t.secondary||t.primary,surface:t.surface||t.background,success:t.success,danger:t.danger,warning:t.warning,error:t.error,info:t.info,text:t.text,textSecondary:t.textSecondary,border:t.border,grid:t.grid}}(Y)??{},[Y]),G=Y?.colors?.categorical??w.colors.categorical,X=(0,Wc.useMemo)(()=>[A[0],A[1],H.length,H.map((e,t)=>(e.id??t)+"").join("|"),M?.join(",")??"",I?.join(",")??""].join("::"),[A,H,M,I]),V=(0,Wc.useMemo)(()=>_c({chartId:n,colorScheme:r,config:s,data:H,layout:u,layoutConfig:h,onObservation:f,semantic:_,skipLayout:L,size:A,themeCategorical:G,xExtent:M,yExtent:I}),[n,A,r,s,u,h,f,H,_,L,G,M,I]);F.current===X&&null!=N.current||(F.current=X,N.current=V.initialSpawns);const U=N.current,K=(0,Wc.useMemo)(()=>{const e=[...V.result.controllers??[],...a??[],...d.controllers??[]];return e.length?e:void 0},[d.controllers,a,V.result.controllers]),Q=(0,Wc.useMemo)(()=>{const e=[...V.result.regionEffects??[],...d.regionEffects??[]];return e.length?e:void 0},[d.regionEffects,V.result.regionEffects]),Z=(0,Wc.useCallback)(e=>{const t=e.datum,n=t&&o?function(e,t,n){return"function"==typeof n?n(e,0):e[n]}(t,0,o)+"":e.id;return{fill:i??V.context.resolveColor(n,t),stroke:x??"#111827",strokeWidth:v??1,opacity:y??.9}},[i,o,y,V.context,x,v]);ka(t,{frameRef:O,spawnDatum:(0,Wc.useCallback)((e,t)=>{const i=e;if(b)return function(e,t,n){return Array.isArray(n)?{datumId:(e.id??n[0]?.id??"physics-custom-"+t)+"",spawns:n}:"spawns"in n?n:{datumId:(e.id??n.id??"physics-custom-"+t)+"",spawns:[n]}}(e,t,b(i,t,V.context));const o=_c({chartId:n,colorScheme:r,config:s,data:[i],layout:u,layoutConfig:h,onObservation:f,semantic:_,size:A,themeCategorical:G,xExtent:M,yExtent:I}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[n,A,r,s,b,u,h,f,V.context,_,G,M,I]),seedRows:H,seedSpawns:U});const J=(0,Wc.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]);if(z)return z;const ee=jc(e.tooltip,d),te=Ac(e,d,V.result.semanticItems,{selection:W,chartMode:$,className:C,title:R??k,description:D,summary:T,accessibleTable:E,enableHover:B,margin:P});return Ic("PhysicsCustomChart",A,(0,Gc.jsx)(fs,{...d,...ee,...te,ref:O,onBodyHover:q,backgroundGraphics:Sc(d.backgroundGraphics,V.result.backgroundOverlays),bodyForces:V.result.bodyForces??d.bodyForces,bodyStyle:V.result.bodyStyle??d.bodyStyle??Z,config:V.config,controllers:K,foregroundGraphics:Sc(d.foregroundGraphics,V.result.overlays),initialSpawnPacing:V.initialSpawnPacing,initialSpawns:U,onBodyPointerDown:J,paused:g,regionEffects:Q,responsiveHeight:e.responsiveHeight,responsiveWidth:e.responsiveWidth,selectedBodyStyle:V.result.selectedBodyStyle??d.selectedBodyStyle,size:A}))});Xc.displayName="PhysicsCustomChart";var Vc=require("react"),Uc=require("react/jsx-runtime");function Kc(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var Qc=(0,Vc.forwardRef)(function(e,t){const{colorBy:n,styleRules:i,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:l,loadingContent:d,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:m,responsiveHeight:f,responsiveWidth:y,seed:g=1,settle:b,xAccessor:x="x",xExtent:v}=e,w=kc(e,[700,360]),{chartSize:k,showProjection:M,className:I,title:S,chartMode:j,margin:A,enableHover:C,description:R,summary:$,accessibleTable:P}=w,B=h??("sparkline"===j?2:"context"===j?4:5),D=(0,Vc.useRef)(null),T=(0,Vc.useMemo)(()=>r??[],[r]),E=(0,Vc.useMemo)(()=>zs({data:T,xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:B,seed:g,size:k,xExtent:v,collisionIterations:o,settle:b}),[T,k,o,c,B,p,g,b,x,v]),O=wc(E.config,m,u);ka(t,{frameRef:D,spawnDatum:(0,Vc.useCallback)((e,t)=>{const n=zs({data:[e],xAccessor:x,groupAccessor:c,radiusAccessor:p,pointRadius:B,seed:g+t+1,size:k,xExtent:v,collisionIterations:o,settle:b}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:ks(k).plot.x,y:ks(k).plot.y,mass:1,shape:{type:"circle",radius:B},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[k,o,c,B,p,g,b,x,v]),seedRows:T,seedSpawns:E.initialSpawns});const N=n??c,F=(0,Vc.useMemo)(()=>Is(N,"#4e79a7",{styleRules:i,valueAccessor:x}),[N,i,x]),{selection:W,onBodyHover:q}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:N,chartType:"CollisionSwarmChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof x?[x]:void 0}),z=Mc({data:r,emptyContent:s,loading:l,loadingContent:d,size:k});if(z)return z;const L=function(e,t){if(!1!==t&&e)return({size:t})=>{const n=[Number(t[0])||700,Number(t[1])||360],i=ks(n),o=i.plot.y+i.plot.height,[r,s]=e.xExtent,a=r+(s-r)/2,c=[{label:Kc(r),x:e.xRange[0]},{label:Kc(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:Kc(s),x:e.xRange[1]}];return(0,Uc.jsxs)("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.map(e=>(0,Uc.jsxs)("g",{children:[(0,Uc.jsx)("line",{x1:i.plot.x,x2:i.plot.x+i.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),(0,Uc.jsx)("text",{x:i.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),(0,Uc.jsxs)("text",{x:i.plot.x+i.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),(0,Uc.jsx)("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>(0,Uc.jsxs)("g",{children:[(0,Uc.jsx)("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),(0,Uc.jsx)("text",{x:e.x,y:Math.min(n[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(E.metadata,M),H=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),n=e.xRange[0]+t/2;return e.groups.map(e=>{const i=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:i,description:i,datum:e,x:n,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(E.metadata),Y=jc(e.tooltip,a),_=Ac(e,a,H,{selection:W,chartMode:j,className:I,title:S,description:R,summary:$,accessibleTable:P,enableHover:C,margin:A});return Ic("CollisionSwarmChart",k,(0,Uc.jsx)(fs,{...a,...Y,..._,ref:D,onBodyHover:q,config:O.config,foregroundGraphics:Sc(L,a?.foregroundGraphics),initialSpawns:E.initialSpawns,paused:u,responsiveHeight:f,responsiveWidth:y,size:k,bodyStyle:F},O.rerunKey))}),Zc={fresh:1,aging:1.5,stale:3};function Jc(e,t,n={}){return Number.isFinite(t)&&t>0?Number.isNaN(e)?"fresh":e===1/0?"expired":0>e||t*(n.fresh??Zc.fresh)>e?"fresh":t*(n.aging??Zc.aging)>e?"aging":t*(n.stale??Zc.stale)>e?"stale":"expired":"fresh"}function el(e,t,n){if(null!=e)return"function"==typeof e?e(t,n):"object"==typeof e&&null!==e&&"constant"in e?e.constant:t[e]}function tl(e){const{data:t,encoding:n}=e,i=[],o=new Map;return t.forEach((e,t)=>{const r=el(n.id,e,t);if(null==r||""===r)throw Error(`[semiotic] Motion encoding row ${t} resolved an empty id.`);const s=r+"";if(o.has(s))throw Error(`[semiotic] Duplicate motion encoding id "${s}".`);const a=el(n.process?.group,e,t),c=el(n.process?.stage,e,t),l=el(n.accessible?.group,e,t)??(null!=a?a+"":null!=c?c+"":void 0),d={};for(const i of Object.keys(n.evidence??{}))d[i]=el(n.evidence?.[i],e,t);const u={id:s,datum:e,time:{arrival:el(n.time?.arrival,e,t),basis:n.time?.basis,unit:n.time?.unit},placement:{x:el(n.placement?.x,e,t),y:el(n.placement?.y,e,t),lane:el(n.placement?.lane,e,t),space:n.placement?.space},kinematics:{velocityX:el(n.kinematics?.velocityX,e,t),velocityY:el(n.kinematics?.velocityY,e,t),space:n.kinematics?.space},process:{group:a,stage:c,target:el(n.process?.target,e,t),work:el(n.process?.work,e,t)},evidence:d,accessible:{description:el(n.accessible?.description,e,t),group:l,label:el(n.accessible?.label,e,t)??s}};i.push(u),o.set(s,u)}),{rows:i,byId:o}}function nl(e){const t=e.now-e.arrival;return{age:t,progress:Number.isFinite(t)&&Number.isFinite(e.ttl)&&e.ttl>0?Math.max(0,t)/e.ttl:t===1/0&&Number.isFinite(e.ttl)&&e.ttl>0?1/0:0,lifecycle:Jc(t,e.ttl,e.thresholds)}}function il(e){const t=Math.max(0,Math.min(1,e.minOpacity??.1));if(Number.isNaN(e.age))return 1;if(e.age===1/0)return t;if(!Number.isFinite(e.extent)||0>=e.extent)return 1;const n=Math.max(0,e.age);if("step"===e.type)return(e.threshold??.5*e.extent)>n?1:t;if("exponential"===e.type){const i=e.halfLife??e.extent/2;return t+Math.pow(.5,n/(i>0?i:e.extent/2))*(1-t)}return t+Math.max(0,Math.min(1,1-n/e.extent))*(1-t)}function ol(e,t){const n=Number.isFinite(e)?e:0,i=Number.isFinite(t)?t:0;return{velocityX:n,velocityY:i,speed:Math.hypot(n,i),direction:Math.atan2(i,n)}}function rl(e,t,n){return Number.isFinite(n)&&n>0?ol((t.x-e.x)/n,(t.y-e.y)/n):ol(0,0)}function sl(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=tl({data:t,encoding:n}),s=[],a=new Map,c=[],l=[],d=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:u}=e,h=Math.max(0,el(n.appearance?.size,u,t)??i.size??6),p=el(n.appearance?.shape,u,t)??i.shape??{type:"circle",radius:h},m=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(m):m,g=o?.y?o.y(f):f,b=el(n.appearance?.color,u,t)??i.color,x=el(n.appearance?.opacity,u,t)??i.opacity,v=el(n.appearance?.stroke,u,t)??i.stroke,w=el(n.appearance?.strokeWidth,u,t)??i.strokeWidth,k=el(n.time?.spawnAt,u,t)??e.time.arrival,M=e.kinematics.velocityX,I=e.kinematics.velocityY,S=el(n.dynamics?.mass,u,t)??i.mass??1,j=el(n.dynamics?.friction,u,t),A=el(n.dynamics?.restitution,u,t),C=el(n.dynamics?.bodyCollisions,u,t),R={id:r,x:y,y:g,mass:S,shape:{...p},datum:u,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=I&&{vy:I},...null!=j&&{friction:j},...null!=A&&{restitution:A},...null!=C&&{bodyCollisions:C}},$={...null!=b&&{fill:b},...null!=x&&{opacity:x},...null!=v&&{stroke:v},...null!=w&&{strokeWidth:w}},P={id:r,datum:u,appearance:{color:b,opacity:x,shape:p,size:h,stroke:v,strokeWidth:w},placement:{x:y,y:g,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:I,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:C,friction:j,mass:S,restitution:A},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:R};s.push(P),a.set(r,P),c.push(R),d.set(r,$),l.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:u,x:y,y:g,group:e.accessible.group})}),{rows:s,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function al(e){return t=>{const n=sl({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}var cl=require("react");function ll(e,t={}){const n=t.id??"physics-process-boundary",i={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...i,id:n,shape:e}];const o=t.thickness??8,r=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...i,id:n+"-top",shape:{type:"segment",x1:r,y1:a,x2:s,y2:a,thickness:o}},{...i,id:n+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:o}},{...i,id:n+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:r,y2:c,thickness:o}},{...i,id:n+"-left",shape:{type:"segment",x1:r,y1:c,x2:r,y2:a,thickness:o}}]}function dl(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},n=e.shape,i="aabb"===n.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:n.x,y:n.y,width:n.width,height:n.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(n.x1+n.x2)/2,y:(n.y1+n.y2)/2,pathData:`M ${n.x1} ${n.y1} L ${n.x2} ${n.y2}`};return{...i,...t,id:t.id??i.id}}function ul(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function hl(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},n={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...n,...t,id:t.id??n.id}]})}var pl="gauntlet-core",ml="gauntlet-positive",fl="gauntlet-negative";function yl(e){const t=Ml(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function gl(e,t,n,i){return n?"function"==typeof n?n(e,t):e[n]??i:i}function bl(e){return e?.label??e?.id??"property"}function xl(e){return`gauntlet:${e}:core`}function vl(e,t){return`gauntlet:${e}:positive:${t}`}function wl(e,t,n){return`gauntlet:${e}:negative:${t}:${n}`}var kl={left:28,top:76,rightInset:30,thickness:8};function Ml(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return kl;const n=Math.max(1,Math.min(e.width,t)),i=Math.max(2,.04*e.width);return{left:i,top:Math.max(2,.08*t),rightInset:i,thickness:Math.max(1,Math.min(4,.04*n))}}function Il(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function Sl(e,t,n,i){const o=Ml(i),r=Math.max(2,n+2),s=o.top+o.thickness/2+r,a=i.floorY-r,c=(e,t,n)=>t>n?(t+n)/2:Math.max(t,Math.min(n,e));return{x:c(e,o.left+o.thickness/2+r,i.width-o.rightInset-o.thickness/2-r),y:c(t,s,a)}}function jl(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function Al(e,t,n,i){const o=jl(n),r=i?.(e,t,n)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function Cl(e,t,n=1){const i=[...e].sort((e,t)=>e.localeCompare(t)),o=Math.max(0,i.indexOf(t));return{angle:.82*-Math.PI+(i.length>1?o/(i.length-1):.5)*Math.PI*.64,index:o,radius:(48+o%2*6)*n}}function Rl(e,t,n){const i=e.activePositiveIds.reduce((e,n)=>e+(t.get(n)?.value??1),0),o=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(n.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*i-8*r-1.2*e.delay-5*o))}function $l(e,t,n,i,o){const r=gl(e,t,n.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=i.map(e=>e.id),a=[...gl(e,t,n.positiveAccessor,s)],c=[...gl(e,t,n.negativeAccessor,[])].filter(e=>o.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...gl(e,t,n.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(gl(e,t,n.startTimeAccessor,0))||0),stage:"project filed",viability:gl(e,t,n.initialViability,100)}}function Pl(e,t,n,i,o,r,s){const a=Il(n),c=Math.max(3,28*a),l=i.startX,d=i.startY+(i.startY===n.routeY?38*t*a:0),u=s?.(e,t,n,i)??{},h=u.x??l,p=u.y??d,m={__gauntlet:!0,kind:pl,projectId:e.id,sourceDatum:e.datum},f=[{...u,id:xl(e.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??e.startedAt,datum:m}],y=Sl(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,n);f[0].x=y.x,f[0].y=y.y;for(const t of e.activePositiveIds){const i=o.get(t);if(!i)continue;const r=Cl(e.activePositiveIds,t,a),s=i.radius??Math.max(2,10*a),c=Sl(y.x+Math.cos(r.angle)*r.radius,y.y+Math.sin(r.angle)*r.radius,s,n);f.push({id:vl(e.id,t),x:c.x,y:c.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:i.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:ml,projectId:e.id,property:i,sourceDatum:e.datum},springs:!1===i.spring?[]:[{target:{type:"body",bodyId:xl(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...i.spring??{}}]})}return e.negativeIds.forEach((t,i)=>{const o=r.get(t);o&&f.push(Bl(e,o,i,y.x,y.y,n,u.spawnAt??e.startedAt))}),f}function Bl(e,t,n,i,o,r,s){const a=Il(r),c=t.radius??Math.max(2,7.2*a),l=Sl(i+(n%4*12-12)*a,o+(54+12*Math.floor(n/4))*a,c,r);return{id:wl(e.id,t.id,n),x:l.x,y:l.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:fl,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:xl(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+n%4*3)*a),...t.spring??{}}]}}function Dl(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function Tl(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function El(e,t){return Tl(e.activePositiveIds,t.popPositive)}function Ol(e){const t=Number(e.budget),n=Number.isFinite(t)?Math.max(0,t):0,i=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),o=e.candidates?new Set(e.candidates):null,r=e.attachedIds.map((e,t)=>{const n=i.get(e),o=Number(n?.work??1),r=Number(n?.priority??t);return{id:e,index:t,priority:Number.isFinite(r)?r:t,work:Number.isFinite(o)&&o>0?o:1}}).filter(e=>!o||o.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of r)c+e.work>n+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:n,remaining:Math.max(0,n-c),skippedIds:a}}function Nl(e,t){if(!t.from||!t.to||t.from===t.to)return{};const n=Math.max(0,Math.floor(Number(t.count??1)||0)),i=e.negativeIds.filter(e=>e===t.from).length,o=Math.min(n,i);return o?{addNegative:{[t.to]:o},popNegative:{ids:Array.from({length:o},()=>t.from)}}:{}}function Fl(e,t){const n=Tl(e.negativeIds,t.popNegative);if(!n.length)return[];const i=new Map;for(const e of n)i.set(e,(i.get(e)??0)+1);const o=[];return e.negativeIds.forEach((e,t)=>{const n=i.get(e)??0;n>0&&(o.push({propertyId:e,index:t}),i.set(e,n-1))}),o}function Wl(e,t,n){if(t.when&&!t.when(n))return e;let i={...e};const o=El(i,t);o.length&&(i={...i,activePositiveIds:i.activePositiveIds.filter(e=>!o.includes(e)),poppedPositiveIds:Array.from(new Set([...i.poppedPositiveIds,...o]))});const r=Fl(i,t);if(r.length){const e=new Set(r.map(e=>e.index));i={...i,negativeIds:i.negativeIds.filter((t,n)=>!e.has(n)),poppedNegativeIds:[...i.poppedNegativeIds,...r.map(e=>e.propertyId)]}}const s=Dl(t.addPositive);s.length&&(i={...i,activePositiveIds:Array.from(new Set([...i.activePositiveIds,...s])),missingPositiveIds:i.missingPositiveIds.filter(e=>!s.includes(e))});const a=Dl(t.addNegative);if(a.length&&(i={...i,negativeIds:[...i.negativeIds,...a]}),t.delayDelta&&(i={...i,delay:i.delay+t.delayDelta}),t.metricsDelta){const e={...i.metrics};for(const[n,i]of Object.entries(t.metricsDelta))e[n]=Number(e[n]??0)+i;i={...i,metrics:e}}return t.viabilityDelta&&(i={...i,viability:i.viability+t.viabilityDelta}),t.stage&&(i={...i,stage:t.stage}),t.outcome&&(i={...i,outcome:t.outcome}),i}function ql(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function zl(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}function Ll(e,t){const n=e.datum;return!(!n?.__gauntlet||n.projectId!==t||n.kind!==fl)}function Hl(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),n=Number(t);return Number.isFinite(n)?n:-1}function Yl(e,t){return 2>Math.hypot(e.vx,e.vy)&&4>Math.hypot(t.x,t.y)?null:t}var _l=require("react/jsx-runtime");function Gl(e){const t=e.data;return t?.__gauntlet?(0,_l.jsxs)("div",{className:"semiotic-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(15, 23, 42, 0.94))",color:"var(--semiotic-tooltip-text, #f8fafc)",padding:"8px 12px",borderRadius:6,boxShadow:"var(--semiotic-tooltip-shadow, 0 8px 24px rgba(0,0,0,0.35))",maxWidth:280},children:[(0,_l.jsx)("strong",{children:t.kind===pl?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:bl(t.property)}),(0,_l.jsx)("div",{children:t.kind===ml?"Positive property":t.kind===fl?"Negative property":"Project core"})]}):null}function Xl(e,t,n){const i=t.datum;if(!i?.__gauntlet)return;const o="circle"===t.shape.type?t.shape.radius:8;if(e.save(),e.translate(t.x,t.y),i.kind===pl)e.fillStyle=Vl(e,n.fill,"#0f766e"),e.strokeStyle=Vl(e,n.stroke,"#f8fafc"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke();else{const t=i.property;e.fillStyle=Vl(e,n.fill??t?.color,"#38bdf8"),e.strokeStyle=Vl(e,n.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),i.kind===fl?e.rect(-o,-o,2*o,2*o):e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=Vl(e,"var(--semiotic-bg, #07111f)","#07111f"),e.font=`900 ${i.kind===fl?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function Vl(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function Ul({layout:e,compact:t,showLabels:n}){const i=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),o=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);return(0,_l.jsx)(_l.Fragment,{children:e.gates.map(r=>(0,_l.jsxs)("g",{children:[(0,_l.jsx)("rect",{x:r.x-r.width/2,y:i,width:r.width,height:o,rx:t?2:12,fill:r.color??"var(--semiotic-primary, #38bdf8)",fillOpacity:.1,stroke:r.color??"var(--semiotic-primary, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),n?(0,_l.jsx)("text",{x:r.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:r.label??r.id}):null]},r.id))})}function Kl({layout:e,states:t,compact:n=!1}){return n?(0,_l.jsx)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:(0,_l.jsx)(Ul,{layout:e,compact:!0,showLabels:!1})}):(0,_l.jsxs)("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,_l.jsx)("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-primary, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),(0,_l.jsx)("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-danger, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),(0,_l.jsx)("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),(0,_l.jsx)(Ul,{layout:e,compact:!1,showLabels:!0}),(0,_l.jsxs)("g",{children:[(0,_l.jsx)("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-success, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-success, #22c55e)",strokeWidth:1.5}),(0,_l.jsx)("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),(0,_l.jsxs)("g",{children:[(0,_l.jsx)("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-danger, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-danger, #ef4444)",strokeOpacity:.7}),(0,_l.jsx)("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),(0,_l.jsx)("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function Ql(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===pl?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${bl(t.property)} ${t.kind===ml?"positive":"negative"} property`,group:t.kind===ml?"positive property":"negative property",description:`${bl(t.property)} attached to ${t.projectId}.`})}function Zl({states:e,layout:t}){const n=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!n.length)return null;const i=Math.max(1,...n.map(e=>e.value)),o=Math.max(40,(t.width-80)/n.length);return(0,_l.jsxs)("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[(0,_l.jsx)("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),n.map((e,t)=>{const n=40+t*o,r=Math.max(2,e.value/i*28),s=/kill|crash|block|grave/i.test(e.outcome);return(0,_l.jsxs)("g",{children:[(0,_l.jsx)("rect",{x:n+.18*o,y:28-r+22,width:Math.max(10,.45*o),height:r,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),(0,_l.jsx)("text",{x:n+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}var Jl=require("react/jsx-runtime"),ed=require("react"),td=[],nd=(0,cl.forwardRef)(function(e,t){const{bodyGroups:n,coreBody:i,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:l,frameProps:d={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:f,onCapacityChange:y,onClick:g,onStateChange:b,outcome:x,paused:v,positiveProperties:w=td,projectPlacement:k,rerunMS:M,responsiveHeight:I,responsiveWidth:S,seed:j,showTethers:A=!0,terminalBehavior:C="outcome",viability:R}=e,$=(0,cl.useRef)(null),P=(0,cl.useMemo)(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),B=kc(e,[900,520]),{chartSize:D,showProjection:T,showChrome:E,className:O,title:N,chartMode:F,margin:W,enableHover:q,description:z,summary:L,accessibleTable:H}=B,{selection:Y,onBodyHover:_}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:void 0,chartType:"GauntletChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:d?.onBodyHover,fallbackFields:"string"==typeof e.idAccessor?[e.idAccessor]:["id"],unwrapSourceDatum:!0}),G=Mc({data:a,emptyContent:c,loading:p,loadingContent:m,size:D}),X=(0,cl.useMemo)(()=>zc(a??[]),[a]),V=(0,cl.useMemo)(()=>X.map((e,t)=>gl(e,t,P.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[X,P.idAccessor]),U=(0,cl.useMemo)(()=>new Map(w.map(e=>[e.id,e])),[w]),K=(0,cl.useMemo)(()=>new Map(f.map(e=>[e.id,e])),[f]),Q=(0,cl.useMemo)(()=>function(e,t,n){const[i,o]=e,r=220>i||160>o,s=Math.round(.48*o),a=r?o-Math.max(3,Math.min(12,.1*o)):o-36,c=(t??[]).filter(e=>!1!==e.enabled),l=Math.max(1,c.length),d=.22*i,u=l>1?(.78*i-d)/(l-1):0,h=r?Math.max(Math.round(.12*i),.08*i+6):Math.max(Math.round(.14*i),110);return{crashY:a-(r?Math.min(n,Math.max(3,.22*o)):n),floorY:a,gates:c.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(d+t*u),width:e.width??Math.max(r?8:54,Math.round(.07*i))})),graveyardX:Math.round(i*(r?.72:.84)),graveyardY:a-4,height:o,routeY:s,socketX:Math.round(i*(r?.82:.92)),startX:h,width:i}}(D,u,s),[D,s,u]),Z=(0,cl.useMemo)(()=>new Map(Q.gates.map(e=>[e.id,e])),[Q.gates]),J=(0,cl.useMemo)(()=>Q.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:pl}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:Q.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(220>Q.width?12:96,e.width*(220>Q.width?2:6)):Math.max(e.width,220>Q.width?10:54),height:Math.max(4,Math.min(360,Q.height-(160>Q.height?8:170)))}})),[Q.gates,Q.height,Q.routeY,Q.width]),[ee,te]=(0,cl.useState)(()=>X.map((e,t)=>{const n=$l(e,t,P,w,K);return{...n,viability:R?.(n,{negativeProperties:K,positiveProperties:U})??Rl(n,U,K)}})),ne=(0,cl.useRef)(ee),ie=(0,cl.useRef)(0),oe=(0,cl.useRef)(new Map),re=(0,cl.useRef)([]),se=(0,cl.useRef)(y);se.current=y;const ae=(0,cl.useRef)(X);ae.current=X;const ce=(0,cl.useRef)(b);ce.current=b;const le=(0,cl.useRef)({negativeById:K,positiveById:U,positiveProperties:w,stateAccessors:P,viability:R});le.current={negativeById:K,positiveById:U,positiveProperties:w,stateAccessors:P,viability:R};const de=(0,cl.useCallback)((e,t,n=0)=>{const i=le.current,o=$l(e,t,i.stateAccessors,i.positiveProperties,i.negativeById);return i.stateAccessors.startTimeAccessor||(o.startedAt=Math.max(0,n)),{...o,viability:i.viability?.(o,{negativeProperties:i.negativeById,positiveProperties:i.positiveById})??Rl(o,i.positiveById,i.negativeById)}},[]),ue=(0,cl.useCallback)(()=>{oe.current.clear(),re.current=[],ie.current=0;const e=ae.current.map((e,t)=>de(e,t));ne.current=e,te(e)},[de]),he=wc((0,cl.useMemo)(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...null!=j&&{seed:j},...d.config?.kernel??{}},colliders:[...yl(Q),...d.config?.colliders??[]]}),[d.config?.colliders,d.config?.kernel,Q,j]),M,v,ue),pe=(0,cl.useMemo)(()=>function(e){const{dataKey:t,gates:n,statesRef:i,processedGateVisitsRef:o}=e;return n.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[Xo({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:pl},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const n=t.datum,o=n?.sourceDatum,r=e.capacity?.unitAccessor,s=i.current.find(e=>e.id===n?.projectId);let a;"function"==typeof r?a=s?r(s):void 0:r&&(a=o?.[r]);const c=Number(a??o?.reviewWork??o?.work??s?.metrics.reviewWork??o?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:t=>{const n=t.datum;if(!n?.projectId)return;const i=`${n.projectId}:${e.id}`;o.current.set(i,(o.current.get(i)??0)+1)}})]:[])}({dataKey:`${V}:${he.rerunKey}`,gates:Q.gates,statesRef:ne,processedGateVisitsRef:oe}),[V,Q.gates,he.rerunKey]),me=(0,cl.useMemo)(()=>[...pe,...d.controllers??[]],[pe,d.controllers]);(0,cl.useEffect)(()=>{oe.current.clear(),re.current=[],ie.current=0;const e=ae.current.map((e,t)=>de(e,t));ne.current=e,te(e)},[de,V]),(0,cl.useEffect)(()=>{ne.current=ee,ce.current?.(ee)},[ee]);const fe=(0,cl.useCallback)(e=>[...("function"==typeof l?l(e,Q):l)??[]].sort((e,t)=>e.time-t.time),[l,Q]),ye=(0,cl.useCallback)((e,t,n)=>{if(!t.gateId||!Z.get(t.gateId)?.capacity)return!0;const i=Number(t.gateVisit),o=Number.isFinite(i)&&i>0?Math.floor(i):n.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return o>0&&(oe.current.get(`${e.id}:${t.gateId}`)??0)>=o},[Z]),ge=(0,cl.useCallback)(()=>{if(!pe.length)return;const e=pe.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,n;(t=re.current).length===(n=e).length&&t.every((e,t)=>{const i=n[t];return!!i&&e.regionId===i.regionId&&e.queueDepth===i.queueDepth&&e.blockedDepth===i.blockedDepth&&e.processedCount===i.processedCount&&e.metricRevision===i.metricRevision})||(re.current=e,se.current?.(e))},[pe]),be=(0,cl.useMemo)(()=>ee.flatMap((e,t)=>{const n=Al(e,t,Q,k);return Pl(e,t,Q,n,U,K,i)}),[i,Q,K,U,k,ee]),xe=(0,cl.useCallback)((e,t)=>{let n=!1;const i=ne.current.map(i=>{if(i.id!==e)return i;const o=t(i);return n=n||o!==i,o});n&&(ne.current=i,te(i))},[]);(0,cl.useImperativeHandle)(t,()=>function(e){const{statesRef:t,setStates:n,elapsedRef:i,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:l,createState:d}=e;return{push:e=>{const u=d(e,t.current.length,i.current),h=Al(u,t.current.length,r,s),p=Pl(u,t.current.length,r,h,a,c,l),m=[...t.current,u];t.current=m,n(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=i.current;e.forEach(e=>{const t=d(e,u.length,p),n=Al(t,u.length,r,s);h.push(...Pl(t,u.length,r,n,a,c,l)),u.push(t)}),t.current=u,n(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:e=>{const i=Array.isArray(e)?e:[e],r=[],s=[];for(const e of i){const n=t.current.find(t=>t.id===e);n&&(r.push(n.datum),s.push(xl(n.id),...n.activePositiveIds.map(e=>vl(n.id,e))),n.negativeIds.forEach((e,t)=>{s.push(wl(n.id,e,t))}))}return t.current=t.current.filter(e=>!i.includes(e.id)),n(t.current),o.current?.remove(s),r},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const n=t.current.find(t=>t.id===e);if(!n)continue;const h=t.current.findIndex(t=>t.id===e);p.push(n.datum);const m=u(n.datum),f=d(m,0>h?t.current.length:h,n.startedAt??i.current),y=Al(f,0>h?t.current.length:h,r,s);o.current?.remove([xl(n.id),...n.activePositiveIds.map(e=>vl(n.id,e)),...n.negativeIds.map((e,t)=>wl(n.id,e,t))]),o.current?.pushMany(Pl(f,0>h?t.current.length:h,r,y,a,c,l)),t.current=t.current.map(t=>t.id===e?f:t)}return n(t.current),p},clear:()=>{t.current=[],n([]),o.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(e,t)=>o.current?.popBodies(e,t)??[]}}({statesRef:ne,setStates:te,elapsedRef:ie,frameRef:$,layout:Q,projectPlacement:k,positiveById:U,negativeById:K,coreBody:i,createState:de}),[i,de,Q,K,U,k]);const ve="sparkline"===F?.22:"mobile"===F?.55:1,we=(0,cl.useCallback)((e,t,n)=>{!function(e){const{project:t,effect:n,controls:i,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c,popScale:l}=e,d=i.readBodies().find(e=>e.id===xl(t.id)),u=i.readBodies(),h=d?.x??o.startX,p=d?.y??o.routeY,m=function(e,t){let n=-1;for(const i of t)Ll(i,e.id)&&(n=Math.max(n,Hl(i)));return Math.max(e.negativeIds.length,n+1)}(t,u),f=Dl(n.addNegative).flatMap((e,n)=>{const i=s.get(e);return i?[Bl(t,i,m+n,h,p,o)]:[]}),y=Dl(n.addPositive).flatMap(e=>{if(!r.get(e)||t.activePositiveIds.includes(e))return[];const n={...jl(o),routeY:p,socketY:p,startX:h,startY:p};return Pl({...t,activePositiveIds:[e],negativeIds:[]},0,o,n,r,s,a).filter(e=>e.id.includes(":positive:"))});(f.length||y.length)&&i.pushMany([...f,...y]);const g=El(t,n);for(const e of g){const n=r.get(e);c([vl(t.id,e)],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??10)+3,scale:l})}const b=Fl(t,n),x=function(e,t,n){const i=t.filter(t=>Ll(t,e.id)).sort((e,t)=>Hl(e)-Hl(t)||e.id.localeCompare(t.id)),o=new Set;return n.map(t=>{const n=i.find(e=>!o.has(e.id)&&e.datum.property?.id===t.propertyId);return n?(o.add(n.id),n.id):wl(e.id,t.propertyId,t.index)})}(t,u,b);b.forEach((e,t)=>{const n=s.get(e.propertyId);c([x[t]],{color:n?.popColor??n?.color,durationMs:900,radius:(n?.radius??7)+3,scale:l})})}({project:e,effect:t,controls:n,layout:Q,positiveById:U,negativeById:K,coreBody:i,popBodies:(e,t)=>$.current?.popBodies(e,t),popScale:ve})},[i,Q,K,U,ve]),ke=(0,cl.useCallback)(({body:e,bodies:t})=>function(e){const{body:t,bodies:n,layout:i,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:l,coreForceMode:d,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(e=>e.id===p.projectId),f=0>m?void 0:o[m];if(!f)return null;const y=Al(f,m,i,r),g=n.find(e=>e.id===xl(f.id)),b=Il(i),x=f.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),v=f.killed?0:58*Math.max(.25,b);if(p.kind!==pl){if(!g)return null;let e;const o=p.property;if(o?.target){const r=n.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===f.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,r.findIndex(e=>e.id===t.id));e=o.target({body:t,bodies:n,core:g,index:s,layout:i,placement:y,project:f})??{x:g.x,y:g.y}}else if(p.kind===ml&&p.property){const t=Cl(f.activePositiveIds,p.property.id,b);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const i=n.filter(e=>e.datum?.kind===fl&&e.datum.projectId===f.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),o=Math.max(0,i.findIndex(e=>e.id===t.id)),r=Math.floor(o/4);e={x:g.x+18*(o%4-(Math.min(4,i.length-4*r)-1)/2)*b,y:g.y+(54+13*r)*b}}const r="circle"===t.shape.type?t.shape.radius:8;e=Sl(e.x,e.y,r,i);const s=Sl(t.x,t.y,r,i);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==ml||f.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===fl?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return Yl(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*v,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a})}if(f.killed)return Yl(t,{x:44*((f.crashX??f.metrics.lastX??t.x)-t.x)-9*t.vx,y:(160+12*x)*b-1.6*t.vy});const w=c(f),k=function(e,t,n,i,o,r,s){const a=Il(n);if(t.killed)return{x:t.metrics.lastX??i.graveyardX,y:i.graveyardY};const c=o[o.length-1];if(!c)return{x:i.socketX,y:i.routeY};const l=o.find(n=>e>=n.time&&!t.eventsApplied.includes(n.id)&&!(!n.gateId||!r.get(n.gateId)?.capacity)),d=l?Math.min(e,l.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(d>c.time+.85){if("hold-last"===s){const e=c.gateId?r.get(c.gateId):void 0;return{x:c.routeX??e?.x??i.socketX,y:c.routeY??i.routeY}}return u?{x:i.socketX,y:i.socketY}:{x:i.graveyardX,y:i.graveyardY-14}}const h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:i.startX,y:i.startY},...o.map(e=>{const t=e.gateId?r.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??i.startX,y:e.routeY??i.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time);let m=p[0],f=p[p.length-1];for(let e=1;p.length>e;e+=1){if(p[e].time>=d){f=p[e];break}m=p[e]}const y=Math.max(0,Math.min(1,(d-m.time)/Math.max(.1,f.time-m.time))),g=y*y*(3-2*y);return{x:m.x+(f.x-m.x)*g,y:m.y+(f.y-m.y)*g+7*Math.sin(2.6*d)*a}}(Math.max(0,h-(f.startedAt??0)),f,i,y,w,l,u),M=f.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return Yl(t,"net"===d?{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:1.25*(y.routeY-t.y)-1.4*t.vy+32*(x-M)}:{x:15*(k.x-t.x)-1.8*t.vx+.18*v,y:15*(k.y-t.y)-1.8*t.vy+13*x-2.2*M})}({body:e,bodies:t,layout:Q,states:ne.current,projectPlacement:k,positiveById:U,negativeById:K,projectEvents:fe,gateById:Z,coreForceMode:o,terminalBehavior:C,elapsed:ie.current}),[o,Z,Q,K,U,fe,k,C]),Me=(0,cl.useCallback)((e,t)=>{!function(e,t,n){const{frameProps:i,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:l,capacityEventReady:d,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:f,outcome:y,reportCapacity:g}=n;i.onTick?.(e,t),o.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of r.current){const n=t.readBodies().find(t=>t.id===xl(e.id));if(!n)continue;if(s&&!e.killed&&n.y+("circle"===n.shape.type?n.shape.radius:28)>=a.crashY){t.readBodies().forEach(n=>{const i=n.datum;i?.__gauntlet&&i.projectId===e.id&&t.applyImpulse(n.id,-n.vx*n.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,o.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(e.startedAt??0))};return{...e,crashX:n.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:n.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const i=Math.max(0,o.current-(e.startedAt??0)),r=c(e),g=r.filter(t=>i>=t.time&&!e.eventsApplied.includes(t.id)&&d(e,t,r));let b=e;for(const n of g){const o=n.gateId?l.get(n.gateId):void 0,r=n.effects??[];for(const e of r){const i={event:n,gate:o,negativeProperties:f,positiveProperties:m,project:b};e.when&&!e.when(i)||(u(b,e,t),b=Wl(b,e,i))}const s={...ql(n,r),appliedAt:i};b=zl(b,s),h(e.id,e=>{let t=zl(e,s);if(t===e)return e;for(const e of r)t=Wl(t,e,{event:n,gate:o,negativeProperties:f,positiveProperties:m,project:t});const i=p?.(t,{negativeProperties:f,positiveProperties:m})??Rl(t,m,f);return t={...t,viability:i},n.final&&(t={...t,outcome:n.outcome??y?.(t,{layout:a,negativeProperties:f,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:d,elapsedRef:ie,statesRef:ne,crashDetection:r,layout:Q,projectEvents:fe,gateById:Z,capacityEventReady:ye,addBodiesForEffect:we,updateProjectState:xe,viability:R,positiveById:U,negativeById:K,outcome:x,reportCapacity:ge})},[we,ye,r,d,Z,Q,K,x,U,fe,ge,xe,R]),Ie=(0,cl.useCallback)((e,t)=>{const n="function"==typeof d.bodyStyle?d.bodyStyle(e,t):d.bodyStyle,i=e.datum;return i?.__gauntlet?{fill:i.kind===pl?"var(--semiotic-primary, #0f766e)":i.property?.color??"var(--semiotic-primary, #38bdf8)",stroke:i.kind===pl?"#f8fafc":"#0f172a",opacity:.96,...n}:n??{}},[d]),Se=(0,cl.useMemo)(()=>"function"==typeof n?n(ee,Q):n??[],[n,Q,ee]),je=(0,cl.useMemo)(()=>hl(Se),[Se]),Ae=(0,cl.useMemo)(()=>T?function(e,t){if(!e.length)return[];const n=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const i=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:i,description:i,datum:e,x:40+(t+.5)*n,y:28,shape:"rect",width:Math.max(16,.55*n),height:22,group:"settled projection"}})}(ee,Q):[],[Q,T,ee]),Ce=(0,cl.useMemo)(()=>[...Ae,...je],[je,Ae]),Re=(0,cl.useCallback)((e,t)=>{d.onBodyPointerDown?.(e,t)},[d]),$e=(0,cl.useCallback)((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),Pe=(0,cl.useCallback)((e,t)=>{d.beforePaint?.(e,t),A&&function(e,t){const n=new Map(t.filter(e=>e.datum?.kind===pl).map(e=>[e.datum.projectId,e]));e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const i of t){const t=i.datum;if(!t?.__gauntlet||t.kind===pl)continue;const o=n.get(t.projectId);o&&(e.globalAlpha=t.kind===fl?.24:.36,e.strokeStyle=t.kind===fl?"#d94a45":"#7a8794",e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}(e,t)},[d,A]),Be=(0,cl.useMemo)(()=>[...J,...d.regionEffects??[]],[d.regionEffects,J]);if(G)return G;const De=jc(e.tooltip,d),Te=Ac(e,d,Ce,{selection:Y,chartMode:F,className:O,title:N,description:z,summary:L,accessibleTable:H,enableHover:q,margin:W}),Ee=T?(0,Jl.jsx)(Zl,{states:ee,layout:Q}):void 0,Oe=Sc(E?(0,Jl.jsx)(Kl,{layout:Q,states:ee,compact:B.resolved.compactMode}):void 0,d.backgroundGraphics),Ne=Sc(Ee,d.foregroundGraphics),Fe=d.renderBody??Xl,We=De.tooltipContent??Gl;return Ic("GauntletChart",D,(0,ed.createElement)(fs,{...d,...De,...Te,key:`${D[0]}x${D[1]}:${V}:${he.rerunKey}`,ref:$,onBodyHover:_,accessibleTable:e.accessibleTable??d.accessibleTable,backgroundGraphics:Oe,bodyForces:ke,bodySemanticItems:d.bodySemanticItems??Ql,bodyStyle:Ie,beforePaint:Pe,onClick:g?$e:Te.onClick,config:he.config,controllers:me,enableHover:De.enableHover??!0,foregroundGraphics:Ne,hoverRadius:e.hoverRadius??d.hoverRadius??18,initialSpawns:be,initialSpawnPacing:h,onBodyPointerDown:Re,onTick:Me,paused:v,regionEffects:Be,renderBody:Fe,responsiveHeight:I,responsiveWidth:S,size:D,tooltipContent:We}))});nd.displayName="GauntletChart";var id=nd;function od(e,t){const{layout:n,positiveProperties:i,negativeProperties:o,viability:r,outcome:s}=t,a=function(e){return new Map(e.gates.map(e=>[e.id,e]))}(n),c=[...("function"==typeof t.events?t.events(e,n):t.events)??[]].sort((e,t)=>e.time-t.time);let l=e;for(const e of c){const t=e.gateId?a.get(e.gateId):void 0,c=e.effects??[],d=zl(l,{...ql(e,c),appliedAt:e.time});if(d!==l){l=d;for(const n of c){const r={event:e,gate:t,negativeProperties:o,positiveProperties:i,project:l};n.when&&!n.when(r)||(l=Wl(l,n,r))}l={...l,viability:r?.(l,{negativeProperties:o,positiveProperties:i})??Rl(l,i,o)},e.final&&(l={...l,outcome:e.outcome??s?.(l,{layout:n,negativeProperties:o,positiveProperties:i})??(l.viability>20?"built":"approved_not_built")})}}return l}function rd(e){return e.projects.map(t=>od(t,e))}var sd=require("react");function ad(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function cd(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}var ld=require("react/jsx-runtime"),dd=require("react");function ud(e){if(!e||"object"!=typeof e)return null;const t=e,n=Number(t.x),i=Number(t.y);return Number.isFinite(n)&&Number.isFinite(i)?{x:n,y:i}:null}function hd(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(ud).filter(e=>null!=e):[]}function pd(e,t){if(2>t.length)return null;let n=0;const i=[];for(let e=1;t.length>e;e+=1){const o=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);i.push(o),n+=o}if(0>=n)return null;let o=null,r=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],l=i[s-1];if(0>=l)continue;const d=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*d+(e.y-a.y)*u)/(l*l))),p={x:a.x+d*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(r+h*l)/n,tangent:{x:d/l,y:u/l},totalLength:n};o&&m.distance>=o.distance||(o=m),r+=l}return o}function md(e,t,n){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=n)return{...e[0]};let i=0;const o=Math.max(0,Math.min(1,t))*n;for(let t=1;e.length>t;t+=1){const n=e[t-1],r=e[t],s=Math.hypot(r.x-n.x,r.y-n.y);if(s>0){if(i+s>=o){const e=(o-i)/s;return{x:n.x+(r.x-n.x)*e,y:n.y+(r.y-n.y)*e}}i+=s}}return{...e[e.length-1]}}function fd(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function yd(e,t,n){const i=Math.hypot(e,t);if(n>=i||0>=i)return[e,t];const o=n/i;return[e*o,t*o]}function gd(e,t,n){const i=pd({...e,x:t[0].x,y:t[0].y},t),o=i?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=fd(e),l=function(e,t){let n=0;for(let t=0;e.length>t;t+=1)n=31*n+e.charCodeAt(t)>>>0;return(n%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*l,y:t[0].y+s*l,vx:s*n,vy:a*n,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var bd=(0,sd.forwardRef)(function(e,t){const{chartId:n,colorBy:i,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:l,links:d,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:f="x",nodeYAccessor:y="y",nodes:g,onObservation:b,particleRadius:x=4,particleRate:v=.16,pathAccessor:w="path",pathConstraint:k="path",paused:M,reducedMotion:I=!1,rerunMS:S,responsiveHeight:j,responsiveWidth:A,seed:C=1,showNodeLabels:R=!0,showSensors:$=!1,showStaticFlow:P=!0,sourceAccessor:B="source",styleRules:D,targetAccessor:T="target",throughputAccessor:E="value"}=e,O=kc(e,[760,420]),{chartSize:N,className:F,title:W,chartMode:q,margin:z,enableHover:L,description:H,summary:Y,accessibleTable:_}=O,G=(0,sd.useRef)(null),X=(0,sd.useMemo)(()=>g??[],[g]),V=(0,sd.useMemo)(()=>d??s??r??[],[r,s,d]),U=(0,sd.useMemo)(()=>Vs({nodes:X,links:V,nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:B,targetAccessor:T,throughputAccessor:E,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:C,size:N}),[V,X,N,o,c,p,m,f,y,x,v,w,k,I,C,B,T,E]);ka(t,{frameRef:G,spawnDatum:(0,sd.useCallback)((e,t)=>{const n=Vs({nodes:X,links:[e],nodeIdAccessor:m,nodeXAccessor:f,nodeYAccessor:y,sourceAccessor:B,targetAccessor:T,throughputAccessor:E,pathAccessor:w,coordinateMode:o,particleRate:v,maxParticles:p,particleRadius:x,flowSpeed:c,pathConstraint:k,reducedMotion:I,seed:C+t+1,size:N}),i={id:(e.id??"physical-flow-push-"+t)+"",x:ks(N).plot.x,y:ks(N).plot.y,mass:1,shape:{type:"circle",radius:x},datum:e},r=n.initialSpawns.length?n.initialSpawns:[i];return{datumId:(e.id??r[0].id)+"",spawns:r}},[X,N,o,c,p,m,f,y,x,v,w,k,I,C,B,T,E]),seedRows:V,seedSpawns:U.initialSpawns});const K=i??"source",Q=(0,sd.useMemo)(()=>Is(K,"#2563eb",{styleRules:D,valueAccessor:E}),[K,D,E]),Z=wc((0,sd.useMemo)(()=>function(e,t,n){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PacketFlowChart",onObservation:n??e.observation?.onObservation}}}(U.config,n,b),[n,U.config,b]),S,M),J=(0,sd.useRef)(l?.onTick);J.current=l?.onTick;const ee=(0,sd.useCallback)((e,t)=>{I||"none"===k||function(e,t){const n=e.readBodies(),i=[],o=[];for(const r of n){const n=hd(r.datum);if(2>n.length)continue;const s=pd(r,n);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),l=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*fd(r))){i.push(r.id),o.push(gd(r,n,l));continue}const d=md(n,Math.min(1,s.progress+Math.max(.035,Math.min(.12,l/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*l-r.vx)*r.mass*.16+(d.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*l-r.vy)*r.mass*.16+(d.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,f]=yd(h,p,r.mass*l*.35);e.applyImpulse(r.id,m,f)}i.length&&e.remove(i),o.length&&e.pushMany(o)}(t,c),J.current?.(e,t)},[c,k,I]),{selection:te,onBodyHover:ne}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:i,chartType:"PacketFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:l?.onBodyHover,fallbackFields:"string"==typeof B?[B]:void 0}),ie=Mc({data:null==d&&null==s&&null==r?void 0:V,emptyContent:a,loading:u,loadingContent:h,size:N});if(ie)return ie;const oe=function(e,t){const{showNodeLabels:n,showSensors:i,showStaticFlow:o}=t;if(e&&(o||i))return({size:t})=>{const r=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return(0,ld.jsxs)("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?e.links.map(e=>{const t=3+e.throughput/s*16,n=e.path[Math.floor(e.path.length/2)];return(0,ld.jsxs)("g",{children:[(0,ld.jsx)("path",{d:cd(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),(0,ld.jsx)("path",{d:cd(e.path),fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),n?(0,ld.jsx)("text",{x:n.x,y:n.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:ad(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>(0,ld.jsxs)("g",{children:[i&&a.has(e.sensorId)?(0,ld.jsx)("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?(0,ld.jsx)("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,n?(0,ld.jsx)("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(U.metadata,{showNodeLabels:R,showSensors:$,showStaticFlow:P}),re=(se=U.metadata)?se.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],n=`${e.sourceLabel} to ${e.targetLabel}: ${ad(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:n,description:n,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:cd(e.path),group:"flow"}}):[];var se;const ae=jc(e.tooltip,l),ce=Ac(e,l,re,{selection:te,chartMode:q,className:F,title:W,description:H,summary:Y,accessibleTable:_,enableHover:L,margin:z});return Ic("PacketFlowChart",N,(0,dd.createElement)(fs,{...l,...ae,...ce,key:Z.rerunKey,ref:G,onBodyHover:ne,config:Z.config,continuous:!I&&"none"!==k,foregroundGraphics:Sc(oe,l?.foregroundGraphics),initialSpawns:U.initialSpawns,onTick:ee,paused:M||I,responsiveHeight:j,responsiveWidth:A,simulationExecution:"none"===k?l?.simulationExecution:"sync",size:N,bodyStyle:Q,workerBodyThreshold:l?.workerBodyThreshold??1/0}))});bd.displayName="PacketFlowChart";var xd=bd,vd=require("react"),wd=require("react/jsx-runtime"),kd={flow:{fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(96, 165, 250, 0.7)",accent:"#60a5fa"},capacity:{fill:"rgba(251, 146, 60, 0.18)",stroke:"rgba(251, 146, 60, 0.85)",accent:"#fb923c"},portal:{fill:"rgba(244, 114, 182, 0.14)",stroke:"rgba(244, 114, 182, 0.7)",accent:"#f472b6"},absorb:{fill:"rgba(52, 211, 153, 0.18)",stroke:"rgba(52, 211, 153, 0.8)",accent:"#34d399"}},Md=6.2;function Id(e,t,n){return Math.max(t,Math.min(n,e))}function Sd(e){return e.length*Md}function jd(e,t){const n=e.trim();if(t>=n.length)return n;if(1>=t)return n.slice(0,1);const i=n.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return i.length>1&&t>=i.length?i:t>3?n.slice(0,Math.max(1,t-2))+"..":n.slice(0,t).toUpperCase()}function Ad(e,t,n="auto"){const i=Math.max(1,Math.floor(t/Md)),o="compact"===n?jd(e,i):"full"===n?e:Sd(e)>t?jd(e,i):e;return{text:o,textLength:Sd(o)>t?Math.max(4,t):void 0}}function Cd(e,t={}){const{showFlowSpine:n=!0,showStageCounts:i=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:l,height:d,left:u,right:h,topY:p,bottomY:m,midY:f,stages:y,groups:g=[]}=e,b=m-p;return(0,wd.jsxs)("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:l,height:d,viewBox:`0 0 ${l} ${d}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[(0,wd.jsx)("defs",{children:(0,wd.jsxs)("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,wd.jsx)("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),(0,wd.jsx)("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),(0,wd.jsx)("rect",{x:0,y:0,width:l,height:d,fill:"url(#semiotic-process-floor)"}),(0,wd.jsx)("rect",{x:u-6,y:p-8,width:h-u+12,height:b+16,rx:14,fill:"var(--semiotic-process-lane, var(--semiotic-surface, #111827))",fillOpacity:.45,stroke:"var(--semiotic-process-border, var(--semiotic-border, #334155))",strokeOpacity:.95}),n?(0,wd.jsx)("line",{x1:u+8,x2:h-8,y1:f,y2:f,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,y.map((e,t)=>{const n=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),r=kd[n],c=Math.max(12,e.width-8),l=Id(c-8,22,88),u=Ad(e.label,Math.max(8,l-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),x=Ad(g,Math.max(16,c-10),"auto"),v=o&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=Ad(w,Math.max(16,c-8),"auto"),M=Math.max(30,p-15),I=M-13;return(0,wd.jsxs)("g",{"data-stage":e.id,"data-role":n,children:[(0,wd.jsx)("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===n?1:1.6}),y.length-1>t?(0,wd.jsx)("polygon",{points:`${e.x1-2},${f-7} ${e.x1+8},${f} ${e.x1-2},${f+7}`,fill:r.accent,opacity:.85}):null,h?(0,wd.jsxs)(wd.Fragment,{children:[(0,wd.jsx)("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-l/2,y:I,width:l,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),(0,wd.jsxs)("text",{x:e.x,y:M,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,wd.jsx)("title",{children:e.label}),u.text]})]}):null,v?(0,wd.jsxs)("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:x.textLength,lengthAdjust:x.textLength?"spacingAndGlyphs":void 0,children:[(0,wd.jsx)("title",{children:g}),x.text]}):null,i&&null!=e.count?(0,wd.jsxs)("text",{x:e.x,y:Math.min(d-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[(0,wd.jsx)("title",{children:w}),k.text]}):null]},e.id)}),r?g.map((e,t)=>{const n=e.total??0,i=e.absorbed??0,o=e.complete??(n>0&&i>=n),r=!o&&n>0&&i/n>=.75,s=o?"rgba(52, 211, 153, 0.35)":r?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=o?"#34d399":r?"#fbbf24":"var(--semiotic-border, #64748b)",c=n>0?`${i}/${n}${o?" shipped":r?" almost":""}`:"feature "+(t+1),l=Id(Math.max(54,Sd(e.label)+18,Sd(c)+16),54,104),d=Ad(e.label,l-12,"auto"),u=Ad(c,l-12,"auto");return(0,wd.jsxs)("g",{"data-group":e.id,children:[(0,wd.jsx)("rect",{x:e.x-l/2,y:e.y-22,width:l,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),(0,wd.jsxs)("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:d.textLength,lengthAdjust:d.textLength?"spacingAndGlyphs":void 0,children:[(0,wd.jsx)("title",{children:e.label}),d.text]}),(0,wd.jsxs)("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[(0,wd.jsx)("title",{children:c}),u.text]})]},e.id)}):null]})}var Rd=require("react/jsx-runtime"),$d=(0,vd.forwardRef)(function(e,t){const{ballRadius:n=6,chromeOptions:i,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:l,groupCompletion:d,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:f,liveCapacity:y=!0,onCapacityChange:g,selection:b,bodyLimit:x,bodyMark:v,loading:w,loadingContent:k,paused:M,radiusAccessor:I,rerunMS:S,responsiveHeight:j,responsiveWidth:A,route:C="horizontal",seed:R=1,settle:$,springDamping:P,springStiffness:B,stageAccessor:D="stage",stages:T,workAccessor:E}=e,O=kc(e,[900,420]),{chartSize:N,showProjection:F,showChrome:W,className:q,title:z,chartMode:L,margin:H,enableHover:Y,description:_,summary:G,accessibleTable:X}=O,V=(0,vd.useRef)(null),U=(0,vd.useMemo)(()=>zc(r??[]),[r]),K=(0,vd.useMemo)(()=>({data:U,stages:T,size:N,idAccessor:m,stageAccessor:D,groupBy:l,groupLabelAccessor:u,workAccessor:E,radiusAccessor:I,ballRadius:n,seed:R,route:C,groupCompletion:d,groupAnchorAlong:c,springStiffness:B,springDamping:P,gravityX:h,gravityY:p,settle:$}),[n,N,h,p,c,l,d,u,m,I,C,U,R,$,P,B,D,T,E]),Q=(0,vd.useMemo)(()=>ga(K),[K]),Z=Q.metadata;ka(t,{frameRef:V,spawnDatum:(0,vd.useCallback)((e,t)=>{const i=ga({...K,data:[e],seed:R+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:ks(N).plot.x,y:ks(N).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[n,K,N,R]),seedRows:U,seedSpawns:Q.initialSpawns});const J=(0,vd.useMemo)(()=>Is(o),[o]),ee=(0,vd.useMemo)(()=>{if(!y)return a.controllers;const e=[...T.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return Xo({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(E?"string"==typeof E?E:e=>{const t=e.datum;if(!t)return 1;try{return Number(E(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,y,T,E]),[te,ne]=(0,vd.useState)({}),ie=(0,vd.useRef)(ee);ie.current=ee;const oe=(0,vd.useRef)(a.onTick);oe.current=a.onTick;const re=!1!==W||null!=g;(0,vd.useEffect)(()=>{if(!g)return;const e=Object.values(te);e.length&&g(e)},[te,g]);const se=(0,vd.useCallback)((e,t)=>{if(oe.current?.(e,t),!re)return;const n=ie.current;if(!n?.length)return;const i={};for(const e of n){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(i[t.regionId]=t)}ne(e=>function(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){const n=e[i],o=t[i];if(!o)return!1;if(n.queueDepth!==o.queueDepth||n.blockedDepth!==o.blockedDepth||n.processedCount!==o.processedCount||n.unitsPerSecond!==o.unitsPerSecond||n.regionId!==o.regionId||n.metricRevision!==o.metricRevision)return!1}return!0}(e,i)?e:i)},[re]),ae=(0,vd.useMemo)(()=>{const e=J,t=a.bodyStyle;return v||t?(n,i)=>{const o="function"==typeof t?t(n,i):t;return{..."function"==typeof e?e(n):e,...o,mark:o?.mark??n.datum?.__physicsMark??n.datum?.mark??v}}:e},[v,J,a.bodyStyle]),ce=wc((0,vd.useMemo)(()=>({...Q.config,...null!=x?{bodyLimit:x,eviction:"oldest"}:{},...a.config}),[x,a.config,Q.config]),S,M),{selection:le,onBodyHover:de}=xc({selection:b,linkedHover:e.linkedHover,colorBy:o,chartType:"ProcessFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof D?[D]:void 0}),ue=Mc({data:r,emptyContent:s,loading:w,loadingContent:k,size:N});if(ue)return ue;if(!T?.length)return Ic("ProcessFlowChart",N,(0,Rd.jsx)("div",{role:"status",style:{width:N[0],height:N[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const he=function(e,t,n={},i){if(!1===t||!e)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=e,c=new Map(o.stages.map(e=>[e.id,e])),l=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||o.width,a=Number(e[1])||o.height,d=r.map(e=>{const t=c.get(e.id),i=n["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:i?.queueDepth,processed:i?.processedCount}}),u=s.map(e=>{const t=l.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return Cd({width:t,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:d,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...i})}}(Z,W,te,i),pe=function(e,t,n){if(!1===n||!t||0===e.length)return;const i=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:n})=>{const o=[Number(n[0])||t.volume.width,Number(n[1])||t.volume.height],r=ks(o),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return(0,Rd.jsx)("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,n)=>{const o=e[n];if(!o)return null;const r=i.get(t.id);if(!r)return null;const l=Math.max(2,o.value/s*a),d=Math.max(8,.35*r.width);return(0,Rd.jsx)("rect",{x:r.x-d/2,y:c,width:d,height:l,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(Q.projectionRows,Z,F),me=[...js(Q.projectionRows,N,"stage"),...hl(Z?.groups??[])],fe=jc(e.tooltip,a),ye=Ac(e,a,me,{chartMode:L,className:q,title:z,description:_,summary:G,accessibleTable:X,enableHover:Y,margin:H}),ge=[...Z?.regionEffects??[],...a.regionEffects??[]];return Ic("ProcessFlowChart",N,(0,Rd.jsx)(fs,{...a,...fe,...ye,ref:V,onBodyHover:de,controllers:ee,regionEffects:ge,selection:le??a.selection,backgroundGraphics:Sc(he,a.backgroundGraphics),foregroundGraphics:Sc(pe,a.foregroundGraphics),initialSpawns:Q.initialSpawns,initialSpawnPacing:f??Q.initialSpawnPacing,onTick:se,paused:M,responsiveHeight:j,responsiveWidth:A,size:N,bodyStyle:ae,config:ce.config}))});$d.displayName="ProcessFlowChart";var Pd=[.1,.5,.9],Bd=1e6,Dd=12;function Td(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Ed(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function Od(e){const t=Number(e.toFixed(Dd));return Object.is(t,-0)?0:t}function Nd(e,t,n,i){const o=e.flatMap((e,o)=>{const r=Td(Ed(e,o,t,n,"time")),s=Td(Ed(e,o,t,i,"value"));return null==r||null==s?[]:[{time:Od(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function Fd(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const c=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function Wd(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function qd(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??Pd).map(e=>{const t=Td(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return Od(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>Bd)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Bd} points`);return Array.from(new Set(e.map(Td).filter(e=>null!=e).map(Od))).sort((e,t)=>e-t)}const t=e,n=Td(t.start),i=Td(t.end),o=Td(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>Bd)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Bd} points`);const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(Od(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(Od(i)),s.length>Bd)throw new RangeError(`physicsReferenceEnvelope sampleAt exceeds ${Bd} points`);return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>Nd(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>Fd(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?Wd(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?Wd(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function zd(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function Ld(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=Td(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=Od(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function Hd(e,t,n){return t>e?"below":e>n?"above":"inside"}function Yd(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,u=(r-o)*n,h=Hd(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function _d(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=Nd(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??zd(t,"lower"),a=n.upper??zd(t,"upper"),c=t.points.map(e=>{const t=Fd(r,e.time,i,o),n=Ld(e,s),c=Ld(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":Hd(t,n,c)}});let l=0,d=0,u=0,h=0,p=null,m=0,f=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,p=e.time),n>m&&(m=n,f=e.time)}let y=0,g=0,b=0,x=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=Yd(t,n);y+=e.below,g+=e.inside,b+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?b+=o:g+=o)}}const v=c[0]?.time,w=c[c.length-1]?.time,k=null==v||null==w?0:Math.max(0,w-v);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:g,aboveDuration:b,peakExcess:h,peakExcessAt:p,peakDeficit:m,peakDeficitAt:f}}function Gd(e){return{id:e,furthestStageIndex:-1,visitedStageIds:[],visitsByStage:{},firstEnteredAt:{},lastEnteredAt:{},regressionCount:0}}function Xd(e){const t=Array.from(new Set(e.bodyIds??[]));return{stages:e.stages.map(e=>({...e})),bodyIds:t,entities:Object.fromEntries(t.map(e=>[e,Gd(e)]))}}function Vd(e,t,n={}){if("region-enter"!==t.type)return e;const i=function(e,t){const n=t.stageId?.(e);if(n)return n;const i=e.region.metadata;if(i&&"object"==typeof i){const e=i.stageId;if("string"==typeof e)return e}return e.region.id}(t,n),o=e.stages.findIndex(e=>e.id===i);if(0>o)return e;const r=n.entityId?.(t)??t.bodyId;if(!r)return e;const s=e.entities[r]??Gd(r),a=s.currentStageId?e.stages.findIndex(e=>e.id===s.currentStageId):-1,c=!s.visitedStageIds.includes(i),l=Number(t.observation.timestamp),d=Number.isFinite(l)?l:0,u={...s,currentStageId:i,furthestStageId:o>s.furthestStageIndex?i:s.furthestStageId,furthestStageIndex:Math.max(s.furthestStageIndex,o),visitedStageIds:c?[...s.visitedStageIds,i]:s.visitedStageIds,visitsByStage:{...s.visitsByStage,[i]:(s.visitsByStage[i]??0)+1},firstEnteredAt:c?{...s.firstEnteredAt,[i]:d}:s.firstEnteredAt,lastEnteredAt:{...s.lastEnteredAt,[i]:d},regressionCount:a>=0&&a>o?s.regressionCount+1:s.regressionCount};return{...e,bodyIds:e.bodyIds.includes(r)?e.bodyIds:[...e.bodyIds,r],entities:{...e.entities,[r]:u}}}function Ud(e){const t=e.bodyIds.map(t=>e.entities[t]??Gd(t)),n=t.length;let i=n;return e.stages.map((e,o)=>{const r=t.filter(e=>e.furthestStageIndex>=o).length,s=t.filter(t=>t.visitedStageIds.includes(e.id)).length,a=t.reduce((t,n)=>t+(n.visitsByStage[e.id]??0),0),c={id:e.id,label:e.label??e.id,reached:r,entered:s,total:n,conversion:n>0?r/n:0,fromPrevious:i>0?r/i:0,dropoff:Math.max(0,i-r),visits:a,repeatVisits:Math.max(0,a-s)};return i=r,c})}var Kd={flow:"down",padding:24,chargeExtent:.12,destinationExtent:.55,projectionExtent:0,channelRatio:1};function Qd(e){const[t,n]=e.size,i=e.flow??Kd.flow,o=function(e){if(null==e){const e=Kd.padding;return{top:e,right:e,bottom:e,left:e}}return"number"==typeof e?{top:e,right:e,bottom:e,left:e}:{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}(e.padding),r=Math.max(.05,Math.min(1,e.channelRatio??Kd.channelRatio)),s={x:o.left,y:o.top,width:Math.max(1,t-o.left-o.right),height:Math.max(1,n-o.top-o.bottom)},a="down"===i?s.height:s.width,c=a*Math.max(0,e.chargeExtent??Kd.chargeExtent),l=a*Math.max(0,e.projectionExtent??Kd.projectionExtent),d=a*Math.max(0,e.destinationExtent??Kd.destinationExtent),u=Math.max(0,a-c-d-l),h=function(e){return"number"==typeof e?Array.from({length:Math.max(1,Math.round(e))},(e,t)=>({id:"bin-"+t,label:t+""})):0===e.length?[{id:"bin-0",label:"0"}]:e.map((e,t)=>({id:e.id,label:e.label??e.id??t+""}))}(e.destinations),p=("down"===i?s.width:s.height)/h.length,m="down"===i?(e,t)=>({x:s.x,y:s.y+e,width:s.width,height:t}):(e,t)=>({x:s.x+e,y:s.y,width:t,height:s.height}),f=m(0,c),y=m(c,u),g=c+u,b=m(g,d),x=m(g+d,l),v=h.map((e,t)=>{const n=t*p,o=p*r,a=(p-o)/2;return"down"===i?{id:e.id,label:e.label,order:t,x:s.x+n+a,y:b.y,width:o,height:b.height,centerX:s.x+(t+.5)*p,centerY:b.y+b.height/2}:{id:e.id,label:e.label,order:t,x:b.x,y:s.y+n+a,width:b.width,height:o,centerX:b.x+b.width/2,centerY:s.y+(t+.5)*p}});return{width:t,height:n,flow:i,charge:f,apparatus:y,destinations:v,projection:x}}function Zd(e,t){return e.destinations.find(e=>e.id===t)}function Jd(e,t,n){const{charge:i,flow:o}=e,r=Math.max(1,n),s=(t%r+.5)/r;return"down"===o?{x:i.x+i.width*s,y:i.y+i.height/2}:{x:i.x+i.width/2,y:i.y+i.height*s}}function eu(e,t={}){const n=t.thickness??4,i=t.idPrefix??"stage",{destinations:o,flow:r,width:s,height:a}=e,c=[];if(o.length>0){const t=o[0];if("down"===r){const r=t.y+t.height;c.push({id:i+"-floor",shape:{type:"segment",x1:e.charge.x,y1:r,x2:e.charge.x+e.charge.width,y2:r,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerX-(o[e].centerX-o[e-1].centerX)/2;c.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:s,y1:t.y,x2:s,y2:r,thickness:n}})}}else{const r=t.x+t.width;c.push({id:i+"-floor",shape:{type:"segment",x1:r,y1:e.charge.y,x2:r,y2:e.charge.y+e.charge.height,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerY-(o[e].centerY-o[e-1].centerY)/2;c.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:t.x,y1:s,x2:r,y2:s,thickness:n}})}}}return!1!==t.walls&&c.push({id:i+"-wall-left",shape:{type:"segment",x1:1,y1:0,x2:1,y2:a,thickness:n}},{id:i+"-wall-right",shape:{type:"segment",x1:s-1,y1:0,x2:s-1,y2:a,thickness:n}}),c}function tu(e,t={}){return`${t.charge??"bodies"} enter at the ${"down"===e.flow?"top":"left"}, travel ${"down"===e.flow?"downward":"left to right"} through ${t.apparatus??"the apparatus"}, and come to rest in ${e.destinations.length} ${t.destination??"destinations"}: ${e.destinations.map(e=>e.label).join(", ")}.`}function nu(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function iu(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function ou(e,t,n){return nu(e[t])??n}function ru(e,t){return"number"==typeof e?e:e?.[t]??0}function su(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=r?c.length-1:c.length-2,d=[];for(let e=r?0:1;l>=e;e+=1){if(!s&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return d}function au(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...ao(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...co({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...su({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...su({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function cu(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===u)return[];const p=u>1?(a-s)/(u-1):0,m=t.width/h,f=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?m/2:0;for(let i=0;h>i;i+=1){const a=t.x+m*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*p,width:2*o,height:2*o},restitution:l,friction:d})}}return f}function lu(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=di(l),p=ru(d,"x"),m=ru(d,"y");return e.map((e,l)=>{const d=iu(t.x,e,l,ou(e,"x",0)),f=iu(t.y,e,l,ou(e,"y",0)),y=iu(i,e,l,5),g="function"==typeof o?o(e,l):o??{type:"circle",radius:y};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*p,y:f+(h()-.5)*m,vx:iu(s,e,l,0),vy:iu(a,e,l,0),mass:iu(r,e,l,1),spawnAt:iu(c,e,l,void 0),shape:g,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function du(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,c=_i(e,a),l=i?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:c,colliders:l}}function uu(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return nu("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-c:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var hu=require("react"),pu=1e-9;function mu(e,t){return t>e?-1:e>t?1:0}function fu(e){return{...e}}function yu(e){return e.map(e=>({...e,sourceIds:e.sourceIds?[...e.sourceIds]:void 0,productIds:e.productIds?[...e.productIds]:void 0,relationIds:e.relationIds?[...e.relationIds]:void 0,outletIds:e.outletIds?[...e.outletIds]:void 0}))}function gu(e){const t=Object.fromEntries(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:fu(t.initialMetrics),metrics:fu(t.metrics),productIds:[...t.productIds],history:yu(t.history)}])),n=Object.fromEntries(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:fu(t.metrics),sourceIds:[...t.sourceIds],history:yu(t.history)}])),i=Object.fromEntries(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?fu(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:n,relations:i,input:{amount:e.input.amount,metrics:fu(e.input.metrics)},metrics:fu(e.metrics),loss:{amount:e.loss.amount,metrics:fu(e.loss.metrics)},history:yu(e.history)}}function bu(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function xu(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(mu)}function vu(e,t){return e?Object.entries(e).flatMap(([e,n])=>Number.isFinite(n)?[]:[bu("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function wu(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}function ku(e,t,n="selector"){const i=[],o=Object.values(e.components),r=new Set(o.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&i.push(bu("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,n+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||i.push(bu("error","invalid-selector-count","Selector count must be a non-negative integer.",n+".count")),i.some(e=>"error"===e.severity))return{ids:[],diagnostics:i};const a=t.ids?new Set(t.ids):null,c=t.categories?new Set(t.categories):null,l=t.statuses?new Set(t.statuses):null,d=t.outletIds?new Set(t.outletIds):null;let u=o.filter(e=>!a||a.has(e.id)).filter(e=>!c||c.has(e.category)).filter(e=>!l||l.has(e.status)).filter(e=>!d||void 0!==e.outletId&&d.has(e.outletId)).map(e=>e.id).sort(mu);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||i.push(bu("warning","empty-selector","Selector matched no source components.",n)),{ids:u,diagnostics:i}}function Mu(e,t,n={}){return{eventId:e.event.id,effectType:t.type,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,label:e.event.label,summary:e.event.summary,...n}}function Iu(e,t){const n={...t,eventId:e.event.id};e.materializations.push(n),e.observations.push({...n,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function Su(e,t,n){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(bu("error","unknown-outlet",`Unknown outlet "${t}".`,n,[t])),1))}function ju(e,t,n){const i=xu(t);t.length||e.diagnostics.push(bu("error","empty-source-list","A product requires at least one source component.",n)),i.length&&e.diagnostics.push(bu("error","duplicate-source",`Source ids may appear only once: ${i.join(", ")}.`,n,i));const o=t.filter(t=>!e.state.components[t]);o.length&&e.diagnostics.push(bu("error","unknown-component",`Unknown source component id${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(bu("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,n,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(bu("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,n,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function Au(e,t,n,i,o){const r=i?.amount??0;(!Number.isFinite(r)||0>r||r>t+pu)&&e.diagnostics.push(bu("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",o+".amount")),e.diagnostics.push(...vu(i?.metrics,o+".metrics"));for(const[t,r]of Object.entries(i?.metrics??{}))(0>r||r>Number(n[t]??0)+pu)&&e.diagnostics.push(bu("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${o}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function Cu(e,t,n,i,o,r,s){return{id:e.id,label:e.label??e.id,description:e.description,category:e.category??"product",color:e.color,order:e.order,declaredAmount:e.amount,amount:r&&void 0!==e.amount?e.amount:n,metrics:r&&e.metrics?{...i,...e.metrics}:i,status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(o.outletIds.has("product")?"product":void 0):void 0,createdByEventId:o.event.id,createdAt:o.context.appliedAt,completedByEventId:r?o.event.id:void 0,completedAt:r?o.context.appliedAt:void 0,history:[s]}}function Ru(e,t,n,i){void 0!==t.amount&&Math.abs(t.amount-n)>pu&&e.diagnostics.push(bu("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${n}.`,i,[t.id]))}function $u(e,t,n){const i=`events.${e.event.id}.effects.${n}`,o=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(bu("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,i+".state")),e.diagnostics.push(...vu(t.metricsDelta,i+".metricsDelta")),Su(e,t.outletId,i+".outletId");const n=ku(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(bu("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Mu(e,t,{sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of n.ids){const n=o.components[e];n.status=t.state,n.outletId=t.outletId,n.reason=t.reason,t.metricsDelta&&wu(n.metrics,t.metricsDelta),n.history.push(s)}return o.history.push(s),void(n.ids.length&&Iu(e,{type:"retarget-component",sourceIds:n.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:n}=t;n.id&&!o.relations[n.id]||e.diagnostics.push(bu("error","duplicate-relation",`Relation id "${n.id}" is missing or already active.`,i+".relation.id",[n.id]));const r=function(e,t,n){const i=xu(t),o=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(bu("error","insufficient-relation-sources","A relation requires at least two source components.",n)),i.length&&e.diagnostics.push(bu("error","duplicate-source",`Relation source ids must be unique: ${i.join(", ")}.`,n,i)),o.length&&e.diagnostics.push(bu("error","unknown-component",`Relation references unknown source component${1===o.length?"":"s"}: ${o.join(", ")}.`,n,o)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,n.sourceIds,i+".relation.sourceIds");if(e.diagnostics.push(...vu(n.metrics,i+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;o.relations[n.id]={...n,sourceIds:[...n.sourceIds],metrics:n.metrics?{...n.metrics}:void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=Mu(e,t,{sourceIds:[...n.sourceIds],relationIds:[n.id]});return o.history.push(s),void Iu(e,{type:"activate-relation",sourceIds:[...n.sourceIds],relationIds:[n.id]})}if("resolve-relation"===t.type){const n=xu(t.relationIds),r=t.relationIds.filter(e=>!o.relations[e]),s=t.relationIds.filter(e=>"resolved"===o.relations[e]?.status);if(n.length&&e.diagnostics.push(bu("error","duplicate-relation","Relation ids must be unique.",i+".relationIds",n)),r.length&&e.diagnostics.push(bu("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,i+".relationIds",r)),s.length&&e.diagnostics.push(bu("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,i+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const n of t.relationIds){const i=o.relations[n];i.status="resolved",i.resolution=t.resolution,i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt,i.reason=t.reason}const a=Mu(e,t,{relationIds:[...t.relationIds]});return o.history.push(a),void Iu(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const n=e.productDefinitions.get(t.productId);n||e.diagnostics.push(bu("error","unknown-product",`Product "${t.productId}" has no declared mold.`,i+".productId",[t.productId]));const r=o.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(bu("error","duplicate-product",`Product "${t.productId}" has already been formed.`,i+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(bu("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,i+".productId",[t.productId]));const s=ju(e,t.sourceIds,i+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,c=function(e,t,n,i){if(!t?.length)return[];const o=xu(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(n),c=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return o.length&&e.diagnostics.push(bu("error","duplicate-relation","Basis relations must be unique.",i,o)),r.length&&e.diagnostics.push(bu("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,i,r)),s.length&&e.diagnostics.push(bu("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,i,s)),c.length&&e.diagnostics.push(bu("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,i,c)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,i+".basisRelationIds");if(!s||!c||!n||e.diagnostics.some(e=>"error"===e.severity))return;const l=s.reduce((e,t)=>e+t.amount,0),d=function(e){const t={};for(const n of e)wu(t,n.metrics);return t}(s);if(!Au(e,l,d,t.loss,i+".loss"))return;const u=l-(t.loss?.amount??0);!function(e,t,n){e.state.loss.amount+=n?.amount??0;for(const[i,o]of Object.entries(n?.metrics??{}))t[i]=Number(t[i]??0)-o,e.state.loss.metrics[i]=Number(e.state.loss.metrics[i]??0)+o}(e,d,t.loss);const h="combine"===t.type&&!1!==t.complete,p=Mu(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let m;if("combine"===t.type){if(h&&Ru(e,n,u,i+".productId"),m=Cu(n,t.sourceIds,u,d,e,h,p),h&&!Su(e,m.outletId,i+".productId"))return;o.products[t.productId]=m}else m=r,m.sourceIds.push(...t.sourceIds),m.amount+=u,wu(m.metrics,d),m.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return o.history.push(p),function(e,t){if(t.length){for(const n of t)n.status="resolved",n.resolution="combined",n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt;Iu(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,c),Iu(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(h&&Iu(e,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===t.type){const n=o.products[t.productId];return n?void function(e,t,n,i,o,r){const s=e.productDefinitions.get(t.id),a=n??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!Su(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(bu("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(Ru(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics={...t.metrics,...s.metrics})),t.status="complete",t.outletId=a,t.reason=i,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const c=Mu(e,o,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(c),e.state.history.push(c),Iu(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,n,t.outletId,t.reason,t,i):void e.diagnostics.push(bu("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,i+".productId",[t.productId]))}if("split"===t.type){const n=ju(e,[t.sourceId],i+".sourceId");t.products.length||e.diagnostics.push(bu("error","empty-split","A split requires at least one product allocation.",i+".products"));const r=t.products.map(e=>e.productId),s=xu(r);s.length&&e.diagnostics.push(bu("error","duplicate-product","Split product ids must be unique.",i+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),c=r.filter((e,t)=>!a[t]),l=r.filter(e=>o.products[e]);c.length&&e.diagnostics.push(bu("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,i+".products",c)),l.length&&e.diagnostics.push(bu("error","duplicate-product",`Split products already exist: ${l.join(", ")}.`,i+".products",l));for(const[n,o]of t.products.entries())void 0===o.amount||Number.isFinite(o.amount)&&o.amount>=0||e.diagnostics.push(bu("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${i}.products.${n}.amount`)),e.diagnostics.push(...vu(o.metrics,`${i}.products.${n}.metrics`));if(!n?.length||e.diagnostics.some(e=>"error"===e.severity))return;const d=n[0];if(!Au(e,d.amount,d.metrics,t.loss,i+".loss"))return;const u=d.amount-(t.loss?.amount??0),h=t.products.map((e,t)=>e.amount??a[t]?.amount),p=h.filter(e=>void 0!==e).length;if(0!==p&&p!==h.length)return void e.diagnostics.push(bu("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",i+".products"));const m=p?h:t.products.map(()=>u/t.products.length),f=m.reduce((e,t)=>e+t,0);if(Math.abs(f-u)>pu)return void e.diagnostics.push(bu("error","split-amount-mismatch",`Split allocations total ${f}, but ${u} remains after loss.`,i+".products"));const y={...d.metrics};for(const[e,n]of Object.entries(t.loss?.metrics??{}))y[e]=Number(y[e]??0)-n;const g=Mu(e,t,{sourceIds:[d.id],productIds:r});if(t.products.forEach((n,r)=>{const s=a[r],c=u>pu?m[r]/u:1/t.products.length,l=Object.fromEntries(Object.entries(y).map(([e,t])=>[e,t*c])),h=n.metrics??s.metrics??l,p=Cu({...s,amount:m[r],metrics:h},[d.id],m[r],{...h},e,!0,g);Su(e,p.outletId,`${i}.products.${r}.productId`)&&(o.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;d.productIds=r,d.status="consumed",d.outletId=void 0,d.history.push(g),o.loss.amount+=t.loss?.amount??0;for(const[e,n]of Object.entries(t.loss?.metrics??{}))o.loss.metrics[e]=Number(o.loss.metrics[e]??0)+n;o.history.push(g),Iu(e,{type:"split-source",sourceIds:[d.id],productIds:r});for(const t of r)Iu(e,{type:"complete-product",sourceIds:[d.id],productIds:[t],outletIds:o.products[t].outletId?[o.products[t].outletId]:void 0});return}if("eject"===t.type){Su(e,t.outletId,i+".outletId");const n=ku(o,t.select,i+".select");e.diagnostics.push(...n.diagnostics);const r=n.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(bu("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,i+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=Mu(e,t,{sourceIds:n.ids,outletIds:[t.outletId]});for(const e of n.ids){const n=o.components[e];n.status=t.state??"ejected",n.outletId=t.outletId,n.reason=t.reason,n.history.push(s)}return o.history.push(s),void(n.ids.length&&Iu(e,{type:"retarget-component",sourceIds:n.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...vu(t.metricsDelta,i+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let n,r;if("run"===t.target)wu(o.metrics,t.metricsDelta);else if("components"in t.target){const r=ku(o,t.target.components,i+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;n=r.ids;for(const e of r.ids)wu(o.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const n=xu(r),s=r.filter(e=>!o.products[e]);if(n.length&&e.diagnostics.push(bu("error","duplicate-product","Metric target product ids must be unique.",i+".target.productIds",n)),s.length&&e.diagnostics.push(bu("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,i+".target.productIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const e of r)wu(o.products[e].metrics,t.metricsDelta)}return void o.history.push(Mu(e,t,{sourceIds:n,productIds:r}))}t.outcome.trim()?(o.outcome=t.outcome,o.summary=t.summary,o.history.push(Mu(e,t)),e.observations.push({type:"crucible-outcome",eventId:e.event.id,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,outcome:t.outcome})):e.diagnostics.push(bu("error","invalid-outcome","Outcome must be a non-empty string.",i+".outcome"))}function Pu(e,t,n){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[bu("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const i=gu(e),o={state:i,event:t,context:n,productDefinitions:new Map(n.products.map(e=>[e.id,e])),outletIds:new Set(n.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[n,i]of t.effects.entries())if($u(o,i,n),o.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:o.diagnostics};return i.elapsed=Math.max(i.elapsed,n.appliedAt),i.phaseId=n.phaseId,i.eventsApplied.push(t.id),o.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:n.phaseId,authoredAt:n.authoredAt,appliedAt:n.appliedAt}),{applied:!0,state:i,materializations:o.materializations,observations:o.observations,diagnostics:o.diagnostics}}function Bu(e,t={}){const n=t.groupBy??"outlet",i=new Map,o=e=>{const t=function(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}({...e,status:e.status??"active"},n),o=i.get(t);if(o)return o.count+=1,o.amount+=e.amount,void wu(o.metrics,e.metrics);i.set(t,{key:t,label:"product"===n&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:{...e.metrics},status:"status"===n?e.status:void 0,outletId:"outlet"===n?e.outletId:void 0,category:"category"===n?e.category:void 0,productId:"product"===n&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||o({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(const t of Object.values(e.products))o({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});const r=new Map((t.order??[]).map((e,t)=>[e,t]));return[...i.values()].sort((e,t)=>(r.get(e.key)??Number.MAX_SAFE_INTEGER)-(r.get(t.key)??Number.MAX_SAFE_INTEGER)||mu(e.key,t.key))}var Du=Bu;function Tu(e,t={}){const n=t.field??"amount",i=e=>"amount"===n?e.amount:Number(e.metrics[n]??0),o="amount"===n?e.input.amount:Number(e.input.metrics[n]??0),r=Object.values(e.products).reduce((e,t)=>e+i(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+i(t),0),a="amount"===n?e.loss.amount:Number(e.loss.metrics[n]??0),c=r+s+a,l=c-o;return{field:n,input:o,products:r,unassigned:s,loss:a,output:c,delta:l,conserved:Math.max(0,t.tolerance??1e-6)>=Math.abs(l)}}function Eu(e,t={}){return{history:yu(e.history),projection:Bu(e,t.projection),conservation:Tu(e,t.conservation)}}var Ou=900,Nu=520,Fu=[Ou,Nu],Wu=[{id:"product",label:"Products",side:"bottom",order:0},{id:"retained",label:"Retained",side:"bottom",order:1},{id:"residue",label:"Residue",side:"left",order:2},{id:"failed",label:"Failed",side:"right",order:3},{id:"recovered",label:"Recovered",side:"right",order:4}],qu=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),zu=1e-9;function Lu(e,t){return t>e?-1:e>t?1:0}function Hu(e,t,n,i,o){return{severity:e,code:t,message:n,path:i,ids:o?[...o]:void 0}}function Yu(e){const t=new Set,n=new Set;for(const i of e)t.has(i)&&n.add(i),t.add(i);return[...n].sort(Lu)}function _u(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Gu(e,t,n,i,o,r){if(!n)return i;try{return("function"==typeof n?n(e,t):e[n])??i}catch(e){return o.push(Hu("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),i}}function Xu(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(Hu("error","invalid-metrics","Metrics must be a numeric object.",n)),{};const i={};for(const[o,r]of Object.entries(e)){const e=_u(r);null!=e?i[o]=e:t.push(Hu("error","invalid-metric",`Metric "${o}" must be finite.`,`${n}.${o}`))}return i}function Vu(e){const t=[],n={},i=[];let o=0;const r={};e.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",l=((Gu(s,a,e.idAccessor,c,t,`data.${a}.id`)??c)+"").trim();if(!l)return void t.push(Hu("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));i.push(l);const d=_u(Gu(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),u=null==d||0>d?0:d;(null==d||0>d)&&t.push(Hu("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[l]));const h=Xu(Gu(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=Gu(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),m=qu.has(p)?p:"active";qu.has(p)||t.push(Hu("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[l]));const f=Gu(s,a,e.labelAccessor,(s.label??s.name??l)+"",t,`data.${a}.label`)+"",y=Gu(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";n[l]||(n[l]={id:l,label:f,category:y,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},o+=u,function(e,t){for(const[n,i]of Object.entries(t))e[n]=Number(e[n]??0)+i}(r,h))});const s=Yu(i);s.length&&t.push(Hu("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=Xu(e.metrics??{},t,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:e.phases[0]?.id??"",phaseIndex:e.phases.length?0:-1,playing:!1,complete:0===e.phases.length,outcome:"in_process",eventsApplied:[],components:n,products:{},relations:{},input:{amount:o,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:t}}function Uu(e){return e.map((e,t)=>({outlet:e,index:t})).sort((e,t)=>(e.outlet.order??e.index)-(t.outlet.order??t.index)||e.index-t.index).map(({outlet:e})=>({...e}))}function Ku(e=Fu,t=Wu){const n=Math.max(1,_u(e[0])??Ou),i=Math.max(1,_u(e[1])??Nu),o=360>n||260>i,r=o?Math.max(4,.035*Math.min(n,i)):20,s=o?Math.max(10,.075*i):34,a={x:r,y:r,width:Math.max(1,n-2*r),height:s},c=o?Math.max(16,.14*i):Math.min(78,.16*i),l={x:r,y:i-r-c,width:Math.max(1,n-2*r),height:c},d=o?Math.max(12,.08*n):Math.min(150,.17*n),u=a.y+a.height+(o?12:38),h=l.y-(o?10:34),p={x:d,y:u,width:Math.max(24,n-2*d),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,o?84:180)),f={x:p.x+(p.width-m)/2,y:p.y-(o?10:24),width:m,height:o?12:28},y=Uu(t),g={left:y.filter(e=>"left"===(e.side??"bottom")),right:y.filter(e=>"right"===e.side),bottom:y.filter(e=>"bottom"===(e.side??"bottom"))},b=[],x=(e,t)=>{const i=Math.max(8,d-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:n-r-i,y:p.y+a*s,width:i,height:Math.max(8,s-(o?2:8))})})};x("left",g.left),x("right",g.right);const v=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*v,y:p.y+p.height+(o?2:7),width:Math.max(8,v-(o?2:8)),height:Math.max(8,l.y-p.y-p.height-(o?4:12))})}),b.sort((e,t)=>y.findIndex(t=>t.id===e.id)-y.findIndex(e=>e.id===t.id)),{width:n,height:i,phaseRail:a,chamber:p,mouth:f,projection:l,outlets:b}}function Qu(e){const{id:t,orientation:n,fixed:i,start:o,end:r,openings:s,thickness:a,friction:c,restitution:l}=e,d=function(e,t,n){const i=n.map(([n,i])=>[Math.max(e,Math.min(n,i)),Math.min(t,Math.max(n,i))]).filter(([e,t])=>t>e+zu).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];let r=e;for(const[e,t]of i)e>r+zu&&o.push([r,e]),r=Math.max(r,t);return t>r+zu&&o.push([r,t]),o}(o,r,s);return d.map(([e,o],r)=>({id:1===d.length?t:`${t}:${r}`,friction:c,restitution:l,shape:"horizontal"===n?{type:"segment",x1:e,y1:i,x2:o,y2:i,thickness:a}:{type:"segment",x1:i,y1:e,x2:i,y2:o,thickness:a}}))}function Zu(e){const{chamber:t,mouth:n}=e,i=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),o=Math.max(t.x,n.x),r=Math.min(t.x+t.width,n.x+n.width),s={left:e.outlets.filter(e=>"left"===e.side),right:e.outlets.filter(e=>"right"===e.side),bottom:e.outlets.filter(e=>"bottom"===e.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:t.x,y1:t.y,x2:o,y2:t.y,thickness:i}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:i}}];a.push(...Qu({id:"crucible:wall:left",orientation:"vertical",fixed:t.x,start:t.y,end:t.y+t.height,openings:s.left.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...Qu({id:"crucible:wall:right",orientation:"vertical",fixed:t.x+t.width,start:t.y,end:t.y+t.height,openings:s.right.map(e=>[e.y,e.y+e.height]),thickness:i,friction:.46,restitution:.12}),...Qu({id:"crucible:wall:bottom",orientation:"horizontal",fixed:t.y+t.height,start:t.x,end:t.x+t.width,openings:s.bottom.map(e=>[e.x,e.x+e.width]),thickness:i,friction:.5,restitution:.08}));for(const t of e.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(t.id),sensor:!0,shape:{type:"aabb",x:t.x+t.width/2,y:t.y+t.height/2,width:t.width,height:t.height}});return a}function Ju(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function eh(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?Ju(e):1}function th(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:eh(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function nh(e){return"crucible:component:"+encodeURIComponent(e)}function ih(e){return"crucible:product:"+encodeURIComponent(e)}function oh(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function rh(e,t,n,i){if(void 0!==n&&Number.isFinite(n)&&n>0)return n;const o=Math.min(...t,e),r=Math.max(...t,e);return r-o>zu?i[0]+(i[1]-i[0])*Math.sqrt(Math.max(0,e-o)/(r-o)):(i[0]+i[1])/2}function sh(e,t){const n=Math.max(.25,Math.min(1,t.width/900,t.height/520)),i=e?.[0]??7*n,o=e?.[1]??18*n,r=Math.max(1,Math.min(i,o));return[r,Math.max(r,Math.max(i,o))]}function ah(e,t,n={}){const i=Object.values(e.components).sort((e,t)=>Lu(e.id,t.id)),o=i.map(e=>e.amount),r=sh(n.radiusRange,t),s=function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(eh(n.seed)),a=t.mouth.x+t.mouth.width/2,c=t.chamber.y+Math.max(18,.18*t.chamber.height),l=Math.max(4,.28*t.chamber.width),d=Math.max(4,.12*t.chamber.height);return i.map((e,t)=>{const u=t/Math.max(1,i.length)*Math.PI*2+.18*(s()-.5),h=rh(e.amount,o,n.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:nh(e.id),x:a+Math.cos(u)*l*(.45+.45*s()),y:c+Math.sin(u)*d*(.45+.45*s()),vx:24*(s()-.5),vy:18*(s()-.5),mass:Math.max(.25,h*h*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:h},datum:p}})}function ch(e,t){if(!e)return[];const n=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),i=Math.max(1,Math.ceil(e/n));return Array.from({length:e},(e,o)=>({x:t.x+t.width/n*(o%n+.5),y:t.y+(Math.floor(o/n)+.5)*(t.height/i)}))}function lh(e){return e.outletId?e.outletId:"failed"===e.status?"failed":"recovered"===e.status?"recovered":"retained"===e.status?"retained":"ejected"===e.status?"residue":void 0}function dh(e,t){return e.outlets.find(e=>e.id===t)||{x:e.chamber.x+.18*e.chamber.width,y:e.chamber.y+.2*e.chamber.height,width:.64*e.chamber.width,height:.6*e.chamber.height}}function uh(e,t,n={}){const i=Object.values(e.products).sort((e,t)=>Lu(e.id,t.id)),o=Object.values(e.components).sort((e,t)=>Lu(e.id,t.id)),r=[...o.map(e=>e.amount),...i.map(e=>e.amount)],s=sh(n.radiusRange,t),a=function(e,t){const n=new Map;for(const t of e){const e=t.outletId??"__chamber__",i=n.get(e)??[];i.push(t),n.set(e,i)}const i=new Map;for(const[e,o]of n){o.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Lu(e.id,t.id));const n=ch(o.length,dh(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>i.set(e.id,n[t]))}return i}(i,t),c=i.map(e=>{const i=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},o=1.28*rh(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:ih(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.018),bodyCollisions:!1,shape:{type:"circle",radius:o},datum:c}}),l=new Map;for(const e of o.filter(e=>!e.productIds.length)){const t=lh(e)??"__chamber__",n=l.get(t)??[];n.push(e),l.set(t,n)}const d=new Map;for(const[e,n]of l){const i=ch(n.length,dh(t,"__chamber__"===e?void 0:e));n.forEach((e,t)=>d.set(e.id,i[t]))}return[...o.map(e=>{let i=d.get(e.id);if(e.productIds.length){const n=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(n.length){i={x:n.reduce((e,t)=>e+t.x,0)/n.length,y:n.reduce((e,t)=>e+t.y,0)/n.length};const o=Ju(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));i={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}i??(i={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const o=rh(e.amount,r,n.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:nh(e.id),x:i.x,y:i.y,mass:Math.max(.25,o*o*.015),shape:{type:"circle",radius:o},datum:c}}),...c]}var hh=uh;function ph(e){return Array.isArray(e)?e.map(ph):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Lu(e,t)).map(([e,t])=>[e,ph(t)])):e}function mh(e){return JSON.stringify(ph(e))}function fh(e,t){const n=_u(t)??0,i=Math.max(0,Math.min(e.duration,n));if(!e.phases.length)return{elapsed:i,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const o=i>=e.duration-zu,r=o?e.phases[e.phases.length-1]:e.phases.find(e=>i>=e.start&&e.end>i)??e.phases[0];return{elapsed:i,phaseId:r.id,phaseIndex:r.index,phaseElapsed:o?r.duration:Math.max(0,i-r.start),complete:o}}function yh(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,_u(t)??0));const n=e.phases.find(e=>e.id===t.phaseId);if(!n)return e.duration;const i=Math.max(0,Math.min(1,_u(t.progress??0)??0));return n.start+n.duration*i}function gh(e,t=e.duration){const n=fh(e,t);let i=gu(e.initialState);const o=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>n.elapsed+zu)break;const a=Pu(i,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});o.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(i=a.state)}return i.elapsed=n.elapsed,i.phaseId=n.phaseId,i.phaseIndex=n.phaseIndex,i.phaseElapsed=n.phaseElapsed,i.complete=n.complete,n.complete&&"in_process"===i.outcome&&(i.outcome="complete"),i.playing=!1,{state:i,diagnostics:o,materializations:r,observations:s}}function bh(e){const t=function(e){const t=[];e.length||t.push(Hu("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const n=Yu(e.map(e=>e.id));n.length&&t.push(Hu("error","duplicate-phase-id",`Phase ids must be unique: ${n.join(", ")}.`,"phases",n));let i=0;return{phases:e.map((e,n)=>{const o=_u(e.duration),r=null!=o&&o>0?o:0;e.id.trim()||t.push(Hu("error","invalid-phase-id","Phase ids may not be empty.",`phases.${n}.id`)),null!=o&&o>0||t.push(Hu("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${n}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(Hu("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${n}.intensity`,[e.id]));const s={...e,duration:r,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:n,start:i,end:i+r};return i=s.end,s}),diagnostics:t}}(e.phases),n=t.phases.at(-1)?.end??0,i=Uu(e.outlets??Wu),o=(e.products??[]).map(e=>({...e,metrics:e.metrics?{...e.metrics}:void 0})),r=function(e,t,n){const i=[],o=Yu(e.map(e=>e.id));o.length&&i.push(Hu("error","duplicate-event-id",`Event ids must be unique: ${o.join(", ")}.`,"events",o));const r=[];return e.forEach((e,o)=>{let s,a,c;if(e.id.trim()||i.push(Hu("error","invalid-event-id","Event ids may not be empty.",`events.${o}.id`)),"time"in e.at&&void 0!==e.at.time){const r=_u(e.at.time);if(null==r||0>r||r>n+zu)return void i.push(Hu("error","event-time-out-of-range",`Event time must fall between 0 and ${n}.`,`events.${o}.at.time`,[e.id]));s=Math.max(0,Math.min(n,r));const l=function(e,t,n){const i=e.find(e=>zu>=Math.abs(e.start-n));if(i)return{phase:i,boundaryRank:1};const o=e.find(e=>n>=e.start&&e.end>n);return o?{phase:o,boundaryRank:0}:zu>=Math.abs(n-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,n,s);a=l.phase,c=l.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void i.push(Hu("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${o}.at.phaseId`,[e.id,e.at.phaseId]));const n=e.at.progress??0;if(!Number.isFinite(n)||0>n||n>1)return void i.push(Hu("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${o}.at.progress`,[e.id]));s=a.start+a.duration*n,c=0===n?1:0}a?r.push({...e,index:o,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):i.push(Hu("error","event-without-phase","Event could not be assigned to a phase.",`events.${o}.at`,[e.id]))}),r.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:r,diagnostics:i}}(e.events??[],t.phases,n),s=Vu(e),a=Ku(e.size??Fu,i),c=Zu(a),l=function(e,t){const n=[],i=new Set(t.map(e=>e.id)),o=Yu(t.map(e=>e.id)),r=Yu(e.map(e=>e.id));return o.length&&n.push(Hu("error","duplicate-outlet-id",`Outlet ids must be unique: ${o.join(", ")}.`,"outlets",o)),r.length&&n.push(Hu("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||n.push(Hu("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||n.push(Hu("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||n.push(Hu("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||n.push(Hu("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0===e.outletId||i.has(e.outletId)||n.push(Hu("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),Xu(e.metrics??{},n,`products.${t}.metrics`)}),n}(o,i),d=mh({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Lu(e.id,t.id)).map(e=>({id:e.id,label:e.label,category:e.category,amount:e.amount,metrics:e.metrics,status:e.status})),phases:t.phases.map(({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:n,description:i,intensity:o,motion:r,color:s,metrics:a})),products:o,outlets:i,events:r.events.map(({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:n,summary:i,authoredAt:o,phaseId:r,boundaryRank:s,effects:a}))}),u=ah(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...l],p={phases:t.phases,events:r.events,products:o,outlets:i,duration:n,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:th(e.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:d,diagnostics:h},m=gh(p),f=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),y=f.length?[Hu("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return p.terminalState=m.state,p.terminalSpawns=hh(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...y],p}function xh(e,t){return e.playing=t&&!e.complete,e}function vh(e,t,n=!1){const i=gh(e,t);return{...i,state:xh(i.state,n)}}function wh(e,t,n,i=t.playing){const o=vh(e,n,i),r=new Set(t.eventsApplied);return{...o,observations:o.observations.filter(e=>!r.has(e.eventId)),materializations:o.materializations.filter(e=>!r.has(e.eventId))}}function kh(e,t,n={}){return uh(t,e.layout,n)}function Mh(e,t){return function(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)/4294967295}function Ih(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function Sh(e,t,n={}){return new Map(kh(e,t,n).flatMap(e=>{const t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function jh(e,t){const n=Object.values(e.terminalState.products).map(e=>e.id).sort(),i=Math.max(0,n.indexOf(t))/Math.max(1,n.length)*Math.PI*2-Math.PI/2,o=Math.min(58,.19*e.layout.chamber.width),r=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(i)*o,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(i)*r}}function Ah(e,t,n){if("string"!=typeof t)return n;if("function"!=typeof getComputedStyle||!e.canvas)return t||n;const i=t.startsWith("var(")?t.match(/var\((--[^,\s)]+)/)?.[1]:t.startsWith("--")?t:null;return i?getComputedStyle(e.canvas).getPropertyValue(i).trim()||n:t||n}function Ch(e){return Number.isFinite(e)?1e3>Math.abs(e)?Number.isInteger(e)?e+"":e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):e.toLocaleString():"0"}function Rh(e){const t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",n=e.reason?` ${e.reason}.`:"";return`${Ch(e.amount)} amount; ${e.status}.${t}${n}`}function $h(e){const t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${Ch(e.amount)} amount.${t}`}function Ph(e,t,n){const i=t.datum;if(!i?.__crucible)return;const o="circle"===t.shape.type?t.shape.radius:8,r=Ah(e,n.fill,"product"===i.kind?"#b8792d":"#356b63"),s=Ah(e,n.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof n.opacity?n.opacity:.96,e.fillStyle=r,e.strokeStyle=s,e.lineWidth="number"==typeof n.strokeWidth?n.strokeWidth:1.25,"product"===i.kind){e.shadowColor=r,e.shadowBlur=10,e.beginPath();for(let t=0;6>t;t+=1){const n=-Math.PI/2+t/6*Math.PI*2,i=Math.cos(n)*o,r=Math.sin(n)*o;0===t?e.moveTo(i,r):e.lineTo(i,r)}e.closePath(),e.fill(),e.shadowBlur=0,e.stroke(),e.beginPath(),e.arc(0,0,Math.max(2,.36*o),0,2*Math.PI),e.strokeStyle=Ah(e,"var(--semiotic-bg, #fffaf0)","#fffaf0"),e.globalAlpha*=.72,e.stroke()}else e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),e.stroke(),e.beginPath(),e.arc(.25*-o,.28*-o,Math.max(1,.18*o),0,2*Math.PI),e.fillStyle="rgba(255,255,255,0.34)",e.fill();e.restore()}c(require("react")),require("react/jsx-runtime");var Bh=require("react/jsx-runtime"),Dh="var(--semiotic-text, #26323a)",Th="var(--semiotic-text-secondary, #6c7377)",Eh="var(--semiotic-primary, #b8792d)",Oh="var(--semiotic-danger, #9f3d35)",Nh="var(--semiotic-success, #356b63)";function Fh(e){const{x:t,y:n,width:i,height:o}=e.chamber,r=Math.min(.14*i,48),s=n+o;return[`M ${t} ${n}`,`L ${t+r} ${s-.16*o}`,`Q ${t+i/2} ${s+.1*o} ${t+i-r} ${s-.16*o}`,`L ${t+i} ${n}`].join(" ")}function Wh({layout:e,phases:t,state:n,compact:i=!1}){const o=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return(0,Bh.jsxs)("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[(0,Bh.jsxs)("defs",{children:[(0,Bh.jsxs)("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[(0,Bh.jsx)("stop",{offset:"0",stopColor:Eh,stopOpacity:"0.03"}),(0,Bh.jsx)("stop",{offset:"0.66",stopColor:Eh,stopOpacity:"0.1"}),(0,Bh.jsx)("stop",{offset:"1",stopColor:Oh,stopOpacity:"0.18"})]}),(0,Bh.jsx)("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:(0,Bh.jsx)("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:Dh,strokeOpacity:"0.08",strokeWidth:"1"})})]}),(0,Bh.jsx)("rect",{x:e.chamber.x,y:e.chamber.y,width:e.chamber.width,height:e.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:Dh,strokeOpacity:"0.52",strokeWidth:i?1:2.2}),(0,Bh.jsx)("path",{d:Fh(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),(0,Bh.jsx)("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:Dh,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:i?2:5}),i?null:(0,Bh.jsx)("g",{"data-testid":"crucible-phase-rail",children:t.map((i,r)=>{const s=t.slice(0,r).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/o*e.phaseRail.width,c=Math.max(0,i.duration)/o*e.phaseRail.width,l=i.id===n.phaseId,d=n.phaseIndex>r||n.complete;return(0,Bh.jsxs)("g",{children:[(0,Bh.jsx)("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,c-2),height:e.phaseRail.height,rx:2,fill:l?i.color??Eh:d?Nh:Dh,fillOpacity:l?.68:d?.28:.09}),46>c?null:(0,Bh.jsx)("text",{x:a+c/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:l?Dh:Th,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:l?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(i.label??i.id).toUpperCase()})]},i.id)})}),e.outlets.map(e=>(0,Bh.jsxs)("g",{children:[(0,Bh.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?Oh:Nh),fillOpacity:"0.1",stroke:e.color??("left"===e.side?Oh:Nh),strokeDasharray:"3 3",strokeOpacity:"0.62"}),i?null:(0,Bh.jsx)("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:Th,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function qh(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}function zh({rows:e,layout:t,projection:n,amountLabel:i}){if(!e.length)return null;const o=n.measure??"count",r=e.map(e=>Math.max(0,qh(e,o))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),c=t.projection.height>48?21:4,l=Math.max(5,t.projection.height-c-5);return(0,Bh.jsx)("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:e.map((e,n)=>{const d=r[n],u=Math.max(d>0?2:0,d/s*l),h=t.projection.x+n*a+.18*a;return(0,Bh.jsxs)("g",{children:[(0,Bh.jsx)("rect",{x:h,y:t.projection.y+l-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===e.status||"ejected"===e.status?Oh:"complete"===e.status?Eh:Nh,fillOpacity:"0.68"}),c>4&&a>=34?(0,Bh.jsxs)(Bh.Fragment,{children:[(0,Bh.jsx)("text",{x:h+.32*a,y:t.projection.y+l+10,fill:Th,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),(0,Bh.jsxs)("text",{x:h+.32*a,y:t.projection.y+l+19,fill:Dh,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[Ch(d),"amount"===o&&i?" "+i:""]})]}):null]},e.key)})})}function Lh({controls:e,duration:t,elapsed:n,phaseLabel:i,playing:o,complete:r,playbackRate:s,disabled:a,onPlayPause:c,onReset:l,onStepPhase:d,onPlaybackRateChange:u}){const h=t>0?Math.min(1,Math.max(0,n/t)):1;return(0,Bh.jsxs)("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:Dh,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[e.playPause?(0,Bh.jsx)("button",{type:"button",disabled:a,onClick:c,"aria-pressed":o,children:o?"Pause":r?"Replay":"Play"}):null,e.stepPhase?(0,Bh.jsx)("button",{type:"button",disabled:a,onClick:d,children:"Next phase"}):null,e.reset?(0,Bh.jsx)("button",{type:"button",disabled:a,onClick:l,children:"Reset"}):null,e.timeline?(0,Bh.jsxs)("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[(0,Bh.jsx)("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:i}),(0,Bh.jsx)("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:(0,Bh.jsx)("span",{style:{background:Eh,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),(0,Bh.jsxs)("span",{style:{color:Th,fontVariantNumeric:"tabular-nums"},children:[n.toFixed(1),"s"]})]}):null,e.speed?(0,Bh.jsxs)("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",(0,Bh.jsxs)("select",{disabled:a,value:s,onChange:e=>u(Number(e.currentTarget.value)),children:[(0,Bh.jsx)("option",{value:.25,children:"¼×"}),(0,Bh.jsx)("option",{value:.5,children:"½×"}),(0,Bh.jsx)("option",{value:1,children:"1×"}),(0,Bh.jsx)("option",{value:2,children:"2×"})]})]}):null]})}function Hh(e,t,n,i){const o="function"==typeof i?i(t,n):i,r=t.datum;return{fill:e,stroke:"product"===r?.kind?"var(--semiotic-bg, #fffaf0)":Dh,strokeWidth:"product"===r?.kind?1.8:1.1,opacity:.96,...o}}var Yh=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function _h(e){let t=2166136261;for(let n=0;e.length>n;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function Gh(e){return"number"==typeof e&&Number.isFinite(e)?e:_h((e??"crucible")+"")}function Xh(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.max(.05,Math.min(8,t)):1}function Vh(e,t,n){return"category"===t?e.category:"status"===t?e.status:"outlet"===t?e.outletId??"in chamber":"product"===t?e.productIds[0]??"unalloyed":function(e,t,n){return(("function"==typeof e?e(t,n):t[e])??"unassigned")+""}(t,e.datum,n)}function Uh(e){return Yh[_h(e)%Yh.length]}function Kh(e,t){const n=Object.keys(e.components).length,i=Object.keys(e.products).length,o=Object.values(e.products).reduce((e,t)=>e+t.amount,0),r=t?" "+t:" amount",s=e.outcome?` Outcome: ${e.outcome}.`:"";return`${n} source component${1===n?"":"s"}; ${i} product${1===i?"":"s"}; ${o.toLocaleString()}${r} in products.${s}`}function Qh(e,t,n){return{id:e.id??t,at:{...e.at},effects:n,...void 0===e.label?null:{label:e.label},...void 0===e.description?null:{description:e.description},...void 0===e.summary?null:{summary:e.summary}}}function Zh(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function Jh(e){const{productId:t,form:n,contributions:i=[],complete:o}=e,r=e.idPrefix??t,s=Zh(n.loss),a=[Qh(n,r+"-form",[{type:"combine",sourceIds:[...n.sourceIds],productId:t,...n.basisRelationIds?{basisRelationIds:[...n.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return i.forEach((e,n)=>{const i=Zh(e.loss);a.push(Qh(e,`${r}-contribute-${n+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...i?{loss:i}:null}]))}),a.push(Qh(o,r+"-complete",[{type:"complete-product",productId:t,...void 0===o.outletId?null:{outletId:o.outletId},...void 0===o.reason?null:{reason:o.reason}}])),a}var ep=require("react/jsx-runtime"),tp=require("react"),np=(0,hu.forwardRef)(function(e,t){const{amountAccessor:n,amountLabel:i,bodyRadius:o,categoryAccessor:r,colorBy:s="category",conservation:a,controls:c,data:l,emptyContent:d,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:f,labelAccessor:y,loading:g,loadingContent:b,metrics:x,metricsAccessor:v,onClick:w,onConservation:k,onCrucibleObservation:M,onDiagnostic:I,onStateChange:S,outlets:j,paused:A,phases:R,playback:P="replay",playbackRate:B=1,products:D,projection:T,radiusRange:E,rerunMS:O,responsiveHeight:N,responsiveWidth:F,seed:W,showBonds:q=!0,snapshotAt:z}=e,L=(0,hu.useRef)(null),H=(0,hu.useRef)(A);H.current=A;const Y=C(),_=V(),G=kc(e,Fu),{chartMode:X,chartSize:U,showChrome:K,showProjection:Q,className:Z,title:J,description:ee,summary:te,accessibleTable:ne,enableHover:ie,margin:oe}=G,[re,se]=$(U,F,!1),ae=F?Math.max(1,se[0]):U[0],ce=U[1],le=(0,hu.useMemo)(()=>[ae,ce],[ce,ae]),de=(0,hu.useMemo)(()=>zc(l??[]),[l]),ue=(0,hu.useMemo)(()=>bh({data:de,phases:R,products:D,outlets:j,events:u,idAccessor:p,labelAccessor:y,categoryAccessor:r,amountAccessor:n,metricsAccessor:v,initialStateAccessor:m,metrics:x,size:le,seed:W,bodyRadius:o,radiusRange:E}),[n,o,r,u,p,m,y,x,v,j,R,D,E,le,de,W]),he=Object.values(ue.initialState.components).map((e,t)=>Vh(e,s,t)).join("\0"),pe=`${ue.semanticKey}:${le[0]}x${le[1]}:${(o??"auto")+""}:${E?.join(",")??"auto"}:${he}`,me=(0,hu.useRef)(ue),fe=(0,hu.useRef)(pe);fe.current!==pe&&(fe.current=pe,me.current=ue);const ye=me.current,ge="snapshot"===P||Y||_,be=ge?function(e,t){return yh(e,t)}(ye,z):0,xe=!ge,ve=(0,hu.useMemo)(()=>vh(ye,be,xe&&!A),[fe.current,be,xe]),[we,ke]=(0,hu.useState)(ve),Me=(0,hu.useRef)(we),[Ie,Se]=(0,hu.useState)(xe),je=(0,hu.useRef)(Ie),[Ae,Ce]=(0,hu.useState)(0),[Re,$e]=(0,hu.useState)(()=>Xh(B)),Pe=(0,hu.useRef)(Sh(ye,ve.state,{seed:W,bodyRadius:o,radiusRange:E})),Be=(0,hu.useRef)(""),De=(0,hu.useRef)(S),Te=(0,hu.useRef)(M),Ee=(0,hu.useRef)(I),Oe=(0,hu.useRef)(k);De.current=S,Te.current=M,Ee.current=I,Oe.current=k;const Ne=(0,hu.useRef)({seed:W,bodyRadius:o,radiusRange:E});Ne.current={seed:W,bodyRadius:o,radiusRange:E};const Fe=(0,hu.useCallback)((e,t=!1)=>{if(Me.current=e,Pe.current=Sh(me.current,e.state,Ne.current),ke(e),t)for(const t of e.observations)Te.current?.(t)},[]);(0,hu.useEffect)(()=>{$e(Xh(B))},[B]),(0,hu.useEffect)(()=>{const e=!ge,t=vh(ye,ge?be:0,e&&!H.current);je.current=e,Se(e),Fe(t)},[Fe,ye,be,ge,pe]),(0,hu.useEffect)(()=>{const e=Me.current,t=je.current&&!A&&!e.state.complete;if(e.state.playing===t)return;const n={...e,state:gu(e.state)};n.state.playing=t,Fe(n)},[Fe,A]),(0,hu.useEffect)(()=>{for(const e of ye.diagnostics)Ee.current?.(e)},[pe,ye.diagnostics]),(0,hu.useEffect)(()=>{if(De.current?.(we.state),a){const e=!0===a?{}:a;Oe.current?.(Tu(we.state,e))}},[a,we.state]);const We=(0,hu.useCallback)(()=>{Be.current="";const e=!ge,t=vh(me.current,0,e&&!A);je.current=e,Se(e),Fe(t)},[Fe,A,ge]),qe=(0,hu.useMemo)(()=>({...ye.config,...h.config,fixedDt:h.config?.fixedDt??ye.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??ye.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??ye.config.settleStepLimit,timeScale:Re,colliders:[...ye.config.colliders??[],...h.config?.colliders??[]],kernel:{...ye.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??ye.config.kernel?.gravity??{x:0,y:0}},observation:{...ye.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,Re,ye.config]),ze=ge||!!A||!Ie&&!we.state.complete,Le=wc(qe,O,ze,We),He=(0,hu.useCallback)(()=>{if("number"!=typeof O||!Number.isFinite(O)||0>O)return;const e=`${pe}:${Ae}:${Le.rerunKey}`;Be.current!==e&&(Be.current=e,Le.config?.observation?.onSimulationStateChange?.("settled","running"))},[Le.config,Le.rerunKey,O,Ae,pe]),Ye=(0,hu.useCallback)(()=>{const e=vh(me.current,0,!1);je.current=!1,Se(!1),Fe(e),Ce(e=>e+1)},[Fe]),_e=(0,hu.useCallback)(()=>{const e=me.current,t=wh(e,Me.current.state,e.duration,!1);je.current=!1,Se(!1),Fe(t,!0);const n=kh(e,t.state,Ne.current),i=L.current;i&&(i.clear(),i.pushMany(n),i.step(0),i.settle()),He()},[Fe,He]),Ge=(0,hu.useCallback)(()=>{je.current=!1,Se(!1);const e={...Me.current,state:gu(Me.current.state)};e.state.playing=!1,Fe(e)},[Fe]),Xe=(0,hu.useCallback)(()=>{if(Be.current="",ge){const e=vh(me.current,be,!1);return je.current=!1,Se(!1),Fe(e),void Ce(e=>e+1)}const e=vh(me.current,0,!A);je.current=!0,Se(!0),Fe(e),Ce(e=>e+1)},[Fe,A,be,ge]),Ve=(0,hu.useCallback)(()=>{if(ge)return void Xe();if(Me.current.state.complete)return void Xe();je.current=!0,Se(!0);const e={...Me.current,state:gu(Me.current.state)};e.state.playing=!A,Fe(e)},[Fe,A,Xe,ge]),Ue=(0,hu.useCallback)(()=>{const e=me.current,t=function(e,t){const n=e.phases.find(e=>e.end>t+1e-7);return n?.end??e.duration}(e,Me.current.state.elapsed),n=wh(e,Me.current.state,t,!1);je.current=!1,Se(!1),Fe(n,!0);const i=L.current;i&&(i.clear(),i.pushMany(kh(e,n.state,Ne.current)),i.step(0))},[Fe]);(0,hu.useImperativeHandle)(t,()=>({play:Ve,pause:Ge,reset:Ye,replay:Xe,stepPhase:Ue,settle:_e,getCrucibleState:()=>gu(Me.current.state)}),[Ge,Ve,Xe,Ye,_e,Ue]);const Ke=(0,hu.useCallback)((e,t)=>{if(h.onTick?.(e,t),ge||A||!je.current)return;const n=Me.current.state,i=Math.min(me.current.duration,e.elapsedSeconds);if(n.elapsed+.045>=i&&me.current.duration>i)return;const o=wh(me.current,n,i,me.current.duration>i),r=o.state.eventsApplied.length!==n.eventsApplied.length;if(r&&function(e,t){const n=new Set(e.readBodies().map(e=>e.id)),i=t.filter(e=>!n.has(e.id));i.length&&e.pushMany([...i]),i.map(e=>e.id)}(t,kh(me.current,o.state,Ne.current)),o.state.complete){je.current=!1,Se(!1);const e=kh(me.current,o.state,Ne.current);t.clear(),t.pushMany(e),t.step(0),t.settle()}Fe(o,r),o.state.complete&&He()},[Fe,h,A,He,ge]),Qe=(0,hu.useCallback)(({body:e})=>function(e){const t=function(e){const{body:t,plan:n,state:i,targets:o}=e,r=t.datum;if(!r?.__crucible)return null;let s=o.get(`${r.kind}:${r.semanticId}`);if(!s)return null;const a=Ih(n,i),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),l=a?.motion??"hold",d=i.elapsed;if("product"===r.kind){const e=i.products[r.semanticId];"forming"===e?.status&&(s=jh(n,e.id))}else{const e=i.components[r.semanticId],t=e?.productIds.map(e=>i.products[e]).find(e=>"forming"===e?.status);if(t){const i=jh(n,t.id),o=Mh(e.id,17)*Math.PI*2,r=Math.max(5,Math.min(18,.026*n.layout.width));s={x:i.x+Math.cos(o)*r,y:i.y+Math.sin(o)*r}}}const u=r.semanticId,h=Mh(u,23)*Math.PI*2;if(!i.complete&&!(n.layout.chamber.x>s.x||s.x>n.layout.chamber.x+n.layout.chamber.width||n.layout.chamber.y>s.y||s.y>n.layout.chamber.y+n.layout.chamber.height))if("mix"===l){const e=Math.min(34,.1*n.layout.chamber.width)*c,t=Math.min(24,.09*n.layout.chamber.height)*c;s={x:s.x+Math.cos(d*(1.4+Mh(u,29))+h)*e,y:s.y+Math.sin(d*(1.8+Mh(u,31))+h)*t}}else if("press"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.56*n.layout.chamber.height;s={x:e+(s.x-e)*Math.max(.3,1-.32*c),y:t+(s.y-t)*Math.max(.35,1-.26*c)}}else if("separate"===l){const e=.5>Mh(u,41)?-1:1;s={x:s.x+e*Math.min(28,.075*n.layout.chamber.width)*c,y:s.y}}else if("bind"===l){const e=n.layout.chamber.x+n.layout.chamber.width/2,t=n.layout.chamber.y+.5*n.layout.chamber.height;s={x:e+.72*(s.x-e),y:t+.72*(s.y-t)}}else"charge"===l?s={x:s.x,y:s.y+4*Math.sin(2*d+h)*c}:"quench"===l&&(s={x:s.x+2*Math.sin(h)*c,y:s.y});return s}(e);if(!t)return null;const{body:n,state:i}=e,o=t.x-n.x,r=t.y-n.y,s=Math.hypot(o,r),a=Math.hypot(n.vx,n.vy);if(i.complete&&.7>s&&.45>a)return null;const c=!i.complete&&"pour"===Ih(e.plan,i)?.motion,l=i.complete?.68:c?.72:.5,d=i.complete?.22:c?.18:.14,u=i.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,o*l-n.vx*d)),y:Math.max(-u,Math.min(u,r*l-n.vy*d))}}({body:e,plan:me.current,state:Me.current.state,targets:Pe.current}),[]),Ze=(0,hu.useMemo)(()=>new Map(Object.keys(ye.initialState.components).map((e,t)=>[e,t])),[ye.initialState.components]),Je=(0,hu.useCallback)(t=>{if(e.color)return e.color;const n=t.datum;if(!n?.__crucible)return"var(--semiotic-primary, #b8792d)";if("product"===n.kind){const e=Me.current.state.products[n.semanticId];return e?.color??Uh(e?.id??n.semanticId)}const i=Me.current.state.components[n.semanticId];return i?Uh(Vh(i,s,Ze.get(i.id)??0)):"var(--semiotic-primary, #356b63)"},[s,Ze,e.color]),et=(0,hu.useCallback)((t,n)=>({...Hh(Je(t),t,n,h.bodyStyle),...void 0!==e.stroke?{stroke:e.stroke}:null,...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:null,...void 0!==e.opacity?{opacity:e.opacity}:null}),[Je,h.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),tt=(0,hu.useCallback)((e,t)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(e,t):void 0)??function(e,t){const n=e.datum;if(!n?.__crucible)return!1;if("component"===n.kind){const e=t.components[n.semanticId];return!!e&&{id:"crucible-component-"+e.id,label:e.label,description:Rh(e),group:"source component · "+e.status,datum:e}}const i=t.products[n.semanticId];return!!i&&{id:"crucible-product-"+i.id,label:i.label,description:$h(i),group:"derived product · "+i.status,datum:i}}(e,Me.current.state),[h]),nt=(0,hu.useCallback)(e=>{if(!w||!e||"object"!=typeof e)return;if(!e.__crucible)return;const t=Me.current.state,n="component"===e.kind?t.components[e.semanticId]:t.products[e.semanticId];n&&w(n)},[w]),it=(0,hu.useCallback)((e,t)=>{h.beforePaint?.(e,t),q&&function(e,t,n){const i=new Map;for(const e of t){const t=e.datum;t?.__crucible&&i.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(const t of Object.values(n.relations)){if("active"!==t.status)continue;const n=t.sourceIds.map(e=>i.get("component:"+e)).filter(e=>!!e);2>n.length||(e.strokeStyle="rejected"===t.category?"#9f3d35":"#b8792d",e.globalAlpha=.4,e.lineWidth=Math.max(.8,1.3*Number(t.strength??1)),e.setLineDash([3,4]),e.beginPath(),n.forEach((t,n)=>{0===n?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(const t of Object.values(n.products)){const n=i.get("product:"+t.id);if(n)for(const o of t.sourceIds){const r=i.get("component:"+o);r&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(n.x,n.y),e.stroke())}}e.restore()}(e,t,Me.current.state)},[h,q]),ot=(0,hu.useMemo)(()=>T??{groupBy:"outlet",measure:"count"},[T]),rt=(0,hu.useMemo)(()=>Bu(we.state,ot),[ot,we.state]),st=(0,hu.useMemo)(()=>Q?function(e,t,n,i){if(!e.length)return[];const o=n.measure??"count",r=t.projection.width/Math.max(1,e.length);return e.map((e,n)=>{const s=qh(e,o),a="amount"===o&&i?`${Ch(s)} ${i}`:`${Ch(s)} ${o}`;return{id:"crucible-projection-"+e.key,label:`${e.label}: ${a}`,description:`${e.count} source component${1===e.count?"":"s"}; ${Ch(e.amount)} amount.`,datum:e,group:"settled composition",x:t.projection.x+(n+.5)*r,y:t.projection.y+t.projection.height/2,shape:"rect",width:Math.max(12,.62*r),height:Math.max(8,t.projection.height-8)}})}(rt,ye.layout,ot,i):[],[i,ye.layout,ot,rt,Q]),at=jc(e.tooltip,h),{selection:ct,onBodyHover:lt}=xc({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"CrucibleChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover}),dt=Ac({...e,onClick:void 0},h,st,{selection:ct,chartMode:X,className:Z,title:J??"Crucible",description:ee??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:te??Kh(we.state,i),accessibleTable:ne,enableHover:ie,margin:oe}),ut=Sc(K?(0,ep.jsx)(Wh,{layout:ye.layout,phases:ye.phases,state:we.state,compact:G.compactMode||360>le[0]||260>le[1]}):void 0,h.backgroundGraphics),ht=Sc(Q?(0,ep.jsx)(zh,{rows:rt,layout:ye.layout,projection:ot,amountLabel:i}):void 0,h.foregroundGraphics),pt=(0,hu.useCallback)(e=>function(e,t){const n=e.data;if(!n?.__crucible)return null;const i="component"===n.kind?t.components[n.semanticId]:t.products[n.semanticId];if(!i)return null;const o="product"===n.kind;return(0,Bh.jsxs)("div",{className:"semiotic-tooltip semiotic-crucible-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(38, 50, 58, 0.96))",border:"1px solid rgba(255,255,255,0.2)",borderRadius:3,boxShadow:"0 8px 24px rgba(0,0,0,0.28)",color:"var(--semiotic-tooltip-text, #fffaf0)",maxWidth:290,padding:"9px 12px"},children:[(0,Bh.jsx)("strong",{children:i.label}),(0,Bh.jsx)("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:o?"Product · "+i.status:"Source · "+i.status}),(0,Bh.jsx)("div",{style:{marginTop:4},children:o?$h(i):Rh(i)})]})}(e,Me.current.state),[]),mt=ge?kh(ye,we.state,Ne.current):ye.initialSpawns,ft=function(e){return e?!0===e?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:e.playPause??!0,reset:e.reset??!0,stepPhase:e.stepPhase??!0,timeline:e.timeline??!0,speed:e.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(c),yt=Object.values(ft).some(Boolean),gt=ye.phases[we.state.phaseIndex],bt=Mc({data:l,emptyContent:d,loading:g,loadingContent:b,size:le});if(bt)return bt;const xt=ye.diagnostics.filter(e=>"error"===e.severity);return xt.length?(0,ep.jsxs)("div",{className:Z,role:"alert",style:{maxWidth:"100%",width:le[0]},children:[(0,ep.jsx)("strong",{children:"CrucibleChart could not compile this treatment tape."}),(0,ep.jsx)("ul",{children:xt.map((e,t)=>(0,ep.jsx)("li",{children:e.message},`${e.code}-${t}`))})]}):Ic("CrucibleChart",le,(0,ep.jsxs)("div",{ref:re,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:F?"100%":le[0]},children:[yt?(0,ep.jsx)(Lh,{controls:ft,duration:ye.duration,elapsed:we.state.elapsed,phaseLabel:gt?.label??gt?.id??"Complete",playing:Ie&&!A,complete:we.state.complete,playbackRate:Re,disabled:ge,onPlayPause:Ie?Ge:Ve,onReset:Ye,onStepPhase:Ue,onPlaybackRateChange:$e}):null,(0,tp.createElement)(fs,{...h,...at,...dt,key:`${pe}:${Ae}:${Le.rerunKey}:${ge?be:"replay"}`,ref:L,onBodyHover:lt,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:ut,bodyForces:Qe,bodySemanticItems:tt,bodyStyle:et,beforePaint:it,config:Le.config,continuous:!ge&&Ie&&!A&&!we.state.complete,enableHover:at.enableHover??ie,foregroundGraphics:ht,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:mt,initialSpawnPacing:f,onClick:w?nt:dt.onClick,onTick:Ke,paused:ze,renderBody:h.renderBody??Ph,responsiveHeight:N,responsiveWidth:!1,seed:Gh(W),size:le,tooltipContent:at.tooltipContent??pt})]}))});np.displayName="CrucibleChart";var ip=require("react");function op(e,t,n={}){const i=new Set,o=[...e.get(t)??[]];let r=0;for(;o.length>r;){const t=o[r];if(r+=1,!i.has(t)){i.add(t);for(const n of e.get(t)??[])o.push(n)}}return n.includeStart&&i.add(t),i}function rp(e,t,n){return el(n,e,t)}function sp(e,t){return t>e?-1:e>t?1:0}function ap(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function cp(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function lp(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function dp(e){const t=[],n=new Map,i=[],o=new Set;e.data.forEach((r,s)=>{const a=(rp(r,s,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(rp(r,s,e.laneAccessor)??"Unassigned")+"";o.has(c)||(o.add(c),i.push(c));const l=rp(r,s,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(sp),u=rp(r,s,e.blockerAccessor),h=rp(r,s,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(rp(r,s,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:s,datum:r,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:rp(r,s,e.startAccessor),end:rp(r,s,e.endAccessor),progress:lp(rp(r,s,e.progressAccessor)),status:h,completionTime:rp(r,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!rp(r,s,e.milestoneAccessor)})});const r=e.laneOrder?[...e.laneOrder,...i.filter(t=>!e.laneOrder?.includes(t))]:i,s=new Map(r.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=s.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((i,o)=>{const r=n.get(i);if(!r)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${i}".`,taskIDs:[e.id,i]});const s={id:ap(i,e.id),sourceID:i,targetID:e.id,sourceIndex:r.index,targetIndex:e.index,socketID:cp(e.id,o),socketIndex:o};l.push(s),a.get(e.id)?.push(s),c.get(i)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),r.outgoingEdgeIDs.push(s.id)});for(const e of a.values())e.sort((e,t)=>sp(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=cp(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>sp(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const p=[...n.keys()].filter(e=>0===u.get(e)).sort(sp);let m=0;for(;p.length;){const e=p.shift();m+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const i=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,i),0===i){const e=p.findIndex(e=>e>t.targetID);0>e?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(sp);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let f=0;const y=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of y)e.level=h.get(e.id)??0,f=Math.max(f,e.level);return{nodes:y,edges:l,byID:n,incoming:a,outgoing:c,lanes:r,maxLevel:f,diagnostics:t,valid:0===t.length}}function up(e,t,n={}){const i=Math.max(240,t.width),o=Math.max(220,t.height),r=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(i-2*r)/Math.max(1,e.lanes.length)),l=Math.max(76,(o-s-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,p=Math.max(1,Math.round(n.gutterCount??3)),m=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=m.get(e)??[];n.push(t),m.set(e,n)}for(const e of m.values())e.sort((e,t)=>sp(e.id,t.id));const f=.86*l,y=e.nodes.map(e=>{const t=m.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id))-(t.length-1)/2,i=(o=t.length)>1?Math.max(22,Math.min(u,(f-4*(o-1))/o)):u;var o;return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:r+c*(e.laneIndex+.5),y:s+l*(e.level+.5)+n*(i+4),width:d,height:i}}),g=new Map(y.map(e=>[e.taskID,e])),b=[],x=[];e.edges.forEach((t,n)=>{const i=g.get(t.sourceID),o=g.get(t.targetID);if(!i||!o)return;const r=e.incoming.get(t.targetID)??[],s=Math.min(.72*o.width,14*Math.max(1,r.length-1)),a=r.length>1?o.x-s/2+s*t.socketIndex/(r.length-1):o.x,c=o.y-o.height/2-h-2;b.push({id:t.socketID,edgeID:t.id,taskID:o.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:i.x,y:i.y+i.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%p-(p-1)/2));var u;x.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const v=new Map(b.map(e=>[e.id,e])),w=new Map(x.map(e=>[e.edgeID,e]));return{tasks:y,sockets:b,routes:x,taskByID:g,socketByID:v,routeByEdgeID:w}}function hp(e,t,n="all"){const i=Array.from(new Set(t)).sort(sp),o=new Set,r=()=>i.every(e=>o.has(e));return{taskID:e,mode:n,incomingEdgeIDs:i,deliver:e=>i.includes(e)?(o.add(e),r()):r(),reset:(e=[])=>{o.clear();for(const t of e)i.includes(t)&&o.add(t)},isSatisfied:r,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...i],deliveredEdgeIDs:[...o].sort(sp),satisfied:r()})}}function pp(e){return e instanceof Date?e.getTime():Number(e)}function mp(e,t){const n=pp("object"!=typeof t||t instanceof Date?t:t.currentTime),i=e.map((e,t)=>({event:e,index:t,time:pp(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),o=new Set,r=new Map,s=new Set,a=new Set;for(const{event:e}of i)"task-completed"===e.type?(o.add(e.taskID),r.delete(e.taskID)):"task-blocked"===e.type?r.set(e.taskID,e.reason):"task-unblocked"===e.type?r.delete(e.taskID):"dependency-delivered"===e.type?s.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:i.map(e=>e.event),completedTaskIDs:o,blockedByTaskID:r,deliveredEdgeIDs:s,armedTaskIDs:a}}function fp(e,t,n={}){const i=new Set(n.completedTaskIDs??[]),o=[...op(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):i.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),r=Array.from(new Set(o.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:o.length,affectedLaneCount:r.length,downstreamTaskIDs:o.map(e=>e.id),affectedLanes:r}}var yp=[];function gp(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function bp(e){if(null==e.completionTime)return null;const t=gp(e.completionTime,NaN);return Number.isFinite(t)?t:null}function xp(e,t,n,i){const o=new Set;for(const r of e.nodes){const s=e.incoming.get(r.id)??[];(i.has(r.id)||!n.has(r.id)&&s.every(e=>t.has(e.id)))&&o.add(r.id)}return o}function vp(e,t,n,i){const o=e.nodes.map(bp).filter(e=>null!=e),r=o.length?Math.min(...o)-1:0,s="replay"!==t||i?n:r,a=new Set,c=new Map;for(const n of e.nodes){const e=bp(n);(null!=e&&s>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||i)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:xp(e,l,c,a),blockers:c,previewTaskID:null}}function wp(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function kp(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Mp(e){const t=kp(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),i=function(e,t){let n=1/0,i=0,o=0;for(let r=1;t.length>r;r+=1){const s=t[r-1],a=t[r],c=a.x-s.x,l=a.y-s.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-s.x)*c+(e.y-s.y)*l)/d)),p=Math.hypot(e.x-(s.x+c*h),e.y-(s.y+l*h));n>p&&(n=p,i=o+h*u),o+=u}return i}(e.body,t.route),o=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let i=1;e.length>i;i+=1){const o=e[i-1],r=e[i],s=r.x-o.x,a=r.y-o.y,c=Math.hypot(s,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:o.x+s*e,y:o.y+a*e},tangent:{x:s/c,y:a/c}}}n+=c}}const i=e[e.length-2],o=e[e.length-1],r=o.x-i.x,s=o.y-i.y,a=Math.hypot(r,s)||1;return{point:o,tangent:{x:r/a,y:s/a}}}(t.route,Math.min(n,i+22));return{x:2.5*(78*o.tangent.x-e.body.vx)+8*(o.point.x-e.body.x),y:2.5*(78*o.tangent.y-e.body.vy)+8*(o.point.y-e.body.y)}}function Ip(e,t){const n=t.points[0]??{x:0,y:0},i=t.points[1]??n,o=i.x-n.x,r=i.y-n.y,s=Math.hypot(o,r)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:o/s*42,vy:r/s*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}var Sp=require("react/jsx-runtime");function jp({machine:e,layout:t,runtime:n,downstreamSet:i,selectedSet:o,width:r,height:s,seed:a,reduced:c,onSelectTask:l}){const d=t.tasks.length?Math.min(...t.tasks.map(e=>e.y-e.height/2)):60,u=Math.max(20,d-12),h=Math.max(26,d-6);return(0,Sp.jsxs)("svg",{"aria-hidden":"true",width:r,height:s,viewBox:`0 0 ${r} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[(0,Sp.jsx)("defs",{children:(0,Sp.jsx)("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:(0,Sp.jsx)("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const i=t.tasks.filter(e=>e.laneIndex===n),o=i[0]?.x??0;return(0,Sp.jsxs)("g",{children:[(0,Sp.jsx)("line",{x1:o,x2:o,y1:h,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),(0,Sp.jsx)("text",{x:o,y:u,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),o=n.inFlight.has(e.edgeID),r=i.has(e.targetID)||i.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");return(0,Sp.jsx)("polyline",{points:s,fill:"none",stroke:r?"var(--semiotic-selection-color, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:r?4:o?3:2,strokeOpacity:t||o||r?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return(0,Sp.jsxs)("g",{children:[(0,Sp.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&(0,Sp.jsx)("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const r=t.taskByID.get(e.id);if(!r)return null;const s=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=o.has(e.id)||u,p=i.has(e.id),m=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-text-secondary, #75818a)"}(e,n),f=r.x-r.width/2,y=r.y-r.height/2,g=Math.max(2,r.height*e.progress);return(0,Sp.jsxs)("g",{children:[(0,Sp.jsxs)("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[(0,Sp.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,rx:e.milestone?12:4,fill:"var(--semiotic-bg, #fff)",stroke:h||p?"var(--semiotic-selection-color, #e08a1e)":m,strokeWidth:h?4:p?3:2}),(0,Sp.jsx)("rect",{x:f+3,y:y+r.height-g+1,width:r.width-6,height:Math.max(0,g-4),rx:2,fill:m,opacity:s?.86:.46})]}),d&&(0,Sp.jsxs)("g",{opacity:u?.28:1,children:[(0,Sp.jsx)("line",{x1:f-8,x2:f+14,y1:r.y+9,y2:r.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),(0,Sp.jsx)("circle",{cx:f-8,cy:r.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),(0,Sp.jsxs)("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[(0,Sp.jsx)("rect",{x:f,y:y,width:r.width,height:r.height,fill:"transparent"}),(0,Sp.jsx)("text",{x:r.x,y:r.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),(0,Sp.jsxs)("text",{x:r.x,y:r.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-secondary, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}var Ap=require("react/jsx-runtime"),Cp={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Rp=(0,ip.forwardRef)(function(e,t){const{data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p,mode:m="snapshot",insight:f="blocker-amplification",currentTime:y,controls:g=!1,selectedTaskIDs:b,onSelectionChange:x,onObservation:v,reducedMotion:w,seed:k=31,width:M=920,height:I=620,responsiveWidth:S,responsiveHeight:j,title:A="Dependency chain reaction",description:C,className:R,accessibleTable:$=!0,enableHover:P=!0}=e,B=(0,ip.useRef)(null),[D,T]=(0,ip.useState)([]),E=b?Array.from(b):D,O=(0,ip.useMemo)(()=>new Set(E),[E]),N=gp(y,1/0),F="settle"===w,W=(0,ip.useMemo)(()=>dp({data:n,taskIDAccessor:i,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:p}),[n,i,o,r,s,a,c,l,d,u,h,p]),q=(0,ip.useMemo)(()=>up(W,{width:M,height:I}),[W,M,I]),[z,L]=(0,ip.useState)(()=>vp(W,m,N,F)),H=(0,ip.useRef)(z),Y=(0,ip.useCallback)(e=>{H.current=e,L(e)},[]),_=(0,ip.useCallback)(e=>v?.(e),[v]);(0,ip.useEffect)(()=>{const e=vp(W,m,N,F);B.current?.clear(),H.current=e,L(e)},[W,m,N,F]);const G=(0,ip.useCallback)(e=>{const t=O.has(e)?E.filter(t=>t!==e):[e];b||T(t),x?.(t)},[b,x,O,E]),X=(0,ip.useCallback)(e=>{if(F)return;const t=wp(H.current),n=[];for(const i of W.outgoing.get(e)??[]){if(t.delivered.has(i.id)||t.inFlight.has(i.id))continue;const e=q.routeByEdgeID.get(i.id);e&&(t.inFlight.add(i.id),n.push(Ip(i,e)))}n.length&&(Y(t),B.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[Y,q,W,F]),V=(0,ip.useCallback)((e,t)=>{const n=W.byID.get(e),i=H.current;if(!n||i.completed.has(e))return;const o=wp(i);o.completed.add(e),o.blockers.delete(e),o.armed.add(e),null!=t&&(o.currentTime=t),Y(o),_({type:"task-completed",taskID:e,datum:n.datum}),X(e)},[Y,_,W,X]),U=(0,ip.useCallback)(e=>{const t=wp(H.current),n=[],i=[];for(const i of e){if(t.delivered.has(i))continue;const e=W.edges.find(e=>e.id===i);e&&(t.delivered.add(i),t.inFlight.delete(i),n.push(e))}for(const e of n){const n=W.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(W.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),i.push(n.id))}if(n.length){Y(t);for(const e of n)_({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of i)_({type:"task-armed",taskID:e})}},[Y,_,W]),K=(0,ip.useCallback)((e,t)=>{const n=[],i=[];for(const e of t.readBodies()){const t=kp(e);if(!t||H.current.delivered.has(t.edgeID))continue;const o=t.route[t.route.length-1];o&&9>=Math.hypot(e.x-o.x,e.y-o.y)&&(n.push(t.edgeID),i.push(e.id))}i.length&&t.remove(i),n.length&&U(n)},[U]),Q=(0,ip.useCallback)(()=>{const e=wp(H.current);for(const t of W.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=xp(W,e.delivered,e.blockers,e.completed),e.playing=!1,B.current?.settle(),Y(e),_({type:"machine-settled"})},[Y,_,W]),Z=(0,ip.useCallback)(()=>{const e=wp(H.current);e.playing=!1,Y(e)},[Y]),J=(0,ip.useCallback)(()=>{const e=H.current,t=W.nodes.map(e=>({node:e,time:bp(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void V(t.node.id,t.time);Z();const n=[...e.blockers.keys()].map(t=>fp(W,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&_({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[_,W,Z,V]),ee=(0,ip.useCallback)(()=>{if(F)return void Q();const e=wp(H.current);e.playing=!0,Y(e)},[Y,F,Q]);(0,ip.useEffect)(()=>{if(!z.playing||"replay"!==m||F)return;const e=window.setInterval(J,760);return()=>window.clearInterval(e)},[m,F,z.playing,J]);const te=(0,ip.useCallback)(()=>{B.current?.clear(),Y(vp(W,m,N,F))},[Y,W,m,N,F]),ne=(0,ip.useCallback)(e=>{if(!W.byID.has(e))return;const t=wp(H.current);t.previewTaskID=e,Y(t);const n=fp(W,e,{completedTaskIDs:t.completed});_({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[Y,_,W]),ie=(0,ip.useCallback)(()=>{const e=wp(H.current);e.previewTaskID=null,Y(e)},[Y]),oe=(0,ip.useCallback)((e,t)=>{if(!W.byID.has(e))return;const n=wp(H.current);n.blockers.set(e,t),n.armed.delete(e),Y(n)},[Y,W]),re=(0,ip.useCallback)(e=>{if(!W.byID.has(e))return;const t=wp(H.current);t.blockers.delete(e),(W.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),Y(t)},[Y,W]),se=(0,ip.useCallback)(e=>fp(W,e,{completedTaskIDs:H.current.completed}),[W]),ae=(0,ip.useCallback)(()=>{const e=H.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...E],tasks:W.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:W.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[W,E]);(0,ip.useImperativeHandle)(t,()=>({play:ee,pause:Z,step:J,reset:te,settle:Q,previewResolve:ne,clearPreview:ie,completeTask:V,blockTask:oe,unblockTask:re,getAmplification:se,getMachineState:ae}),[oe,ie,se,ae,Z,V,ee,ne,te,Q,J,re]);const ce=z.previewTaskID??E[0]??null,le=ce?fp(W,ce,{completedTaskIDs:z.completed}):null,de=(0,ip.useMemo)(()=>new Set(le?.downstreamTaskIDs??[]),[le?.downstreamTaskIDs]),ue=(0,ip.useMemo)(()=>function(e,t,n){return e.nodes.flatMap(i=>{const o=t.taskByID.get(i.id);if(!o)return[];const r=e.incoming.get(i.id)??[],s=r.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(i.id),c=n.completed.has(i.id)?"completed":a?"blocked: "+a:n.armed.has(i.id)?"armed":"waiting";return[{id:i.id,label:`${i.label}, ${i.lane}, ${Math.round(100*i.progress)}%, ${c}`,description:`${s} of ${r.length} prerequisites delivered.`,datum:i.datum,x:o.x,y:o.y,width:o.width,height:o.height,shape:"rect",group:i.lane}]})}(W,q,z),[q,W,z]),he=(0,ip.useMemo)(()=>(0,Ap.jsx)(jp,{machine:W,layout:q,runtime:z,downstreamSet:de,selectedSet:O,width:M,height:I,seed:k,reduced:F,onSelectTask:G}),[de,I,q,W,F,z,k,G,O,M]),pe=(0,ip.useMemo)(()=>{const e=[...z.blockers.keys()].map(e=>fp(W,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${W.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[W,z.blockers,z.completed]),me=(0,ip.useMemo)(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:I,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:M-2,y1:0,x2:M-2,y2:I,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:M,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:I-2,x2:M,y2:I-2,thickness:4}}],[I,M]),fe=!0===g?["play","pause","step","reset","settle"]:g||[];return(0,Ap.jsxs)("div",W.valid?{className:R,style:{width:M,maxWidth:"100%",position:"relative"},children:[fe.length>0&&(0,Ap.jsx)("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:fe.map(e=>(0,Ap.jsx)("button",{type:"button",onClick:"play"===e?ee:"pause"===e?Z:"step"===e?J:"reset"===e?te:Q,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),(0,Ap.jsx)(fs,{ref:B,size:[M,I],responsiveWidth:S,responsiveHeight:j,title:A,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${le&&"blocker-amplification"===f?` Selected task reaches ${le.downstreamTaskCount} unfinished tasks across ${le.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:P,initialSpawns:yp,bodyForces:Mp,bodyStyle:{fill:"var(--semiotic-primary, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:ue,onSemanticItemActivate:e=>e.id&&G(e.id),foregroundGraphics:()=>he,paused:F,continuous:z.inFlight.size>0,onTick:K,config:{bodyLimit:Math.max(16,W.edges.length+4),colliders:me,settleStepLimit:2200,kernel:{seed:k,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),$&&(0,Ap.jsxs)("table",{style:Cp,children:[(0,Ap.jsx)("caption",{children:pe}),(0,Ap.jsx)("thead",{children:(0,Ap.jsxs)("tr",{children:[(0,Ap.jsx)("th",{children:"Task"}),(0,Ap.jsx)("th",{children:"Lane"}),(0,Ap.jsx)("th",{children:"Progress"}),(0,Ap.jsx)("th",{children:"State"}),(0,Ap.jsx)("th",{children:"Waiting on"}),(0,Ap.jsx)("th",{children:"Downstream reach"})]})}),(0,Ap.jsx)("tbody",{children:W.nodes.map(e=>{const t=fp(W,e.id,{completedTaskIDs:z.completed});return(0,Ap.jsxs)("tr",{children:[(0,Ap.jsx)("th",{scope:"row",children:e.label}),(0,Ap.jsx)("td",{children:e.lane}),(0,Ap.jsxs)("td",{children:[Math.round(100*e.progress),"%"]}),(0,Ap.jsx)("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),(0,Ap.jsx)("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),(0,Ap.jsxs)("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:R,role:"alert",style:{width:M,maxWidth:"100%"},children:[(0,Ap.jsx)("strong",{children:"ChainReactionChart could not compile this dependency graph."}),(0,Ap.jsx)("ul",{children:W.diagnostics.map((e,t)=>(0,Ap.jsx)("li",{children:e.message},`${e.code}-${t}`))})]})});Rp.displayName="ChainReactionChart";var $p=fs;