mintwaterfall 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +223 -0
- package/CONTRIBUTING.md +199 -0
- package/README.md +363 -0
- package/dist/index.d.ts +149 -0
- package/dist/mintwaterfall.cjs.js +7978 -0
- package/dist/mintwaterfall.esm.js +7907 -0
- package/dist/mintwaterfall.min.js +7 -0
- package/dist/mintwaterfall.umd.js +7978 -0
- package/index.d.ts +149 -0
- package/package.json +126 -0
- package/src/enterprise/enterprise-core.js +0 -0
- package/src/enterprise/enterprise-feature-template.js +0 -0
- package/src/enterprise/feature-registry.js +0 -0
- package/src/enterprise/features/breakdown.js +0 -0
- package/src/features/breakdown.js +0 -0
- package/src/features/conditional-formatting.js +0 -0
- package/src/index.js +111 -0
- package/src/mintwaterfall-accessibility.ts +680 -0
- package/src/mintwaterfall-advanced-data.ts +1034 -0
- package/src/mintwaterfall-advanced-interactions.ts +649 -0
- package/src/mintwaterfall-advanced-performance.ts +582 -0
- package/src/mintwaterfall-animations.ts +595 -0
- package/src/mintwaterfall-brush.ts +471 -0
- package/src/mintwaterfall-chart-core.ts +296 -0
- package/src/mintwaterfall-chart.ts +1915 -0
- package/src/mintwaterfall-data.ts +1100 -0
- package/src/mintwaterfall-export.ts +475 -0
- package/src/mintwaterfall-hierarchical-layouts.ts +724 -0
- package/src/mintwaterfall-layouts.ts +647 -0
- package/src/mintwaterfall-performance.ts +573 -0
- package/src/mintwaterfall-scales.ts +437 -0
- package/src/mintwaterfall-shapes.ts +385 -0
- package/src/mintwaterfall-statistics.ts +821 -0
- package/src/mintwaterfall-themes.ts +391 -0
- package/src/mintwaterfall-tooltip.ts +450 -0
- package/src/mintwaterfall-zoom.ts +399 -0
- package/src/types/js-modules.d.ts +25 -0
- package/src/utils/compatibility-layer.js +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* MintWaterfall v0.8.6
|
|
3
|
+
* D3.js-compatible waterfall chart component
|
|
4
|
+
* (c) 2024 David Duarte
|
|
5
|
+
* Released under the MIT License
|
|
6
|
+
*/
|
|
7
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("d3"),require("d3-color"),require("d3-array"),require("d3-drag"),require("d3-force")):"function"==typeof define&&define.amd?define(["exports","d3","d3-color","d3-array","d3-drag","d3-force"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).MintWaterfall={},e.d3,e.d3,e.d3,e.d3,e.d3)}(this,function(e,t,n,a,r,o){"use strict";function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var l=i(t);function s(){let e=[0,800];function t(t,n={}){const{range:a=e,nice:r=!0,tickFormat:o="auto"}=n,i=l.extent(t),s=l.scaleTime().domain(i).range(a);if(r&&s.nice(),"auto"===o&&i[0]&&i[1]&&i[0]instanceof Date&&i[1]instanceof Date){const e=(i[1].getTime()-i[0].getTime())/864e5;s.tickFormat=e<1?l.timeFormat("%H:%M"):e<30?l.timeFormat("%m/%d"):e<365?l.timeFormat("%b %Y"):l.timeFormat("%Y")}else"string"==typeof o&&(s.tickFormat=l.timeFormat(o));return s}function n(t,n={}){const{padding:a=.1,paddingInner:r=null,paddingOuter:o=null,align:i=.5,range:s=e}=n,c=[...new Set(t.map(String))],u=l.scaleBand().domain(c).range(s).align(i);return null!==r&&u.paddingInner(r),null!==o&&u.paddingOuter(o),null===r&&null===o&&u.padding(a),u}function a(t,n={}){const{range:a=e,nice:r=!0,zero:o=!1,clamp:i=!1}=n;let s=l.extent(t);o&&(s=[Math.min(0,s[0]),Math.max(0,s[1])]);const c=l.scaleLinear().domain(s).range(a);return r&&c.nice(),i&&c.clamp(!0),c}return{createAdaptiveScale:function(r,o="x"){const i=r.map(e=>"x"===o?e.label:e.cumulativeTotal);return i.every(e=>e instanceof Date)?t(i):i.every(e=>"string"==typeof e||isNaN(e))?n(i):i.every(e=>"number"==typeof e)?a(i):l.scaleBand().domain(i.map(String)).range(e)},createTimeScale:t,createOrdinalScale:function(e,t={}){const{range:n=l.schemeCategory10,unknown:a="#ccc"}=t,r=[...new Set(e)];return l.scaleOrdinal().domain(r).range(n).unknown(a)},createBandScale:n,createLinearScale:a,createLogScale:function(t,n={}){if(t.some(e=>e<=0))return a(t,n);const{range:r=e,nice:o=!0,clamp:i=!1}=n,s=l.extent(t),c=l.scaleLog().domain(s).range(r);return o&&c.nice(),i&&c.clamp(!0),c},setDefaultRange:function(t){e=t},getScaleInfo:function(e){const t={type:"unknown",domain:[],range:[]};try{t.domain=e.domain(),t.range=e.range(),"function"==typeof e.bandwidth?(t.type="band",t.bandwidth=e.bandwidth(),"function"==typeof e.step&&(t.step=e.step())):"function"==typeof e.nice?t.domain.length>0&&t.domain[0]instanceof Date?t.type="time":t.type="linear":"function"==typeof e.unknown&&(t.type="ordinal")}catch(e){console.warn("Could not extract complete scale info:",e)}return t},scaleUtils:c()}}function c(){return{formatTickValue:function(e,t){return"function"==typeof e.tickFormat?e.tickFormat()(t):e.tickFormat?e.tickFormat(t):"number"==typeof t?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toFixed(0):String(t)},getTickCount:function(e,t){const n=e.range(),a=Math.abs(n[1]-n[0]),r=Math.max(2,Math.floor(a/75));return Math.min(10,Math.max(2,r))},createColorScale:function(e,t=l.schemeCategory10){return l.scaleOrdinal().domain(e).range([...t])},invertScale:function(e,t){if("function"==typeof e.invert)return e.invert(t);if("function"==typeof e.bandwidth){const n=e.domain(),a=e.bandwidth();e.step();for(let r=0;r<n.length;r++){const o=e(n[r]);if(t>=o&&t<=o+a)return n[r]}const r=n.map(n=>Math.abs(e(n)+a/2-t));return n[r.indexOf(Math.min(...r))]}},detectScaleType:function(e){return e.every(e=>e instanceof Date)?"time":e.every(e=>"string"==typeof e||isNaN(e))?"band":e.every(e=>"number"==typeof e)?"linear":"adaptive"},createAxis:function(e,t="bottom"){let n;switch(t){case"top":n=l.axisTop(e);break;case"bottom":default:n=l.axisBottom(e);break;case"left":n=l.axisLeft(e);break;case"right":n=l.axisRight(e)}return n}}}function u(){const e={enabled:!0,extent:[[0,0],[800,400]],handleSize:6,filter:null,touchable:!0,keyModifiers:!0,selection:{fill:"#007acc",fillOpacity:.3,stroke:"#007acc",strokeWidth:1,strokeDasharray:null},handles:{fill:"#fff",stroke:"#007acc",strokeWidth:1,size:6}};let t=null,n=null,a=null,r=[];const o=l.dispatch("brushstart","brush","brushend","clear");function i(e){const t=u(e.selection);n=t;const a={selection:t,sourceEvent:e.sourceEvent,type:"start"};o.call("brushstart",void 0,a)}function s(e){const t=u(e.selection);n=t;const a={selection:t,sourceEvent:e.sourceEvent,type:"brush"};o.call("brush",void 0,a)}function c(e){const t=u(e.selection);n=t;const a={selection:t,sourceEvent:e.sourceEvent,type:"end"};o.call("brushend",void 0,a)}function u(e){if(!e)return null;const[[t,n],[a,r]]=e;return{x:[Math.min(t,a),Math.max(t,a)],y:[Math.min(n,r),Math.max(n,r)]}}function d(){a&&(a.selectAll(".selection").style("fill",e.selection.fill).style("fill-opacity",e.selection.fillOpacity).style("stroke",e.selection.stroke).style("stroke-width",e.selection.strokeWidth),e.selection.strokeDasharray&&a.selectAll(".selection").style("stroke-dasharray",e.selection.strokeDasharray),a.selectAll(".handle").style("fill",e.handles.fill).style("stroke",e.handles.stroke).style("stroke-width",e.handles.strokeWidth))}const f={enable:function(){return e.enabled=!0,t&&a&&(a.call(t),d()),f},disable:function(){return e.enabled=!1,a&&a.on(".brush",null),f},attach:function(n){if(a=n,e.enabled){const a=t||(t=l.brush().extent(e.extent).handleSize(e.handleSize).touchable(e.touchable).keyModifiers(e.keyModifiers).on("start",i).on("brush",s).on("end",c),e.filter&&t.filter(e.filter),t);n.call(a),d()}return f},detach:function(){return a&&(a.on(".brush",null),a.selectAll(".brush").remove(),a=null),f},clear:function(){return a&&t&&(a.call(t.clear),n=null,o.call("clear",void 0,{selection:null,sourceEvent:null,type:"end"})),f},getSelection:function(){return n},setSelection:function(e){if(a&&t){if(e){const n=function(e){return[[e.x[0],e.y[0]],[e.x[1],e.y[1]]]}(e);a.call(t.move,n)}else a.call(t.clear);n=e}return f},getSelectedData:function(){return n?function(e){if(!e||0===r.length)return[];const[t,n]=e.x,[a,o]=e.y;return r.filter(e=>e.x>=t&&e.x<=n&&e.y>=a&&e.y<=o)}(n):[]},setData:function(e){return r=[...e],f},configure:function(n){const r=e.extent;return Object.assign(e,n),t&&(n.extent&&n.extent!==r&&t.extent(n.extent),void 0!==n.handleSize&&t.handleSize(n.handleSize),void 0!==n.touchable&&t.touchable(n.touchable),void 0!==n.keyModifiers&&t.keyModifiers(n.keyModifiers),void 0!==n.filter&&n.filter&&t.filter(n.filter)),a&&d(),f},setExtent:function(n){return e.extent=n,t&&t.extent(n),f},isEnabled:function(){return e.enabled},on:function(e,t){return o.on(e,t),f},off:function(e,t){return o.on(e,null),f}};return f}function d(){let e=-1,t=[],a=null,r=null;function o(n,a,r){switch(n.key){case"Tab":break;case"ArrowRight":case"ArrowDown":n.preventDefault(),s(1,a,r);break;case"ArrowLeft":case"ArrowUp":n.preventDefault(),s(-1,a,r);break;case"Home":n.preventDefault(),c(0,a,r);break;case"End":n.preventDefault(),c(t.length-1,a,r);break;case"Enter":case" ":n.preventDefault(),e>=0?u(a[e],e,r):function(e,t){const n=t.formatNumber||(e=>e.toString()),a=e.reduce((e,t)=>e+t.stacks.reduce((e,t)=>e+t.value,0),0),r=`Waterfall chart with ${e.length} categories. Total value: ${n(a)}. Use arrow keys to navigate between bars.`;d(r)}(a,r);break;case"Escape":n.preventDefault(),function(){const t=l.select("svg[role='img']");if(!t.empty()){const n=t.node();n&&n.focus(),e=-1}}()}}function i(e,t,n,a,r){switch(e.key){case"Enter":case" ":e.preventDefault(),u(t,n,r),l.select(e.target).dispatch("click");break;case"ArrowRight":case"ArrowDown":e.preventDefault(),s(1,a,r);break;case"ArrowLeft":case"ArrowUp":e.preventDefault(),s(-1,a,r)}}function s(n,a,r){if(0===t.length)return;let o=e+n;o>=t.length?o=0:o<0&&(o=t.length-1),c(o,a,r)}function c(n,a,r){if(n<0||n>=t.length)return;e=n;const o=t[n];o&&o.focus&&o.focus();!function(e,t,n){const a=n.formatNumber||(e=>e.toString()),r=e.stacks.reduce((e,t)=>e+t.value,0),o=`Focused on ${e.label}, value ${a(r)}`;d(o)}(a[n],0,r)}function u(e,t,n){const a=n.formatNumber||(e=>e.toString()),r=e.stacks.reduce((e,t)=>e+t.value,0);let o=`${e.label}: Total value ${a(r)}`;if(e.stacks.length>1){o+=`. Contains ${e.stacks.length} segments: `;o+=e.stacks.map(e=>`${e.label||a(e.value)}`).join(", ")}void 0!==e.cumulative&&(o+=`. Cumulative total: ${a(e.cumulative)}`),d(o)}function d(e){const t=l.select("#waterfall-live-region");t.empty()||t.text(e),a&&a(e)}function f(){if(window.matchMedia){if(window.matchMedia("(forced-colors: active)").matches)return!0;if(window.matchMedia("(prefers-contrast: high)").matches)return!0;if(window.matchMedia("(prefers-contrast: more)").matches)return!0;if(window.matchMedia("(inverted-colors: inverted)").matches)return!0;try{const e=document.createElement("div");e.style.color="rgb(1, 2, 3)",e.style.position="absolute",e.style.visibility="hidden",document.body.appendChild(e);const t=window.getComputedStyle(e).color;return document.body.removeChild(e),"rgb(1, 2, 3)"!==t}catch(e){return!1}}return!1}function m(){return!!window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}return{createLiveRegion:function(e){return e.append("div").attr("id","waterfall-live-region").attr("aria-live","polite").attr("aria-atomic","true").style("position","absolute").style("left","-10000px").style("width","1px").style("height","1px").style("overflow","hidden")},createChartDescription:function(e,t,n={}){const{title:a="Waterfall Chart",summary:o="Interactive waterfall chart showing data progression",totalItems:i=(Array.isArray(t)?t.length:1),showTotal:l=!1}=n,s="waterfall-description-"+Math.random().toString(36).substr(2,9),c=e.append("div").attr("id",s).attr("class","sr-only").style("position","absolute").style("left","-10000px").style("width","1px").style("height","1px").style("overflow","hidden");let u=0,d=0,f=0;if(Array.isArray(t))u=t.reduce((e,t)=>t.stacks&&Array.isArray(t.stacks)?e+t.stacks.reduce((e,t)=>e+(t.value||0),0):e,0),d=t.filter(e=>e.stacks&&e.stacks.some(e=>(e.value||0)>0)).length,f=t.filter(e=>e.stacks&&e.stacks.some(e=>e.value<0)).length;else if(t&&"object"==typeof t&&t.children){function m(e){return e.children&&Array.isArray(e.children)?e.children.reduce((e,t)=>e+m(t),0):e.value||0}u=m(t),d=1,f=0}return c.html(`\n <h3>${a}</h3>\n <p>${o}</p>\n <p>This chart contains ${i} data categories${l?" plus a total bar":""}.</p>\n <p>Total value: ${n.formatNumber?n.formatNumber(u):u}</p>\n <p>${d} categories have positive values, ${f} have negative values.</p>\n <p>Use Tab to navigate between bars, Enter to hear details, and Arrow keys to move between bars.</p>\n <p>Press Escape to return focus to the chart container.</p>\n `),r=s,s},makeAccessible:function(n,a,s={}){const c=n.select("svg");c.attr("role","img").attr("aria-labelledby",r).attr("tabindex","0").attr("aria-describedby",r),c.on("keydown",function(e){o(e,a,s)});const u=c.selectAll(".bar-group");return u.each(function(t,n){const a=l.select(this),r=t;a.attr("role","button").attr("tabindex","-1").attr("aria-label",function(e,t,n={}){if(!e||!e.stacks||!Array.isArray(e.stacks))return`Item ${t+1}: Invalid data`;const a=e.stacks.reduce((e,t)=>e+t.value,0),r=e.stacks.length,o=n.formatNumber||(e=>e.toString());let i=`${e.label}: ${o(a)}`;r>1&&(i+=`, ${r} segments`);void 0!==e.cumulative&&(i+=`, cumulative total: ${o(e.cumulative)}`);return i+=". Press Enter for details.",i}(r,n,s)).attr("aria-describedby",`bar-description-${n}`).on("keydown",function(e){i(e,r,n,[r],s)}).on("focus",function(){e=n;const t=this;t&&function(e){l.select(e).style("outline","3px solid #4A90E2").style("outline-offset","2px")}(t)}).on("blur",function(){const e=this;e&&function(e){l.select(e).style("outline",null).style("outline-offset",null)}(e)})}),t=u&&u.nodes&&"function"==typeof u.nodes?u.nodes().filter(e=>null!==e):[],{bars:u,focusableElements:t.length}},handleChartKeydown:o,handleBarKeydown:i,moveFocus:s,focusElement:c,announce:d,detectHighContrast:f,applyHighContrastStyles:function(e){if(!f())return;const t=e.select("svg");t.selectAll(".bar-group rect").style("stroke","CanvasText").style("stroke-width","2px").style("fill","ButtonFace"),t.selectAll(".x-axis, .y-axis").style("stroke","CanvasText").style("stroke-width","2px"),t.selectAll("text").style("fill","CanvasText").style("font-weight","bold"),t.selectAll(".trend-line").style("stroke","Highlight").style("stroke-width","3px"),t.selectAll(".tooltip").style("background","Canvas").style("border","2px solid CanvasText").style("color","CanvasText")},injectForcedColorsCSS:function(){if("undefined"==typeof document)return;const e="mintwaterfall-forced-colors-css";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="\n @media (forced-colors: active) {\n .mintwaterfall-chart svg {\n forced-color-adjust: none;\n }\n \n .mintwaterfall-chart .bar-group rect {\n stroke: CanvasText !important;\n stroke-width: 2px !important;\n }\n \n .mintwaterfall-chart .x-axis,\n .mintwaterfall-chart .y-axis {\n stroke: CanvasText !important;\n stroke-width: 2px !important;\n }\n \n .mintwaterfall-chart text {\n fill: CanvasText !important;\n font-weight: bold !important;\n }\n \n .mintwaterfall-chart .trend-line {\n stroke: Highlight !important;\n stroke-width: 3px !important;\n }\n \n .mintwaterfall-tooltip {\n background: Canvas !important;\n border: 2px solid CanvasText !important;\n color: CanvasText !important;\n forced-color-adjust: none;\n }\n }\n \n @media (prefers-contrast: high) {\n .mintwaterfall-chart .bar-group rect {\n stroke-width: 2px !important;\n }\n \n .mintwaterfall-chart text {\n font-weight: bold !important;\n }\n }\n ",document.head.appendChild(t)},respectsReducedMotion:m,getAccessibleAnimationDuration:function(e){return m()?0:e},validateColorContrast:function(e,t){const a=e=>{const t=n.rgb(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:0},r=a(e),o=a(t),i=(Math.max(r,o)+.05)/(Math.min(r,o)+.05);return{ratio:i,passesAA:i>=4.5,passesAAA:i>=7}},setAnnounceFunction(e){return a=e,this},getCurrentFocus:()=>e,getFocusableCount:()=>t.length}}const f=d();function m(){let e=null,t=null,n={className:"mintwaterfall-tooltip",theme:"default",position:"smart",offset:{x:10,y:-10},animation:{duration:200,easing:"ease-out"},collision:{boundary:"viewport",flip:!0,shift:!0},content:{maxWidth:300,padding:12}};function a(t){if(!e)return;const a={default:{background:"rgba(0, 0, 0, 0.9)",color:"#ffffff",border:"none",borderRadius:"6px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",maxWidth:`${n.content.maxWidth}px`,padding:`${n.content.padding}px`},light:{background:"rgba(255, 255, 255, 0.95)",color:"#333333",border:"1px solid rgba(0, 0, 0, 0.1)",borderRadius:"6px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",maxWidth:`${n.content.maxWidth}px`,padding:`${n.content.padding}px`},minimal:{background:"#333333",color:"#ffffff",border:"none",borderRadius:"3px",fontSize:"12px",fontFamily:"monospace",boxShadow:"none",maxWidth:`${n.content.maxWidth}px`,padding:"8px 10px"},corporate:{background:"#2c3e50",color:"#ecf0f1",border:"1px solid #34495e",borderRadius:"4px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.2)",maxWidth:`${n.content.maxWidth}px`,padding:`${n.content.padding}px`}},r=a[t]||a.default;Object.keys(r).forEach(t=>{const n=t.replace(/([A-Z])/g,"-$1").toLowerCase(),a=r[t];e.style(n,a)})}function r(t){if(!e)return;const a=t,r=e.node();if(!r)return;const o=r.getBoundingClientRect(),i=window.innerWidth,l=window.innerHeight;let s=a.pageX+n.offset.x,c=a.pageY+n.offset.y;if("smart"===n.position){const e=function(e,t,a){const r=10;let o=e.x+n.offset.x,i=e.y+n.offset.y,l=1;o+t.width+r>a.width&&(o=e.x-t.width-Math.abs(n.offset.x),l=2);i+t.height+r>a.height&&(i=e.y-t.height-Math.abs(n.offset.y),l=2===l?3:4);o<r&&(o=r);i<r&&(i=r);return{x:o,y:i,quadrant:l}}({x:a.clientX,y:a.clientY},{width:o.width,height:o.height},{width:i,height:l});s=e.x+window.pageXOffset,c=e.y+window.pageYOffset}e.style("left",`${s}px`).style("top",`${c}px`)}const o={show:function(o,i,s=null){e||e||(e=l.select("body").append("div").attr("class",n.className).style("position","absolute").style("visibility","hidden").style("pointer-events","none").style("z-index","9999").style("opacity","0").style("transition",`opacity ${n.animation.duration}ms ${n.animation.easing}`),a(n.theme));const c=function(e,t){if("function"==typeof e)return e(t);if("string"==typeof e)return e;if("object"==typeof e&&e&&"template"in e)return function(e,t,n={}){if(!t)return e;let a=e;return a=a.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g,(e,a)=>{const r=(o=t,a.split(".").reduce((e,t)=>e?.[t],o));var o;const i=n[a];return i&&"function"==typeof i?i(r):null!=r?String(r):""}),a}(e.template,t,e.formatters);if(t)return function(e){const t=n.formatNumber||(e=>e.toLocaleString());let a=`<div class="tooltip-header"><strong>${e.label}</strong></div>`;if(e.stacks&&e.stacks.length>0){const n=e.stacks.reduce((e,t)=>e+t.value,0);a+=`<div class="tooltip-total">Total: ${t(n)}</div>`,e.stacks.length>1&&(a+='<div class="tooltip-stacks">',e.stacks.forEach(e=>{const n=e.color||"#666",r=e.label||t(e.value);a+=`\n <div class="tooltip-stack-item">\n <span class="tooltip-color-indicator" style="background-color: ${n}"></span>\n <span class="tooltip-stack-label">${r}</span>\n <span class="tooltip-stack-value">${t(e.value)}</span>\n </div>\n `}),a+="</div>")}return a}(t);return""}(o,s);return e.html(c).style("visibility","visible"),r(i),e.transition().duration(n.animation.duration).style("opacity","1"),t={content:o,event:i,data:s},e},hide:function(){if(e)return e.transition().duration(n.animation.duration).style("opacity","0").on("end",function(){l.select(this).style("visibility","hidden")}),t=null,e},move:function(n){if(e&&t)return r(n),e},theme:function(t){return n.theme=t,e&&a(t),o},configure:function(t){return n={...n,...t},e&&t.theme&&a(t.theme),o},destroy:function(){e&&(e.remove(),e=null),t=null},isVisible:function(){return null!==e&&"visible"===e.style("visibility")},getCurrentData:function(){return t?.data||null}};return o}function h(){const e={enabled:!0,scaleExtent:[.1,10],translateExtent:null,wheelDelta:null,touchable:!0,filter:null,constrain:{x:!0,y:!0},duration:250,ease:l.easeQuadOut};let t=null,n=l.zoomIdentity,a=null,r={width:800,height:400,margin:{top:60,right:80,bottom:60,left:80}};const o=l.dispatch("zoomstart","zoom","zoomend","reset");function i(){return t||(t=l.zoom().scaleExtent(e.scaleExtent).touchable(e.touchable).filter(e.filter||s).on("start",u).on("zoom",d).on("end",f),null!==e.wheelDelta&&t.wheelDelta(e.wheelDelta),c(),t)}function s(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function c(){if(!t||!r)return;const{width:n,height:a,margin:o}=r,i=n-o.left-o.right,l=a-o.top-o.bottom,s=e.translateExtent||[[2*-i,2*-l],[3*i,3*l]];t.translateExtent(s)}function u(e){const t={transform:e.transform,sourceEvent:e.sourceEvent};o.call("zoomstart",void 0,t)}function d(t){n=t.transform,e.constrain.x||(n=n.translate(-n.x,0)),e.constrain.y||(n=n.translate(0,-n.y)),a&&function(t,n){const a=t.select(".chart-group");a.empty()||a.attr("transform",n.toString());!function(t,n){if(e.constrain.x){const e=t.select(".x-axis");if(!e.empty()){const t=m(e);if(t){const a=n.rescaleX(t);e.call(l.axisBottom(a))}}}if(e.constrain.y){const e=t.select(".y-axis");if(!e.empty()){const t=m(e);if(t){const a=n.rescaleY(t);e.call(l.axisLeft(a))}}}}(t,n)}(a,n);const r={transform:n,sourceEvent:t.sourceEvent};o.call("zoom",void 0,r)}function f(e){const t={transform:e.transform,sourceEvent:e.sourceEvent};o.call("zoomend",void 0,t)}function m(e){try{const t=e.node();if(t&&t.__scale__)return t.__scale__}catch(e){}return null}function h(n,a,r=0){return t||i(),r>0?n.transition().duration(r).ease(e.ease).call(t.transform,a):n.call(t.transform,a),p}const p={enable:function(){return e.enabled=!0,t&&a&&a.call(t),p},disable:function(){return e.enabled=!1,a&&a.on(".zoom",null),p},attach:function(t){if(a=t,e.enabled){const e=i();t.call(e)}return p},detach:function(){return a&&(a.on(".zoom",null),a=null),p},transform:h,reset:function(t=e.duration){return a&&(h(a,l.zoomIdentity,t),o.call("reset",void 0,{transform:l.zoomIdentity,sourceEvent:null})),p},zoomTo:function(t,n=e.duration){if(!a||!r)return p;const{width:o,height:i,margin:s}=r,c=o-s.left-s.right,u=i-s.top-s.bottom,[d,f]=t.x,[m,g]=t.y,y=Math.min(c/(f-d),u/(g-m)),b=c/2-y*(d+f)/2,v=u/2-y*(m+g)/2,x=l.zoomIdentity.translate(b,v).scale(y);return h(a,x,n),p},setDimensions:function(e){return r=e,c(),p},configure:function(n){return Object.assign(e,n),t&&(n.scaleExtent&&t.scaleExtent(n.scaleExtent),void 0!==n.touchable&&t.touchable(n.touchable),void 0!==n.filter&&t.filter(n.filter||s),void 0!==n.wheelDelta&&n.wheelDelta&&t.wheelDelta(n.wheelDelta)),c(),p},getCurrentTransform:function(){return n},isEnabled:function(){return e.enabled},on:function(e,t){return o.on(e,t),p},off:function(e,t){return o.on(e,null),p}};return p}function p(){let e={renderTime:0,dataProcessingTime:0,memoryUsage:0,visibleElements:0,totalElements:0,fps:0,lastFrameTime:0,averageFrameTime:0,peakMemoryUsage:0,renderCalls:0},t={enabled:!1,chunkSize:1e3,renderThreshold:1e4,bufferSize:200,preloadCount:3,recycleNodes:!0},n={memoryPooling:!0},a={elements:new Map,maxSize:1e3,currentSize:0,hitCount:0,missCount:0},r=new Map,o=null,i=0,l=performance.now();function s(){if("memory"in performance){const t=performance.memory;e.memoryUsage=t.usedJSHeapSize,e.peakMemoryUsage=Math.max(e.peakMemoryUsage,t.usedJSHeapSize)}return{...e}}function c(){if(!o)return;const e=s(),n=(e.memoryUsage/1024/1024).toFixed(2),r=(e.peakMemoryUsage/1024/1024).toFixed(2);o.innerHTML=`\n <div><strong>MintWaterfall Performance</strong></div>\n <div>FPS: ${e.fps}</div>\n <div>Render Time: ${e.renderTime.toFixed(2)}ms</div>\n <div>Memory: ${n}MB (Peak: ${r}MB)</div>\n <div>Visible Elements: ${e.visibleElements}/${e.totalElements}</div>\n <div>Render Calls: ${e.renderCalls}</div>\n <div>Virtualization: ${t.enabled?"ON":"OFF"}</div>\n <div>Pool Hit Rate: ${a.hitCount+a.missCount>0?(a.hitCount/(a.hitCount+a.missCount)*100).toFixed(1):0}%</div>\n `}const u={enableVirtualization:function(e={}){return Object.assign(t,e),t.enabled=!0,console.log("MintWaterfall: Virtualization enabled with config:",t),u},disableVirtualization:function(){return t.enabled=!1,console.log("MintWaterfall: Virtualization disabled"),u},optimizeRendering:function(n,a){const r=performance.now();e.totalElements=a.length,t.enabled&&a.length>t.renderThreshold?function(n,a){const r=n.node();if(!r)return;const o=r.clientHeight,i=r.scrollTop||0,l=30,[s,c]=function(e,n,a){const r=Math.floor(e/a),o=r+Math.ceil(n/a);return[Math.max(0,r-t.bufferSize),o+t.bufferSize]}(i,o,l),u=a.slice(s,Math.min(c,a.length));u.map((e,t)=>t+s),e.visibleElements=u.length;const d=n.selectAll(".virtual-item").data(u,(e,t)=>`item-${t+s}`);d.exit().remove();const f=d.enter().append("g").attr("class","virtual-item");d.merge(f).attr("transform",(e,t)=>`translate(0, ${(t+s)*l})`)}(n,a):function(t,n){e.visibleElements=n.length;const a=t.selectAll(".chart-element").data(n);a.exit().remove();const r=a.enter().append("g").attr("class","chart-element");a.merge(r)}(n,a);const o=performance.now();return e.renderTime=o-r,e.renderCalls++,function(){i++;const t=performance.now();t-l>=1e3&&(e.fps=Math.round(1e3*i/(t-l)),e.averageFrameTime=(t-l)/i,i=0,l=t);e.lastFrameTime=t}(),u},profileOperation:function(e,t){const n=performance.now(),a=t(),o=performance.now()-n;r.has(e)||r.set(e,{startTime:0,endTime:0,samples:[],averageTime:0,minTime:1/0,maxTime:0});const i=r.get(e);return i.samples.push(o),i.minTime=Math.min(i.minTime,o),i.maxTime=Math.max(i.maxTime,o),i.averageTime=i.samples.reduce((e,t)=>e+t,0)/i.samples.length,i.samples.length>100&&i.samples.shift(),a},getMetrics:s,resetMetrics:function(){return e={renderTime:0,dataProcessingTime:0,memoryUsage:0,visibleElements:0,totalElements:0,fps:0,lastFrameTime:0,averageFrameTime:0,peakMemoryUsage:0,renderCalls:0},r.clear(),i=0,l=performance.now(),u},enableMemoryPooling:function(e={}){return Object.assign(a,e),n.memoryPooling=!0,console.log("MintWaterfall: Memory pooling enabled"),u},createRenderBatch:function(){return{operations:[],priority:1,timestamp:performance.now(),elementCount:0}},flushRenderBatch:function(t){const n=performance.now();t.operations.sort((e,t)=>{const n=["remove","create","update","style","attribute"];return n.indexOf(e.type)-n.indexOf(t.type)}),t.operations.forEach(e=>{!function(e){const{type:t,element:n,properties:a}=e;switch(t){case"create":case"update":break;case"remove":n&&n.remove&&n.remove();break;case"style":n&&a&&Object.keys(a).forEach(e=>{n.style(e,a[e])});break;case"attribute":n&&a&&Object.keys(a).forEach(e=>{n.attr(e,a[e])})}}(e)});const a=performance.now();return e.renderTime+=a-n,u},setUpdateStrategy:function(e){return console.log(`MintWaterfall: Update strategy set to ${e}`),u},getDashboard:function(){return o},enableDashboard:function(e){o||(o=function(){const e=document.createElement("div");return e.className="mintwaterfall-performance-dashboard",e.style.cssText="\n position: fixed;\n top: 10px;\n right: 10px;\n background: rgba(0, 0, 0, 0.8);\n color: white;\n padding: 10px;\n border-radius: 5px;\n font-family: monospace;\n font-size: 12px;\n z-index: 10000;\n max-width: 300px;\n ",e}());const t=e||document.body;return t&&!t.contains(o)&&t.appendChild(o),setInterval(c,500),u},disableDashboard:function(){return o&&o.parentNode&&(o.parentNode.removeChild(o),o=null),u},optimizeMemory:function(){return window.gc&&window.gc(),a.elements.forEach((e,t)=>{e.length>50&&e.splice(25)}),r.forEach(e=>{e.samples.length>50&&e.samples.splice(0,e.samples.length-50)}),console.log("MintWaterfall: Memory optimization completed"),u},getRecommendations:function(){const e=[],r=s();return r.totalElements>5e3&&!t.enabled&&e.push("Enable virtualization for improved performance with large datasets"),r.fps<30&&e.push("Consider reducing visual complexity or enabling performance optimizations"),r.memoryUsage>104857600&&e.push("Memory usage is high - consider enabling memory pooling or reducing data size"),r.renderTime>100&&e.push("Render time is slow - consider batching updates or optimizing render operations"),a.hitCount/(a.hitCount+a.missCount||1)<.5&&n.memoryPooling&&e.push("Memory pool efficiency is low - consider adjusting pool size or strategy"),e}};return u}"undefined"!=typeof document&&f.injectForcedColorsCSS();const g={default:{name:"Default",background:"#ffffff",gridColor:"#e0e0e0",axisColor:"#666666",textColor:"#333333",totalColor:"#95A5A6",colors:["#3498db","#2ecc71","#e74c3c","#f39c12","#9b59b6","#1abc9c","#e67e22","#f1c40f"],sequentialScale:{type:"sequential",interpolator:l.interpolateBlues},divergingScale:{type:"diverging",interpolator:l.interpolateRdYlBu},conditionalFormatting:{positive:"#2ecc71",negative:"#e74c3c",neutral:"#95a5a6"}},dark:{name:"Dark",background:"#2c3e50",gridColor:"#34495e",axisColor:"#bdc3c7",textColor:"#ecf0f1",totalColor:"#95a5a6",colors:["#3498db","#2ecc71","#e74c3c","#f39c12","#9b59b6","#1abc9c","#e67e22","#f1c40f"],sequentialScale:{type:"sequential",interpolator:l.interpolateViridis},divergingScale:{type:"diverging",interpolator:l.interpolatePiYG},conditionalFormatting:{positive:"#2ecc71",negative:"#e74c3c",neutral:"#95a5a6"}},corporate:{name:"Corporate",background:"#ffffff",gridColor:"#e8e8e8",axisColor:"#555555",textColor:"#333333",totalColor:"#7f8c8d",colors:["#2c3e50","#34495e","#7f8c8d","#95a5a6","#bdc3c7","#ecf0f1"],sequentialScale:{type:"sequential",interpolator:l.interpolateGreys},divergingScale:{type:"diverging",interpolator:l.interpolateRdBu},conditionalFormatting:{positive:"#27ae60",negative:"#c0392b",neutral:"#7f8c8d"}},accessible:{name:"Accessible",background:"#ffffff",gridColor:"#cccccc",axisColor:"#000000",textColor:"#000000",totalColor:"#666666",colors:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f"],sequentialScale:{type:"sequential",interpolator:e=>l.interpolateHsl("#ffffff","#000000")(e)},divergingScale:{type:"diverging",interpolator:l.interpolateRdBu},conditionalFormatting:{positive:"#1f77b4",negative:"#d62728",neutral:"#666666"}},colorful:{name:"Colorful",background:"#ffffff",gridColor:"#f0f0f0",axisColor:"#666666",textColor:"#333333",totalColor:"#34495e",colors:["#ff6b6b","#4ecdc4","#45b7d1","#f9ca24","#f0932b","#eb4d4b","#6c5ce7","#a29bfe"],sequentialScale:{type:"sequential",interpolator:l.interpolateRainbow},divergingScale:{type:"diverging",interpolator:l.interpolateSpectral},conditionalFormatting:{positive:"#4ecdc4",negative:"#ff6b6b",neutral:"#f9ca24"}}};function y(e,t="default"){const n=g[t]||g.default,a=n.sequentialScale?.interpolator||l.interpolateBlues;return l.scaleSequential(a).domain(e)}function b(e,t="default"){const n=g[t]||g.default,a=n.divergingScale?.interpolator||l.interpolateRdYlBu;return l.scaleDiverging(a).domain(e)}function v(e,t="default",n=0){const a=(g[t]||g.default).conditionalFormatting||{positive:"#2ecc71",negative:"#e74c3c",neutral:"#95a5a6"};return Math.abs(e)<=Math.abs(n)?a.neutral:e>n?a.positive:a.negative}function x(e,t,n="default"){const a=g[n]||g.default,r=a.sequentialScale?.interpolator||l.interpolateBlues,o=(e-t[0])/(t[1]-t[0]);return r(Math.max(0,Math.min(1,o)))}function w(e,t,n=[],a="default",r="conditional"){switch(r){case"conditional":return v(e,a);case"sequential":if(n.length>0){const t=n.map(e=>e.barTotal||e.value||0);return x(e,l.extent(t),a)}return t;case"diverging":if(n.length>0){const t=n.map(e=>e.barTotal||e.value||0),r=Math.max(...t.map(Math.abs));return b([-r,0,r],a)(e)}return v(e,a);default:return t}}const k={financial:{name:"Financial",background:"#ffffff",gridColor:"#f5f5f5",axisColor:"#333333",textColor:"#333333",totalColor:"#2c3e50",colors:["#27ae60","#e74c3c","#3498db","#f39c12","#9b59b6"],sequentialScale:{type:"sequential",interpolator:l.interpolateRdYlGn},divergingScale:{type:"diverging",interpolator:l.interpolateRdYlGn},conditionalFormatting:{positive:"#27ae60",negative:"#e74c3c",neutral:"#95a5a6"}},professional:{name:"Professional",background:"#ffffff",gridColor:"#e8e8e8",axisColor:"#444444",textColor:"#333333",totalColor:"#2c3e50",colors:["#1f4e79","#2e75b6","#70ad47","#ffc000","#c55a11"],sequentialScale:{type:"sequential",interpolator:e=>l.interpolateHsl("#f0f8ff","#1f4e79")(e)},divergingScale:{type:"diverging",interpolator:l.interpolateRdYlBu},conditionalFormatting:{positive:"#70ad47",negative:"#c55a11",neutral:"#7f8c8d"}},heatmap:{name:"Heat Map",background:"#ffffff",gridColor:"#f0f0f0",axisColor:"#333333",textColor:"#333333",totalColor:"#2c3e50",colors:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],sequentialScale:{type:"sequential",interpolator:l.interpolateYlOrRd},divergingScale:{type:"diverging",interpolator:l.interpolateRdYlBu},conditionalFormatting:{positive:"#2ca02c",negative:"#d62728",neutral:"#ff7f0e"}}};function M(){const e={linear:l.curveLinear,basis:l.curveBasis,cardinal:l.curveCardinal,catmullRom:l.curveCatmullRom,monotoneX:l.curveMonotoneX,monotoneY:l.curveMonotoneY,natural:l.curveNatural,step:l.curveStep,stepBefore:l.curveStepBefore,stepAfter:l.curveStepAfter,bumpX:l.curveBumpX,bumpY:l.curveBumpY},t={circle:l.symbolCircle,square:l.symbolSquare,triangle:l.symbolTriangle,diamond:l.symbolDiamond,star:l.symbolStar,cross:l.symbolCross,wye:l.symbolWye};function n(e,t={}){const{curve:n=l.curveMonotoneX,strokeColor:a="#e74c3c",strokeWidth:r=2,opacity:o=.8}=t;return l.line().x(e=>e.x).y(e=>e.y).curve(n)(e)||""}return{createConfidenceBand:function(e,t={}){const{curve:n=l.curveMonotoneX,opacity:a=.3,fillColor:r="#95a5a6"}=t;return l.area().x(e=>e.x).y0(e=>e.yLower).y1(e=>e.yUpper).curve(n)(e)||""},createEnvelopeArea:function(e,t={}){const{curve:n=l.curveMonotoneX}=t;return l.area().x(e=>e.x).y0(e=>e.y0).y1(e=>e.y1).curve(n)(e)||""},createDataPointMarkers:function(e,n={}){const{size:a=64,fillColor:r="#3498db",strokeColor:o="#ffffff",strokeWidth:i=2}=n;return e.map(e=>{const s=t[e.type]||l.symbolCircle,c=e.size||a;return{path:l.symbol().type(s).size(c)()||"",transform:`translate(${e.x}, ${e.y})`,config:{...n,fillColor:e.color||r,strokeColor:o,strokeWidth:i}}})},createCustomSymbol:function(e,n=64){const a=t[e]||l.symbolCircle;return l.symbol().type(a).size(n)()||""},createSmoothTrendLine:n,createMultipleTrendLines:function(e){return e.map(e=>n(e.data,e.config))},getCurveTypes:function(){return{...e}},getSymbolTypes:function(){return{...t}}}}function A(e,t,n,a){const r=M();let o=0,i=0,s=0;const c=e.map((e,r)=>{o+=e.value,i+=t.optimistic[r]?.value||e.value,s+=t.pessimistic[r]?.value||e.value;return{x:(n(e.label)||0)+n.bandwidth()/2,y:a(o),yUpper:a(i),yLower:a(s),label:e.label}}),u=c.map(e=>({x:e.x,y:e.yUpper})),d=c.map(e=>({x:e.x,y:e.yLower}));return{confidencePath:r.createConfidenceBand(c,{fillColor:"rgba(52, 152, 219, 0.2)",curve:l.curveMonotoneX}),optimisticPath:r.createSmoothTrendLine(u,{strokeColor:"#27ae60",strokeWidth:2,strokeDasharray:"5,5",curve:l.curveMonotoneX}),pessimisticPath:r.createSmoothTrendLine(d,{strokeColor:"#e74c3c",strokeWidth:2,strokeDasharray:"5,5",curve:l.curveMonotoneX})}}function S(e,t,n){const a=M(),r=e.map(e=>{const a={target:{type:"star",color:"#f39c12",size:100},threshold:{type:"diamond",color:"#9b59b6",size:80},alert:{type:"triangle",color:"#e74c3c",size:90},achievement:{type:"circle",color:"#27ae60",size:85}},r=a[e.type]||a.target;return{x:(t(e.label)||0)+t.bandwidth()/2,y:n(e.value),type:r.type,size:r.size,color:r.color,label:e.description||e.label}});return a.createDataPointMarkers(r,{strokeColor:"#ffffff",strokeWidth:2})}function C(e,t,n){if(e.bandwidth){return e.bandwidth()}return n*(1-.1)/t}function T(e,t,n){return e.bandwidth?e(t):e(t)-n/2}function $(){let e=800,t=400,n={top:60,right:80,bottom:60,left:80},a=!1,r="Total",o="#95A5A6",i=!1,c=.05,d=750,f=l.easeQuadInOut,g=l.format(".0f"),y=null,b=!1,v={},x=!1,k=100,M="auto",$={enabled:!1,scaleType:"auto",themeName:"default",neutralThreshold:0},E="conditional",z={enabled:!1,opacity:.3,showTrendLines:!0},D={enabled:!1,milestones:[]},R=!1,F="#e74c3c",O=2,P="solid",B=.8,I="linear",q=3,W=2,L=!0,N=!1,j={},U=!0,V={},H=!1,Y={},G=null,Q=new Map,X=null,_=null;const K=s();u();const J=m();h();const Z=p();let ee=!1,te=!1,ne=1e4;const ae=l.dispatch("barClick","barMouseover","barMouseout","chartUpdate","brushSelection");function re(r){r.each(function(r){if(!r||!Array.isArray(r))return void console.warn("MintWaterfall: Invalid data provided. Expected an array.");if(0===r.length)return void console.warn("MintWaterfall: Empty data array provided.");if(!r.every(e=>e&&"string"==typeof e.label&&Array.isArray(e.stacks)&&e.stacks.every(e=>"number"==typeof e.value&&"string"==typeof e.color)))return void console.error("MintWaterfall: Invalid data structure. Each item must have a 'label' string and 'stacks' array with 'value' numbers and 'color' strings.");const o=l.select(this);let s;if("svg"===this.tagName)s=o;else{s=o.selectAll("svg").data([0]);const n=s.enter().append("svg");s=n.merge(s),s.attr("width",e).attr("height",t)}const u=s.node();if(u){const n=u.getAttribute("width"),a=u.getAttribute("height");n&&(e=parseInt(n,10)),a&&(t=parseInt(a,10))}const m=s.selectAll(".waterfall-container").data([r]),p=s,y=m.enter().append("g").attr("class","waterfall-container").merge(m);let b=y.select(".chart-group");b.empty()&&(b=y.append("g").attr("class","chart-group"));const v=`chart-clip-${Date.now()}`;s.select(`#${v}`).remove();const U=s.append("defs").append("clipPath").attr("id",v).append("rect");b.attr("clip-path",`url(#${v})`);try{r.length>=ne&&ee&&Z.enableVirtualization({chunkSize:Math.min(1e3,Math.floor(r.length/10)),renderThreshold:ne});const o=JSON.stringify(r).slice(0,100)+`_showTotal:${a}`;let u;o===X&&_?u=_:(r.length>5e4?(console.warn("MintWaterfall: Large dataset detected, using synchronous processing"),u=oe(r)):u=oe(r),X=o,_=u);const m=function(e,n){const a=e.flatMap(e=>[e.cumulativeTotal,e.prevCumulativeTotal||0]),r=l.max(a)||0,o=l.min(a)||0,i=16,s=8,c=i+s,u=20,d=o<0,f=Math.max(n.top,80);let m;const h=[t-n.bottom,f];if(d){const e=.05*(r-o);m=l.scaleLinear().domain([o-e,r+e]).range(h)}else{const e=1.02*r;m=l.scaleLinear().domain([0,e]).range(h).nice()}const p=e.map(e=>m(e.cumulativeTotal)-s),y=Math.min(...p),b=Math.max(f-y+c,c+u),v=Math.max(0,b-f);let x=0;if(d){const a=e.filter(e=>e.cumulativeTotal<0);if(a.length>0){const e=Math.max(...a.map(e=>m(e.cumulativeTotal)+i+s));e>t-n.bottom&&(x=e-(t-n.bottom))}}const w=Math.max(...e.map(e=>g(e.cumulativeTotal).length)),k=9*w,M=Math.max(n.right,k/2+15),A={top:f+v+u,right:M,bottom:n.bottom+x+(d?u:10),left:n.left};return A}(u,n);let v;if("auto"===M)v=K.createAdaptiveScale(u,"x"),v.padding&&v.padding(c);else if("time"===M){const e=u.map(e=>new Date(e.label));v=K.createTimeScale(e)}else v="ordinal"===M?K.createOrdinalScale(u.map(e=>e.label)):l.scaleBand().domain(u.map(e=>e.label)).padding(c);v.range([m.left,e-m.right]),K.setDefaultRange([m.left,e-m.right]);const V=30;U.attr("x",m.left).attr("y",Math.max(0,m.top-V)).attr("width",e-m.left-m.right).attr("height",t-m.top-m.bottom+V);const Y=u.map(e=>e.cumulativeTotal),[G,Q]=l.extent(Y);let te;if(G<0){const e=.05*(Q-G);te=l.scaleLinear().domain([G-e,Q+e]).range([t-m.bottom,m.top])}else te=K.createLinearScale(Y,{range:[t-m.bottom,m.top],nice:!0});!function(t,n,a){const r=t.selectAll(".grid-group").data([0]),o=r.enter().append("g").attr("class","grid-group").merge(r),i=n.ticks(),l=o.selectAll(".grid-line").data(i),s=l.enter().append("line").attr("class","grid-line").attr("x1",a.left).attr("x2",e-a.right).attr("stroke","rgba(224, 224, 224, 0.5)").attr("stroke-width",1).style("opacity",0);s.merge(l).transition().duration(d).ease(f).attr("y1",e=>n(e)).attr("y2",e=>n(e)).attr("x1",a.left).attr("x2",e-a.right).style("opacity",1),l.exit().transition().duration(d).ease(f).style("opacity",0).remove()}(y,te,m),function(e,n,a,r){const o=e.selectAll(".y-axis").data([0]),i=o.enter().append("g").attr("class","y-axis").attr("transform",`translate(${r.left},0)`);i.merge(o).transition().duration(d).ease(f).call(l.axisLeft(a).tickFormat(e=>g(e)));const s=e.selectAll(".x-axis").data([0]),c=s.enter().append("g").attr("class","x-axis").attr("transform",`translate(0,${t-r.bottom})`);c.merge(s).transition().duration(d).ease(f).call(l.axisBottom(n))}(y,v,te,m),function(t,n,a,r,o){const s=t.selectAll(".bars-group").data([0]),c=s.enter().append("g").attr("class","bars-group"),u=c.merge(s).selectAll(".bar-group").data(n,e=>e.label),m=u.enter().append("g").attr("class","bar-group").attr("transform",t=>{if(a.bandwidth)return`translate(${a(t.label)}, 0)`;{const r=C(a,n.length,e-o.left-o.right);return`translate(${T(a,t.label,r)}, 0)`}}),h=m.merge(u).transition().duration(d).ease(f).attr("transform",t=>{if(a.bandwidth)return`translate(${a(t.label)}, 0)`;{const r=C(a,n.length,e-o.left-o.right);return`translate(${T(a,t.label,r)}, 0)`}});i?function(t,n,a,r){t.each(function(o){const i=l.select(this),s=o.stacks.map((e,t)=>({...e,stackIndex:t,parent:o}));let c=o.prevCumulativeTotal||0;s.forEach(e=>{e.startY=c,e.endY=c+e.value,e.y=a(Math.max(e.startY,e.endY)),e.height=Math.abs(a(e.startY)-a(e.endY)),c+=e.value});const u=i.selectAll(".stack").data(s),m=n.bandwidth?n.bandwidth():C(n,t.size(),e-r.left-r.right);u.enter().append("rect").attr("class","stack").attr("x",0).attr("width",m).attr("y",a(0)).attr("height",0).attr("fill",e=>e.color).merge(u).transition().duration(d).ease(f).attr("y",e=>e.y).attr("height",e=>e.height).attr("fill",e=>e.color).attr("width",m),u.exit().transition().duration(d).ease(f).attr("height",0).attr("y",a(0)).remove();const h=i.selectAll(".stack-label").data(s.filter(e=>e.label));h.enter().append("text").attr("class","stack-label").attr("text-anchor","middle").attr("x",m/2).attr("y",a(0)).style("opacity",0).merge(h).transition().duration(d).ease(f).attr("y",e=>e.y+e.height/2+4).attr("x",m/2).style("opacity",1).text(e=>e.label),h.exit().transition().duration(d).ease(f).style("opacity",0).remove()})}(h,a,r,o):function(t,n,a,r,o=[]){t.each(function(i){const s=l.select(this),c=n.bandwidth?n.bandwidth():C(n,t.size(),e-r.left-r.right),u=1===i.stacks.length?i.stacks[0].color:"#3498db",m=$.enabled?w(i.barTotal,u,o,$.themeName||"default",E):u,h=[{value:i.barTotal,color:m,y:i.isTotal?Math.min(a(0),a(i.cumulativeTotal)):a(Math.max(i.prevCumulativeTotal,i.cumulativeTotal)),height:i.isTotal?Math.abs(a(0)-a(i.cumulativeTotal)):Math.abs(a(i.prevCumulativeTotal||0)-a(i.cumulativeTotal)),parent:i}],p=s.selectAll(".waterfall-bar").data(h);p.enter().append("rect").attr("class","waterfall-bar").attr("x",0).attr("width",c).attr("y",a(0)).attr("height",0).attr("fill",e=>e.color).merge(p).transition().duration(d).ease(f).attr("y",e=>e.y).attr("height",e=>e.height).attr("fill",e=>e.color).attr("width",c),p.exit().transition().duration(d).ease(f).attr("height",0).attr("y",a(0)).remove()})}(h,a,r,o,n);(function(t,n,a,r){t.each(function(o){const i=l.select(this),s=C(n,t.size(),e-r.left-r.right),c=[{value:o.barTotal,formattedValue:g(o.barTotal),parent:o}],u=i.selectAll(".total-label").data(c);u.enter().append("text").attr("class","total-label").attr("text-anchor","middle").attr("x",s/2).attr("y",a(0)).style("opacity",0).style("font-family","Arial, sans-serif").merge(u).transition().duration(d).ease(f).attr("y",e=>a(e.parent.cumulativeTotal)-8).attr("x",s/2).style("opacity",1).style("fill","#333").style("font-weight","bold").style("font-size","14px").style("pointer-events","none").style("visibility","visible").style("display","block").attr("clip-path","none").text(e=>e.formattedValue).each(function(e){}),u.exit().transition().duration(d).ease(f).style("opacity",0).remove()})})(h,a,r,o),u.exit().transition().duration(d).ease(f).style("opacity",0).remove()}(b,u,v,te,m),function(t,a,r,o){if(i||a.length<2)return;const l=t.selectAll(".connectors-group").data([0]),s=l.enter().append("g").attr("class","connectors-group").merge(l),c=[];for(let t=0;t<a.length-1;t++){const i=a[t],l=a[t+1],s=C(r,a.length,e-n.left-n.right),u=T(r,i.label,s),d=T(r,l.label,s);c.push({x1:u+s,x2:d,y:o(i.cumulativeTotal),id:`${i.label}-${l.label}`})}const u=s.selectAll(".connector").data(c,e=>e.id);u.enter().append("line").attr("class","connector").attr("stroke","#bdc3c7").attr("stroke-width",1).attr("stroke-dasharray","3,3").style("opacity",0).attr("x1",e=>e.x1).attr("x2",e=>e.x1).attr("y1",e=>e.y).attr("y2",e=>e.y).merge(u).transition().duration(d).ease(f).delay((e,t)=>x?t*k:0).attr("x1",e=>e.x1).attr("x2",e=>e.x2).attr("y1",e=>e.y).attr("y2",e=>e.y).style("opacity",.6),u.exit().transition().duration(d).ease(f).style("opacity",0).remove()}(b,u,v,te),function(t,a,r,o){if(!R||a.length<2)return void t.selectAll(".trend-group").remove();const i=t.selectAll(".trend-group").data([0]),s=i.enter().append("g").attr("class","trend-group").merge(i),c=[],u=[];for(let t=0;t<a.length;t++){const i=a[t],l=C(r,a.length,e-n.left-n.right),s=T(r,i.label,l)+l/2,c=o(i.cumulativeTotal);u.push({x:s,y:c,value:i.cumulativeTotal})}if("linear"===I){const e=u.length,t=u.reduce((e,t,n)=>e+n,0),n=u.reduce((e,t)=>e+t.value,0),a=(e*u.reduce((e,t,n)=>e+n*t.value,0)-t*n)/(e*u.reduce((e,t,n)=>e+n*n,0)-t*t),r=(n-a*t)/e;u.forEach((e,t)=>{const n=a*t+r;c.push({x:e.x,y:o(n)})})}else if("moving-average"===I){const e=q;for(let t=0;t<u.length;t++){const n=Math.max(0,t-Math.floor(e/2)),a=Math.min(u.length,n+e),r=u.slice(n,a),i=r.reduce((e,t)=>e+t.value,0)/r.length;c.push({x:u[t].x,y:o(i)})}}else if("polynomial"===I){const e=u.length;if(e>=3){const t=W/10;for(let n=0;n<e;n++){const a=u[n];let r=a.value;if(e>2){const o=n/(e-1),i=Math.sin(o*Math.PI)*t,l=u.reduce((e,t)=>e+t.value,0)/e;r=a.value+(a.value-l)*i*.5}c.push({x:a.x,y:o(r)})}}else u.forEach(e=>{c.push({x:e.x,y:e.y})})}else u.forEach(e=>{c.push({x:e.x,y:e.y})});const m=l.line().x(e=>e.x).y(e=>e.y).curve("polynomial"===I?l.curveCardinal:"moving-average"===I?l.curveMonotoneX:l.curveLinear),h=s.selectAll(".trend-line").data([c]),p=h.enter().append("path").attr("class","trend-line").attr("fill","none").attr("stroke",F).attr("stroke-width",O).attr("stroke-opacity",B).style("opacity",0);function g(e){"dashed"===P?e.attr("stroke-dasharray","5,5"):"dotted"===P?e.attr("stroke-dasharray","2,3"):e.attr("stroke-dasharray",null)}g(p);const y=p.merge(h);g(y),y.transition().duration(d).ease(f).attr("d",m).attr("stroke",F).attr("stroke-width",O).attr("stroke-opacity",B).style("opacity",1),h.exit().transition().duration(d).ease(f).style("opacity",0).remove()}(b,u,v,te),function(e,t,n,a){if(!z.enabled||!z.scenarios)return;const r=e.selectAll(".confidence-bands-group").data([0]),o=r.enter().append("g").attr("class","confidence-bands-group").merge(r),i=A(t.map(e=>({label:e.label,value:e.barTotal})),z.scenarios,n,a),l=o.selectAll(".confidence-band").data([i.confidencePath]);if(l.enter().append("path").attr("class","confidence-band").attr("fill",`rgba(52, 152, 219, ${z.opacity||.3})`).attr("stroke","none").style("opacity",0).merge(l).transition().duration(d).ease(f).attr("d",i.confidencePath).style("opacity",1),z.showTrendLines){const e=o.selectAll(".optimistic-trend").data([i.optimisticPath]);e.enter().append("path").attr("class","optimistic-trend").attr("fill","none").attr("stroke","#27ae60").attr("stroke-width",2).attr("stroke-dasharray","5,5").style("opacity",0).merge(e).transition().duration(d).ease(f).attr("d",i.optimisticPath).style("opacity",.8);const t=o.selectAll(".pessimistic-trend").data([i.pessimisticPath]);t.enter().append("path").attr("class","pessimistic-trend").attr("fill","none").attr("stroke","#e74c3c").attr("stroke-width",2).attr("stroke-dasharray","5,5").style("opacity",0).merge(t).transition().duration(d).ease(f).attr("d",i.pessimisticPath).style("opacity",.8)}l.exit().transition().duration(d).style("opacity",0).remove()}(b,u,v,te),function(e,t,n,a){if(!D.enabled||0===D.milestones.length)return;const r=e.selectAll(".milestones-group").data([0]),o=r.enter().append("g").attr("class","milestones-group").merge(r),i=S(D.milestones,n,a),l=o.selectAll(".milestone-marker").data(i);l.enter().append("path").attr("class","milestone-marker").attr("transform",e=>e.transform).attr("d",e=>e.path).attr("fill",e=>e.config.fillColor||"#f39c12").attr("stroke",e=>e.config.strokeColor||"#ffffff").attr("stroke-width",e=>e.config.strokeWidth||2).style("opacity",0).merge(l).transition().duration(d).ease(f).attr("transform",e=>e.transform).attr("d",e=>e.path).attr("fill",e=>e.config.fillColor||"#f39c12").style("opacity",1),l.exit().transition().duration(d).style("opacity",0).remove()}(b,0,v,te),setTimeout(()=>{L&&function(e,t){if(!L)return;e.attr("role","img").attr("aria-label",`Waterfall chart with ${t.length} data points`);const n=e.selectAll("title").data([0]);n.enter().append("title").merge(n).text(`Waterfall chart showing ${i?"stacked":"sequential"} data visualization`);const a=e.selectAll("desc").data([0]);function r(e,t){e.classed("focused",!1);const n=l.select(e.nodes()[t]);n.classed("focused",!0);const a=n.datum();o(`${a.parent?.label||a.label}: ${g(a.value||a.barTotal)}`)}function o(e){const t=l.select("body").selectAll(".sr-announcement").data([0]);t.enter().append("div").attr("class","sr-announcement").attr("aria-live","polite").attr("aria-atomic","true").style("position","absolute").style("left","-10000px").style("width","1px").style("height","1px").style("overflow","hidden").merge(t).text(e)}a.enter().append("desc").merge(a).text(()=>{const e=t[t.length-1]?.cumulativeTotal||0;return`Chart contains ${t.length} data points. Final cumulative value: ${g(e)}. Data ranges from ${t[0]?.label} to ${t[t.length-1]?.label}.`}),e.attr("tabindex","0").on("keydown",function(t){const n=e.select(".focused"),a=e.selectAll(".waterfall-bar, .stack"),o=a.nodes().indexOf(n.node());switch(t.key){case"ArrowRight":case"ArrowDown":t.preventDefault();const e=Math.min(o+1,a.size()-1);r(a,e);break;case"ArrowLeft":case"ArrowUp":t.preventDefault();r(a,Math.max(o-1,0));break;case"Home":t.preventDefault(),r(a,0);break;case"End":t.preventDefault(),r(a,a.size()-1)}});const s=e.selectAll("style.accessibility-styles").data([0]);s.enter().append("style").attr("class","accessibility-styles").merge(s).text("\n .focused {\n stroke: #0066cc !important;\n stroke-width: 3px !important;\n filter: brightness(1.1);\n }\n .waterfall-bar:focus,\n .stack:focus {\n outline: 2px solid #0066cc;\n outline-offset: 2px;\n }\n ")}(s,u),N&&function(e){if(!N)return;const t=J;t.configure(j),e.selectAll(".waterfall-bar, .stack").on("mouseover",function(e,n){const a=l.select(this),r=n.parent||n,o=`\n <div style="font-weight: bold; margin-bottom: 8px;">${r.label}</div>\n <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">\n <span>Value:</span>\n <span style="font-weight: bold;">${g(n.value||r.barTotal)}</span>\n </div>\n ${void 0!==r.cumulativeTotal?`\n <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">\n <span>Cumulative:</span>\n <span style="font-weight: bold;">${g(r.cumulativeTotal)}</span>\n </div>\n `:""}\n ${n.label&&n.label!==r.label?`\n <div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.3);">\n <div style="font-size: 11px; opacity: 0.8;">${n.label}</div>\n </div>\n `:""}\n `;t.show(o,e,{label:r.label,value:n.value||r.barTotal,cumulative:r.cumulativeTotal,color:n.color||(r.stacks&&r.stacks[0]?r.stacks[0].color:"#3498db"),x:parseFloat(a.attr("x")||"0"),y:parseFloat(a.attr("y")||"0"),quadrant:1}),a.style("opacity",.8)}).on("mousemove",function(e){t.move(e)}).on("mouseout",function(){t.hide(),l.select(this).style("opacity",null)}),e.selectAll(".total-label").on("mouseover",function(e,n){const a=n.parent,r=`\n <div style="font-weight: bold; margin-bottom: 8px;">${a.label}</div>\n <div style="display: flex; justify-content: space-between;">\n <span>Total Value:</span>\n <span style="font-weight: bold;">${g(a.barTotal)}</span>\n </div>\n `;t.show(r,e,{label:a.label,value:a.barTotal,cumulative:a.cumulativeTotal,color:"#333",x:0,y:0,quadrant:1})}).on("mousemove",function(e){t.move(e)}).on("mouseout",function(){t.hide()})}(s),H?(re.zoomSystemInstance||(re.zoomSystemInstance=h()),re.zoomSystemInstance.attach(p),re.zoomSystemInstance.setDimensions({width:e,height:t,margin:m}),re.zoomSystemInstance.enable()):re.zoomSystemInstance&&(re.zoomSystemInstance.disable(),re.zoomSystemInstance.detach())},50)}catch(n){console.error("MintWaterfall rendering error:",n),console.error("Stack trace:",n.stack),y.selectAll("*").remove(),y.append("text").attr("x",e/2).attr("y",t/2).attr("text-anchor","middle").style("font-size","14px").style("fill","#ff6b6b").text(`Chart Error: ${n.message}`)}})}function oe(e){let t=[...e];G&&G.enabled&&(t=function(e){return e}(t));let n=0,i=0;const l=t.map((e,t)=>{const a=e.stacks.reduce((e,t)=>e+t.value,0);i=n,n+=a;let r=e.stacks;Q.size>0&&(r=e.stacks);return{...e,stacks:r,barTotal:a,cumulativeTotal:n,prevCumulativeTotal:0===t?0:i}});if(a&&l.length>0){const e=n;l.push({label:r,stacks:[{value:e,color:o}],barTotal:e,cumulativeTotal:e,prevCumulativeTotal:0})}return l}return re.width=function(t){return arguments.length?(e=t,re):e},re.height=function(e){return arguments.length?(t=e,re):t},re.margin=function(e){return arguments.length?(n=e,re):n},re.stacked=function(e){return arguments.length?(i=e,re):i},re.showTotal=function(e){return arguments.length?(a=e,re):a},re.totalLabel=function(e){return arguments.length?(r=e,re):r},re.totalColor=function(e){return arguments.length?(o=e,re):o},re.barPadding=function(e){return arguments.length?(c=e,re):c},re.duration=function(e){return arguments.length?(d=e,re):d},re.ease=function(e){return arguments.length?(f=e,re):f},re.formatNumber=function(e){return arguments.length?(g=e,re):g},re.theme=function(e){return arguments.length?(y=e,re):y},re.enableBrush=function(e){return arguments.length?(b=e,re):b},re.brushOptions=function(e){return arguments.length?(v={...v,...e},re):v},re.staggeredAnimations=function(e){return arguments.length?(x=e,re):x},re.staggerDelay=function(e){return arguments.length?(k=e,re):k},re.scaleType=function(e){return arguments.length?(M=e,re):M},re.showTrendLine=function(e){return arguments.length?(R=e,re):R},re.trendLineColor=function(e){return arguments.length?(F=e,re):F},re.trendLineWidth=function(e){return arguments.length?(O=e,re):O},re.trendLineStyle=function(e){return arguments.length?(P=e,re):P},re.trendLineOpacity=function(e){return arguments.length?(B=e,re):B},re.trendLineType=function(e){return arguments.length?(I=e,re):I},re.trendLineWindow=function(e){return arguments.length?(q=e,re):q},re.trendLineDegree=function(e){return arguments.length?(W=e,re):W},re.enableAccessibility=function(e){return arguments.length?(L=e,re):L},re.enableTooltips=function(e){return arguments.length?(N=e,re):N},re.tooltipConfig=function(e){return arguments.length?(j={...j,...e},re):j},re.enableExport=function(e){return arguments.length?(U=e,re):U},re.exportConfig=function(e){return arguments.length?(V={...V,...e},re):V},re.enableZoom=function(e){return arguments.length?(H=e,re):H},re.zoomConfig=function(e){return arguments.length?(Y={...Y,...e},re):Y},re.breakdownConfig=function(e){return arguments.length?(G=e,re):G},re.enablePerformanceOptimization=function(e){return arguments.length?(ee=e,re):ee},re.performanceDashboard=function(e){return arguments.length?(te=e,re):te},re.virtualizationThreshold=function(e){return arguments.length?(ne=e,re):ne},re.data=function(e){return re},re.advancedColors=function(e){return arguments.length?($={...$,...e},re):$},re.enableAdvancedColors=function(e){return arguments.length?($.enabled=e,re):$.enabled},re.colorScaleType=function(e){return arguments.length?($.scaleType=e,re):$.scaleType},re.colorMode=function(e){return arguments.length?(E=e,re):E},re.colorTheme=function(e){return arguments.length?($.themeName=e,re):$.themeName||"default"},re.neutralThreshold=function(e){return arguments.length?($.neutralThreshold=e,re):$.neutralThreshold||0},re.confidenceBands=function(e){return arguments.length?(z={...z,...e},re):z},re.enableConfidenceBands=function(e){return arguments.length?(z.enabled=e,re):z.enabled},re.milestones=function(e){return arguments.length?(D={...D,...e},re):D},re.enableMilestones=function(e){return arguments.length?(D.enabled=e,re):D.enabled},re.addMilestone=function(e){return D.milestones.push(e),re},re.on=function(){const e=ae.on.apply(ae,Array.from(arguments));return e===ae?re:e},re}function E(e,t={}){const{valueColumn:n="value",labelColumn:a="label",colorColumn:r="color",defaultColor:o="#3498db",parseNumbers:i=!0}=t;if(!Array.isArray(e))throw new Error("Data must be an array");return e.map((e,t)=>{if(e.label&&Array.isArray(e.stacks))return e;const l=e[a]||`Item ${t+1}`;let s=e[n];i&&"string"==typeof s?s=parseFloat(s.replace(/[,$]/g,""))||0:"number"!=typeof s&&(s=0);const c=e[r]||o;return{label:String(l),stacks:[{value:s,color:c,label:e.stackLabel||`${s>=0?"+":""}${s}`}]}})}function z(){function e(e){if(!e||!Array.isArray(e))throw new Error("Data must be an array");if(0===e.length)throw new Error("Data array cannot be empty");return e.every((e,t)=>{if(!e||"object"!=typeof e)throw new Error(`Item at index ${t} must be an object`);if("string"!=typeof e.label)throw new Error(`Item at index ${t} must have a string 'label' property`);if(!Array.isArray(e.stacks))throw new Error(`Item at index ${t} must have an array 'stacks' property`);if(0===e.stacks.length)throw new Error(`Item at index ${t} must have at least one stack`);return e.stacks.forEach((e,n)=>{if("number"!=typeof e.value||isNaN(e.value))throw new Error(`Stack ${n} in item ${t} must have a numeric 'value'`);if("string"!=typeof e.color)throw new Error(`Stack ${n} in item ${t} must have a string 'color'`)}),!0})}return{validateData:e,loadData:async function(e,t={}){return await async function(e,t={}){try{let n;if("string"==typeof e)if(e.endsWith(".csv"))n=await l.csv(e);else if(e.endsWith(".json"))n=await l.json(e);else if(e.endsWith(".tsv"))n=await l.tsv(e);else{if(!e.startsWith("http"))throw new Error(`Unsupported file format: ${e}`);{const t=await fetch(e),a=t.headers.get("content-type");if(a?.includes("application/json"))n=await t.json();else if(a?.includes("text/csv")){const e=await t.text();n=l.csvParse(e)}else n=await t.json()}}else{if(!Array.isArray(e))throw new Error("Source must be a URL, file path, or data array");n=e}return E(n,t)}catch(e){throw console.error("Error loading data:",e),e}}(e,t)},transformToWaterfallFormat:function(e,t={}){return E(e,t)},aggregateData:function(t,n="sum"){return e(t),t.map(e=>{let t;switch(n){case"sum":default:t=e.stacks.reduce((e,t)=>e+t.value,0);break;case"average":t=e.stacks.reduce((e,t)=>e+t.value,0)/e.stacks.length;break;case"max":t=Math.max(...e.stacks.map(e=>e.value));break;case"min":t=Math.min(...e.stacks.map(e=>e.value))}return{...e,aggregatedValue:t,originalStacks:e.stacks}})},sortData:function(t,n="label",a="ascending"){return e(t),[...t].sort((e,t)=>{let r,o,i;switch(n){case"label":default:r=e.label.toLowerCase(),o=t.label.toLowerCase();break;case"total":const n=e.stacks.reduce((e,t)=>e+t.value,0),a=t.stacks.reduce((e,t)=>e+t.value,0);r=Math.abs(n),o=Math.abs(a);break;case"maxStack":r=Math.max(...e.stacks.map(e=>e.value)),o=Math.max(...t.stacks.map(e=>e.value));break;case"minStack":r=Math.min(...e.stacks.map(e=>e.value)),o=Math.min(...t.stacks.map(e=>e.value))}return i="string"==typeof r&&"string"==typeof o?r.localeCompare(o):r-o,"ascending"===a?i:-i})},filterData:function(t,n){return e(t),t.filter(n)},getDataSummary:function(t){e(t);const n=[],a=[];let r=0;t.forEach(e=>{e.stacks.forEach(e=>{n.push(e.value),a.push(e.color),r++})});const o={min:Math.min(...n),max:Math.max(...n)},i=n.reduce((e,t)=>e+t,0),l=[...new Set(a)],s=t.map(e=>e.label);return{totalItems:t.length,totalStacks:r,valueRange:o,cumulativeTotal:i,stackColors:l,labels:s}},transformData:function(t,n){return e(t),t.map(n)},groupData:function(t,n){e(t);const a=new Map;return t.forEach(e=>{const t="function"==typeof n?n(e):e.label;a.has(t)||a.set(t,[]),a.get(t).push(e)}),a},transformStacks:function(e,t){if("function"!=typeof t)throw new Error("Transformer must be a function");return e.map(e=>({...e,stacks:e.stacks.map(t)}))},normalizeValues:function(e,t){let n=0;if(e.forEach(e=>{e.stacks.forEach(e=>{n=Math.max(n,Math.abs(e.value))})}),0===n)return e;const a=t/n;return e.map(e=>({...e,stacks:e.stacks.map(e=>({...e,originalValue:e.value,value:e.value*a}))}))},groupByCategory:function(e,t){if("function"!=typeof t)throw new Error("Category function must be a function");const n={};return e.forEach(e=>{const a=t(e);n[a]||(n[a]=[]),n[a].push(e)}),n},calculatePercentages:function(e){return e.map(e=>{const t=e.stacks.reduce((e,t)=>e+Math.abs(t.value),0);return{...e,stacks:e.stacks.map(e=>({...e,percentage:0===t?0:Math.abs(e.value)/t*100}))}})},interpolateData:function(e,t,n){if(e.length!==t.length)throw new Error("Data arrays must have the same length");return e.map((e,a)=>{const r=t[a],o=Math.min(e.stacks.length,r.stacks.length);return{label:e.label,stacks:Array.from({length:o},(t,a)=>({value:e.stacks[a].value+(r.stacks[a].value-e.stacks[a].value)*n,color:e.stacks[a].color,label:e.stacks[a].label}))}})},generateSampleData:function(e,t,n=[10,100]){const[a,r]=n,o=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"];return Array.from({length:e},(e,n)=>({label:`Item ${n+1}`,stacks:Array.from({length:t},(e,t)=>({value:Math.random()*(r-a)+a,color:o[t%o.length],label:`Stack ${t+1}`}))}))},groupBy:function(e,...t){if(!Array.isArray(e))throw new Error("Data must be an array");if(0===t.length)throw new Error("At least one grouping key must be provided");if(1===t.length)return l.group(e,t[0]);if(2===t.length)return l.group(e,t[0],t[1]);if(3===t.length)return l.group(e,t[0],t[1],t[2]);throw new Error("Maximum 3 levels of grouping supported")},rollupBy:function(e,t,...n){if(!Array.isArray(e))throw new Error("Data must be an array");if("function"!=typeof t)throw new Error("Reducer must be a function");if(0===n.length)throw new Error("At least one grouping key must be provided");if(1===n.length)return l.rollup(e,t,n[0]);if(2===n.length)return l.rollup(e,t,n[0],n[1]);if(3===n.length)return l.rollup(e,t,n[0],n[1],n[2]);throw new Error("Maximum 3 levels of rollup supported")},flatRollupBy:function(e,t,...n){if(!Array.isArray(e))throw new Error("Data must be an array");if("function"!=typeof t)throw new Error("Reducer must be a function");if(0===n.length)throw new Error("At least one grouping key must be provided");return l.flatRollup(e,t,...n)},crossTabulate:function(e,t,n){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Both data arrays must be arrays");return n?l.cross(e,t,(e,t)=>({row:e,col:t,value:n(e,t)})):l.cross(e,t,(e,t)=>({row:e,col:t,value:void 0}))},indexBy:function(e,...t){if(!Array.isArray(e))throw new Error("Data must be an array");if(0===t.length)throw new Error("At least one indexing key must be provided");if(1===t.length)return l.index(e,t[0]);if(2===t.length)return l.index(e,t[0],t[1]);throw new Error("Maximum 2 levels of indexing supported")},aggregateByTime:function(e,t){const{timeAccessor:n,valueAccessor:a,interval:r,aggregation:o="sum"}=t;if(!Array.isArray(e))throw new Error("Data must be an array");if("function"!=typeof n||"function"!=typeof a)throw new Error("Time and value accessors must be functions");const i=l.rollup(e,e=>{switch(o){case"sum":default:return l.sum(e,a);case"average":return l.mean(e,a)||0;case"max":return l.max(e,a)||0;case"min":return l.min(e,a)||0}},e=>r(n(e)));return Array.from(i.entries()).map(([e,t])=>({label:l.timeFormat("%Y-%m-%d")(e),stacks:[{value:t,color:t>=0?"#2ecc71":"#e74c3c",label:`${t>=0?"+":""}${l.format(".2f")(t)}`}]}))},createMultiDimensionalWaterfall:function(e,t,n){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Data and groupKeys must be arrays");if(0===t.length)throw new Error("At least one group key must be provided");const a=t.map(e=>t=>t[e]);return l.flatRollup(e,e=>l.sum(e,e=>e[n]||0),...a).map(e=>{const t=e.slice(0,-1),n=e[e.length-1],a=["#3498db","#2ecc71","#f39c12","#e74c3c","#9b59b6"];return{label:t.join(" → "),stacks:[{value:n,color:a[Math.abs(t.join("").split("").reduce((e,t)=>e+t.charCodeAt(0),0))%a.length],label:`${n>=0?"+":""}${l.format(".2f")(n)}`}]}})},aggregateWaterfallByPeriod:function(t,n,a){e(t);const r=l.rollup(t,e=>{const t=[];e.forEach(e=>t.push(...e.stacks));const n=l.rollup(t,e=>({value:l.sum(e,e=>e.value),label:e[0].label,color:e[0].color}),e=>e.color);return Array.from(n.values())},e=>{const t=e[n]||e.label,r=new Date(t);return isNaN(r.getTime())?new Date:a(r)});return Array.from(r.entries()).map(([e,t])=>({label:l.timeFormat("%Y-%m-%d")(e),stacks:t}))},createBreakdownWaterfall:function(e,t,n,a){if(!Array.isArray(e))throw new Error("Data must be an array");const r=l.rollup(e,e=>l.sum(e,e=>e[a]||0),e=>e[t],e=>e[n]);return Array.from(r.entries()).map(([e,t])=>{const n=Array.from(t.entries()).map(([e,t],n)=>{const a=["#3498db","#2ecc71","#f39c12","#e74c3c","#9b59b6","#1abc9c","#34495e"];return{value:t,color:a[n%a.length],label:`${e}: ${t>=0?"+":""}${l.format(".2f")(t)}`}});return{label:String(e),stacks:n}})}}}Object.assign(g,k);const D=z();const R={sum:e=>l.sum(e,e=>e.value||0),average:e=>l.mean(e,e=>e.value||0)||0,weightedAverage:(e,t="weight")=>{const n=l.sum(e,e=>e[t]||0);return 0===n?0:l.sum(e,e=>(e.value||0)*(e[t]||0))/n},variance:e=>{const t=l.mean(e,e=>e.value||0)||0;return l.mean(e,e=>Math.pow((e.value||0)-t,2))||0},percentile:e=>t=>{const n=t.map(e=>e.value||0).sort(l.ascending);return l.quantile(n,e/100)||0}},F={group:l.group,rollup:l.rollup,flatRollup:l.flatRollup,cross:l.cross,index:l.index,sum:l.sum,mean:l.mean,median:l.median,quantile:l.quantile,min:l.min,max:l.max,extent:l.extent,ascending:l.ascending,descending:l.descending};function O(){function e(e){const t=e.filter(e=>null!=e&&!isNaN(e)).sort(l.ascending);if(0===t.length)return{count:0,sum:0,mean:0,median:0,mode:[],variance:0,standardDeviation:0,min:0,max:0,range:0,quartiles:[0,0,0],percentiles:{p5:0,p10:0,p25:0,p75:0,p90:0,p95:0}};const n=t.length,r=l.sum(t),o=l.mean(t)||0,i=a.median(t)||0,s=a.variance(t)||0,c=a.deviation(t)||0,u=l.min(t)||0,d=l.max(t)||0,f=d-u,m=a.quantile(t,.25)||0,h=i,p=a.quantile(t,.75)||0,g={p5:a.quantile(t,.05)||0,p10:a.quantile(t,.1)||0,p25:m,p75:p,p90:a.quantile(t,.9)||0,p95:a.quantile(t,.95)||0},y=new Map;t.forEach(e=>{y.set(e,(y.get(e)||0)+1)});let b=0;const v=[];return y.forEach((e,t)=>{e>b?(b=e,v.length=0,v.push(t)):e===b&&v.push(t)}),{count:n,sum:r,mean:o,median:i,mode:v,variance:s,standardDeviation:c,min:u,max:d,range:f,quartiles:[m,h,p],percentiles:g}}function t(t,n=[]){const a=e(t),[r,o,i]=a.quartiles,l=i-r,s=r-1.5*l,c=i+1.5*l,u=r-3*l,d=i+3*l,f=[],m=[];t.forEach((e,t)=>{if(null==e||isNaN(e))return;const a=e<u||e>d;e<s||e>c?f.push({value:e,index:t,label:n[t],severity:a?"extreme":"mild",type:e<s?"lower":"upper"}):m.push({value:e,index:t,label:n[t]})});const h=f.filter(e=>"mild"===e.severity).length,p=f.filter(e=>"extreme"===e.severity).length;return{outliers:f,cleanData:m,method:"iqr",threshold:{lowerBound:s,upperBound:c,extremeLowerBound:u,extremeUpperBound:d},statistics:{mean:a.mean,median:a.median,q1:r,q3:i,iqr:l},summary:{totalOutliers:f.length,mildOutliers:h,extremeOutliers:p,outlierPercentage:t.length>0?f.length/t.length*100:0}}}function n(e){return a.bisector(e)}return{calculateSummary:e,detectOutliers:t,assessDataQuality:function(e,n={}){const{expectedRange:r,allowedTypes:o=["number"],nullTolerance:i=.05,duplicateTolerance:s=.1}=n,c=e.length;let u=0,d=0,f=0;const m=new Set,h=new Set;e.forEach(e=>{if(null==e||e&&null==e.value)return void u++;const t=e&&"object"==typeof e&&"value"in e?e.value:e,n=typeof t;o.includes(n)&&d++,"number"===n&&r?t>=r[0]&&t<=r[1]&&f++:r||f++;const a=JSON.stringify(t);h.has(a)?m.add(a):h.add(a)});const p=(c-u)/c,g=d/c,y=f/c,b=e.filter(e=>"number"==typeof e&&!isNaN(e)),v=b.length>0?(a.deviation(b)||0)/(l.mean(b)||1):0,x=Math.max(0,100-100*v),w=b.length>0?t(b):{outliers:[],cleanData:[],method:"None - No numeric data",threshold:{},statistics:{mean:0,median:0,q1:0,q3:0,iqr:0},summary:{totalOutliers:0,mildOutliers:0,extremeOutliers:0,outlierPercentage:0}},k=[];p<1-i&&(k.push(`Improve data completeness: ${u} missing values detected`),k.push("Remove or impute missing values")),g<.95&&k.push(`Validate data types: ${c-d} invalid types found`),y<.9&&r&&k.push(`Check data accuracy: ${c-f} values outside expected range`),m.size>s*c&&k.push(`Remove duplicates: ${m.size} duplicate values detected`),w.summary.outlierPercentage>5&&k.push(`Investigate outliers: ${w.summary.totalOutliers} outliers detected (${w.summary.outlierPercentage.toFixed(1)}%)`);const M=[];return u>0&&M.push(`${u} null or missing values found`),c-d>0&&M.push(c-d+" invalid data types found"),r&&c-f>0&&M.push(c-f+" values outside expected range"),m.size>0&&M.push(`${m.size} duplicate values found`),w.summary.totalOutliers>0&&M.push(`${w.summary.totalOutliers} outliers detected`),{completeness:p,consistency:x,accuracy:y,validity:g,duplicates:m.size,issues:M,anomalies:w,recommendations:k}},analyzeVariance:function(e){const t=e.map(e=>e.value),n=a.variance(t)||0,r=t.filter(e=>e>0),o=t.filter(e=>e<0),i=r.length>0&&a.variance(r)||0,s=o.length>0&&a.variance(o)||0,c=l.mean(t)||0,u=e.map(e=>{const t=Math.pow(e.value-c,2),a=n>0?t/n*100:0;return{label:e.label,value:e.value,variance:t,contribution:a}}),d=[...u].sort((e,t)=>t.contribution-e.contribution),f=d.slice(0,Math.min(5,d.length)).map(e=>({label:e.label,impact:e.contribution>20?"high":e.contribution>10?"medium":"low",variance:e.variance})),m=l.mean(t)||0,h=new Map;e.forEach(e=>{const t=e.label.match(/^([A-Za-z]+)/)?.[1]||(e.value>0?"positive":"negative");h.has(t)||h.set(t,[]),h.get(t).push(e.value)});const p=Array.from(h.entries()).map(([e,t])=>({name:e,values:t})).filter(e=>e.values.length>0);let g=0;if(p.length>1){const e=p.map(e=>l.mean(e.values)||0),n=p.map(e=>e.values.length);t.length,g=p.reduce((t,a,r)=>{const o=e[r];return t+n[r]*Math.pow(o-m,2)},0)/(p.length-1)}const y=p.length>0?p.reduce((e,t)=>e+(a.variance(t.values)||0)*(t.values.length-1),0)/Math.max(1,t.length-p.length):n,b=g>0&&y>0?g/y:0;return{totalVariance:n,positiveVariance:i,negativeVariance:s,withinGroupVariance:y,betweenGroupVariance:g,fStatistic:b,significance:b>4?"significant":b>2?"moderate":"not significant",varianceContributions:u,significantFactors:f}},analyzeTrend:function(e){if(e.length<2)return{slope:0,intercept:0,correlation:0,rSquared:0,direction:"stable",strength:"none",confidence:0,trend:"stable",projectedValues:[],forecast:[]};const t=e.map(e=>e.x),n=e.map(e=>e.y),r=l.mean(t)||0,o=l.mean(n)||0;let i=0,s=0;for(let a=0;a<e.length;a++){const e=t[a]-r;i+=e*(n[a]-o),s+=e*e}const c=0!==s?i/s:0,u=a.deviation(t)||0,d=a.deviation(n)||0,f=u*d!==0?i/(Math.sqrt(s)*d*Math.sqrt(e.length-1)):0,m=c>.01?"increasing":c<-.01?"decreasing":"stable",h=Math.abs(f)>.7?"strong":Math.abs(f)>.3?"moderate":"weak",p=100*Math.abs(f),g=Math.max(...t),y=Array.from({length:3},(t,i)=>{const l=g+(i+1),s=o+c*(l-r),u=Math.sqrt(a.variance(n)||0)/Math.sqrt(e.length);return{period:l,value:s,x:l,y:s,confidence:{lower:s-1.96*u,upper:s+1.96*u}}});return{slope:c,intercept:o-c*r,correlation:f,rSquared:f*f,direction:m,strength:h,confidence:p,trend:m,projectedValues:y,forecast:y}},createBisector:n,createSearch:function(e,t){const r=n(t),o=[...e].sort((e,n)=>a.ascending(t(e),t(n)));return e=>{const n=r.left(o,e);if(0===n)return o[0];if(n>=o.length)return o[o.length-1];const a=o[n-1],i=o[n];return Math.abs(t(a)-e)<=Math.abs(t(i)-e)?a:i}},calculateMovingAverage:function(e,t){if(t<=0||t>e.length||0===e.length)return[];const n=[];for(let a=0;a<=e.length-t;a++){const r=e.slice(a,a+t),o=l.mean(r)||0;n.push(o)}return n},calculateExponentialSmoothing:function(e,t){if(t<0||t>1||0===e.length)return[];const n=[];let a=e[0];n.push(a);for(let r=1;r<e.length;r++)a=t*e[r]+(1-t)*a,n.push(a);return n},detectSeasonality:function(e,t){if(e.length<2*t)return!1;const n=l.mean(e)||0;let a=0,r=0;for(let r=0;r<e.length-t;r++)a+=(e[r]-n)*(e[r+t]-n);for(let t=0;t<e.length;t++)r+=Math.pow(e[t]-n,2);const o=0!==r?a/r:0;return Math.abs(o)>.3}}}function P(){let e=l.quadtree().x(e=>e.x).y(e=>e.y);return{quadTree:e,search:function(t,n,a=10){const r=[];return e.visit((e,o,i,l,s)=>{if(!e.length){const o=e;if(o.data){Math.sqrt(Math.pow(o.data.x-t,2)+Math.pow(o.data.y-n,2))<=a&&r.push(o.data)}}return o>t+a||i>n+a||l<t-a||s<n-a}),r},findNearest:function(t,n){return e.find(t,n)},add:function(t){e.add(t)},remove:function(t){e.remove(t)},clear:function(){e=l.quadtree().x(e=>e.x).y(e=>e.y)},size:function(){let t=0;return e.visit(()=>(t++,!1)),t}}}function B(e){let t={...e},n=0,a=0,r=60;function o(e){const n=Math.floor(e/t.itemHeight),a=Math.ceil((e+t.containerHeight)/t.itemHeight);return{start:Math.max(0,n-t.overscan),end:a+t.overscan}}return{getVisibleRange:o,getVirtualizedData:function(e,i){const l=performance.now();if(!(e.length>=t.threshold)){const n=performance.now();return{visibleData:e,offsetY:0,totalHeight:e.length*t.itemHeight,metrics:{renderTime:n-l,dataProcessingTime:n-l,memoryUsage:W(),frameRate:r,itemsRendered:e.length,totalItems:e.length,virtualizationActive:!1}}}const{start:s,end:c}=o(i),u=e.slice(s,Math.min(c,e.length)),d=s*t.itemHeight,f=e.length*t.itemHeight,m=performance.now();if(a++,a%60==0){const e=performance.now();n>0&&(r=6e4/(e-n)),n=e}return{visibleData:u,offsetY:d,totalHeight:f,metrics:{renderTime:m-l,dataProcessingTime:m-l,memoryUsage:W(),frameRate:r,itemsRendered:u.length,totalItems:e.length,virtualizationActive:!0}}},updateConfig:function(e){t={...t,...e}},destroy:function(){}}}function I(e){const t=document.createElement("canvas"),n=t.getContext("2d");return e.appendChild(t),{render:function(e,a){const{xScale:r,yScale:o}=a;n.clearRect(0,0,t.width,t.height),n.save(),e.forEach((e,t)=>{const a=r(e.label)||0,i=o(e.value)||0,l=r.bandwidth?r.bandwidth():20,s=Math.abs(o(0)-i);n.fillStyle=e.color||"#3498db",n.fillRect(a,Math.min(i,o(0)),l,s),n.strokeStyle="#ffffff",n.lineWidth=1,n.strokeRect(a,Math.min(i,o(0)),l,s)}),n.restore()},clear:function(){n.clearRect(0,0,t.width,t.height)},getCanvas:function(){return t},setDimensions:function(e,n){t.width=e,t.height=n,t.style.width=`${e}px`,t.style.height=`${n}px`},enableHighDPI:function(){const e=window.devicePixelRatio||1,a=t.getBoundingClientRect();t.width=a.width*e,t.height=a.height*e,t.style.width=`${a.width}px`,t.style.height=`${a.height}px`,n.scale(e,e)}}}function q(){const e=new Map,t=new Map;let n=0,a=performance.now();function r(){const e=t.get("render")||[],r=t.get("dataProcessing")||[];return{renderTime:e.length>0&&l.mean(e)||0,dataProcessingTime:r.length>0&&l.mean(r)||0,memoryUsage:W(),frameRate:n>0?1e3/((performance.now()-a)/n):0,itemsRendered:0,totalItems:0,virtualizationActive:!1}}return{startTiming:function(t){e.set(t,performance.now())},endTiming:function(n){const a=e.get(n);if(!a)return console.warn(`No start time found for timing label: ${n}`),0;const r=performance.now()-a;t.has(n)||t.set(n,[]),t.get(n).push(r);const o=t.get(n);return o.length>100&&o.shift(),e.delete(n),r},getMetrics:r,getMemoryUsage:W,trackFrameRate:function(){n++,1===n&&(a=performance.now())},generateReport:function(){const e=r();return`\nPerformance Report:\n- Average Render Time: ${e.renderTime.toFixed(2)}ms\n- Average Processing Time: ${e.dataProcessingTime.toFixed(2)}ms\n- Memory Usage: ${e.memoryUsage.toFixed(2)}MB\n- Frame Rate: ${e.frameRate.toFixed(1)}fps\n- Items Rendered: ${e.itemsRendered}/${e.totalItems}\n- Virtualization: ${e.virtualizationActive?"Active":"Inactive"}\n `.trim()}}}function W(){if("memory"in performance){return performance.memory.usedJSHeapSize/1048576}return 0}function L(e,t=1e3){if(e.length<=t)return e;const n=Math.ceil(e.length/t),a=[];for(let t=0;t<e.length;t+=n)a.push(e[t]);return a}function N(e){switch(e){case"uniform":return(e,t)=>{if(t>=e.length)return e;const n=e.length/t,a=[];for(let r=0;r<t;r++){const t=Math.floor(r*n);a.push(e[t])}return a};case"random":return(e,t)=>{if(t>=e.length)return e;return[...e].sort(()=>.5-Math.random()).slice(0,t)};case"importance":return(e,t)=>{if(t>=e.length)return e;const n=[e[0]];if(t>2){const a=N("uniform")(e.slice(1,-1),t-2);n.push(...a)}return t>1&&n.push(e[e.length-1]),n};default:throw new Error(`Unknown sampling strategy: ${e}`)}}function j(){return{createSpatialIndex:P,createVirtualScrollManager:B,createCanvasRenderer:I,createPerformanceMonitor:q,optimizeDataForRendering:L,createDataSampler:N}}function U(){function e(e){return"number"==typeof e?e:void 0!==e.value?e.value:e.stacks&&Array.isArray(e.stacks)?e.stacks.reduce((e,t)=>e+(t.value||0),0):0}return{groupBy:function(e,t){return e&&Array.isArray(e)&&t?a.group(e,t):new Map},rollupBy:function(e,t,n){return e&&Array.isArray(e)&&t&&n?a.rollup(e,t,n):new Map},flatRollupBy:function(e,t,n){return e&&Array.isArray(e)&&t&&n?a.flatRollup(e,t,n):[]},crossTabulate:function(e,t,n){return Array.isArray(e)&&Array.isArray(t)?n?a.cross(e,t,n):a.cross(e,t):[]},indexBy:function(e,t){if(!e||!Array.isArray(e)||!t)return new Map;try{return a.index(e,t)}catch(n){const a=new Map;return e.forEach(e=>{const n=t(e);a.has(n)||a.set(n,e)}),a}},aggregateByTime:function(e,t,n,r){if(!(e&&Array.isArray(e)&&t&&r))return[];const o=a.group(e,e=>{const a=t(e);if(!(a&&a instanceof Date))return"invalid";switch(n){case"day":default:return a.toISOString().split("T")[0];case"week":const e=new Date(a);return e.setDate(a.getDate()-a.getDay()),e.toISOString().split("T")[0];case"month":return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`;case"year":return String(a.getFullYear())}});return Array.from(o.entries()).map(([e,t])=>({period:e,data:r(t),count:t.length}))},createMultiDimensionalWaterfall:function(e,t){const n=[],{aggregationMethod:a="sum"}=t;if(!e||"object"!=typeof e)return n;const r=Object.keys(e);let o=0;for(const i of r){const r=e[i];if(!Array.isArray(r))continue;let l=0;for(const e of r){let t=0;switch(void 0!==e.value?t=e.value:e.stacks&&Array.isArray(e.stacks)&&(t=e.stacks.reduce((e,t)=>e+(t.value||0),0)),n.push({...e,region:i,value:t,label:`${i}: ${e.label}`}),a){case"sum":case"average":l+=t;break;case"count":l+=1;break;case"max":l=Math.max(l,t);break;case"min":l=0===l?t:Math.min(l,t)}}t.includeRegionalTotals&&n.push({label:`${i} Total`,value:"average"===a?l/r.length:l,region:i,isRegionalTotal:!0}),o+=l}return t.includeGrandTotal&&n.push({label:"Grand Total",value:o,isGrandTotal:!0}),n},aggregateWaterfallByPeriod:function(e,t,n){if(!e||!Array.isArray(e))return[];const r=a.group(e,e=>e[t]||"unknown"),o=Array.from(r.entries()).map(([e,t])=>{const n=t.reduce((e,t)=>void 0!==t.value?e+t.value:t.stacks&&Array.isArray(t.stacks)?e+t.stacks.reduce((e,t)=>e+(t.value||0),0):e,0);return{period:e,items:t,total:n,count:t.length,average:n/t.length,movingAverage:0,growthRate:0}});if(n.includeMovingAverage){const e=n.movingAverageWindow||3;o.forEach((t,n)=>{const a=Math.max(0,n-Math.floor(e/2)),r=Math.min(o.length,a+e),i=o.slice(a,r);t.movingAverage=i.reduce((e,t)=>e+t.total,0)/i.length})}return n.calculateGrowthRates&&o.forEach((e,t)=>{if(t>0){const n=o[t-1];e.growthRate=0!==n.total?(e.total-n.total)/n.total:0}}),o},createBreakdownWaterfall:function(e,t,n){if(!e||!Array.isArray(e))return[];const a=[];for(const r of e){const e=r[t];if(e&&Array.isArray(e)){n.maintainOriginalStructure&&a.push({...r,isMainItem:!0});let t=0;e.forEach((o,i)=>{const l={...o,parentLabel:r.label,isBreakdown:!0,breakdownIndex:i,color:n.colorByBreakdown?`hsl(${360*i/e.length}, 70%, 60%)`:o.color};a.push(l),t+=o.value||0}),n.includeSubtotals&&e.length>1&&a.push({label:`${r.label} Subtotal`,value:t,parentLabel:r.label,isSubtotal:!0})}else a.push({...r,hasBreakdown:!1})}return a},analyzeSequence:function(t){return!Array.isArray(t)||t.length<2?[]:t.slice(1).map((n,a)=>{const r=t[a],o=n,i=e(r),l=e(o),s=l-i;return{index:a,from:r.label||`Item ${a}`,to:o.label||`Item ${a+1}`,fromValue:i,toValue:l,change:s,percentChange:0!==i?s/i*100:0,direction:s>0?"increase":s<0?"decrease":"stable",magnitude:Math.abs(s)>1e3?"large":Math.abs(s)>100?"medium":"small"}})},suggestDataOptimizations:function(e){const t=[];return Array.isArray(e)&&0!==e.length?(e.length>20&&t.push({type:"aggregation",priority:"medium",description:"Consider grouping similar items for better readability",impact:"Reduces visual clutter"}),t):t},generateCustomTicks:function(e,t){const n=t.targetTickCount||8;return l.ticks(e[0],e[1],n)}}}function V(){function e(e){return"number"==typeof e?e:void 0!==e.value?e.value:e.stacks&&Array.isArray(e.stacks)?e.stacks.reduce((e,t)=>e+(t.value||0),0):0}function t(e){return"string"==typeof e?e:void 0!==e.label?e.label:void 0!==e.name?e.name:"Unnamed"}return{createTreemapLayout:function(e,t){const n=l.hierarchy(e).sum(e=>e.value||0).sort((e,t)=>(t.value||0)-(e.value||0));return l.treemap().size([t.width,t.height]).padding(t.padding).tile(t.tile).round(t.round)(n)},renderTreemap:function(e,t,n){const a=n.colorScale||l.scaleOrdinal(l.schemeCategory10),r=e.selectAll(".treemap-group").data([0]),o=r.enter().append("g").attr("class","treemap-group").merge(r),i=t.leaves(),s=o.selectAll(".treemap-cell").data(i,e=>e.data.name),c=s.enter().append("g").attr("class","treemap-cell");c.append("rect").attr("class","treemap-rect"),c.append("text").attr("class","treemap-label"),c.append("text").attr("class","treemap-value");const u=c.merge(s);u.select(".treemap-rect").transition().duration(750).attr("x",e=>e.x0).attr("y",e=>e.y0).attr("width",e=>e.x1-e.x0).attr("height",e=>e.y1-e.y0).attr("fill",e=>a(e.data.category||e.data.name)).attr("stroke","#fff").attr("stroke-width",1).attr("opacity",.8),u.select(".treemap-label").attr("x",e=>(e.x0+e.x1)/2).attr("y",e=>(e.y0+e.y1)/2-8).attr("text-anchor","middle").attr("font-size",e=>Math.min(12,(e.x1-e.x0)/8)).attr("fill","#333").text(e=>e.data.name),u.select(".treemap-value").attr("x",e=>(e.x0+e.x1)/2).attr("y",e=>(e.y0+e.y1)/2+8).attr("text-anchor","middle").attr("font-size",e=>Math.min(10,(e.x1-e.x0)/10)).attr("fill","#666").text(e=>{return t=e.value||0,Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toFixed(0);var t}),u.style("cursor","pointer").on("click",(e,t)=>{n.onNodeClick&&n.onNodeClick(t)}).on("mouseenter",(e,t)=>{l.select(e.currentTarget).select(".treemap-rect").attr("opacity",1).attr("stroke-width",2),n.onNodeHover&&n.onNodeHover(t)}).on("mouseleave",(e,t)=>{l.select(e.currentTarget).select(".treemap-rect").attr("opacity",.8).attr("stroke-width",1)}),s.exit().transition().duration(300).attr("opacity",0).remove()},createPartitionLayout:function(e,t){const n=l.hierarchy(e).sum(e=>e.value||0).sort((e,t)=>(t.value||0)-(e.value||0));return l.partition().size([2*Math.PI,Math.min(t.width,t.height)/2])(n)},renderPartition:function(e,t,n){const a=n.colorScale||l.scaleOrdinal(l.schemeCategory10),r=Math.min(n.width,n.height)/2,o=(n.innerRadius,e.selectAll(".partition-group").data([0])),i=o.enter().append("g").attr("class","partition-group").attr("transform",`translate(${n.width/2}, ${n.height/2})`).merge(o);"sunburst"===n.type?function(e,t,n,a,r,o){const i=l.arc().startAngle(e=>e.x0).endAngle(e=>e.x1).innerRadius(e=>Math.sqrt(e.y0)*a/Math.sqrt(t.y1)).outerRadius(e=>Math.sqrt(e.y1)*a/Math.sqrt(t.y1)),s=t.descendants().filter(e=>e.depth>0),c=e.selectAll(".partition-arc").data(s,e=>e.data.name),u=c.enter().append("path").attr("class","partition-arc").attr("fill",e=>n(e.data.category||e.data.name)).attr("stroke","#fff").attr("stroke-width",1).style("cursor","pointer");u.merge(c).transition().duration(750).attr("d",i),u.merge(c).on("click",(e,t)=>{o.onNodeClick&&o.onNodeClick(t)}),c.exit().transition().duration(300).attr("opacity",0).remove()}(i,t,a,r,0,n):function(e,t,n,a){const r=t.descendants(),o=e.selectAll(".partition-rect").data(r,e=>e.data.name),i=o.enter().append("rect").attr("class","partition-rect").attr("fill",e=>n(e.data.category||e.data.name)).attr("stroke","#fff").attr("stroke-width",1).style("cursor","pointer");i.merge(o).transition().duration(750).attr("x",e=>e.y0).attr("y",e=>e.x0).attr("width",e=>e.y1-e.y0).attr("height",e=>e.x1-e.x0),i.merge(o).on("click",(e,t)=>{a.onNodeClick&&a.onNodeClick(t)}),o.exit().transition().duration(300).attr("opacity",0).remove()}(i,t,a,n)},createClusterLayout:function(e,t){const n=l.hierarchy(e),a=l.cluster().size([t.width,t.height]).nodeSize(t.nodeSize);return t.separation&&a.separation(t.separation),a(n)},renderCluster:function(e,t,n){const a=e.selectAll(".cluster-group").data([0]),r=a.enter().append("g").attr("class","cluster-group").merge(a),o=t.descendants(),i=t.links(),s=r.selectAll(".cluster-link").data(i,e=>`${e.source.data.name}-${e.target.data.name}`);s.enter().append("path").attr("class","cluster-link").attr("fill","none").attr("stroke",n.linkColor||"#999").attr("stroke-width",1).merge(s).transition().duration(750).attr("d",l.linkHorizontal().x(e=>e.y||0).y(e=>e.x||0)),s.exit().remove();const c=r.selectAll(".cluster-node").data(o,e=>e.data.name),u=c.enter().append("g").attr("class","cluster-node");u.append("circle").attr("r",5).attr("fill",n.nodeColor||"#69b3a2"),u.append("text").attr("dy",3).attr("x",8).style("font-size","12px").text(e=>e.data.name),u.merge(c).transition().duration(750).attr("transform",e=>`translate(${e.y},${e.x})`),c.exit().transition().duration(300).attr("opacity",0).remove()},createPackLayout:function(e,t){const n=l.hierarchy(e).sum(t.sizeAccessor||(e=>e.value||0)).sort((e,t)=>(t.value||0)-(e.value||0));return l.pack().size([t.width,t.height]).padding(t.padding)(n)},renderPack:function(e,t,n){const a=n.colorScale||l.scaleOrdinal(l.schemeCategory10),r=e.selectAll(".pack-group").data([0]),o=r.enter().append("g").attr("class","pack-group").merge(r),i=t.descendants().filter(e=>e.depth>0),s=o.selectAll(".pack-node").data(i,e=>e.data.name),c=s.enter().append("g").attr("class","pack-node");c.append("circle").attr("class","pack-circle").style("cursor","pointer"),c.append("text").attr("class","pack-label").attr("text-anchor","middle").attr("dy","0.3em").style("font-size","10px").style("fill","#333").style("pointer-events","none");const u=c.merge(s);u.transition().duration(750).attr("transform",e=>`translate(${e.x},${e.y})`),u.select(".pack-circle").transition().duration(750).attr("r",e=>e.r).attr("fill",e=>a(e.data.category||e.data.name)).attr("stroke","#fff").attr("stroke-width",1).attr("opacity",.7),u.select(".pack-label").text(e=>e.r>15?e.data.name:"").attr("font-size",e=>Math.min(e.r/3,12)),u.on("click",(e,t)=>{n.onNodeClick&&n.onNodeClick(t)}).on("mouseenter",(e,t)=>{l.select(e.currentTarget).select(".pack-circle").attr("opacity",1).attr("stroke-width",2)}).on("mouseleave",(e,t)=>{l.select(e.currentTarget).select(".pack-circle").attr("opacity",.7).attr("stroke-width",1)}),s.exit().transition().duration(300).attr("opacity",0).remove()},transformWaterfallToHierarchy:function(n){const a=l.group(n,e=>e.category||"Default"),r=[];for(const[n,o]of a){const a={name:n,value:l.sum(o,t=>Math.abs(e(t))),category:n,children:o.map(a=>({name:t(a),value:Math.abs(e(a)),category:n,metadata:a}))};r.push(a)}return{name:"Root",children:r,value:l.sum(r,e=>e.value||0)}},createDrillDownNavigation:function(e){const t=[];return function e(n,a=[]){const r=[...a,n.name];t.push({path:r,name:n.name,value:n.value,level:r.length-1,hasChildren:!!(n.children&&n.children.length>0)}),n.children&&n.children.forEach(t=>e(t,r))}(e),t},calculateHierarchicalMetrics:function(e){return{depth:e.depth,height:e.height,value:e.value,leafCount:e.leaves().length,descendants:e.descendants().length,ancestors:e.ancestors().length,totalValue:e.descendants().reduce((e,t)=>e+(t.value||0),0),averageValue:e.value&&e.leaves().length?e.value/e.leaves().length:0}}}}"undefined"!=typeof window&&window.d3&&(window.d3.waterfallChart=$),e.analyzeWaterfallStatistics=function(e,t={}){const n=O(),a=e.map(e=>e.value),r=n.calculateSummary(a),o=n.analyzeVariance(e),i=n.assessDataQuality(a,{expectedRange:t.currency?[-1e6,1e6]:void 0}),l=[];if(o.significantFactors.length>0){const e=o.significantFactors[0];l.push(`${e.label} is the primary driver of variance (${e.impact} impact)`)}r.standardDeviation>Math.abs(r.mean)&&l.push("High volatility detected - consider risk management strategies");const s=a.filter(e=>e>0).length/a.filter(e=>e<0).length;return s>2?l.push("Predominantly positive contributors - strong growth pattern"):s<.5&&l.push("Predominantly negative contributors - potential cost management focus needed"),i.anomalies.summary.outlierPercentage>10&&l.push(`${i.anomalies.summary.totalOutliers} outliers detected - data validation recommended`),{summary:r,variance:o,quality:i,insights:l}},e.applyTheme=function(e,t="default"){const n=g[t]||g.default;return e.totalColor(n.totalColor),n},e.createAccessibilitySystem=d,e.createAdvancedDataProcessor=U,e.createAdvancedInteractionSystem=function(e,t,n){let a=null,i=!1,s=null,c=[],u=new Map;function d(t){t&&t.enabled?(a=r.drag().on("start",(e,n)=>{l.select(e.sourceEvent.target).raise().attr("stroke","#ff6b6b").attr("stroke-width",2),t.onDragStart&&t.onDragStart(e,n),y("dragStart",{event:e,data:n})}).on("drag",(e,a)=>{const r=l.select(e.sourceEvent.target);let o=a.value||0;if("vertical"===t.axis||"both"===t.axis){const i=e.y;if(o=n.invert(i),t.constraints){const{minValue:e,maxValue:n,snapToGrid:a,gridSize:r}=t.constraints;void 0!==e&&(o=Math.max(e,o)),void 0!==n&&(o=Math.min(n,o)),a&&r&&(o=Math.round(o/r)*r)}const l=Math.abs(n(0)-n(o)),s=n(o>=0?o:0);r.attr("y",s).attr("height",l),a.value=o,a.stacks&&a.stacks.length>0&&(a.stacks[0].value=o)}if("horizontal"===t.axis||"both"===t.axis){const t=e.x,n=parseFloat(r.attr("width")||"0");r.attr("transform",`translate(${t-n/2}, 0)`)}t.onDrag&&t.onDrag(e,a),y("drag",{event:e,data:a,newValue:o})}).on("end",(e,n)=>{l.select(e.sourceEvent.target).attr("stroke",null).attr("stroke-width",null),t.onDragEnd&&t.onDragEnd(e,n),y("dragEnd",{event:e,data:n})}),e.selectAll(".bar").call(a),y("dragEnabled",t)):f()}function f(){a&&(e.selectAll(".bar").on(".drag",null),a=null,y("dragDisabled"))}function m(t){if(!t||!t.enabled||0===c.length)return void h();i=!0;const a=e.selectAll(".enhanced-hover-group").data([0]),r=a.enter().append("g").attr("class","enhanced-hover-group").merge(a).selectAll(".hover-zone").data(c);r.enter().append("rect").attr("class","hover-zone").merge(r).attr("x",e=>b(e)-.75*x()).attr("y",e=>Math.min(v(e),n(0))-10).attr("width",e=>1.5*x()).attr("height",e=>Math.abs(n(0)-v(e))+20).style("fill","transparent").style("pointer-events","all").on("mouseenter",function(n,a){var r;r=a,e.selectAll(".bar").filter(e=>e===r).transition().duration(150).attr("opacity",.8).attr("stroke","#ff6b6b").attr("stroke-width",2),t.onCellEnter&&t.onCellEnter(n,a),y("enhancedHoverEnter",{event:n,data:a})}).on("mouseleave",function(n,a){var r;r=a,e.selectAll(".bar").filter(e=>e===r).transition().duration(150).attr("opacity",1).attr("stroke",null).attr("stroke-width",null),t.onCellLeave&&t.onCellLeave(n,a),y("enhancedHoverLeave",{event:n,data:a})}).on("click",function(e,n){t.onCellClick&&t.onCellClick(e,n),y("enhancedHoverClick",{event:e,data:n})}),r.exit().remove(),y("enhancedHoverEnabled",t)}function h(){try{if(e&&e.selectAll&&"function"==typeof e.selectAll){const t=e.selectAll(".enhanced-hover-group");t&&t.remove&&"function"==typeof t.remove&&t.remove()}}catch(e){}i=!1,y("enhancedHoverDisabled")}function p(a){if(!a||!a.enabled||0===c.length)return o.forceSimulation([]);if(g(),s=o.forceSimulation(c),a.forces.collision&&s.force("collision",o.forceCollide().radius(e=>x()/2+5).strength(a.strength.collision||.7)),a.forces.centering){const e=(t.range()[0]+t.range()[1])/2,r=(n.range()[0]+n.range()[1])/2;s.force("center",o.forceCenter(e,r).strength(a.strength.centering||.1))}if(a.forces.positioning&&(s.force("x",l.forceX(e=>b(e)).strength(a.strength.positioning||.5)),s.force("y",l.forceY(e=>v(e)).strength(a.strength.positioning||.5))),a.forces.links&&c.length>1){const e=c.slice(1).map((e,t)=>({source:c[t],target:e}));s.force("link",l.forceLink(e).distance(50).strength(a.strength.links||.3))}if(s.on("tick",()=>{!function(){if(!o.forceSimulation)return;e.selectAll(".bar").data(c).attr("transform",e=>{const t=e.x||b(e),n=e.y||v(e);return`translate(${t-x()/2}, ${n})`})}(),a.onTick&&s&&a.onTick(s),y("forceTick",s)}),s.on("end",()=>{a.onEnd&&s&&a.onEnd(s),y("forceEnd",s)}),a.duration){const e=.001,t=1-Math.pow(e,1/a.duration);s.alphaDecay(t)}return y("forceSimulationStarted",a),s}function g(){s&&(s.stop(),s=null,y("forceSimulationStopped"))}function y(e,t){const n=u.get(e);n&&n.forEach(e=>e(t))}function b(e){const n=t;return n.bandwidth?(n(e.label)||0)+n.bandwidth()/2:n(parseFloat(e.label)||0)}function v(e){const t=e.value||(e.stacks&&e.stacks[0]?e.stacks[0].value:0);return n(t/2)}function x(e){const n=t;return n.bandwidth?n.bandwidth():40}return{enableDrag:d,disableDrag:f,updateDragConstraints:function(e){y("dragConstraintsUpdated",e)},enableEnhancedHover:m,disableEnhancedHover:h,updateHoverExtent:function(e){if(i){m({enabled:!0,extent:e})}},startForceSimulation:p,stopForceSimulation:g,updateForces:function(e){s&&(e.collision||s.force("collision",null),e.centering||s.force("center",null),e.positioning||(s.force("x",null),s.force("y",null)),e.links||s.force("link",null),s.alpha(1).restart(),y("forcesUpdated",e))},setInteractionMode:function(e){f(),h(),g();const a=t.range()||[0,800],r=n.range()||[400,0];switch(e){case"drag":d({enabled:!0,axis:"vertical",constraints:{snapToGrid:!0,gridSize:10}});break;case"voronoi":m({enabled:!0,extent:[[0,0],[a[1],r[0]]]});break;case"force":p({enabled:!0,forces:{collision:!0,positioning:!0},strength:{collision:.7,positioning:.5},duration:1e3});break;case"combined":m({enabled:!0,extent:[[0,0],[a[1],r[0]]]}),d({enabled:!0,axis:"vertical"})}y("interactionModeChanged",e)},getActiveInteractions:function(){const e=[];return a&&e.push("drag"),i&&e.push("hover"),s&&e.push("force"),e},updateData:function(e){if(c=e,i){m({enabled:!0,extent:[[0,0],[800,600]]})}s&&(s.nodes(e),s.alpha(1).restart())},on:function(e,t){u.has(e)||u.set(e,[]),u.get(e).push(t)},off:function(e){u.delete(e)},trigger:y}},e.createAdvancedPerformanceSystem=j,e.createAnimationSystem=function(){const e={staggerDelay:100,defaultDuration:750,defaultEase:"easeOutQuad"},t={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:(4-2*e)*e-1,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,easeInSine:e=>1-Math.cos(e*Math.PI/2),easeOutSine:e=>Math.sin(e*Math.PI/2),easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,easeInElastic:e=>{const t=2*Math.PI/3;return 0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*t)},easeOutElastic:e=>{const t=2*Math.PI/3;return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((10*e-.75)*t)+1},easeOutBounce:e=>{const t=7.5625,n=2.75;return e<1/n?t*e*e:e<2/n?t*(e-=1.5/n)*e+.75:e<2.5/n?t*(e-=2.25/n)*e+.9375:t*(e-=2.625/n)*e+.984375}};function n(e,n,a,r="easeOutQuad",o,i){const l=performance.now(),s=n-e,c=t[r]||t.easeOutQuad;requestAnimationFrame(function t(n){const r=n-l,u=Math.min(r/a,1),d=c(u);o&&o(e+s*d,u),u<1?requestAnimationFrame(t):i&&i()})}function a(e,t,a,r=500,o="easeOutQuad"){return new Promise(i=>{n(t,a,r,o,t=>{e&&e.style?e.style.opacity=t.toString():e&&e.attr&&e.attr("opacity",t)},()=>i())})}function r(e,t,a,r=500,o="easeOutQuad"){return new Promise(i=>{n(t,a,r,o,t=>{e&&e.style?e.style.transform=`translateX(${t}px)`:e&&e.attr&&e.attr("transform",`translate(${t}, 0)`)},()=>i())})}function o(e,t,a,r=500,o="easeOutQuad"){return new Promise(i=>{n(t,a,r,o,t=>{e&&e.style?e.style.transform=`scale(${t})`:e&&e.attr&&e.attr("transform",`scale(${t})`)},()=>i())})}function i(){const e=[];let t=!1;const n={add:function(t,a=0){return e.push({fn:t,delay:a}),n},parallel:function(...t){return e.push({fn:()=>Promise.all(t.map(e=>e())),delay:0}),n},play:async function(){if(t)throw new Error("Sequence is already running");t=!0;try{for(const t of e)t.delay>0&&await new Promise(e=>setTimeout(e,t.delay)),await t.fn()}finally{t=!1}},stop:function(){t=!1},get isRunning(){return t}};return n}const l={slideInLeft:(e,t=500)=>r(e,-100,0,t,"easeOutQuad"),slideInRight:(e,t=500)=>r(e,100,0,t,"easeOutQuad"),fadeIn:(e,t=500)=>a(e,0,1,t,"easeOutQuad"),fadeOut:(e,t=500)=>a(e,1,0,t,"easeOutQuad"),scaleIn:(e,t=500)=>o(e,0,1,t,"easeOutElastic"),scaleOut:(e,t=500)=>o(e,1,0,t,"easeInQuad"),pulse:(e,t=300)=>i().add(()=>o(e,1,1.1,t/2,"easeOutQuad")).add(()=>o(e,1.1,1,t/2,"easeInQuad")).play(),bounce:(e,t=600)=>o(e,0,1,t,"easeOutBounce")};return{easingFunctions:t,animateValue:n,staggeredAnimation:function(e,t,n=100,a=1e3){if(!Array.isArray(e))throw new Error("Items must be an array");e.forEach((e,r)=>{const o=r*n,i=a-o;setTimeout(()=>{i>0&&t(e,r,i)},o)})},morphShape:function(e,n,a=1e3,r="easeInOutQuad",o,i){if("string"!=typeof e||"string"!=typeof n)throw new Error("Path values must be strings");const l=performance.now(),s=t[r]||t.easeInOutQuad;requestAnimationFrame(function t(r){const c=r-l,u=Math.min(c/a,1),d=s(u);o&&o(u<.5?e:n,d),u<1?requestAnimationFrame(t):i&&i()})},fadeTransition:a,slideTransition:r,scaleTransition:o,createTransitionSequence:i,createSpringAnimation:function(e=300,t=20){return{animate:function(n,a,r,o){let i=n,l=0,s=performance.now();requestAnimationFrame(function n(c){const u=(c-s)/1e3;s=c;const d=i-a;l+=(-e*d+-t*l)*u,i+=l*u,r&&r(i),Math.abs(d)<.01&&Math.abs(l)<.01?o&&o():requestAnimationFrame(n)})}}},createStaggeredTransition:function(t,n,a={}){const{delay:r=e.staggerDelay,duration:o=e.defaultDuration,ease:i=e.defaultEase,reverse:l=!1}=a,s=Array.isArray(t)?t:Array.from(t),c=l?[...s].reverse():s;return Promise.all(c.map((e,t)=>new Promise(a=>{setTimeout(()=>{n(e,o,i).then(a)},t*r)})))},createCustomTween:function(e,t,n){return function(a){return"function"==typeof n?n(e,t,a):e+(t-e)*a}},createTransitionWithEvents:function(t,n){const{duration:a=e.defaultDuration,onStart:r,onEnd:o,onInterrupt:i}=n;let l=!1;return{start(){return r&&r(),this},interrupt(){return l=!0,i&&i(),this},then(e){return!l&&o&&setTimeout(()=>{o(),e&&e()},a),this}}},transitionConfig:e,presets:l}},e.createBrushSystem=function(){const e={createBrush:function(e={}){const{type:t="xy"}=e;switch(t){case"x":return l.brushX();case"y":return l.brushY();default:return l.brush()}},filterDataByBrush:function(e,t,n){if(!t||!n)return e;const[a,r]=t;return e.filter(e=>{const t=n(e.x||e.label||e.value);return t>=a&&t<=r})},getSelectedIndices:function(e,t,n){if(!t||!n)return[];const[a,r]=t,o=[];return e.forEach((e,t)=>{const i=n(e.x||e.label||e.value);i>=a&&i<=r&&o.push(t)}),o},selectionUtils:{createSelectionSummary(e){if(!e||0===e.length)return{count:0,sum:0,average:0,min:0,max:0};const t=e.map(e=>e.cumulativeTotal||e.value||e.y||0),n=t.reduce((e,t)=>e+t,0),a=Math.min(...t),r=Math.max(...t);return{count:e.length,sum:n,average:n/e.length,min:a,max:r,extent:[a,r]}}},onStart:t=>e,onMove:t=>e,onEnd:t=>e};return e},e.createComparisonWaterfall=function(e,t,n,a){const r=l.index(t,n);return e.map(e=>{const t=n(e),o=a(e),i=r.get(t),s=o-(i?a(i):0);return{label:t,stacks:[{value:s,color:s>=0?"#2ecc71":"#e74c3c",label:`Change: ${s>=0?"+":""}${l.format(".2f")(s)}`}]}})},e.createDataProcessor=z,e.createDivergingScale=b,e.createExportSystem=function(){let e={filename:"waterfall-chart",quality:1,scale:1,background:"#ffffff",padding:20,includeStyles:!0,includeData:!0};function t(t,n={}){const a={...e,...n};try{const e=t.select("svg");if(e.empty())throw new Error("No SVG element found in chart container");const n=e.node(),o=new XMLSerializer,i=n.cloneNode(!0);a.includeStyles&&function(e){try{const t=Array.from(document.styleSheets);let n="";if(t.forEach(e=>{try{Array.from(e.cssRules||e.rules).forEach(e=>{if(e.type===CSSRule.STYLE_RULE){const t=e;t.selectorText&&(t.selectorText.includes(".mintwaterfall")||t.selectorText.includes("svg")||t.selectorText.includes("chart"))&&(n+=t.cssText)}})}catch(e){console.warn("Could not access stylesheet:",e)}}),n){const t=document.createElementNS("http://www.w3.org/2000/svg","style");t.textContent=n,e.insertBefore(t,e.firstChild)}}catch(e){console.warn("Failed to add inline styles:",e)}}(i),a.background&&"transparent"!==a.background&&function(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","rect");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("fill",t),e.insertBefore(n,e.firstChild)}(i,a.background);const l=o.serializeToString(i),s=new Blob([l],{type:"image/svg+xml;charset=utf-8"});return{blob:s,url:URL.createObjectURL(s),data:l,download:()=>r(s,`${a.filename}.svg`)}}catch(e){throw console.error("SVG export failed:",e),e}}function n(n,a={}){const o={...e,scale:2,quality:.95,...a};return new Promise((e,a)=>{try{const i=n.select("svg");if(i.empty())return void a(new Error("No SVG element found in chart container"));const l=i.node().getBBox(),s=(l.width+2*o.padding)*o.scale,c=(l.height+2*o.padding)*o.scale,u=document.createElement("canvas");u.width=s,u.height=c;const d=u.getContext("2d");if(!d)return void a(new Error("Failed to get canvas context"));d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",o.background&&"transparent"!==o.background&&(d.fillStyle=o.background,d.fillRect(0,0,s,c));const f=t(n,{...o,includeStyles:!0,background:"transparent"}),m=new Image;m.onload=()=>{try{d.drawImage(m,o.padding*o.scale,o.padding*o.scale),u.toBlob(t=>{t?(URL.revokeObjectURL(f.url),e({blob:t,url:URL.createObjectURL(t),data:f.data,download:()=>r(t,`${o.filename}.png`)})):a(new Error("Failed to create PNG blob"))},"image/png",o.quality)}catch(e){a(new Error(`PNG rendering failed: ${e}`))}},m.onerror=()=>{a(new Error("Failed to load SVG image for PNG conversion"))},m.src=`data:image/svg+xml;base64,${btoa(f.data)}`}catch(e){a(new Error(`PNG export failed: ${e}`))}})}function a(e,t=","){if(!e||0===e.length)return"";const n=Object.keys(e[0]);return[n.join(t),...e.map(e=>n.map(n=>{const a=e[n],r=null!=a?String(a):"";return r.includes(t)||r.includes('"')||r.includes("\n")?`"${r.replace(/"/g,'""')}"`:r}).join(t))].join("\n")}function r(e,t){const n=URL.createObjectURL(e),a=document.createElement("a");a.href=n,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(n)}const o={exportSVG:t,exportPNG:n,exportPDF:function(t,a={}){const o={...e,orientation:"landscape",pageFormat:"a4",...a};return new Promise((e,a)=>{if("undefined"!=typeof window&&window.jsPDF)try{n(t,{...o,scale:2,quality:.95}).then(t=>{const n=new(0,window.jsPDF)({orientation:o.orientation,unit:"mm",format:o.pageFormat}),i=n.internal.pageSize.getWidth(),l=n.internal.pageSize.getHeight(),s=new FileReader;s.onload=()=>{try{const a=s.result,c=new Image;c.onload=()=>{const s=c.width/c.height;let u=i-20,d=u/s;d>l-20&&(d=l-20,u=d*s);const f=(i-u)/2,m=(l-d)/2;n.addImage(a,"PNG",f,m,u,d);const h=n.output("blob");URL.revokeObjectURL(t.url),e({blob:h,url:URL.createObjectURL(h),data:h,download:()=>r(h,`${o.filename}.pdf`)})},c.src=a}catch(e){a(new Error(`PDF generation failed: ${e}`))}},s.onerror=()=>{a(new Error("Failed to read PNG data for PDF conversion"))},s.readAsDataURL(t.blob)}).catch(a)}catch(e){a(new Error(`PDF export failed: ${e}`))}else a(new Error('jsPDF library is required for PDF export. Please include it: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"><\/script>'))})},exportData:function(t,n={}){const o={...e,dataFormat:"json",includeMetadata:!0,delimiter:",",...n};try{let e,n,i;switch(o.dataFormat){case"json":const r=o.includeMetadata?{data:t,metadata:{exportDate:(new Date).toISOString(),count:t.length}}:t;e=JSON.stringify(r,null,2),n="application/json",i="json";break;case"csv":e=a(t,o.delimiter||","),n="text/csv",i="csv";break;case"tsv":e=a(t,"\t"),n="text/tab-separated-values",i="tsv";break;default:throw new Error(`Unsupported data export format: ${o.dataFormat}`)}const l=new Blob([e],{type:`${n};charset=utf-8`});return{blob:l,url:URL.createObjectURL(l),data:e,download:()=>r(l,`${o.filename}.${i}`)}}catch(e){throw console.error("Data export failed:",e),e}},configure:function(t){return e={...e,...t},o},downloadFile:function(e,t,n="text/plain"){r(e instanceof Blob?e:new Blob([e],{type:n}),t)}};return o},e.createHierarchicalLayout=function(){let e=[800,400],t=0,n=!1,a="treemap",r=0,o=0,i=0,s=0,c=0,u=0,d=1.618033988749895,f={orientation:"horizontal"},m={nodeSize:null,separation:null};function h(a){const d=l.treemap().size(e).round(n).padding(t);return void 0!==r&&d.paddingInner(r),void 0!==o&&d.paddingOuter(o),void 0!==i&&d.paddingTop(i),void 0!==s&&d.paddingRight(s),void 0!==c&&d.paddingBottom(c),void 0!==u&&d.paddingLeft(u),d(a)}const p=function(r){if(!r)throw console.error("MintWaterfall: No hierarchical data provided to layout"),new Error("No hierarchical data provided");const o=r;switch(a){case"treemap":return h(o);case"partition":return function(a){const r=l.partition().size(e).round(n).padding(t)(a);"vertical"===f.orientation&&r.each(e=>{if(void 0!==e.x0&&void 0!==e.y0&&void 0!==e.x1&&void 0!==e.y1){const t=e.x0;e.x0=e.y0,e.y0=t;const n=e.x1;e.x1=e.y1,e.y1=n}});return r}(o);case"pack":return function(n){return l.pack().size(e).padding(t)(n)}(o);case"cluster":return function(t){const n=l.cluster().size(e);m.nodeSize&&n.nodeSize(m.nodeSize);m.separation&&n.separation(m.separation);return n(t)}(o);case"tree":return function(t){const n=l.tree().size(e);m.nodeSize&&n.nodeSize(m.nodeSize);m.separation&&n.separation(m.separation);return n(t)}(o);default:return console.warn(`MintWaterfall: Unknown layout type '${a}', falling back to treemap`),h(o)}};return p.size=function(t){return arguments.length?(e=t,p):e},p.padding=function(e){return arguments.length?(t=e,p):t},p.paddingInner=function(e){return arguments.length?(r=e,p):r},p.paddingOuter=function(e){return arguments.length?(o=e,p):o},p.paddingTop=function(e){return arguments.length?(i=e,p):i},p.paddingRight=function(e){return arguments.length?(s=e,p):s},p.paddingBottom=function(e){return arguments.length?(c=e,p):c},p.paddingLeft=function(e){return arguments.length?(u=e,p):u},p.round=function(e){return arguments.length?(n=e,p):n},p.ratio=function(e){return arguments.length?(d=e,p):d},p.type=function(e){return arguments.length?(a=e,p):a},p.partitionOrientation=function(e){return arguments.length?(f.orientation=e,p):f.orientation},p.nodeSize=function(e){return arguments.length?(m.nodeSize=e,p):m.nodeSize},p.separation=function(e){return arguments.length?(m.separation=e,p):m.separation},p},e.createHierarchicalLayoutSystem=V,e.createPerformanceManager=p,e.createRevenueWaterfall=function(e,t,n="revenue"){return D.createMultiDimensionalWaterfall(e,t,n)},e.createScaleSystem=s,e.createSequentialScale=y,e.createShapeGenerators=M,e.createStatisticalSystem=O,e.createTemporalWaterfall=function(e,t,n,a="month"){const r={day:l.timeDay,week:l.timeWeek,month:l.timeMonth,quarter:l.timeMonth.every(3),year:l.timeYear};return D.aggregateByTime(e,{timeAccessor:e=>new Date(e[t]),valueAccessor:e=>e[n]||0,interval:r[a],aggregation:"sum"})},e.createTooltipSystem=m,e.createVarianceWaterfall=function(e,t,n="actual",a="budget"){return e.map(e=>{const r=(e[n]||0)-(e[a]||0);return{label:e[t],stacks:[{value:r,color:r>=0?"#2ecc71":"#e74c3c",label:`Variance: ${r>=0?"+":""}${l.format(".2f")(r)}`}]}})},e.createVirtualWaterfallRenderer=function(e,t){const n=j(),a=n.createVirtualScrollManager(t),r=n.createPerformanceMonitor();return{virtualScrollManager:a,performanceMonitor:r,render:function(e,t){r.startTiming("render"),a.getVirtualizedData(e,t),r.endTiming("render"),r.trackFrameRate()}}},e.createWaterfallBubbles=function(e,t,n,a){const r=V(),o=r.transformWaterfallToHierarchy(e),i={width:n,height:a,padding:3,colorScale:l.scaleOrdinal(l.schemePastel1),sizeAccessor:e=>Math.abs(e.value||0)},s=r.createPackLayout(o,i);r.renderPack(t,s,i)},e.createWaterfallColorScale=function(e,t="default",n="auto"){const a=e.map(e=>e.value),r=l.extent(a),o=r[0]<0&&r[1]>0;if("auto"===n&&(n=o?"diverging":"sequential"),"diverging"===n&&o){const e=Math.max(Math.abs(r[0]),Math.abs(r[1]));return b([-e,0,e],t)}return y(r,t)},e.createWaterfallConfidenceBands=A,e.createWaterfallDragBehavior=function(e,t){return{enabled:!0,axis:"vertical",constraints:{minValue:t?.min,maxValue:t?.max,snapToGrid:!0,gridSize:100},onDrag:(t,n)=>{e&&e(n,n.value)}}},e.createWaterfallForceConfig=function(e=1e3){return{enabled:!0,forces:{collision:!0,positioning:!0,centering:!1,links:!1},strength:{collision:.8,positioning:.6},duration:e}},e.createWaterfallMilestones=S,e.createWaterfallSequenceAnalyzer=function(e){const t=U(),n=t.analyzeSequence(e),a=[];let r=0;e.forEach((e,t)=>{const n=function(e){if("number"==typeof e)return e;if(void 0!==e.value)return e.value;if(e.stacks&&Array.isArray(e.stacks))return e.stacks.reduce((e,t)=>e+(t.value||0),0);return 0}(e);r+=n,a.push({step:t,cumulative:r,change:n})});const o=n.filter(e=>"large"===e.magnitude).map(e=>`${e.from} → ${e.to}`),i=t.suggestDataOptimizations(e);return{flowAnalysis:n,cumulativeFlow:a,criticalPaths:o,optimizationSuggestions:i}},e.createWaterfallSpatialIndex=function(e,t,n){const a=P();return e.forEach((e,r)=>{const o=(t(e.label)||0)+(t.bandwidth?t.bandwidth()/2:0),i=n(e.value)||0;a.add({x:o,y:i,data:e,index:r})}),a},e.createWaterfallSunburst=function(e,t,n,a){const r=V(),o=r.transformWaterfallToHierarchy(e),i={width:n,height:a,innerRadius:40,type:"sunburst",colorScale:l.scaleOrdinal(l.schemeCategory10)},s=r.createPartitionLayout(o,i);r.renderPartition(t,s,i)},e.createWaterfallTickGenerator=function(e,t){const n=U().generateCustomTicks(e,{count:8,nice:!0,includeZero:!0,threshold:Math.abs(e[1]-e[0])/100}),a=n.map(e=>0===e?"0":Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(0)),r=n.filter(n=>t.some(t=>Math.abs(function(e){if("number"==typeof e)return e;if(void 0!==e.value)return e.value;if(e.stacks&&Array.isArray(e.stacks))return e.stacks.reduce((e,t)=>e+(t.value||0),0);return 0}(t)-n)<Math.abs(e[1]-e[0])/50));return{ticks:n,labels:a,keyMarkers:r}},e.createWaterfallTreemap=function(e,t,n,a){const r=V(),o=r.transformWaterfallToHierarchy(e),i={width:n,height:a,padding:2,tile:l.treemapBinary,round:!0,colorScale:l.scaleOrdinal(l.schemeSet3)},s=r.createTreemapLayout(o,i);r.renderTreemap(t,s,i)},e.createWaterfallVoronoiConfig=function(e,t,n){return{enabled:!0,extent:[[n.left,n.top],[e-n.right,t-n.bottom]],showCells:!1,cellOpacity:.1}},e.createZoomSystem=h,e.d3DataUtils=F,e.dataProcessor=D,e.default=$,e.financialReducers=R,e.getAdvancedBarColor=w,e.getConditionalColor=v,e.groupWaterfallData=function(e,t,n,a){const r=D.flatRollupBy(e,e=>l.sum(e,n),...t),o=["#3498db","#2ecc71","#f39c12","#e74c3c","#9b59b6","#1abc9c","#34495e","#95a5a6"];return r.map((t,n)=>{const r=t.slice(0,-1),i=t[t.length-1];return{label:a&&e[0]?r.map((t,n)=>`${Object.keys(e[0])[n]}: ${t}`).join(" | "):r.join(" → "),stacks:[{value:i,color:o[n%o.length],label:`${i>=0?"+":""}${l.format(".2f")(i)}`}]}})},e.interpolateThemeColor=x,e.themes=g,e.transformTransactionData=function(e,t,n,a="amount",r){if(n)return D.createBreakdownWaterfall(e,t,n,a);{const n=D.rollupBy(e,e=>l.sum(e,e=>e[a]||0),e=>e[t]),r=["#3498db","#2ecc71","#f39c12","#e74c3c","#9b59b6"];let o=0;return Array.from(n.entries()).map(([e,t])=>({label:String(e),stacks:[{value:t,color:r[o++%r.length],label:`${t>=0?"+":""}${l.format(".2f")(t)}`}]}))}},e.version="0.8.6",e.waterfallChart=$,Object.defineProperty(e,"__esModule",{value:!0})});
|